DB_query_builder.php 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2019, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
  33. * @license https://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 1.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * Query Builder Class
  41. *
  42. * This is the platform-independent base Query Builder implementation class.
  43. *
  44. * @package CodeIgniter
  45. * @subpackage Drivers
  46. * @category Database
  47. * @author EllisLab Dev Team
  48. * @link https://codeigniter.com/user_guide/database/
  49. */
  50. abstract class CI_DB_query_builder extends CI_DB_driver {
  51. /**
  52. * Return DELETE SQL flag
  53. *
  54. * @var bool
  55. */
  56. protected $return_delete_sql = FALSE;
  57. /**
  58. * Reset DELETE data flag
  59. *
  60. * @var bool
  61. */
  62. protected $reset_delete_data = FALSE;
  63. /**
  64. * QB SELECT data
  65. *
  66. * @var array
  67. */
  68. protected $qb_select = array();
  69. /**
  70. * QB DISTINCT flag
  71. *
  72. * @var bool
  73. */
  74. protected $qb_distinct = FALSE;
  75. /**
  76. * QB FROM data
  77. *
  78. * @var array
  79. */
  80. protected $qb_from = array();
  81. /**
  82. * QB JOIN data
  83. *
  84. * @var array
  85. */
  86. protected $qb_join = array();
  87. /**
  88. * QB WHERE data
  89. *
  90. * @var array
  91. */
  92. protected $qb_where = array();
  93. /**
  94. * QB GROUP BY data
  95. *
  96. * @var array
  97. */
  98. protected $qb_groupby = array();
  99. /**
  100. * QB HAVING data
  101. *
  102. * @var array
  103. */
  104. protected $qb_having = array();
  105. /**
  106. * QB keys
  107. *
  108. * @var array
  109. */
  110. protected $qb_keys = array();
  111. /**
  112. * QB LIMIT data
  113. *
  114. * @var int
  115. */
  116. protected $qb_limit = FALSE;
  117. /**
  118. * QB OFFSET data
  119. *
  120. * @var int
  121. */
  122. protected $qb_offset = FALSE;
  123. /**
  124. * QB ORDER BY data
  125. *
  126. * @var array
  127. */
  128. protected $qb_orderby = array();
  129. /**
  130. * QB data sets
  131. *
  132. * @var array
  133. */
  134. protected $qb_set = array();
  135. /**
  136. * QB data set for update_batch()
  137. *
  138. * @var array
  139. */
  140. protected $qb_set_ub = array();
  141. /**
  142. * QB aliased tables list
  143. *
  144. * @var array
  145. */
  146. protected $qb_aliased_tables = array();
  147. /**
  148. * QB WHERE group started flag
  149. *
  150. * @var bool
  151. */
  152. protected $qb_where_group_started = FALSE;
  153. /**
  154. * QB WHERE group count
  155. *
  156. * @var int
  157. */
  158. protected $qb_where_group_count = 0;
  159. // Query Builder Caching variables
  160. /**
  161. * QB Caching flag
  162. *
  163. * @var bool
  164. */
  165. protected $qb_caching = FALSE;
  166. /**
  167. * QB Cache exists list
  168. *
  169. * @var array
  170. */
  171. protected $qb_cache_exists = array();
  172. /**
  173. * QB Cache SELECT data
  174. *
  175. * @var array
  176. */
  177. protected $qb_cache_select = array();
  178. /**
  179. * QB Cache FROM data
  180. *
  181. * @var array
  182. */
  183. protected $qb_cache_from = array();
  184. /**
  185. * QB Cache JOIN data
  186. *
  187. * @var array
  188. */
  189. protected $qb_cache_join = array();
  190. /**
  191. * QB Cache aliased tables list
  192. *
  193. * @var array
  194. */
  195. protected $qb_cache_aliased_tables = array();
  196. /**
  197. * QB Cache WHERE data
  198. *
  199. * @var array
  200. */
  201. protected $qb_cache_where = array();
  202. /**
  203. * QB Cache GROUP BY data
  204. *
  205. * @var array
  206. */
  207. protected $qb_cache_groupby = array();
  208. /**
  209. * QB Cache HAVING data
  210. *
  211. * @var array
  212. */
  213. protected $qb_cache_having = array();
  214. /**
  215. * QB Cache ORDER BY data
  216. *
  217. * @var array
  218. */
  219. protected $qb_cache_orderby = array();
  220. /**
  221. * QB Cache data sets
  222. *
  223. * @var array
  224. */
  225. protected $qb_cache_set = array();
  226. /**
  227. * QB No Escape data
  228. *
  229. * @var array
  230. */
  231. protected $qb_no_escape = array();
  232. /**
  233. * QB Cache No Escape data
  234. *
  235. * @var array
  236. */
  237. protected $qb_cache_no_escape = array();
  238. // --------------------------------------------------------------------
  239. /**
  240. * Select
  241. *
  242. * Generates the SELECT portion of the query
  243. *
  244. * @param string
  245. * @param mixed
  246. * @return CI_DB_query_builder
  247. */
  248. public function select($select = '*', $escape = NULL)
  249. {
  250. if (is_string($select))
  251. {
  252. $select = explode(',', $select);
  253. }
  254. // If the escape value was not set, we will base it on the global setting
  255. is_bool($escape) OR $escape = $this->_protect_identifiers;
  256. foreach ($select as $val)
  257. {
  258. $val = trim($val);
  259. if ($val !== '')
  260. {
  261. $this->qb_select[] = $val;
  262. $this->qb_no_escape[] = $escape;
  263. if ($this->qb_caching === TRUE)
  264. {
  265. $this->qb_cache_select[] = $val;
  266. $this->qb_cache_exists[] = 'select';
  267. $this->qb_cache_no_escape[] = $escape;
  268. }
  269. }
  270. }
  271. return $this;
  272. }
  273. // --------------------------------------------------------------------
  274. /**
  275. * Select Max
  276. *
  277. * Generates a SELECT MAX(field) portion of a query
  278. *
  279. * @param string the field
  280. * @param string an alias
  281. * @return CI_DB_query_builder
  282. */
  283. public function select_max($select = '', $alias = '')
  284. {
  285. return $this->_max_min_avg_sum($select, $alias, 'MAX');
  286. }
  287. // --------------------------------------------------------------------
  288. /**
  289. * Select Min
  290. *
  291. * Generates a SELECT MIN(field) portion of a query
  292. *
  293. * @param string the field
  294. * @param string an alias
  295. * @return CI_DB_query_builder
  296. */
  297. public function select_min($select = '', $alias = '')
  298. {
  299. return $this->_max_min_avg_sum($select, $alias, 'MIN');
  300. }
  301. // --------------------------------------------------------------------
  302. /**
  303. * Select Average
  304. *
  305. * Generates a SELECT AVG(field) portion of a query
  306. *
  307. * @param string the field
  308. * @param string an alias
  309. * @return CI_DB_query_builder
  310. */
  311. public function select_avg($select = '', $alias = '')
  312. {
  313. return $this->_max_min_avg_sum($select, $alias, 'AVG');
  314. }
  315. // --------------------------------------------------------------------
  316. /**
  317. * Select Sum
  318. *
  319. * Generates a SELECT SUM(field) portion of a query
  320. *
  321. * @param string the field
  322. * @param string an alias
  323. * @return CI_DB_query_builder
  324. */
  325. public function select_sum($select = '', $alias = '')
  326. {
  327. return $this->_max_min_avg_sum($select, $alias, 'SUM');
  328. }
  329. // --------------------------------------------------------------------
  330. /**
  331. * SELECT [MAX|MIN|AVG|SUM]()
  332. *
  333. * @used-by select_max()
  334. * @used-by select_min()
  335. * @used-by select_avg()
  336. * @used-by select_sum()
  337. *
  338. * @param string $select Field name
  339. * @param string $alias
  340. * @param string $type
  341. * @return CI_DB_query_builder
  342. */
  343. protected function _max_min_avg_sum($select = '', $alias = '', $type = 'MAX')
  344. {
  345. if ( ! is_string($select) OR $select === '')
  346. {
  347. $this->display_error('db_invalid_query');
  348. }
  349. $type = strtoupper($type);
  350. if ( ! in_array($type, array('MAX', 'MIN', 'AVG', 'SUM')))
  351. {
  352. show_error('Invalid function type: '.$type);
  353. }
  354. if ($alias === '')
  355. {
  356. $alias = $this->_create_alias_from_table(trim($select));
  357. }
  358. $sql = $type.'('.$this->protect_identifiers(trim($select)).') AS '.$this->escape_identifiers(trim($alias));
  359. $this->qb_select[] = $sql;
  360. $this->qb_no_escape[] = NULL;
  361. if ($this->qb_caching === TRUE)
  362. {
  363. $this->qb_cache_select[] = $sql;
  364. $this->qb_cache_exists[] = 'select';
  365. }
  366. return $this;
  367. }
  368. // --------------------------------------------------------------------
  369. /**
  370. * Determines the alias name based on the table
  371. *
  372. * @param string $item
  373. * @return string
  374. */
  375. protected function _create_alias_from_table($item)
  376. {
  377. if (strpos($item, '.') !== FALSE)
  378. {
  379. $item = explode('.', $item);
  380. return end($item);
  381. }
  382. return $item;
  383. }
  384. // --------------------------------------------------------------------
  385. /**
  386. * DISTINCT
  387. *
  388. * Sets a flag which tells the query string compiler to add DISTINCT
  389. *
  390. * @param bool $val
  391. * @return CI_DB_query_builder
  392. */
  393. public function distinct($val = TRUE)
  394. {
  395. $this->qb_distinct = is_bool($val) ? $val : TRUE;
  396. return $this;
  397. }
  398. // --------------------------------------------------------------------
  399. /**
  400. * From
  401. *
  402. * Generates the FROM portion of the query
  403. *
  404. * @param mixed $from can be a string or array
  405. * @return CI_DB_query_builder
  406. */
  407. public function from($from)
  408. {
  409. foreach ((array) $from as $val)
  410. {
  411. if (strpos($val, ',') !== FALSE)
  412. {
  413. foreach (explode(',', $val) as $v)
  414. {
  415. $v = trim($v);
  416. $this->_track_aliases($v);
  417. $this->qb_from[] = $v = $this->protect_identifiers($v, TRUE, NULL, FALSE);
  418. if ($this->qb_caching === TRUE)
  419. {
  420. $this->qb_cache_from[] = $v;
  421. $this->qb_cache_exists[] = 'from';
  422. }
  423. }
  424. }
  425. else
  426. {
  427. $val = trim($val);
  428. // Extract any aliases that might exist. We use this information
  429. // in the protect_identifiers to know whether to add a table prefix
  430. $this->_track_aliases($val);
  431. $this->qb_from[] = $val = $this->protect_identifiers($val, TRUE, NULL, FALSE);
  432. if ($this->qb_caching === TRUE)
  433. {
  434. $this->qb_cache_from[] = $val;
  435. $this->qb_cache_exists[] = 'from';
  436. }
  437. }
  438. }
  439. return $this;
  440. }
  441. // --------------------------------------------------------------------
  442. /**
  443. * JOIN
  444. *
  445. * Generates the JOIN portion of the query
  446. *
  447. * @param string
  448. * @param string the join condition
  449. * @param string the type of join
  450. * @param string whether not to try to escape identifiers
  451. * @return CI_DB_query_builder
  452. */
  453. public function join($table, $cond, $type = '', $escape = NULL)
  454. {
  455. if ($type !== '')
  456. {
  457. $type = strtoupper(trim($type));
  458. if ( ! in_array($type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER'), TRUE))
  459. {
  460. $type = '';
  461. }
  462. else
  463. {
  464. $type .= ' ';
  465. }
  466. }
  467. // Extract any aliases that might exist. We use this information
  468. // in the protect_identifiers to know whether to add a table prefix
  469. $this->_track_aliases($table);
  470. is_bool($escape) OR $escape = $this->_protect_identifiers;
  471. if ( ! $this->_has_operator($cond))
  472. {
  473. $cond = ' USING ('.($escape ? $this->escape_identifiers($cond) : $cond).')';
  474. }
  475. elseif ($escape === FALSE)
  476. {
  477. $cond = ' ON '.$cond;
  478. }
  479. else
  480. {
  481. // Split multiple conditions
  482. if (preg_match_all('/\sAND\s|\sOR\s/i', $cond, $joints, PREG_OFFSET_CAPTURE))
  483. {
  484. $conditions = array();
  485. $joints = $joints[0];
  486. array_unshift($joints, array('', 0));
  487. for ($i = count($joints) - 1, $pos = strlen($cond); $i >= 0; $i--)
  488. {
  489. $joints[$i][1] += strlen($joints[$i][0]); // offset
  490. $conditions[$i] = substr($cond, $joints[$i][1], $pos - $joints[$i][1]);
  491. $pos = $joints[$i][1] - strlen($joints[$i][0]);
  492. $joints[$i] = $joints[$i][0];
  493. }
  494. }
  495. else
  496. {
  497. $conditions = array($cond);
  498. $joints = array('');
  499. }
  500. $cond = ' ON ';
  501. for ($i = 0, $c = count($conditions); $i < $c; $i++)
  502. {
  503. $operator = $this->_get_operator($conditions[$i]);
  504. $cond .= $joints[$i];
  505. $cond .= preg_match("/(\(*)?([\[\]\w\.'-]+)".preg_quote($operator)."(.*)/i", $conditions[$i], $match)
  506. ? $match[1].$this->protect_identifiers($match[2]).$operator.$this->protect_identifiers($match[3])
  507. : $conditions[$i];
  508. }
  509. }
  510. // Do we want to escape the table name?
  511. if ($escape === TRUE)
  512. {
  513. $table = $this->protect_identifiers($table, TRUE, NULL, FALSE);
  514. }
  515. // Assemble the JOIN statement
  516. $this->qb_join[] = $join = $type.'JOIN '.$table.$cond;
  517. if ($this->qb_caching === TRUE)
  518. {
  519. $this->qb_cache_join[] = $join;
  520. $this->qb_cache_exists[] = 'join';
  521. }
  522. return $this;
  523. }
  524. // --------------------------------------------------------------------
  525. /**
  526. * WHERE
  527. *
  528. * Generates the WHERE portion of the query.
  529. * Separates multiple calls with 'AND'.
  530. *
  531. * @param mixed
  532. * @param mixed
  533. * @param bool
  534. * @return CI_DB_query_builder
  535. */
  536. public function where($key, $value = NULL, $escape = NULL)
  537. {
  538. return $this->_wh('qb_where', $key, $value, 'AND ', $escape);
  539. }
  540. // --------------------------------------------------------------------
  541. /**
  542. * OR WHERE
  543. *
  544. * Generates the WHERE portion of the query.
  545. * Separates multiple calls with 'OR'.
  546. *
  547. * @param mixed
  548. * @param mixed
  549. * @param bool
  550. * @return CI_DB_query_builder
  551. */
  552. public function or_where($key, $value = NULL, $escape = NULL)
  553. {
  554. return $this->_wh('qb_where', $key, $value, 'OR ', $escape);
  555. }
  556. // --------------------------------------------------------------------
  557. /**
  558. * WHERE, HAVING
  559. *
  560. * @used-by where()
  561. * @used-by or_where()
  562. * @used-by having()
  563. * @used-by or_having()
  564. *
  565. * @param string $qb_key 'qb_where' or 'qb_having'
  566. * @param mixed $key
  567. * @param mixed $value
  568. * @param string $type
  569. * @param bool $escape
  570. * @return CI_DB_query_builder
  571. */
  572. protected function _wh($qb_key, $key, $value = NULL, $type = 'AND ', $escape = NULL)
  573. {
  574. $qb_cache_key = ($qb_key === 'qb_having') ? 'qb_cache_having' : 'qb_cache_where';
  575. if ( ! is_array($key))
  576. {
  577. $key = array($key => $value);
  578. }
  579. // If the escape value was not set will base it on the global setting
  580. is_bool($escape) OR $escape = $this->_protect_identifiers;
  581. foreach ($key as $k => $v)
  582. {
  583. $prefix = (count($this->$qb_key) === 0 && count($this->$qb_cache_key) === 0)
  584. ? $this->_group_get_type('')
  585. : $this->_group_get_type($type);
  586. if ($v !== NULL)
  587. {
  588. if ($escape === TRUE)
  589. {
  590. $v = $this->escape($v);
  591. }
  592. if ( ! $this->_has_operator($k))
  593. {
  594. $k .= ' = ';
  595. }
  596. }
  597. elseif ( ! $this->_has_operator($k))
  598. {
  599. // value appears not to have been set, assign the test to IS NULL
  600. $k .= ' IS NULL';
  601. }
  602. elseif (preg_match('/\s*(!?=|<>|\sIS(?:\s+NOT)?\s)\s*$/i', $k, $match, PREG_OFFSET_CAPTURE))
  603. {
  604. $k = substr($k, 0, $match[0][1]).($match[1][0] === '=' ? ' IS NULL' : ' IS NOT NULL');
  605. }
  606. ${$qb_key} = array('condition' => $prefix.$k, 'value' => $v, 'escape' => $escape);
  607. $this->{$qb_key}[] = ${$qb_key};
  608. if ($this->qb_caching === TRUE)
  609. {
  610. $this->{$qb_cache_key}[] = ${$qb_key};
  611. $this->qb_cache_exists[] = substr($qb_key, 3);
  612. }
  613. }
  614. return $this;
  615. }
  616. // --------------------------------------------------------------------
  617. /**
  618. * WHERE IN
  619. *
  620. * Generates a WHERE field IN('item', 'item') SQL query,
  621. * joined with 'AND' if appropriate.
  622. *
  623. * @param string $key The field to search
  624. * @param array $values The values searched on
  625. * @param bool $escape
  626. * @return CI_DB_query_builder
  627. */
  628. public function where_in($key = NULL, $values = NULL, $escape = NULL)
  629. {
  630. return $this->_where_in($key, $values, FALSE, 'AND ', $escape);
  631. }
  632. // --------------------------------------------------------------------
  633. /**
  634. * OR WHERE IN
  635. *
  636. * Generates a WHERE field IN('item', 'item') SQL query,
  637. * joined with 'OR' if appropriate.
  638. *
  639. * @param string $key The field to search
  640. * @param array $values The values searched on
  641. * @param bool $escape
  642. * @return CI_DB_query_builder
  643. */
  644. public function or_where_in($key = NULL, $values = NULL, $escape = NULL)
  645. {
  646. return $this->_where_in($key, $values, FALSE, 'OR ', $escape);
  647. }
  648. // --------------------------------------------------------------------
  649. /**
  650. * WHERE NOT IN
  651. *
  652. * Generates a WHERE field NOT IN('item', 'item') SQL query,
  653. * joined with 'AND' if appropriate.
  654. *
  655. * @param string $key The field to search
  656. * @param array $values The values searched on
  657. * @param bool $escape
  658. * @return CI_DB_query_builder
  659. */
  660. public function where_not_in($key = NULL, $values = NULL, $escape = NULL)
  661. {
  662. return $this->_where_in($key, $values, TRUE, 'AND ', $escape);
  663. }
  664. // --------------------------------------------------------------------
  665. /**
  666. * OR WHERE NOT IN
  667. *
  668. * Generates a WHERE field NOT IN('item', 'item') SQL query,
  669. * joined with 'OR' if appropriate.
  670. *
  671. * @param string $key The field to search
  672. * @param array $values The values searched on
  673. * @param bool $escape
  674. * @return CI_DB_query_builder
  675. */
  676. public function or_where_not_in($key = NULL, $values = NULL, $escape = NULL)
  677. {
  678. return $this->_where_in($key, $values, TRUE, 'OR ', $escape);
  679. }
  680. // --------------------------------------------------------------------
  681. /**
  682. * Internal WHERE IN
  683. *
  684. * @used-by where_in()
  685. * @used-by or_where_in()
  686. * @used-by where_not_in()
  687. * @used-by or_where_not_in()
  688. *
  689. * @param string $key The field to search
  690. * @param array $values The values searched on
  691. * @param bool $not If the statement would be IN or NOT IN
  692. * @param string $type
  693. * @param bool $escape
  694. * @return CI_DB_query_builder
  695. */
  696. protected function _where_in($key = NULL, $values = NULL, $not = FALSE, $type = 'AND ', $escape = NULL)
  697. {
  698. if ($key === NULL OR $values === NULL)
  699. {
  700. return $this;
  701. }
  702. if ( ! is_array($values))
  703. {
  704. $values = array($values);
  705. }
  706. is_bool($escape) OR $escape = $this->_protect_identifiers;
  707. $not = ($not) ? ' NOT' : '';
  708. if ($escape === TRUE)
  709. {
  710. $where_in = array();
  711. foreach ($values as $value)
  712. {
  713. $where_in[] = $this->escape($value);
  714. }
  715. }
  716. else
  717. {
  718. $where_in = array_values($values);
  719. }
  720. $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0)
  721. ? $this->_group_get_type('')
  722. : $this->_group_get_type($type);
  723. $where_in = array(
  724. 'condition' => $prefix.$key.$not.' IN('.implode(', ', $where_in).')',
  725. 'value' => NULL,
  726. 'escape' => $escape
  727. );
  728. $this->qb_where[] = $where_in;
  729. if ($this->qb_caching === TRUE)
  730. {
  731. $this->qb_cache_where[] = $where_in;
  732. $this->qb_cache_exists[] = 'where';
  733. }
  734. return $this;
  735. }
  736. // --------------------------------------------------------------------
  737. /**
  738. * LIKE
  739. *
  740. * Generates a %LIKE% portion of the query.
  741. * Separates multiple calls with 'AND'.
  742. *
  743. * @param mixed $field
  744. * @param string $match
  745. * @param string $side
  746. * @param bool $escape
  747. * @return CI_DB_query_builder
  748. */
  749. public function like($field, $match = '', $side = 'both', $escape = NULL)
  750. {
  751. return $this->_like($field, $match, 'AND ', $side, '', $escape);
  752. }
  753. // --------------------------------------------------------------------
  754. /**
  755. * NOT LIKE
  756. *
  757. * Generates a NOT LIKE portion of the query.
  758. * Separates multiple calls with 'AND'.
  759. *
  760. * @param mixed $field
  761. * @param string $match
  762. * @param string $side
  763. * @param bool $escape
  764. * @return CI_DB_query_builder
  765. */
  766. public function not_like($field, $match = '', $side = 'both', $escape = NULL)
  767. {
  768. return $this->_like($field, $match, 'AND ', $side, 'NOT', $escape);
  769. }
  770. // --------------------------------------------------------------------
  771. /**
  772. * OR LIKE
  773. *
  774. * Generates a %LIKE% portion of the query.
  775. * Separates multiple calls with 'OR'.
  776. *
  777. * @param mixed $field
  778. * @param string $match
  779. * @param string $side
  780. * @param bool $escape
  781. * @return CI_DB_query_builder
  782. */
  783. public function or_like($field, $match = '', $side = 'both', $escape = NULL)
  784. {
  785. return $this->_like($field, $match, 'OR ', $side, '', $escape);
  786. }
  787. // --------------------------------------------------------------------
  788. /**
  789. * OR NOT LIKE
  790. *
  791. * Generates a NOT LIKE portion of the query.
  792. * Separates multiple calls with 'OR'.
  793. *
  794. * @param mixed $field
  795. * @param string $match
  796. * @param string $side
  797. * @param bool $escape
  798. * @return CI_DB_query_builder
  799. */
  800. public function or_not_like($field, $match = '', $side = 'both', $escape = NULL)
  801. {
  802. return $this->_like($field, $match, 'OR ', $side, 'NOT', $escape);
  803. }
  804. // --------------------------------------------------------------------
  805. /**
  806. * Internal LIKE
  807. *
  808. * @used-by like()
  809. * @used-by or_like()
  810. * @used-by not_like()
  811. * @used-by or_not_like()
  812. *
  813. * @param mixed $field
  814. * @param string $match
  815. * @param string $type
  816. * @param string $side
  817. * @param string $not
  818. * @param bool $escape
  819. * @return CI_DB_query_builder
  820. */
  821. protected function _like($field, $match = '', $type = 'AND ', $side = 'both', $not = '', $escape = NULL)
  822. {
  823. if ( ! is_array($field))
  824. {
  825. $field = array($field => $match);
  826. }
  827. is_bool($escape) OR $escape = $this->_protect_identifiers;
  828. // lowercase $side in case somebody writes e.g. 'BEFORE' instead of 'before' (doh)
  829. $side = strtolower($side);
  830. foreach ($field as $k => $v)
  831. {
  832. $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0)
  833. ? $this->_group_get_type('') : $this->_group_get_type($type);
  834. if ($escape === TRUE)
  835. {
  836. $v = $this->escape_like_str($v);
  837. }
  838. switch ($side)
  839. {
  840. case 'none':
  841. $v = "'{$v}'";
  842. break;
  843. case 'before':
  844. $v = "'%{$v}'";
  845. break;
  846. case 'after':
  847. $v = "'{$v}%'";
  848. break;
  849. case 'both':
  850. default:
  851. $v = "'%{$v}%'";
  852. break;
  853. }
  854. // some platforms require an escape sequence definition for LIKE wildcards
  855. if ($escape === TRUE && $this->_like_escape_str !== '')
  856. {
  857. $v .= sprintf($this->_like_escape_str, $this->_like_escape_chr);
  858. }
  859. $qb_where = array('condition' => "{$prefix} {$k} {$not} LIKE {$v}", 'value' => NULL, 'escape' => $escape);
  860. $this->qb_where[] = $qb_where;
  861. if ($this->qb_caching === TRUE)
  862. {
  863. $this->qb_cache_where[] = $qb_where;
  864. $this->qb_cache_exists[] = 'where';
  865. }
  866. }
  867. return $this;
  868. }
  869. // --------------------------------------------------------------------
  870. /**
  871. * Starts a query group.
  872. *
  873. * @param string $not (Internal use only)
  874. * @param string $type (Internal use only)
  875. * @return CI_DB_query_builder
  876. */
  877. public function group_start($not = '', $type = 'AND ')
  878. {
  879. $type = $this->_group_get_type($type);
  880. $this->qb_where_group_started = TRUE;
  881. $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0) ? '' : $type;
  882. $where = array(
  883. 'condition' => $prefix.$not.str_repeat(' ', ++$this->qb_where_group_count).' (',
  884. 'value' => NULL,
  885. 'escape' => FALSE
  886. );
  887. $this->qb_where[] = $where;
  888. if ($this->qb_caching)
  889. {
  890. $this->qb_cache_where[] = $where;
  891. }
  892. return $this;
  893. }
  894. // --------------------------------------------------------------------
  895. /**
  896. * Starts a query group, but ORs the group
  897. *
  898. * @return CI_DB_query_builder
  899. */
  900. public function or_group_start()
  901. {
  902. return $this->group_start('', 'OR ');
  903. }
  904. // --------------------------------------------------------------------
  905. /**
  906. * Starts a query group, but NOTs the group
  907. *
  908. * @return CI_DB_query_builder
  909. */
  910. public function not_group_start()
  911. {
  912. return $this->group_start('NOT ', 'AND ');
  913. }
  914. // --------------------------------------------------------------------
  915. /**
  916. * Starts a query group, but OR NOTs the group
  917. *
  918. * @return CI_DB_query_builder
  919. */
  920. public function or_not_group_start()
  921. {
  922. return $this->group_start('NOT ', 'OR ');
  923. }
  924. // --------------------------------------------------------------------
  925. /**
  926. * Ends a query group
  927. *
  928. * @return CI_DB_query_builder
  929. */
  930. public function group_end()
  931. {
  932. $this->qb_where_group_started = FALSE;
  933. $where = array(
  934. 'condition' => str_repeat(' ', $this->qb_where_group_count--).')',
  935. 'value' => NULL,
  936. 'escape' => FALSE
  937. );
  938. $this->qb_where[] = $where;
  939. if ($this->qb_caching)
  940. {
  941. $this->qb_cache_where[] = $where;
  942. }
  943. return $this;
  944. }
  945. // --------------------------------------------------------------------
  946. /**
  947. * Group_get_type
  948. *
  949. * @used-by group_start()
  950. * @used-by _like()
  951. * @used-by _wh()
  952. * @used-by _where_in()
  953. *
  954. * @param string $type
  955. * @return string
  956. */
  957. protected function _group_get_type($type)
  958. {
  959. if ($this->qb_where_group_started)
  960. {
  961. $type = '';
  962. $this->qb_where_group_started = FALSE;
  963. }
  964. return $type;
  965. }
  966. // --------------------------------------------------------------------
  967. /**
  968. * GROUP BY
  969. *
  970. * @param string $by
  971. * @param bool $escape
  972. * @return CI_DB_query_builder
  973. */
  974. public function group_by($by, $escape = NULL)
  975. {
  976. is_bool($escape) OR $escape = $this->_protect_identifiers;
  977. if (is_string($by))
  978. {
  979. $by = ($escape === TRUE)
  980. ? explode(',', $by)
  981. : array($by);
  982. }
  983. foreach ($by as $val)
  984. {
  985. $val = trim($val);
  986. if ($val !== '')
  987. {
  988. $val = array('field' => $val, 'escape' => $escape);
  989. $this->qb_groupby[] = $val;
  990. if ($this->qb_caching === TRUE)
  991. {
  992. $this->qb_cache_groupby[] = $val;
  993. $this->qb_cache_exists[] = 'groupby';
  994. }
  995. }
  996. }
  997. return $this;
  998. }
  999. // --------------------------------------------------------------------
  1000. /**
  1001. * HAVING
  1002. *
  1003. * Separates multiple calls with 'AND'.
  1004. *
  1005. * @param string $key
  1006. * @param string $value
  1007. * @param bool $escape
  1008. * @return CI_DB_query_builder
  1009. */
  1010. public function having($key, $value = NULL, $escape = NULL)
  1011. {
  1012. return $this->_wh('qb_having', $key, $value, 'AND ', $escape);
  1013. }
  1014. // --------------------------------------------------------------------
  1015. /**
  1016. * OR HAVING
  1017. *
  1018. * Separates multiple calls with 'OR'.
  1019. *
  1020. * @param string $key
  1021. * @param string $value
  1022. * @param bool $escape
  1023. * @return CI_DB_query_builder
  1024. */
  1025. public function or_having($key, $value = NULL, $escape = NULL)
  1026. {
  1027. return $this->_wh('qb_having', $key, $value, 'OR ', $escape);
  1028. }
  1029. // --------------------------------------------------------------------
  1030. /**
  1031. * ORDER BY
  1032. *
  1033. * @param string $orderby
  1034. * @param string $direction ASC, DESC or RANDOM
  1035. * @param bool $escape
  1036. * @return CI_DB_query_builder
  1037. */
  1038. public function order_by($orderby, $direction = '', $escape = NULL)
  1039. {
  1040. $direction = strtoupper(trim($direction));
  1041. if ($direction === 'RANDOM')
  1042. {
  1043. $direction = '';
  1044. // Do we have a seed value?
  1045. $orderby = ctype_digit((string) $orderby)
  1046. ? sprintf($this->_random_keyword[1], $orderby)
  1047. : $this->_random_keyword[0];
  1048. }
  1049. elseif (empty($orderby))
  1050. {
  1051. return $this;
  1052. }
  1053. elseif ($direction !== '')
  1054. {
  1055. $direction = in_array($direction, array('ASC', 'DESC'), TRUE) ? ' '.$direction : '';
  1056. }
  1057. is_bool($escape) OR $escape = $this->_protect_identifiers;
  1058. if ($escape === FALSE)
  1059. {
  1060. $qb_orderby[] = array('field' => $orderby, 'direction' => $direction, 'escape' => FALSE);
  1061. }
  1062. else
  1063. {
  1064. $qb_orderby = array();
  1065. foreach (explode(',', $orderby) as $field)
  1066. {
  1067. $qb_orderby[] = ($direction === '' && preg_match('/\s+(ASC|DESC)$/i', rtrim($field), $match, PREG_OFFSET_CAPTURE))
  1068. ? array('field' => ltrim(substr($field, 0, $match[0][1])), 'direction' => ' '.$match[1][0], 'escape' => TRUE)
  1069. : array('field' => trim($field), 'direction' => $direction, 'escape' => TRUE);
  1070. }
  1071. }
  1072. $this->qb_orderby = array_merge($this->qb_orderby, $qb_orderby);
  1073. if ($this->qb_caching === TRUE)
  1074. {
  1075. $this->qb_cache_orderby = array_merge($this->qb_cache_orderby, $qb_orderby);
  1076. $this->qb_cache_exists[] = 'orderby';
  1077. }
  1078. return $this;
  1079. }
  1080. // --------------------------------------------------------------------
  1081. /**
  1082. * LIMIT
  1083. *
  1084. * @param int $value LIMIT value
  1085. * @param int $offset OFFSET value
  1086. * @return CI_DB_query_builder
  1087. */
  1088. public function limit($value, $offset = 0)
  1089. {
  1090. is_null($value) OR $this->qb_limit = (int) $value;
  1091. empty($offset) OR $this->qb_offset = (int) $offset;
  1092. return $this;
  1093. }
  1094. // --------------------------------------------------------------------
  1095. /**
  1096. * Sets the OFFSET value
  1097. *
  1098. * @param int $offset OFFSET value
  1099. * @return CI_DB_query_builder
  1100. */
  1101. public function offset($offset)
  1102. {
  1103. empty($offset) OR $this->qb_offset = (int) $offset;
  1104. return $this;
  1105. }
  1106. // --------------------------------------------------------------------
  1107. /**
  1108. * LIMIT string
  1109. *
  1110. * Generates a platform-specific LIMIT clause.
  1111. *
  1112. * @param string $sql SQL Query
  1113. * @return string
  1114. */
  1115. protected function _limit($sql)
  1116. {
  1117. return $sql.' LIMIT '.($this->qb_offset ? $this->qb_offset.', ' : '').(int) $this->qb_limit;
  1118. }
  1119. // --------------------------------------------------------------------
  1120. /**
  1121. * The "set" function.
  1122. *
  1123. * Allows key/value pairs to be set for inserting or updating
  1124. *
  1125. * @param mixed
  1126. * @param string
  1127. * @param bool
  1128. * @return CI_DB_query_builder
  1129. */
  1130. public function set($key, $value = '', $escape = NULL)
  1131. {
  1132. $key = $this->_object_to_array($key);
  1133. if ( ! is_array($key))
  1134. {
  1135. $key = array($key => $value);
  1136. }
  1137. is_bool($escape) OR $escape = $this->_protect_identifiers;
  1138. foreach ($key as $k => $v)
  1139. {
  1140. $this->qb_set[$this->protect_identifiers($k, FALSE, $escape)] = ($escape)
  1141. ? $this->escape($v) : $v;
  1142. }
  1143. return $this;
  1144. }
  1145. // --------------------------------------------------------------------
  1146. /**
  1147. * Get SELECT query string
  1148. *
  1149. * Compiles a SELECT query string and returns the sql.
  1150. *
  1151. * @param string the table name to select from (optional)
  1152. * @param bool TRUE: resets QB values; FALSE: leave QB values alone
  1153. * @return string
  1154. */
  1155. public function get_compiled_select($table = '', $reset = TRUE)
  1156. {
  1157. if ($table !== '')
  1158. {
  1159. $this->_track_aliases($table);
  1160. $this->from($table);
  1161. }
  1162. $select = $this->_compile_select();
  1163. if ($reset === TRUE)
  1164. {
  1165. $this->_reset_select();
  1166. }
  1167. return $select;
  1168. }
  1169. // --------------------------------------------------------------------
  1170. /**
  1171. * Get
  1172. *
  1173. * Compiles the select statement based on the other functions called
  1174. * and runs the query
  1175. *
  1176. * @param string the table
  1177. * @param string the limit clause
  1178. * @param string the offset clause
  1179. * @return CI_DB_result
  1180. */
  1181. public function get($table = '', $limit = NULL, $offset = NULL)
  1182. {
  1183. if ($table !== '')
  1184. {
  1185. $this->_track_aliases($table);
  1186. $this->from($table);
  1187. }
  1188. if ( ! empty($limit))
  1189. {
  1190. $this->limit($limit, $offset);
  1191. }
  1192. $result = $this->query($this->_compile_select());
  1193. $this->_reset_select();
  1194. return $result;
  1195. }
  1196. // --------------------------------------------------------------------
  1197. /**
  1198. * "Count All Results" query
  1199. *
  1200. * Generates a platform-specific query string that counts all records
  1201. * returned by an Query Builder query.
  1202. *
  1203. * @param string
  1204. * @param bool the reset clause
  1205. * @return int
  1206. */
  1207. public function count_all_results($table = '', $reset = TRUE)
  1208. {
  1209. if ($table !== '')
  1210. {
  1211. $this->_track_aliases($table);
  1212. $this->from($table);
  1213. }
  1214. // ORDER BY usage is often problematic here (most notably
  1215. // on Microsoft SQL Server) and ultimately unnecessary
  1216. // for selecting COUNT(*) ...
  1217. $qb_orderby = $this->qb_orderby;
  1218. $qb_cache_orderby = $this->qb_cache_orderby;
  1219. $this->qb_orderby = $this->qb_cache_orderby = array();
  1220. $result = ($this->qb_distinct === TRUE OR ! empty($this->qb_groupby) OR ! empty($this->qb_cache_groupby) OR $this->qb_limit OR $this->qb_offset)
  1221. ? $this->query($this->_count_string.$this->protect_identifiers('numrows')."\nFROM (\n".$this->_compile_select()."\n) CI_count_all_results")
  1222. : $this->query($this->_compile_select($this->_count_string.$this->protect_identifiers('numrows')));
  1223. if ($reset === TRUE)
  1224. {
  1225. $this->_reset_select();
  1226. }
  1227. else
  1228. {
  1229. $this->qb_orderby = $qb_orderby;
  1230. $this->qb_cache_orderby = $qb_cache_orderby;
  1231. }
  1232. if ($result->num_rows() === 0)
  1233. {
  1234. return 0;
  1235. }
  1236. $row = $result->row();
  1237. return (int) $row->numrows;
  1238. }
  1239. // --------------------------------------------------------------------
  1240. /**
  1241. * get_where()
  1242. *
  1243. * Allows the where clause, limit and offset to be added directly
  1244. *
  1245. * @param string $table
  1246. * @param string $where
  1247. * @param int $limit
  1248. * @param int $offset
  1249. * @return CI_DB_result
  1250. */
  1251. public function get_where($table = '', $where = NULL, $limit = NULL, $offset = NULL)
  1252. {
  1253. if ($table !== '')
  1254. {
  1255. $this->from($table);
  1256. }
  1257. if ($where !== NULL)
  1258. {
  1259. $this->where($where);
  1260. }
  1261. if ( ! empty($limit))
  1262. {
  1263. $this->limit($limit, $offset);
  1264. }
  1265. $result = $this->query($this->_compile_select());
  1266. $this->_reset_select();
  1267. return $result;
  1268. }
  1269. // --------------------------------------------------------------------
  1270. /**
  1271. * Insert_Batch
  1272. *
  1273. * Compiles batch insert strings and runs the queries
  1274. *
  1275. * @param string $table Table to insert into
  1276. * @param array $set An associative array of insert values
  1277. * @param bool $escape Whether to escape values and identifiers
  1278. * @return int Number of rows inserted or FALSE on failure
  1279. */
  1280. public function insert_batch($table, $set = NULL, $escape = NULL, $batch_size = 100)
  1281. {
  1282. if ($set === NULL)
  1283. {
  1284. if (empty($this->qb_set))
  1285. {
  1286. return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
  1287. }
  1288. }
  1289. else
  1290. {
  1291. if (empty($set))
  1292. {
  1293. return ($this->db_debug) ? $this->display_error('insert_batch() called with no data') : FALSE;
  1294. }
  1295. $this->set_insert_batch($set, '', $escape);
  1296. }
  1297. if (strlen($table) === 0)
  1298. {
  1299. if ( ! isset($this->qb_from[0]))
  1300. {
  1301. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1302. }
  1303. $table = $this->qb_from[0];
  1304. }
  1305. // Batch this baby
  1306. $affected_rows = 0;
  1307. for ($i = 0, $total = count($this->qb_set); $i < $total; $i += $batch_size)
  1308. {
  1309. if ($this->query($this->_insert_batch($this->protect_identifiers($table, TRUE, $escape, FALSE), $this->qb_keys, array_slice($this->qb_set, $i, $batch_size))))
  1310. {
  1311. $affected_rows += $this->affected_rows();
  1312. }
  1313. }
  1314. $this->_reset_write();
  1315. return $affected_rows;
  1316. }
  1317. // --------------------------------------------------------------------
  1318. /**
  1319. * Insert batch statement
  1320. *
  1321. * Generates a platform-specific insert string from the supplied data.
  1322. *
  1323. * @param string $table Table name
  1324. * @param array $keys INSERT keys
  1325. * @param array $values INSERT values
  1326. * @return string
  1327. */
  1328. protected function _insert_batch($table, $keys, $values)
  1329. {
  1330. return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES '.implode(', ', $values);
  1331. }
  1332. // --------------------------------------------------------------------
  1333. /**
  1334. * The "set_insert_batch" function. Allows key/value pairs to be set for batch inserts
  1335. *
  1336. * @param mixed
  1337. * @param string
  1338. * @param bool
  1339. * @return CI_DB_query_builder
  1340. */
  1341. public function set_insert_batch($key, $value = '', $escape = NULL)
  1342. {
  1343. $key = $this->_object_to_array_batch($key);
  1344. if ( ! is_array($key))
  1345. {
  1346. $key = array($key => $value);
  1347. }
  1348. is_bool($escape) OR $escape = $this->_protect_identifiers;
  1349. $keys = array_keys($this->_object_to_array(reset($key)));
  1350. sort($keys);
  1351. foreach ($key as $row)
  1352. {
  1353. $row = $this->_object_to_array($row);
  1354. if (count(array_diff($keys, array_keys($row))) > 0 OR count(array_diff(array_keys($row), $keys)) > 0)
  1355. {
  1356. // batch function above returns an error on an empty array
  1357. $this->qb_set[] = array();
  1358. return;
  1359. }
  1360. ksort($row); // puts $row in the same order as our keys
  1361. if ($escape !== FALSE)
  1362. {
  1363. $clean = array();
  1364. foreach ($row as $value)
  1365. {
  1366. $clean[] = $this->escape($value);
  1367. }
  1368. $row = $clean;
  1369. }
  1370. $this->qb_set[] = '('.implode(',', $row).')';
  1371. }
  1372. foreach ($keys as $k)
  1373. {
  1374. $this->qb_keys[] = $this->protect_identifiers($k, FALSE, $escape);
  1375. }
  1376. return $this;
  1377. }
  1378. // --------------------------------------------------------------------
  1379. /**
  1380. * Get INSERT query string
  1381. *
  1382. * Compiles an insert query and returns the sql
  1383. *
  1384. * @param string the table to insert into
  1385. * @param bool TRUE: reset QB values; FALSE: leave QB values alone
  1386. * @return string
  1387. */
  1388. public function get_compiled_insert($table = '', $reset = TRUE)
  1389. {
  1390. if ($this->_validate_insert($table) === FALSE)
  1391. {
  1392. return FALSE;
  1393. }
  1394. $sql = $this->_insert(
  1395. $this->protect_identifiers(
  1396. $this->qb_from[0], TRUE, NULL, FALSE
  1397. ),
  1398. array_keys($this->qb_set),
  1399. array_values($this->qb_set)
  1400. );
  1401. if ($reset === TRUE)
  1402. {
  1403. $this->_reset_write();
  1404. }
  1405. return $sql;
  1406. }
  1407. // --------------------------------------------------------------------
  1408. /**
  1409. * Insert
  1410. *
  1411. * Compiles an insert string and runs the query
  1412. *
  1413. * @param string the table to insert data into
  1414. * @param array an associative array of insert values
  1415. * @param bool $escape Whether to escape values and identifiers
  1416. * @return bool TRUE on success, FALSE on failure
  1417. */
  1418. public function insert($table = '', $set = NULL, $escape = NULL)
  1419. {
  1420. if ($set !== NULL)
  1421. {
  1422. $this->set($set, '', $escape);
  1423. }
  1424. if ($this->_validate_insert($table) === FALSE)
  1425. {
  1426. return FALSE;
  1427. }
  1428. $sql = $this->_insert(
  1429. $this->protect_identifiers(
  1430. $this->qb_from[0], TRUE, $escape, FALSE
  1431. ),
  1432. array_keys($this->qb_set),
  1433. array_values($this->qb_set)
  1434. );
  1435. $this->_reset_write();
  1436. return $this->query($sql);
  1437. }
  1438. // --------------------------------------------------------------------
  1439. /**
  1440. * Validate Insert
  1441. *
  1442. * This method is used by both insert() and get_compiled_insert() to
  1443. * validate that the there data is actually being set and that table
  1444. * has been chosen to be inserted into.
  1445. *
  1446. * @param string the table to insert data into
  1447. * @return string
  1448. */
  1449. protected function _validate_insert($table = '')
  1450. {
  1451. if (count($this->qb_set) === 0)
  1452. {
  1453. return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
  1454. }
  1455. if ($table !== '')
  1456. {
  1457. $this->qb_from[0] = $table;
  1458. }
  1459. elseif ( ! isset($this->qb_from[0]))
  1460. {
  1461. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1462. }
  1463. return TRUE;
  1464. }
  1465. // --------------------------------------------------------------------
  1466. /**
  1467. * Replace
  1468. *
  1469. * Compiles an replace into string and runs the query
  1470. *
  1471. * @param string the table to replace data into
  1472. * @param array an associative array of insert values
  1473. * @return bool TRUE on success, FALSE on failure
  1474. */
  1475. public function replace($table = '', $set = NULL)
  1476. {
  1477. if ($set !== NULL)
  1478. {
  1479. $this->set($set);
  1480. }
  1481. if (count($this->qb_set) === 0)
  1482. {
  1483. return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
  1484. }
  1485. if ($table === '')
  1486. {
  1487. if ( ! isset($this->qb_from[0]))
  1488. {
  1489. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1490. }
  1491. $table = $this->qb_from[0];
  1492. }
  1493. $sql = $this->_replace($this->protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->qb_set), array_values($this->qb_set));
  1494. $this->_reset_write();
  1495. return $this->query($sql);
  1496. }
  1497. // --------------------------------------------------------------------
  1498. /**
  1499. * Replace statement
  1500. *
  1501. * Generates a platform-specific replace string from the supplied data
  1502. *
  1503. * @param string the table name
  1504. * @param array the insert keys
  1505. * @param array the insert values
  1506. * @return string
  1507. */
  1508. protected function _replace($table, $keys, $values)
  1509. {
  1510. return 'REPLACE INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
  1511. }
  1512. // --------------------------------------------------------------------
  1513. /**
  1514. * FROM tables
  1515. *
  1516. * Groups tables in FROM clauses if needed, so there is no confusion
  1517. * about operator precedence.
  1518. *
  1519. * Note: This is only used (and overridden) by MySQL and CUBRID.
  1520. *
  1521. * @return string
  1522. */
  1523. protected function _from_tables()
  1524. {
  1525. return implode(', ', $this->qb_from);
  1526. }
  1527. // --------------------------------------------------------------------
  1528. /**
  1529. * Get UPDATE query string
  1530. *
  1531. * Compiles an update query and returns the sql
  1532. *
  1533. * @param string the table to update
  1534. * @param bool TRUE: reset QB values; FALSE: leave QB values alone
  1535. * @return string
  1536. */
  1537. public function get_compiled_update($table = '', $reset = TRUE)
  1538. {
  1539. // Combine any cached components with the current statements
  1540. $this->_merge_cache();
  1541. if ($this->_validate_update($table) === FALSE)
  1542. {
  1543. return FALSE;
  1544. }
  1545. $sql = $this->_update($this->qb_from[0], $this->qb_set);
  1546. if ($reset === TRUE)
  1547. {
  1548. $this->_reset_write();
  1549. }
  1550. return $sql;
  1551. }
  1552. // --------------------------------------------------------------------
  1553. /**
  1554. * UPDATE
  1555. *
  1556. * Compiles an update string and runs the query.
  1557. *
  1558. * @param string $table
  1559. * @param array $set An associative array of update values
  1560. * @param mixed $where
  1561. * @param int $limit
  1562. * @return bool TRUE on success, FALSE on failure
  1563. */
  1564. public function update($table = '', $set = NULL, $where = NULL, $limit = NULL)
  1565. {
  1566. // Combine any cached components with the current statements
  1567. $this->_merge_cache();
  1568. if ($set !== NULL)
  1569. {
  1570. $this->set($set);
  1571. }
  1572. if ($this->_validate_update($table) === FALSE)
  1573. {
  1574. return FALSE;
  1575. }
  1576. if ($where !== NULL)
  1577. {
  1578. $this->where($where);
  1579. }
  1580. if ( ! empty($limit))
  1581. {
  1582. $this->limit($limit);
  1583. }
  1584. $sql = $this->_update($this->qb_from[0], $this->qb_set);
  1585. $this->_reset_write();
  1586. return $this->query($sql);
  1587. }
  1588. // --------------------------------------------------------------------
  1589. /**
  1590. * Validate Update
  1591. *
  1592. * This method is used by both update() and get_compiled_update() to
  1593. * validate that data is actually being set and that a table has been
  1594. * chosen to be update.
  1595. *
  1596. * @param string the table to update data on
  1597. * @return bool
  1598. */
  1599. protected function _validate_update($table)
  1600. {
  1601. if (count($this->qb_set) === 0)
  1602. {
  1603. return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
  1604. }
  1605. if ($table !== '')
  1606. {
  1607. $this->qb_from = array($this->protect_identifiers($table, TRUE, NULL, FALSE));
  1608. }
  1609. elseif ( ! isset($this->qb_from[0]))
  1610. {
  1611. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1612. }
  1613. return TRUE;
  1614. }
  1615. // --------------------------------------------------------------------
  1616. /**
  1617. * Update_Batch
  1618. *
  1619. * Compiles an update string and runs the query
  1620. *
  1621. * @param string the table to retrieve the results from
  1622. * @param array an associative array of update values
  1623. * @param string the where key
  1624. * @return int number of rows affected or FALSE on failure
  1625. */
  1626. public function update_batch($table, $set = NULL, $index = NULL, $batch_size = 100)
  1627. {
  1628. // Combine any cached components with the current statements
  1629. $this->_merge_cache();
  1630. if ($index === NULL)
  1631. {
  1632. return ($this->db_debug) ? $this->display_error('db_must_use_index') : FALSE;
  1633. }
  1634. if ($set === NULL)
  1635. {
  1636. if (empty($this->qb_set_ub))
  1637. {
  1638. return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
  1639. }
  1640. }
  1641. else
  1642. {
  1643. if (empty($set))
  1644. {
  1645. return ($this->db_debug) ? $this->display_error('update_batch() called with no data') : FALSE;
  1646. }
  1647. $this->set_update_batch($set, $index);
  1648. }
  1649. if (strlen($table) === 0)
  1650. {
  1651. if ( ! isset($this->qb_from[0]))
  1652. {
  1653. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1654. }
  1655. $table = $this->qb_from[0];
  1656. }
  1657. // Batch this baby
  1658. $affected_rows = 0;
  1659. for ($i = 0, $total = count($this->qb_set_ub); $i < $total; $i += $batch_size)
  1660. {
  1661. if ($this->query($this->_update_batch($this->protect_identifiers($table, TRUE, NULL, FALSE), array_slice($this->qb_set_ub, $i, $batch_size), $index)))
  1662. {
  1663. $affected_rows += $this->affected_rows();
  1664. }
  1665. $this->qb_where = array();
  1666. }
  1667. $this->_reset_write();
  1668. return $affected_rows;
  1669. }
  1670. // --------------------------------------------------------------------
  1671. /**
  1672. * Update_Batch statement
  1673. *
  1674. * Generates a platform-specific batch update string from the supplied data
  1675. *
  1676. * @param string $table Table name
  1677. * @param array $values Update data
  1678. * @param string $index WHERE key
  1679. * @return string
  1680. */
  1681. protected function _update_batch($table, $values, $index)
  1682. {
  1683. $ids = array();
  1684. foreach ($values as $key => $val)
  1685. {
  1686. $ids[] = $val[$index]['value'];
  1687. foreach (array_keys($val) as $field)
  1688. {
  1689. if ($field !== $index)
  1690. {
  1691. $final[$val[$field]['field']][] = 'WHEN '.$val[$index]['field'].' = '.$val[$index]['value'].' THEN '.$val[$field]['value'];
  1692. }
  1693. }
  1694. }
  1695. $cases = '';
  1696. foreach ($final as $k => $v)
  1697. {
  1698. $cases .= $k." = CASE \n"
  1699. .implode("\n", $v)."\n"
  1700. .'ELSE '.$k.' END, ';
  1701. }
  1702. $this->where($val[$index]['field'].' IN('.implode(',', $ids).')', NULL, FALSE);
  1703. return 'UPDATE '.$table.' SET '.substr($cases, 0, -2).$this->_compile_wh('qb_where');
  1704. }
  1705. // --------------------------------------------------------------------
  1706. /**
  1707. * The "set_update_batch" function. Allows key/value pairs to be set for batch updating
  1708. *
  1709. * @param array
  1710. * @param string
  1711. * @param bool
  1712. * @return CI_DB_query_builder
  1713. */
  1714. public function set_update_batch($key, $index = '', $escape = NULL)
  1715. {
  1716. $key = $this->_object_to_array_batch($key);
  1717. if ( ! is_array($key))
  1718. {
  1719. // @todo error
  1720. }
  1721. is_bool($escape) OR $escape = $this->_protect_identifiers;
  1722. foreach ($key as $k => $v)
  1723. {
  1724. $index_set = FALSE;
  1725. $clean = array();
  1726. foreach ($v as $k2 => $v2)
  1727. {
  1728. if ($k2 === $index)
  1729. {
  1730. $index_set = TRUE;
  1731. }
  1732. $clean[$k2] = array(
  1733. 'field' => $this->protect_identifiers($k2, FALSE, $escape),
  1734. 'value' => ($escape === FALSE ? $v2 : $this->escape($v2))
  1735. );
  1736. }
  1737. if ($index_set === FALSE)
  1738. {
  1739. return $this->display_error('db_batch_missing_index');
  1740. }
  1741. $this->qb_set_ub[] = $clean;
  1742. }
  1743. return $this;
  1744. }
  1745. // --------------------------------------------------------------------
  1746. /**
  1747. * Empty Table
  1748. *
  1749. * Compiles a delete string and runs "DELETE FROM table"
  1750. *
  1751. * @param string the table to empty
  1752. * @return bool TRUE on success, FALSE on failure
  1753. */
  1754. public function empty_table($table = '')
  1755. {
  1756. if ($table === '')
  1757. {
  1758. if ( ! isset($this->qb_from[0]))
  1759. {
  1760. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1761. }
  1762. $table = $this->qb_from[0];
  1763. }
  1764. else
  1765. {
  1766. $table = $this->protect_identifiers($table, TRUE, NULL, FALSE);
  1767. }
  1768. $sql = $this->_delete($table);
  1769. $this->_reset_write();
  1770. return $this->query($sql);
  1771. }
  1772. // --------------------------------------------------------------------
  1773. /**
  1774. * Truncate
  1775. *
  1776. * Compiles a truncate string and runs the query
  1777. * If the database does not support the truncate() command
  1778. * This function maps to "DELETE FROM table"
  1779. *
  1780. * @param string the table to truncate
  1781. * @return bool TRUE on success, FALSE on failure
  1782. */
  1783. public function truncate($table = '')
  1784. {
  1785. if ($table === '')
  1786. {
  1787. if ( ! isset($this->qb_from[0]))
  1788. {
  1789. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1790. }
  1791. $table = $this->qb_from[0];
  1792. }
  1793. else
  1794. {
  1795. $table = $this->protect_identifiers($table, TRUE, NULL, FALSE);
  1796. }
  1797. $sql = $this->_truncate($table);
  1798. $this->_reset_write();
  1799. return $this->query($sql);
  1800. }
  1801. // --------------------------------------------------------------------
  1802. /**
  1803. * Truncate statement
  1804. *
  1805. * Generates a platform-specific truncate string from the supplied data
  1806. *
  1807. * If the database does not support the truncate() command,
  1808. * then this method maps to 'DELETE FROM table'
  1809. *
  1810. * @param string the table name
  1811. * @return string
  1812. */
  1813. protected function _truncate($table)
  1814. {
  1815. return 'TRUNCATE '.$table;
  1816. }
  1817. // --------------------------------------------------------------------
  1818. /**
  1819. * Get DELETE query string
  1820. *
  1821. * Compiles a delete query string and returns the sql
  1822. *
  1823. * @param string the table to delete from
  1824. * @param bool TRUE: reset QB values; FALSE: leave QB values alone
  1825. * @return string
  1826. */
  1827. public function get_compiled_delete($table = '', $reset = TRUE)
  1828. {
  1829. $this->return_delete_sql = TRUE;
  1830. $sql = $this->delete($table, '', NULL, $reset);
  1831. $this->return_delete_sql = FALSE;
  1832. return $sql;
  1833. }
  1834. // --------------------------------------------------------------------
  1835. /**
  1836. * Delete
  1837. *
  1838. * Compiles a delete string and runs the query
  1839. *
  1840. * @param mixed the table(s) to delete from. String or array
  1841. * @param mixed the where clause
  1842. * @param mixed the limit clause
  1843. * @param bool
  1844. * @return mixed
  1845. */
  1846. public function delete($table = '', $where = '', $limit = NULL, $reset_data = TRUE)
  1847. {
  1848. // Combine any cached components with the current statements
  1849. $this->_merge_cache();
  1850. if ($table === '')
  1851. {
  1852. if ( ! isset($this->qb_from[0]))
  1853. {
  1854. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1855. }
  1856. $table = $this->qb_from[0];
  1857. }
  1858. elseif (is_array($table))
  1859. {
  1860. empty($where) && $reset_data = FALSE;
  1861. foreach ($table as $single_table)
  1862. {
  1863. $this->delete($single_table, $where, $limit, $reset_data);
  1864. }
  1865. return;
  1866. }
  1867. else
  1868. {
  1869. $table = $this->protect_identifiers($table, TRUE, NULL, FALSE);
  1870. }
  1871. if ($where !== '')
  1872. {
  1873. $this->where($where);
  1874. }
  1875. if ( ! empty($limit))
  1876. {
  1877. $this->limit($limit);
  1878. }
  1879. if (count($this->qb_where) === 0)
  1880. {
  1881. return ($this->db_debug) ? $this->display_error('db_del_must_use_where') : FALSE;
  1882. }
  1883. $sql = $this->_delete($table);
  1884. if ($reset_data)
  1885. {
  1886. $this->_reset_write();
  1887. }
  1888. return ($this->return_delete_sql === TRUE) ? $sql : $this->query($sql);
  1889. }
  1890. // --------------------------------------------------------------------
  1891. /**
  1892. * Delete statement
  1893. *
  1894. * Generates a platform-specific delete string from the supplied data
  1895. *
  1896. * @param string the table name
  1897. * @return string
  1898. */
  1899. protected function _delete($table)
  1900. {
  1901. return 'DELETE FROM '.$table.$this->_compile_wh('qb_where')
  1902. .($this->qb_limit !== FALSE ? ' LIMIT '.$this->qb_limit : '');
  1903. }
  1904. // --------------------------------------------------------------------
  1905. /**
  1906. * DB Prefix
  1907. *
  1908. * Prepends a database prefix if one exists in configuration
  1909. *
  1910. * @param string the table
  1911. * @return string
  1912. */
  1913. public function dbprefix($table = '')
  1914. {
  1915. if ($table === '')
  1916. {
  1917. $this->display_error('db_table_name_required');
  1918. }
  1919. return $this->dbprefix.$table;
  1920. }
  1921. // --------------------------------------------------------------------
  1922. /**
  1923. * Set DB Prefix
  1924. *
  1925. * Set's the DB Prefix to something new without needing to reconnect
  1926. *
  1927. * @param string the prefix
  1928. * @return string
  1929. */
  1930. public function set_dbprefix($prefix = '')
  1931. {
  1932. return $this->dbprefix = $prefix;
  1933. }
  1934. // --------------------------------------------------------------------
  1935. /**
  1936. * Track Aliases
  1937. *
  1938. * Used to track SQL statements written with aliased tables.
  1939. *
  1940. * @param string The table to inspect
  1941. * @return string
  1942. */
  1943. protected function _track_aliases($table)
  1944. {
  1945. if (is_array($table))
  1946. {
  1947. foreach ($table as $t)
  1948. {
  1949. $this->_track_aliases($t);
  1950. }
  1951. return;
  1952. }
  1953. // Does the string contain a comma? If so, we need to separate
  1954. // the string into discreet statements
  1955. if (strpos($table, ',') !== FALSE)
  1956. {
  1957. return $this->_track_aliases(explode(',', $table));
  1958. }
  1959. // if a table alias is used we can recognize it by a space
  1960. if (strpos($table, ' ') !== FALSE)
  1961. {
  1962. // if the alias is written with the AS keyword, remove it
  1963. $table = preg_replace('/\s+AS\s+/i', ' ', $table);
  1964. // Grab the alias
  1965. $table = trim(strrchr($table, ' '));
  1966. // Store the alias, if it doesn't already exist
  1967. if ( ! in_array($table, $this->qb_aliased_tables, TRUE))
  1968. {
  1969. $this->qb_aliased_tables[] = $table;
  1970. if ($this->qb_caching === TRUE && ! in_array($table, $this->qb_cache_aliased_tables, TRUE))
  1971. {
  1972. $this->qb_cache_aliased_tables[] = $table;
  1973. $this->qb_cache_exists[] = 'aliased_tables';
  1974. }
  1975. }
  1976. }
  1977. }
  1978. // --------------------------------------------------------------------
  1979. /**
  1980. * Compile the SELECT statement
  1981. *
  1982. * Generates a query string based on which functions were used.
  1983. * Should not be called directly.
  1984. *
  1985. * @param bool $select_override
  1986. * @return string
  1987. */
  1988. protected function _compile_select($select_override = FALSE)
  1989. {
  1990. // Combine any cached components with the current statements
  1991. $this->_merge_cache();
  1992. // Write the "select" portion of the query
  1993. if ($select_override !== FALSE)
  1994. {
  1995. $sql = $select_override;
  1996. }
  1997. else
  1998. {
  1999. $sql = ( ! $this->qb_distinct) ? 'SELECT ' : 'SELECT DISTINCT ';
  2000. if (count($this->qb_select) === 0)
  2001. {
  2002. $sql .= '*';
  2003. }
  2004. else
  2005. {
  2006. // Cycle through the "select" portion of the query and prep each column name.
  2007. // The reason we protect identifiers here rather than in the select() function
  2008. // is because until the user calls the from() function we don't know if there are aliases
  2009. foreach ($this->qb_select as $key => $val)
  2010. {
  2011. $no_escape = isset($this->qb_no_escape[$key]) ? $this->qb_no_escape[$key] : NULL;
  2012. $this->qb_select[$key] = $this->protect_identifiers($val, FALSE, $no_escape);
  2013. }
  2014. $sql .= implode(', ', $this->qb_select);
  2015. }
  2016. }
  2017. // Write the "FROM" portion of the query
  2018. if (count($this->qb_from) > 0)
  2019. {
  2020. $sql .= "\nFROM ".$this->_from_tables();
  2021. }
  2022. // Write the "JOIN" portion of the query
  2023. if (count($this->qb_join) > 0)
  2024. {
  2025. $sql .= "\n".implode("\n", $this->qb_join);
  2026. }
  2027. $sql .= $this->_compile_wh('qb_where')
  2028. .$this->_compile_group_by()
  2029. .$this->_compile_wh('qb_having')
  2030. .$this->_compile_order_by(); // ORDER BY
  2031. // LIMIT
  2032. if ($this->qb_limit !== FALSE OR $this->qb_offset)
  2033. {
  2034. return $this->_limit($sql."\n");
  2035. }
  2036. return $sql;
  2037. }
  2038. // --------------------------------------------------------------------
  2039. /**
  2040. * Compile WHERE, HAVING statements
  2041. *
  2042. * Escapes identifiers in WHERE and HAVING statements at execution time.
  2043. *
  2044. * Required so that aliases are tracked properly, regardless of whether
  2045. * where(), or_where(), having(), or_having are called prior to from(),
  2046. * join() and dbprefix is added only if needed.
  2047. *
  2048. * @param string $qb_key 'qb_where' or 'qb_having'
  2049. * @return string SQL statement
  2050. */
  2051. protected function _compile_wh($qb_key)
  2052. {
  2053. if (count($this->$qb_key) > 0)
  2054. {
  2055. for ($i = 0, $c = count($this->$qb_key); $i < $c; $i++)
  2056. {
  2057. // Is this condition already compiled?
  2058. if (is_string($this->{$qb_key}[$i]))
  2059. {
  2060. continue;
  2061. }
  2062. elseif ($this->{$qb_key}[$i]['escape'] === FALSE)
  2063. {
  2064. $this->{$qb_key}[$i] = $this->{$qb_key}[$i]['condition'].(isset($this->{$qb_key}[$i]['value']) ? ' '.$this->{$qb_key}[$i]['value'] : '');
  2065. continue;
  2066. }
  2067. // Split multiple conditions
  2068. $conditions = preg_split(
  2069. '/((?:^|\s+)AND\s+|(?:^|\s+)OR\s+)/i',
  2070. $this->{$qb_key}[$i]['condition'],
  2071. -1,
  2072. PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
  2073. );
  2074. for ($ci = 0, $cc = count($conditions); $ci < $cc; $ci++)
  2075. {
  2076. if (($op = $this->_get_operator($conditions[$ci])) === FALSE
  2077. OR ! preg_match('/^(\(?)(.*)('.preg_quote($op, '/').')\s*(.*(?<!\)))?(\)?)$/i', $conditions[$ci], $matches))
  2078. {
  2079. continue;
  2080. }
  2081. // $matches = array(
  2082. // 0 => '(test <= foo)', /* the whole thing */
  2083. // 1 => '(', /* optional */
  2084. // 2 => 'test', /* the field name */
  2085. // 3 => ' <= ', /* $op */
  2086. // 4 => 'foo', /* optional, if $op is e.g. 'IS NULL' */
  2087. // 5 => ')' /* optional */
  2088. // );
  2089. if ( ! empty($matches[4]))
  2090. {
  2091. $this->_is_literal($matches[4]) OR $matches[4] = $this->protect_identifiers(trim($matches[4]));
  2092. $matches[4] = ' '.$matches[4];
  2093. }
  2094. $conditions[$ci] = $matches[1].$this->protect_identifiers(trim($matches[2]))
  2095. .' '.trim($matches[3]).$matches[4].$matches[5];
  2096. }
  2097. $this->{$qb_key}[$i] = implode('', $conditions).(isset($this->{$qb_key}[$i]['value']) ? ' '.$this->{$qb_key}[$i]['value'] : '');
  2098. }
  2099. return ($qb_key === 'qb_having' ? "\nHAVING " : "\nWHERE ")
  2100. .implode("\n", $this->$qb_key);
  2101. }
  2102. return '';
  2103. }
  2104. // --------------------------------------------------------------------
  2105. /**
  2106. * Compile GROUP BY
  2107. *
  2108. * Escapes identifiers in GROUP BY statements at execution time.
  2109. *
  2110. * Required so that aliases are tracked properly, regardless of whether
  2111. * group_by() is called prior to from(), join() and dbprefix is added
  2112. * only if needed.
  2113. *
  2114. * @return string SQL statement
  2115. */
  2116. protected function _compile_group_by()
  2117. {
  2118. if (count($this->qb_groupby) > 0)
  2119. {
  2120. for ($i = 0, $c = count($this->qb_groupby); $i < $c; $i++)
  2121. {
  2122. // Is it already compiled?
  2123. if (is_string($this->qb_groupby[$i]))
  2124. {
  2125. continue;
  2126. }
  2127. $this->qb_groupby[$i] = ($this->qb_groupby[$i]['escape'] === FALSE OR $this->_is_literal($this->qb_groupby[$i]['field']))
  2128. ? $this->qb_groupby[$i]['field']
  2129. : $this->protect_identifiers($this->qb_groupby[$i]['field']);
  2130. }
  2131. return "\nGROUP BY ".implode(', ', $this->qb_groupby);
  2132. }
  2133. return '';
  2134. }
  2135. // --------------------------------------------------------------------
  2136. /**
  2137. * Compile ORDER BY
  2138. *
  2139. * Escapes identifiers in ORDER BY statements at execution time.
  2140. *
  2141. * Required so that aliases are tracked properly, regardless of whether
  2142. * order_by() is called prior to from(), join() and dbprefix is added
  2143. * only if needed.
  2144. *
  2145. * @return string SQL statement
  2146. */
  2147. protected function _compile_order_by()
  2148. {
  2149. if (empty($this->qb_orderby))
  2150. {
  2151. return '';
  2152. }
  2153. for ($i = 0, $c = count($this->qb_orderby); $i < $c; $i++)
  2154. {
  2155. if (is_string($this->qb_orderby[$i]))
  2156. {
  2157. continue;
  2158. }
  2159. if ($this->qb_orderby[$i]['escape'] !== FALSE && ! $this->_is_literal($this->qb_orderby[$i]['field']))
  2160. {
  2161. $this->qb_orderby[$i]['field'] = $this->protect_identifiers($this->qb_orderby[$i]['field']);
  2162. }
  2163. $this->qb_orderby[$i] = $this->qb_orderby[$i]['field'].$this->qb_orderby[$i]['direction'];
  2164. }
  2165. return "\nORDER BY ".implode(', ', $this->qb_orderby);
  2166. }
  2167. // --------------------------------------------------------------------
  2168. /**
  2169. * Object to Array
  2170. *
  2171. * Takes an object as input and converts the class variables to array key/vals
  2172. *
  2173. * @param object
  2174. * @return array
  2175. */
  2176. protected function _object_to_array($object)
  2177. {
  2178. if ( ! is_object($object))
  2179. {
  2180. return $object;
  2181. }
  2182. $array = array();
  2183. foreach (get_object_vars($object) as $key => $val)
  2184. {
  2185. // There are some built in keys we need to ignore for this conversion
  2186. if ( ! is_object($val) && ! is_array($val) && $key !== '_parent_name')
  2187. {
  2188. $array[$key] = $val;
  2189. }
  2190. }
  2191. return $array;
  2192. }
  2193. // --------------------------------------------------------------------
  2194. /**
  2195. * Object to Array
  2196. *
  2197. * Takes an object as input and converts the class variables to array key/vals
  2198. *
  2199. * @param object
  2200. * @return array
  2201. */
  2202. protected function _object_to_array_batch($object)
  2203. {
  2204. if ( ! is_object($object))
  2205. {
  2206. return $object;
  2207. }
  2208. $array = array();
  2209. $out = get_object_vars($object);
  2210. $fields = array_keys($out);
  2211. foreach ($fields as $val)
  2212. {
  2213. // There are some built in keys we need to ignore for this conversion
  2214. if ($val !== '_parent_name')
  2215. {
  2216. $i = 0;
  2217. foreach ($out[$val] as $data)
  2218. {
  2219. $array[$i++][$val] = $data;
  2220. }
  2221. }
  2222. }
  2223. return $array;
  2224. }
  2225. // --------------------------------------------------------------------
  2226. /**
  2227. * Start Cache
  2228. *
  2229. * Starts QB caching
  2230. *
  2231. * @return CI_DB_query_builder
  2232. */
  2233. public function start_cache()
  2234. {
  2235. $this->qb_caching = TRUE;
  2236. return $this;
  2237. }
  2238. // --------------------------------------------------------------------
  2239. /**
  2240. * Stop Cache
  2241. *
  2242. * Stops QB caching
  2243. *
  2244. * @return CI_DB_query_builder
  2245. */
  2246. public function stop_cache()
  2247. {
  2248. $this->qb_caching = FALSE;
  2249. return $this;
  2250. }
  2251. // --------------------------------------------------------------------
  2252. /**
  2253. * Flush Cache
  2254. *
  2255. * Empties the QB cache
  2256. *
  2257. * @return CI_DB_query_builder
  2258. */
  2259. public function flush_cache()
  2260. {
  2261. $this->_reset_run(array(
  2262. 'qb_cache_select' => array(),
  2263. 'qb_cache_from' => array(),
  2264. 'qb_cache_join' => array(),
  2265. 'qb_cache_where' => array(),
  2266. 'qb_cache_groupby' => array(),
  2267. 'qb_cache_having' => array(),
  2268. 'qb_cache_orderby' => array(),
  2269. 'qb_cache_set' => array(),
  2270. 'qb_cache_exists' => array(),
  2271. 'qb_cache_no_escape' => array(),
  2272. 'qb_cache_aliased_tables' => array()
  2273. ));
  2274. return $this;
  2275. }
  2276. // --------------------------------------------------------------------
  2277. /**
  2278. * Merge Cache
  2279. *
  2280. * When called, this function merges any cached QB arrays with
  2281. * locally called ones.
  2282. *
  2283. * @return void
  2284. */
  2285. protected function _merge_cache()
  2286. {
  2287. if (count($this->qb_cache_exists) === 0)
  2288. {
  2289. return;
  2290. }
  2291. elseif (in_array('select', $this->qb_cache_exists, TRUE))
  2292. {
  2293. $qb_no_escape = $this->qb_cache_no_escape;
  2294. }
  2295. foreach (array_unique($this->qb_cache_exists) as $val) // select, from, etc.
  2296. {
  2297. $qb_variable = 'qb_'.$val;
  2298. $qb_cache_var = 'qb_cache_'.$val;
  2299. $qb_new = $this->$qb_cache_var;
  2300. for ($i = 0, $c = count($this->$qb_variable); $i < $c; $i++)
  2301. {
  2302. if ( ! in_array($this->{$qb_variable}[$i], $qb_new, TRUE))
  2303. {
  2304. $qb_new[] = $this->{$qb_variable}[$i];
  2305. if ($val === 'select')
  2306. {
  2307. $qb_no_escape[] = $this->qb_no_escape[$i];
  2308. }
  2309. }
  2310. }
  2311. $this->$qb_variable = $qb_new;
  2312. if ($val === 'select')
  2313. {
  2314. $this->qb_no_escape = $qb_no_escape;
  2315. }
  2316. }
  2317. }
  2318. // --------------------------------------------------------------------
  2319. /**
  2320. * Is literal
  2321. *
  2322. * Determines if a string represents a literal value or a field name
  2323. *
  2324. * @param string $str
  2325. * @return bool
  2326. */
  2327. protected function _is_literal($str)
  2328. {
  2329. $str = trim($str);
  2330. if (empty($str) OR ctype_digit($str) OR (string) (float) $str === $str OR in_array(strtoupper($str), array('TRUE', 'FALSE'), TRUE))
  2331. {
  2332. return TRUE;
  2333. }
  2334. static $_str;
  2335. if (empty($_str))
  2336. {
  2337. $_str = ($this->_escape_char !== '"')
  2338. ? array('"', "'") : array("'");
  2339. }
  2340. return in_array($str[0], $_str, TRUE);
  2341. }
  2342. // --------------------------------------------------------------------
  2343. /**
  2344. * Reset Query Builder values.
  2345. *
  2346. * Publicly-visible method to reset the QB values.
  2347. *
  2348. * @return CI_DB_query_builder
  2349. */
  2350. public function reset_query()
  2351. {
  2352. $this->_reset_select();
  2353. $this->_reset_write();
  2354. return $this;
  2355. }
  2356. // --------------------------------------------------------------------
  2357. /**
  2358. * Resets the query builder values. Called by the get() function
  2359. *
  2360. * @param array An array of fields to reset
  2361. * @return void
  2362. */
  2363. protected function _reset_run($qb_reset_items)
  2364. {
  2365. foreach ($qb_reset_items as $item => $default_value)
  2366. {
  2367. $this->$item = $default_value;
  2368. }
  2369. }
  2370. // --------------------------------------------------------------------
  2371. /**
  2372. * Resets the query builder values. Called by the get() function
  2373. *
  2374. * @return void
  2375. */
  2376. protected function _reset_select()
  2377. {
  2378. $this->_reset_run(array(
  2379. 'qb_select' => array(),
  2380. 'qb_from' => array(),
  2381. 'qb_join' => array(),
  2382. 'qb_where' => array(),
  2383. 'qb_groupby' => array(),
  2384. 'qb_having' => array(),
  2385. 'qb_orderby' => array(),
  2386. 'qb_aliased_tables' => array(),
  2387. 'qb_no_escape' => array(),
  2388. 'qb_distinct' => FALSE,
  2389. 'qb_limit' => FALSE,
  2390. 'qb_offset' => FALSE
  2391. ));
  2392. }
  2393. // --------------------------------------------------------------------
  2394. /**
  2395. * Resets the query builder "write" values.
  2396. *
  2397. * Called by the insert() update() insert_batch() update_batch() and delete() functions
  2398. *
  2399. * @return void
  2400. */
  2401. protected function _reset_write()
  2402. {
  2403. $this->_reset_run(array(
  2404. 'qb_set' => array(),
  2405. 'qb_set_ub' => array(),
  2406. 'qb_from' => array(),
  2407. 'qb_join' => array(),
  2408. 'qb_where' => array(),
  2409. 'qb_orderby' => array(),
  2410. 'qb_keys' => array(),
  2411. 'qb_limit' => FALSE
  2412. ));
  2413. }
  2414. }