PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/test_PDO_SQLite.php

https://bitbucket.org/SuRaMoN/surosql
PHP | 335 lines | 243 code | 66 blank | 26 comment | 35 complexity | 8365de77028e641186ce5d525eb09d7f MD5 | raw file
Possible License(s): LGPL-3.0, AGPL-1.0, GPL-2.0, LGPL-2.1
  1. <?php
  2. // version: 3.0.0
  3. require_once(dirname(__FILE__) . '/../surosql/Surosql.class.php');
  4. require_once(dirname(__FILE__) . '/../surosql/SurosqlOO.class.php');
  5. require_once(dirname(__FILE__) . '/../surosql/SurosqlPDO.class.php');
  6. require_once(dirname(__FILE__) . '/../surosql/SurosqlPDOCache.class.php');
  7. require_once(dirname(__FILE__) . '/../surosql/suracache/SuraCache.class.php');
  8. require_once(dirname(__FILE__) . '/../surosql/suracache/SuraCacheRequest.class.php');
  9. use ns\SurosqlOO, ns\SurosqlBindable, ns\SurosqlPDOCache, ns\SurosqlOOManager, ns\SurosqlPDO;
  10. use ns\Surosql as osql;
  11. use \Exception;
  12. class User extends SurosqlOO {
  13. static $surosql = array(
  14. 'columns' => array('id', 'name', 'registrationdate', 'meta', 'meta2'),
  15. 'primary' => 'id',
  16. 'alias' => 'user',
  17. 'serialization' => array('meta' => array('json_encode', 'json_decode'), 'meta2'),
  18. 'table' => 'wp_users');
  19. public $unused_var;
  20. }
  21. class wp_postmeta {
  22. static $surosql = array(
  23. 'primary' => 'id',
  24. );
  25. static $unused_var;
  26. public $id;
  27. public $meta;
  28. }
  29. class Comment {
  30. static $surosql = array(
  31. 'table' => 'wp_comments',
  32. 'alias' => 'comment',
  33. 'connections' => array(
  34. 'author(user)' => '`%comment%`.`author_id` = `%author%`.`id`'
  35. )
  36. );
  37. public $content;
  38. }
  39. spl_autoload_register(create_function('$a', 'throw new Exception("Loading unnecessary class: " . addslashes($a));'));
  40. class SurosqlTest {
  41. static $assertValues = array();
  42. function __construct() {
  43. $this->osql = $osql = SurosqlPDO::register('dsn=sqlite::memory:');
  44. $osql->aliases['post'] = array('table' => 'wp_posts', 'where' => '`%post%`.`approved` = 1', 'columns' => array('id', 'title'));
  45. $osql->aliases['user2'] = array('class' => 'UnexistingCLass', 'table' => 'wp_users', 'columns' => array('id', 'name'));
  46. $osql->aliases['alias_with_columns'] = array('table' => 'table', 'columns' => array());
  47. $osql->addclass('Comment');
  48. $osql->addclass('User');
  49. $osql->connect('post - comment', '`%post%`.`id` = `%comment%`.`post_id`')
  50. ->connect('post - author(user)', '`%post%`.`author_id` = `%author%`.`id`')
  51. ->connect('post - meta(wp_postmeta)', '`%post%`.`id` = `%meta%`.`post_id`')
  52. ->connect('user - friendships', '`%user%`.`id` = `%friendships%`.`first`')
  53. ->connect('friendships - friend(user)', '`%friendships%`.`second` = `%friend%`.`id`')
  54. ->connect('user - friend(user)', 'friendships - friend', array('jointype' => 'm2m'));
  55. $osql->exec(file_get_contents(dirname(__FILE__) . '/test_db.sqlite.sql'));
  56. }
  57. function testBindables() {
  58. assert(osql::q('5 < ', 6, ' AND a IN', array(1, 2, 3))->parts === array('5 < ', 6, ' AND a IN (', 1, ', ', 2, ', ', 3, ') '));
  59. assert(osql::q('a < ', 1)->andq('b > ', 2)->parts === array('(a < ', 1 ,') AND (b > ', 2, ')'));
  60. assert(osql::q('a < ', 1, '+1')->orq('b > ', 2, '+1')->parts === array('(a < ', 1, '+1) OR (b > ', 2, '+1)'));
  61. assert(osql::q('a <', 1)->andq('b >', 2)->orq('c > ', 2, ' +1')->orq('d ==', 4)->parts === array ('(((a <', 1, ') AND (b >', 2, ')) OR (c > ', 2, ' +1)) OR (d ==', 4, ')'));
  62. }
  63. function testQuoting() {
  64. $osql = $this->osql;
  65. assert($osql->quote("'") === "''''");
  66. assert($osql->quote_rec(array("'" => "'")) === array("'" => "''''"));
  67. assert($osql->quote_rec(array(array("'")), 1) === array("'Array'"));
  68. assert($osql->quote_rec((object) array('a' => "'"))->a === "''''");
  69. }
  70. /*
  71. function testOperators() {
  72. $osql = $this->osql;
  73. assert($osql->is('a <', '5')->str === '(a < :bound_var_1th)');
  74. assert($osql->from('table')->ifeq('id', 2)->ifis('age <', 10)->sql() === 'SELECT * FROM `table` WHERE ((((id = :bound_var_2th))) AND ((age < :bound_var_3th)))');
  75. assert($osql->eq('123', '3,4,5')->str === '(123 = :bound_var_4th)');
  76. assert($osql->neq(array('123', '456'), '3,4,5')->str === '(123 != :bound_var_5th) AND (456 != :bound_var_6th)');
  77. assert($osql->in('123', array('3', '4\'', '5'))->str === '(123 IN (:bound_var_7th, :bound_var_8th, :bound_var_9th))');
  78. assert($osql->from('a')->ifnin('b', array('c', 'd'))->sql() === 'SELECT * FROM `a` WHERE (((b NOT IN (:bound_var_10th, :bound_var_11th))))');
  79. assert($osql->like(array('f1', 'f2'), "%'v'%")->str === '(f1 LIKE :bound_var_12th) AND (f2 LIKE :bound_var_13th)');
  80. assert($osql->like('f1', "%'v'%")->str === '(f1 LIKE :bound_var_14th)');
  81. assert($osql->from('tbl')->iflike('f', 'v')->sql() === 'SELECT * FROM `tbl` WHERE (((f LIKE :bound_var_15th)))');
  82. }
  83. function testLogicalConnectives() {
  84. $osql = $this->osql;
  85. assert($osql->logand('1', '2', array('2', '3'))->str === '(1) AND (2) AND (2) AND (3)');
  86. assert($osql->logor(array())->str === '0');
  87. assert($osql->logand()->str === '1');
  88. }
  89. */
  90. function testPropertieRetrieval() {
  91. $osql = $this->osql;
  92. assert($osql->count()->limit(0, 30)->limit() === '0,30');
  93. assert($osql->count()->select() === 'COUNT(*)');
  94. }
  95. function testSQLConstruction() {
  96. $osql = $this->osql;
  97. assert($osql->wp_postmeta->sql() === 'SELECT `wp_postmeta`.`id` AS `wp_postmeta_id`, `wp_postmeta`.`meta` AS `wp_postmeta_meta` FROM `wp_postmeta`');
  98. assert($osql->count()->from('abc AS `def`, `ghi` jkl')->join('INNER JOIN `123`')->sql() === 'SELECT COUNT(*) FROM `abc` AS `def` ,`ghi` AS `jkl` INNER JOIN `123`');
  99. assert($osql->count()->from('abc AS `def`, `ghi` jkl')->sql() === 'SELECT COUNT(*) FROM `abc` AS `def` ,`ghi` AS `jkl`');
  100. }
  101. function testSelectParsing() {
  102. assert(osql::select('"a %p, a" a, %p, \'"", %p, \' b, %u')->from('comment p, comment u')->sql() === 'SELECT "a %p, a" a, `p`.`content` AS `p_content`, \'"", %p, \' b, `u`.`content` AS `u_content` FROM `wp_comments` AS `p` ,`wp_comments` AS `u`');
  103. assert(osql::select('"" a')->from('p')->sql() === 'SELECT "" a FROM `p`');
  104. assert(osql::select('"\"" a')->from('p')->sql() === 'SELECT "\"" a FROM `p`');
  105. assert(osql::select('"\\\'" a')->from('p')->sql() === 'SELECT "\\\'" a FROM `p`');
  106. assert(osql::select('"\\\\" a')->from('p')->sql() === 'SELECT "\\\\" a FROM `p`');
  107. }
  108. function testPHP52Style() {
  109. if(version_compare(PHP_VERSION, '5.3', '>=')) {
  110. return;
  111. }
  112. assert(osql('user')->sql() === 'SELECT `user`.`id` AS `user_id`, `user`.`name` AS `user_name`, `user`.`registrationdate` AS `user_registrationdate`, `user`.`meta` AS `user_meta`, `user`.`meta2` AS `user_meta2` FROM `wp_users` AS `user`');
  113. }
  114. function testPHP53Style() {
  115. if(version_compare(PHP_VERSION, '5.3', '<')) {
  116. return;
  117. }
  118. assert(osql::count()->from('table')->sql() === 'SELECT COUNT(*) FROM `table`');
  119. $osql = $this->osql;
  120. assert($osql('user')->sql() === 'SELECT `user`.`id` AS `user_id`, `user`.`name` AS `user_name`, `user`.`registrationdate` AS `user_registrationdate`, `user`.`meta` AS `user_meta`, `user`.`meta2` AS `user_meta2` FROM `wp_users` AS `user`');
  121. }
  122. function testNoClassExistsCall() {
  123. $osql = $this->osql;
  124. assert($osql->from('UnexistingTable')->sql() === 'SELECT * FROM `UnexistingTable`');
  125. osql::fromoo('alias_with_columns')->sql(); // no exception == good
  126. }
  127. function testDataRetrieval() {
  128. $osql = $this->osql;
  129. assert($osql->select('id')->from('wp_postmeta')->col() === array('1'));
  130. assert($osql->select()->from('wp_postmeta')->ifeq('id', 1)->first()->id == 1);
  131. assert($osql->count()->from('wp_posts')->var() == 3);
  132. assert($osql->count()->from('wp_posts s')->var() == 3);
  133. assert($osql->count()->from('`post`')->var() == 2);
  134. assert($osql->count()->from('post AS `s`')->var() == 2);
  135. assert($osql->select('"a %p, a" a, %p, \'"", %p, \' b, %u')->from('post p, post u')->first()->a === 'a %p, a');
  136. assert($osql->select('%*, "c" c')->from('post a, post b')->first()->b->id == 1);
  137. assert($osql->select()->from('user u, comment')->first() instanceof stdClass);
  138. assert($osql->select('%*')->from('post p')->first()->title === 'My first post!');
  139. assert($osql->select()->from('user2')->first()->name !== null);
  140. }
  141. function testObjectOrientatedDataRetrieval() {
  142. $osql = $this->osql;
  143. assert($osql->selectoo()->from('comment')->select('%*')->sql() === 'SELECT `comment`.`content` AS `comment_content` FROM `wp_comments` AS `comment`');
  144. assert($osql->selectoo()->from('post p')->where('p.id=-1')->fetch() === false);
  145. assert($osql->selectoo()->from('post p')->where('p.id=-1')->first(0) === 0);
  146. assert($osql->selectoo('%m, m.meta')->from('wp_postmeta m')->first()->meta === 'meta post 1');
  147. assert($osql->selectoo()->from('User u, Comment')->first()->u instanceof User);
  148. assert($osql->selectoo('%m')->from('wp_postmeta m')->first() instanceof wp_postmeta);
  149. assert(count($osql->selectoo()->from('post - comment')->fetchAll()) == 1);
  150. }
  151. function testDataRetrievalFromManager() {
  152. assert(User::get(1)->first()->id == 1);
  153. assert(User::get()->ifeq('id', 1)->first()->id == 1);
  154. assert(User::get(array('id' => 1))->first()->id == 1);
  155. }
  156. function testDataRetrievalWithRelations() {
  157. $osql = $this->osql;
  158. assert($osql->count()->from('comment - author')->fetchVar() == 1);
  159. assert($osql->count('s.title, comment.content AS comment')->from('post s - comment')->var() == 1);
  160. assert($osql->count()->from('post - (comment c, author, meta AS `m`)')->var() == 1);
  161. assert($osql->count()->from('post s - (`comment`, author)')->var() == 1);
  162. }
  163. function testDataRetrievalWithManyToManyRelation() {
  164. $osql = $this->osql;
  165. assert($osql->count()->from('user u - friend f')->var() == 1);
  166. }
  167. function testDataModification() {
  168. $osql = $this->osql;
  169. assert($osql->exec('UPDATE wp_users SET name="Willem" WHERE id=1') == 1);
  170. assert($osql->update('user')->set('name = ?, registrationdate = date("NOW")')->where('id=?')->bind('Willem', 1)->exec() == 1);
  171. assert($osql->update('user')->set(array('name' => 'Johan'))->where('id=:idvar')->bind(array('idvar' => '1'))->exec() == 1);
  172. assert($osql->update('user')->setq('name=', 'Hans')->whereq('id=', 1)->exec() == 1);
  173. assert(User::get(1)->first()->name === 'Hans');
  174. assert($osql->insert('wp_postmeta', array('id' => 5, 'post_id' => 1, 'meta' => 'meta')));
  175. assert(count($osql->select()->from('User')->all()) === 4);
  176. assert(count($osql->selectoo('u.id')->from('User u')->all()) === 4);
  177. assert(count($osql->selectoo()->from('user')->all()) === 4);
  178. try {
  179. assert($osql->selectoo()->from('post p')->where('p.id=-1')->first() || false);
  180. assert(false);
  181. } catch(Exception $e) {
  182. assert($e->getMessage() == 'Trying to fetch from empty resultset.');
  183. }
  184. SuraCache::register('backend=SuraCacheRequest');
  185. SurosqlPDOCache::register();
  186. assert($osql->count()->from('wp_postmeta')->cached_var() == 2);
  187. $meta = new wp_postmeta();
  188. $meta->meta = 'test123';
  189. $meta->post_id = 1;
  190. assert((int) SurosqlOOManager::insertorupdate($meta) > 0); // insert
  191. $meta->post_id = 78;
  192. assert((int) SurosqlOOManager::insertorupdate($meta) > 0); // update
  193. assert(osql::count()->from('wp_postmeta')->ifeq('post_id', 78)->var() == 1); // check
  194. assert($osql->count()->from('wp_postmeta')->cached_var() == 2);
  195. assert($osql->count()->from('wp_postmeta')->var() == 3);
  196. $user = new User(array('name' => 'Lowie', 'blabla' => 'bloblo'));
  197. assert(!isset($user->blabla));
  198. $user->meta = array('key' => 'value');
  199. $user->meta2 = array('key' => 'value');
  200. $user->insert(null, array('registrationdate' => 'date("NOW")'));
  201. assert($user->id > 0);
  202. assert(strlen($osql->selectoo()->from('user')->where('id=?')->bind($user->id)->first()->registrationdate) > 7);
  203. assert($osql->selectoo()->from('user')->where('id=?')->bind($user->id)->first()->meta->key == 'value');
  204. assert($osql->selectoo()->from('user')->where('id=?')->bind($user->id)->first()->meta2['key'] == 'value');
  205. $user->name = 'Hedwig';
  206. assert($user->update(array('name')) == 1);
  207. assert($osql->updateobj($user, array(), array('registrationdate' => 'date("now")')) == 1);
  208. $user->id = -1;
  209. try {
  210. $user->update();
  211. assert(false);
  212. } catch(Exception $e) {
  213. assert(strpos($e->getMessage(), 'No rows found to update.') !== false);
  214. }
  215. try {
  216. $user = new User();
  217. $user->id = 1;
  218. $user->name = 'Jos';
  219. $osql->insertobj($user);
  220. assert(false);
  221. } catch(PDOException $e) {
  222. assert(strpos($e->getMessage(), 'Integrity constraint violation') !== false);
  223. }
  224. assert($osql->count()->from('user')->where('id=?')->bind($user->id)->var() == 1);
  225. $user->delete();
  226. assert($osql->count()->from('user')->where('id=?')->bind($user->id)->var() == 0);
  227. $iterator_count = 0;
  228. foreach($osql->select()->from('user') as $u) {
  229. $iterator_count++;
  230. }
  231. assert($iterator_count > 2);
  232. }
  233. static function setupAssertHandler() {
  234. self::$assertValues = array(
  235. 'ASSERT_ACTIVE' => assert_options(ASSERT_ACTIVE, 1),
  236. 'ASSERT_WARNING' => assert_options(ASSERT_WARNING, 0),
  237. 'ASSERT_CALLBACK' => assert_options(ASSERT_CALLBACK, create_function('$file,$line,$code', 'echo "------------\nAssertion Failed: File \'$file\'\nLine \'$line\'\nCode \'$code\'\n------------\n";')),
  238. 'error_reporting' => error_reporting(E_ERROR),
  239. 'error_handler' => set_error_handler(create_function('$errno, $errstr, $errfile, $errline', 'if(error_reporting() != 0) {throw new Exception($errstr, $errno);}'))
  240. );
  241. }
  242. static function tearDownAssertHandler() {
  243. assert_options(ASSERT_ACTIVE, self::$assertValues['ASSERT_ACTIVE']);
  244. assert_options(ASSERT_WARNING, self::$assertValues['ASSERT_WARNING']);
  245. assert_options(ASSERT_CALLBACK, self::$assertValues['ASSERT_CALLBACK']);
  246. error_reporting(self::$assertValues['error_reporting']);
  247. set_error_handler(is_null(self::$assertValues['error_handler']) ? create_function('', 'return false;') : self::$assertValues['error_handler']);
  248. }
  249. static function runTests() {
  250. self::setupAssertHandler();
  251. echo "<pre>\n";
  252. $inst = new self();
  253. foreach(get_class_methods($inst) as $test) {
  254. if(substr($test, 0, 4) == 'test') {
  255. echo '-<b>', substr($test, 4), "</b>\n";
  256. call_user_func(array($inst, $test));
  257. }
  258. }
  259. echo "------------\nAll tests executed\n</pre>";
  260. self::tearDownAssertHandler();
  261. }
  262. }
  263. SurosqlTest::runTests();
  264. ?>