Source for file DibiFluent.php

Documentation is available at DibiFluent.php

  1. 1: <?php
  2. 2:  
  3. 3: /**
  4. 4:  * dibi - tiny'n'smart database abstraction layer
  5. 5:  * ----------------------------------------------
  6. 6:  *
  7. 7:  * @copyright  Copyright (c) 2005, 2010 David Grudl
  8. 8:  * @license    http://dibiphp.com/license  dibi license
  9. 9:  * @link       http://dibiphp.com
  10. 10:  * @package    dibi
  11. 11:  */
  12. 12:  
  13. 13:  
  14. 14:  
  15. 15: /**
  16. 16:  * dibi SQL builder via fluent interfaces. EXPERIMENTAL!
  17. 17:  *
  18. 18:  * @copyright  Copyright (c) 2005, 2010 David Grudl
  19. 19:  * @package    dibi
  20. 20:  *
  21. 21:  * @property-read string $command 
  22. 22:  * @property-read DibiConnection $connection 
  23. 23:  * @property-read DibiResultIterator $iterator 
  24. 24:  * @method DibiFluent select($field)
  25. 25:  * @method DibiFluent distinct()
  26. 26:  * @method DibiFluent from($table)
  27. 27:  * @method DibiFluent where($cond)
  28. 28:  * @method DibiFluent groupBy($field)
  29. 29:  * @method DibiFluent having($cond)
  30. 30:  * @method DibiFluent orderBy($field)
  31. 31:  * @method DibiFluent limit(int $limit)
  32. 32:  * @method DibiFluent offset(int $offset)
  33. 33:  */
  34. 34: class DibiFluent extends DibiObject implements IDataSource
  35. 35: {
  36. 36:     const REMOVE = FALSE;
  37. 37:  
  38. 38:     /** @var array */
  39. 39:     public static $masks array(
  40. 40:         'SELECT' => array('SELECT''DISTINCT''FROM''WHERE''GROUP BY',
  41. 41:             'HAVING''ORDER BY''LIMIT''OFFSET'),
  42. 42:         'UPDATE' => array('UPDATE''SET''WHERE''ORDER BY''LIMIT'),
  43. 43:         'INSERT' => array('INSERT''INTO''VALUES''SELECT'),
  44. 44:         'DELETE' => array('DELETE''FROM''USING''WHERE''ORDER BY''LIMIT'),
  45. 45:     );
  46. 46:  
  47. 47:     /** @var array  default modifiers for arrays */
  48. 48:     public static $modifiers array(
  49. 49:         'SELECT' => '%n',
  50. 50:         'FROM' => '%n',
  51. 51:         'IN' => '%in',
  52. 52:         'VALUES' => '%l',
  53. 53:         'SET' => '%a',
  54. 54:         'WHERE' => '%and',
  55. 55:         'HAVING' => '%and',
  56. 56:         'ORDER BY' => '%by',
  57. 57:         'GROUP BY' => '%by',
  58. 58:     );
  59. 59:  
  60. 60:     /** @var array  clauses separators */
  61. 61:     public static $separators array(
  62. 62:         'SELECT' => ',',
  63. 63:         'FROM' => ',',
  64. 64:         'WHERE' => 'AND',
  65. 65:         'GROUP BY' => ',',
  66. 66:         'HAVING' => 'AND',
  67. 67:         'ORDER BY' => ',',
  68. 68:         'LIMIT' => FALSE,
  69. 69:         'OFFSET' => FALSE,
  70. 70:         'SET' => ',',
  71. 71:         'VALUES' => ',',
  72. 72:         'INTO' => FALSE,
  73. 73:     );
  74. 74:  
  75. 75:     /** @var array  clauses */
  76. 76:     public static $clauseSwitches array(
  77. 77:         'JOIN' => 'FROM',
  78. 78:         'INNER JOIN' => 'FROM',
  79. 79:         'LEFT JOIN' => 'FROM',
  80. 80:         'RIGHT JOIN' => 'FROM',
  81. 81:     );
  82. 82:  
  83. 83:     /** @var DibiConnection */
  84. 84:     private $connection;
  85. 85:  
  86. 86:     /** @var string */
  87. 87:     private $command;
  88. 88:  
  89. 89:     /** @var array */
  90. 90:     private $clauses array();
  91. 91:  
  92. 92:     /** @var array */
  93. 93:     private $flags array();
  94. 94:  
  95. 95:     /** @var array */
  96. 96:     private $cursor;
  97. 97:  
  98. 98:     /** @var DibiLazyStorage  normalized clauses */
  99. 99:     private static $normalizer;
  100. 100:  
  101. 101:  
  102. 102:  
  103. 103:     /**
  104. 104:      * @param  DibiConnection 
  105. 105:      */
  106. 106:     public function __construct(DibiConnection $connection)
  107. 107:     {
  108. 108:         $this->connection $connection;
  109. 109:  
  110. 110:         if (self::$normalizer === NULL{
  111. 111:             self::$normalizer new DibiLazyStorage(array(__CLASS__'_formatClause'));
  112. 112:         }
  113. 113:     }
  114. 114:  
  115. 115:  
  116. 116:  
  117. 117:     /**
  118. 118:      * Appends new argument to the clause.
  119. 119:      * @param  string clause name
  120. 120:      * @param  array  arguments
  121. 121:      * @return DibiFluent  provides a fluent interface
  122. 122:      */
  123. 123:     public function __call($clause$args)
  124. 124:     {
  125. 125:         $clause self::$normalizer->$clause;
  126. 126:  
  127. 127:         // lazy initialization
  128. 128:         if ($this->command === NULL{
  129. 129:             if (isset(self::$masks[$clause])) {
  130. 130:                 $this->clauses array_fill_keys(self::$masks[$clause]NULL);
  131. 131:             }
  132. 132:             $this->cursor $this->clauses[$clause];
  133. 133:             $this->cursor array();
  134. 134:             $this->command $clause;
  135. 135:         }
  136. 136:  
  137. 137:         // auto-switch to a clause
  138. 138:         if (isset(self::$clauseSwitches[$clause])) {
  139. 139:             $this->cursor $this->clauses[self::$clauseSwitches[$clause]];
  140. 140:         }
  141. 141:  
  142. 142:         if (array_key_exists($clause$this->clauses)) {
  143. 143:             // append to clause
  144. 144:             $this->cursor $this->clauses[$clause];
  145. 145:  
  146. 146:             // TODO: really delete?
  147. 147:             if ($args === array(self::REMOVE)) {
  148. 148:                 $this->cursor NULL;
  149. 149:                 return $this;
  150. 150:             }
  151. 151:  
  152. 152:             if (isset(self::$separators[$clause])) {
  153. 153:                 $sep self::$separators[$clause];
  154. 154:                 if ($sep === FALSE// means: replace
  155. 155:                     $this->cursor array();
  156. 156:  
  157. 157:                 elseif (!empty($this->cursor)) {
  158. 158:                     $this->cursor[$sep;
  159. 159:                 }
  160. 160:             }
  161. 161:  
  162. 162:         else {
  163. 163:             // append to currect flow
  164. 164:             if ($args === array(self::REMOVE)) {
  165. 165:                 return $this;
  166. 166:             }
  167. 167:  
  168. 168:             $this->cursor[$clause;
  169. 169:         }
  170. 170:  
  171. 171:         if ($this->cursor === NULL{
  172. 172:             $this->cursor array();
  173. 173:         }
  174. 174:  
  175. 175:         // special types or argument
  176. 176:         if (count($args=== 1{
  177. 177:             $arg $args[0];
  178. 178:             // TODO: really ignore TRUE?
  179. 179:             if ($arg === TRUE// flag
  180. 180:                 return $this;
  181. 181:  
  182. 182:             elseif (is_string($arg&& preg_match('#^[a-z:_][a-z0-9_.:]*$#i'$arg)) // identifier
  183. 183:                 $args array('%n'$arg);
  184. 184:  
  185. 185:             elseif ($arg instanceof self{
  186. 186:                 $args array_merge(array('(')$arg->_export()array(')'));
  187. 187:  
  188. 188:             elseif (is_array($arg|| $arg instanceof Traversable// any array
  189. 189:                 if (isset(self::$modifiers[$clause])) {
  190. 190:                     $args array(self::$modifiers[$clause]$arg);
  191. 191:  
  192. 192:                 elseif (is_string(key($arg))) // associative array
  193. 193:                     $args array('%a'$arg);
  194. 194:                 }
  195. 195:             // case $arg === FALSE is handled above
  196. 196:         }
  197. 197:  
  198. 198:         foreach ($args as $arg$this->cursor[$arg;
  199. 199:  
  200. 200:         return $this;
  201. 201:     }
  202. 202:  
  203. 203:  
  204. 204:  
  205. 205:     /**
  206. 206:      * Switch to a clause.
  207. 207:      * @param  string clause name
  208. 208:      * @return DibiFluent  provides a fluent interface
  209. 209:      */
  210. 210:     public function clause($clause$remove FALSE)
  211. 211:     {
  212. 212:         $this->cursor $this->clauses[self::$normalizer->$clause];
  213. 213:  
  214. 214:         if ($remove// deprecated, use removeClause
  215. 215:             trigger_error(__METHOD__ . '(..., TRUE) is deprecated; use removeClause() instead.'E_USER_NOTICE);
  216. 216:             $this->cursor NULL;
  217. 217:  
  218. 218:         elseif ($this->cursor === NULL{
  219. 219:             $this->cursor array();
  220. 220:         }
  221. 221:  
  222. 222:         return $this;
  223. 223:     }
  224. 224:  
  225. 225:  
  226. 226:  
  227. 227:     /**
  228. 228:      * Removes a clause.
  229. 229:      * @param  string clause name
  230. 230:      * @return DibiFluent  provides a fluent interface
  231. 231:      */
  232. 232:     public function removeClause($clause)
  233. 233:     {
  234. 234:         $this->clauses[self::$normalizer->$clauseNULL;
  235. 235:         return $this;
  236. 236:     }
  237. 237:  
  238. 238:  
  239. 239:  
  240. 240:     /**
  241. 241:      * Change a SQL flag.
  242. 242:      * @param  string  flag name
  243. 243:      * @param  bool  value
  244. 244:      * @return DibiFluent  provides a fluent interface
  245. 245:      */
  246. 246:     public function setFlag($flag$value TRUE)
  247. 247:     {
  248. 248:         $flag strtoupper($flag);
  249. 249:         if ($value{
  250. 250:             $this->flags[$flagTRUE;
  251. 251:         else {
  252. 252:             unset($this->flags[$flag]);
  253. 253:         }
  254. 254:         return $this;
  255. 255:     }
  256. 256:  
  257. 257:  
  258. 258:  
  259. 259:     /**
  260. 260:      * Is a flag set?
  261. 261:      * @param  string  flag name
  262. 262:      * @return bool 
  263. 263:      */
  264. 264:     final public function getFlag($flag)
  265. 265:     {
  266. 266:         return isset($this->flags[strtoupper($flag)]);
  267. 267:     }
  268. 268:  
  269. 269:  
  270. 270:  
  271. 271:     /**
  272. 272:      * Returns SQL command.
  273. 273:      * @return string 
  274. 274:      */
  275. 275:     final public function getCommand()
  276. 276:     {
  277. 277:         return $this->command;
  278. 278:     }
  279. 279:  
  280. 280:  
  281. 281:  
  282. 282:     /**
  283. 283:      * Returns the dibi connection.
  284. 284:      * @return DibiConnection 
  285. 285:      */
  286. 286:     final public function getConnection()
  287. 287:     {
  288. 288:         return $this->connection;
  289. 289:     }
  290. 290:  
  291. 291:  
  292. 292:  
  293. 293:     /********************* executing ****************d*g**/
  294. 294:  
  295. 295:  
  296. 296:  
  297. 297:     /**
  298. 298:      * Generates and executes SQL query.
  299. 299:      * @param  mixed what to return?
  300. 300:      * @return DibiResult|int result set object (if any)
  301. 301:      * @throws DibiException
  302. 302:      */
  303. 303:     public function execute($return NULL)
  304. 304:     {
  305. 305:         $res $this->connection->query($this->_export());
  306. 306:         return $return === dibi::IDENTIFIER $this->connection->getInsertId($res;
  307. 307:     }
  308. 308:  
  309. 309:  
  310. 310:  
  311. 311:     /**
  312. 312:      * Generates, executes SQL query and fetches the single row.
  313. 313:      * @return DibiRow|FALSE array on success, FALSE if no next record
  314. 314:      */
  315. 315:     public function fetch()
  316. 316:     {
  317. 317:         if ($this->command === 'SELECT'{
  318. 318:             return $this->connection->query($this->_export(NULLarray('%lmt'1)))->fetch();
  319. 319:         else {
  320. 320:             return $this->connection->query($this->_export())->fetch();
  321. 321:         }
  322. 322:     }
  323. 323:  
  324. 324:  
  325. 325:  
  326. 326:     /**
  327. 327:      * Like fetch(), but returns only first field.
  328. 328:      * @return mixed  value on success, FALSE if no next record
  329. 329:      */
  330. 330:     public function fetchSingle()
  331. 331:     {
  332. 332:         if ($this->command === 'SELECT'{
  333. 333:             return $this->connection->query($this->_export(NULLarray('%lmt'1)))->fetchSingle();
  334. 334:         else {
  335. 335:             return $this->connection->query($this->_export())->fetchSingle();
  336. 336:         }
  337. 337:     }
  338. 338:  
  339. 339:  
  340. 340:  
  341. 341:     /**
  342. 342:      * Fetches all records from table.
  343. 343:      * @param  int  offset
  344. 344:      * @param  int  limit
  345. 345:      * @return array 
  346. 346:      */
  347. 347:     public function fetchAll($offset NULL$limit NULL)
  348. 348:     {
  349. 349:         return $this->connection->query($this->_export(NULLarray('%ofs %lmt'$offset$limit)))->fetchAll();
  350. 350:     }
  351. 351:  
  352. 352:  
  353. 353:  
  354. 354:     /**
  355. 355:      * Fetches all records from table and returns associative tree.
  356. 356:      * @param  string  associative descriptor
  357. 357:      * @return array 
  358. 358:      */
  359. 359:     public function fetchAssoc($assoc)
  360. 360:     {
  361. 361:         return $this->connection->query($this->_export())->fetchAssoc($assoc);
  362. 362:     }
  363. 363:  
  364. 364:  
  365. 365:  
  366. 366:     /**
  367. 367:      * Fetches all records from table like $key => $value pairs.
  368. 368:      * @param  string  associative key
  369. 369:      * @param  string  value
  370. 370:      * @return array 
  371. 371:      */
  372. 372:     public function fetchPairs($key NULL$value NULL)
  373. 373:     {
  374. 374:         return $this->connection->query($this->_export())->fetchPairs($key$value);
  375. 375:     }
  376. 376:  
  377. 377:  
  378. 378:  
  379. 379:     /**
  380. 380:      * Required by the IteratorAggregate interface.
  381. 381:      * @param  int  offset
  382. 382:      * @param  int  limit
  383. 383:      * @return DibiResultIterator 
  384. 384:      */
  385. 385:     public function getIterator($offset NULL$limit NULL)
  386. 386:     {
  387. 387:         return $this->connection->query($this->_export(NULLarray('%ofs %lmt'$offset$limit)))->getIterator();
  388. 388:     }
  389. 389:  
  390. 390:  
  391. 391:  
  392. 392:     /**
  393. 393:      * Generates and prints SQL query or it's part.
  394. 394:      * @param  string clause name
  395. 395:      * @return bool 
  396. 396:      */
  397. 397:     public function test($clause NULL)
  398. 398:     {
  399. 399:         return $this->connection->test($this->_export($clause));
  400. 400:     }
  401. 401:  
  402. 402:  
  403. 403:  
  404. 404:     /**
  405. 405:      * @return int 
  406. 406:      */
  407. 407:     public function count()
  408. 408:     {
  409. 409:         return (int) $this->connection->query(
  410. 410:             'SELECT COUNT(*) FROM (%ex'$this->_export()') AS [data]'
  411. 411:         )->fetchSingle();
  412. 412:     }
  413. 413:  
  414. 414:  
  415. 415:  
  416. 416:     /********************* exporting ****************d*g**/
  417. 417:  
  418. 418:  
  419. 419:  
  420. 420:     /**
  421. 421:      * @return DibiDataSource 
  422. 422:      */
  423. 423:     public function toDataSource()
  424. 424:     {
  425. 425:         return new DibiDataSource($this->connection->translate($this->_export())$this->connection);
  426. 426:     }
  427. 427:  
  428. 428:  
  429. 429:  
  430. 430:     /**
  431. 431:      * Returns SQL query.
  432. 432:      * @return string 
  433. 433:      */
  434. 434:     final public function __toString()
  435. 435:     {
  436. 436:         return $this->connection->translate($this->_export());
  437. 437:     }
  438. 438:  
  439. 439:  
  440. 440:  
  441. 441:     /**
  442. 442:      * Generates parameters for DibiTranslator.
  443. 443:      * @param  string clause name
  444. 444:      * @return array 
  445. 445:      */
  446. 446:     protected function _export($clause NULL$args array())
  447. 447:     {
  448. 448:         if ($clause === NULL{
  449. 449:             $data $this->clauses;
  450. 450:  
  451. 451:         else {
  452. 452:             $clause self::$normalizer->$clause;
  453. 453:             if (array_key_exists($clause$this->clauses)) {
  454. 454:                 $data array($clause => $this->clauses[$clause]);
  455. 455:             else {
  456. 456:                 return array();
  457. 457:             }
  458. 458:         }
  459. 459:  
  460. 460:         foreach ($data as $clause => $statement{
  461. 461:             if ($statement !== NULL{
  462. 462:                 $args[$clause;
  463. 463:                 if ($clause === $this->command && $this->flags{
  464. 464:                     $args[implode(' 'array_keys($this->flags));
  465. 465:                 }
  466. 466:                 foreach ($statement as $arg$args[$arg;
  467. 467:             }
  468. 468:         }
  469. 469:  
  470. 470:         return $args;
  471. 471:     }
  472. 472:  
  473. 473:  
  474. 474:  
  475. 475:     /**
  476. 476:      * Format camelCase clause name to UPPER CASE.
  477. 477:      * @param  string 
  478. 478:      * @return string 
  479. 479:      * @ignore internal
  480. 480:      */
  481. 481:     public static function _formatClause($s)
  482. 482:     {
  483. 483:         if ($s === 'order' || $s === 'group'{
  484. 484:             $s .= 'By';
  485. 485:             trigger_error("Did you mean '$s'?"E_USER_NOTICE);
  486. 486:         }
  487. 487:         return strtoupper(preg_replace('#[a-z](?=[A-Z])#''$0 '$s));
  488. 488:     }
  489. 489:  
  490. 490:  
  491. 491:  
  492. 492:     public function __clone()
  493. 493:     {
  494. 494:         // remove references
  495. 495:         foreach ($this->clauses as $clause => $val{
  496. 496:             $this->clauses[$clause$val;
  497. 497:             unset($val);
  498. 498:         }
  499. 499:         $this->cursor $foo;
  500. 500:     }
  501. 501: