DB_query_builder.php 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803
  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 - 2017, 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 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
  33. * @license http://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. $this->{$qb_key}[] = array('condition' => $prefix.$k.$v, 'escape' => $escape);
  607. if ($this->qb_caching === TRUE)
  608. {
  609. $this->{$qb_cache_key}[] = array('condition' => $prefix.$k.$v, 'escape' => $escape);
  610. $this->qb_cache_exists[] = substr($qb_key, 3);
  611. }
  612. }
  613. return $this;
  614. }
  615. // --------------------------------------------------------------------
  616. /**
  617. * WHERE IN
  618. *
  619. * Generates a WHERE field IN('item', 'item') SQL query,
  620. * joined with 'AND' if appropriate.
  621. *
  622. * @param string $key The field to search
  623. * @param array $values The values searched on
  624. * @param bool $escape
  625. * @return CI_DB_query_builder
  626. */
  627. public function where_in($key = NULL, $values = NULL, $escape = NULL)
  628. {
  629. return $this->_where_in($key, $values, FALSE, 'AND ', $escape);
  630. }
  631. // --------------------------------------------------------------------
  632. /**
  633. * OR WHERE IN
  634. *
  635. * Generates a WHERE field IN('item', 'item') SQL query,
  636. * joined with 'OR' if appropriate.
  637. *
  638. * @param string $key The field to search
  639. * @param array $values The values searched on
  640. * @param bool $escape
  641. * @return CI_DB_query_builder
  642. */
  643. public function or_where_in($key = NULL, $values = NULL, $escape = NULL)
  644. {
  645. return $this->_where_in($key, $values, FALSE, 'OR ', $escape);
  646. }
  647. // --------------------------------------------------------------------
  648. /**
  649. * WHERE NOT IN
  650. *
  651. * Generates a WHERE field NOT IN('item', 'item') SQL query,
  652. * joined with 'AND' if appropriate.
  653. *
  654. * @param string $key The field to search
  655. * @param array $values The values searched on
  656. * @param bool $escape
  657. * @return CI_DB_query_builder
  658. */
  659. public function where_not_in($key = NULL, $values = NULL, $escape = NULL)
  660. {
  661. return $this->_where_in($key, $values, TRUE, 'AND ', $escape);
  662. }
  663. // --------------------------------------------------------------------
  664. /**
  665. * OR WHERE NOT IN
  666. *
  667. * Generates a WHERE field NOT IN('item', 'item') SQL query,
  668. * joined with 'OR' if appropriate.
  669. *
  670. * @param string $key The field to search
  671. * @param array $values The values searched on
  672. * @param bool $escape
  673. * @return CI_DB_query_builder
  674. */
  675. public function or_where_not_in($key = NULL, $values = NULL, $escape = NULL)
  676. {
  677. return $this->_where_in($key, $values, TRUE, 'OR ', $escape);
  678. }
  679. // --------------------------------------------------------------------
  680. /**
  681. * Internal WHERE IN
  682. *
  683. * @used-by where_in()
  684. * @used-by or_where_in()
  685. * @used-by where_not_in()
  686. * @used-by or_where_not_in()
  687. *
  688. * @param string $key The field to search
  689. * @param array $values The values searched on
  690. * @param bool $not If the statement would be IN or NOT IN
  691. * @param string $type
  692. * @param bool $escape
  693. * @return CI_DB_query_builder
  694. */
  695. protected function _where_in($key = NULL, $values = NULL, $not = FALSE, $type = 'AND ', $escape = NULL)
  696. {
  697. if ($key === NULL OR $values === NULL)
  698. {
  699. return $this;
  700. }
  701. if ( ! is_array($values))
  702. {
  703. $values = array($values);
  704. }
  705. is_bool($escape) OR $escape = $this->_protect_identifiers;
  706. $not = ($not) ? ' NOT' : '';
  707. if ($escape === TRUE)
  708. {
  709. $where_in = array();
  710. foreach ($values as $value)
  711. {
  712. $where_in[] = $this->escape($value);
  713. }
  714. }
  715. else
  716. {
  717. $where_in = array_values($values);
  718. }
  719. $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0)
  720. ? $this->_group_get_type('')
  721. : $this->_group_get_type($type);
  722. $where_in = array(
  723. 'condition' => $prefix.$key.$not.' IN('.implode(', ', $where_in).')',
  724. 'escape' => $escape
  725. );
  726. $this->qb_where[] = $where_in;
  727. if ($this->qb_caching === TRUE)
  728. {
  729. $this->qb_cache_where[] = $where_in;
  730. $this->qb_cache_exists[] = 'where';
  731. }
  732. return $this;
  733. }
  734. // --------------------------------------------------------------------
  735. /**
  736. * LIKE
  737. *
  738. * Generates a %LIKE% portion of the query.
  739. * Separates multiple calls with 'AND'.
  740. *
  741. * @param mixed $field
  742. * @param string $match
  743. * @param string $side
  744. * @param bool $escape
  745. * @return CI_DB_query_builder
  746. */
  747. public function like($field, $match = '', $side = 'both', $escape = NULL)
  748. {
  749. return $this->_like($field, $match, 'AND ', $side, '', $escape);
  750. }
  751. // --------------------------------------------------------------------
  752. /**
  753. * NOT LIKE
  754. *
  755. * Generates a NOT LIKE portion of the query.
  756. * Separates multiple calls with 'AND'.
  757. *
  758. * @param mixed $field
  759. * @param string $match
  760. * @param string $side
  761. * @param bool $escape
  762. * @return CI_DB_query_builder
  763. */
  764. public function not_like($field, $match = '', $side = 'both', $escape = NULL)
  765. {
  766. return $this->_like($field, $match, 'AND ', $side, 'NOT', $escape);
  767. }
  768. // --------------------------------------------------------------------
  769. /**
  770. * OR LIKE
  771. *
  772. * Generates a %LIKE% portion of the query.
  773. * Separates multiple calls with 'OR'.
  774. *
  775. * @param mixed $field
  776. * @param string $match
  777. * @param string $side
  778. * @param bool $escape
  779. * @return CI_DB_query_builder
  780. */
  781. public function or_like($field, $match = '', $side = 'both', $escape = NULL)
  782. {
  783. return $this->_like($field, $match, 'OR ', $side, '', $escape);
  784. }
  785. // --------------------------------------------------------------------
  786. /**
  787. * OR NOT LIKE
  788. *
  789. * Generates a NOT LIKE portion of the query.
  790. * Separates multiple calls with 'OR'.
  791. *
  792. * @param mixed $field
  793. * @param string $match
  794. * @param string $side
  795. * @param bool $escape
  796. * @return CI_DB_query_builder
  797. */
  798. public function or_not_like($field, $match = '', $side = 'both', $escape = NULL)
  799. {
  800. return $this->_like($field, $match, 'OR ', $side, 'NOT', $escape);
  801. }
  802. // --------------------------------------------------------------------
  803. /**
  804. * Internal LIKE
  805. *
  806. * @used-by like()
  807. * @used-by or_like()
  808. * @used-by not_like()
  809. * @used-by or_not_like()
  810. *
  811. * @param mixed $field
  812. * @param string $match
  813. * @param string $type
  814. * @param string $side
  815. * @param string $not
  816. * @param bool $escape
  817. * @return CI_DB_query_builder
  818. */
  819. protected function _like($field, $match = '', $type = 'AND ', $side = 'both', $not = '', $escape = NULL)
  820. {
  821. if ( ! is_array($field))
  822. {
  823. $field = array($field => $match);
  824. }
  825. is_bool($escape) OR $escape = $this->_protect_identifiers;
  826. // lowercase $side in case somebody writes e.g. 'BEFORE' instead of 'before' (doh)
  827. $side = strtolower($side);
  828. foreach ($field as $k => $v)
  829. {
  830. $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0)
  831. ? $this->_group_get_type('') : $this->_group_get_type($type);
  832. if ($escape === TRUE)
  833. {
  834. $v = $this->escape_like_str($v);
  835. }
  836. if ($side === 'none')
  837. {
  838. $like_statement = "{$prefix} {$k} {$not} LIKE '{$v}'";
  839. }
  840. elseif ($side === 'before')
  841. {
  842. $like_statement = "{$prefix} {$k} {$not} LIKE '%{$v}'";
  843. }
  844. elseif ($side === 'after')
  845. {
  846. $like_statement = "{$prefix} {$k} {$not} LIKE '{$v}%'";
  847. }
  848. else
  849. {
  850. $like_statement = "{$prefix} {$k} {$not} LIKE '%{$v}%'";
  851. }
  852. // some platforms require an escape sequence definition for LIKE wildcards
  853. if ($escape === TRUE && $this->_like_escape_str !== '')
  854. {
  855. $like_statement .= sprintf($this->_like_escape_str, $this->_like_escape_chr);
  856. }
  857. $this->qb_where[] = array('condition' => $like_statement, 'escape' => $escape);
  858. if ($this->qb_caching === TRUE)
  859. {
  860. $this->qb_cache_where[] = array('condition' => $like_statement, 'escape' => $escape);
  861. $this->qb_cache_exists[] = 'where';
  862. }
  863. }
  864. return $this;
  865. }
  866. // --------------------------------------------------------------------
  867. /**
  868. * Starts a query group.
  869. *
  870. * @param string $not (Internal use only)
  871. * @param string $type (Internal use only)
  872. * @return CI_DB_query_builder
  873. */
  874. public function group_start($not = '', $type = 'AND ')
  875. {
  876. $type = $this->_group_get_type($type);
  877. $this->qb_where_group_started = TRUE;
  878. $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0) ? '' : $type;
  879. $where = array(
  880. 'condition' => $prefix.$not.str_repeat(' ', ++$this->qb_where_group_count).' (',
  881. 'escape' => FALSE
  882. );
  883. $this->qb_where[] = $where;
  884. if ($this->qb_caching)
  885. {
  886. $this->qb_cache_where[] = $where;
  887. }
  888. return $this;
  889. }
  890. // --------------------------------------------------------------------
  891. /**
  892. * Starts a query group, but ORs the group
  893. *
  894. * @return CI_DB_query_builder
  895. */
  896. public function or_group_start()
  897. {
  898. return $this->group_start('', 'OR ');
  899. }
  900. // --------------------------------------------------------------------
  901. /**
  902. * Starts a query group, but NOTs the group
  903. *
  904. * @return CI_DB_query_builder
  905. */
  906. public function not_group_start()
  907. {
  908. return $this->group_start('NOT ', 'AND ');
  909. }
  910. // --------------------------------------------------------------------
  911. /**
  912. * Starts a query group, but OR NOTs the group
  913. *
  914. * @return CI_DB_query_builder
  915. */
  916. public function or_not_group_start()
  917. {
  918. return $this->group_start('NOT ', 'OR ');
  919. }
  920. // --------------------------------------------------------------------
  921. /**
  922. * Ends a query group
  923. *
  924. * @return CI_DB_query_builder
  925. */
  926. public function group_end()
  927. {
  928. $this->qb_where_group_started = FALSE;
  929. $where = array(
  930. 'condition' => str_repeat(' ', $this->qb_where_group_count--).')',
  931. 'escape' => FALSE
  932. );
  933. $this->qb_where[] = $where;
  934. if ($this->qb_caching)
  935. {
  936. $this->qb_cache_where[] = $where;
  937. }
  938. return $this;
  939. }
  940. // --------------------------------------------------------------------
  941. /**
  942. * Group_get_type
  943. *
  944. * @used-by group_start()
  945. * @used-by _like()
  946. * @used-by _wh()
  947. * @used-by _where_in()
  948. *
  949. * @param string $type
  950. * @return string
  951. */
  952. protected function _group_get_type($type)
  953. {
  954. if ($this->qb_where_group_started)
  955. {
  956. $type = '';
  957. $this->qb_where_group_started = FALSE;
  958. }
  959. return $type;
  960. }
  961. // --------------------------------------------------------------------
  962. /**
  963. * GROUP BY
  964. *
  965. * @param string $by
  966. * @param bool $escape
  967. * @return CI_DB_query_builder
  968. */
  969. public function group_by($by, $escape = NULL)
  970. {
  971. is_bool($escape) OR $escape = $this->_protect_identifiers;
  972. if (is_string($by))
  973. {
  974. $by = ($escape === TRUE)
  975. ? explode(',', $by)
  976. : array($by);
  977. }
  978. foreach ($by as $val)
  979. {
  980. $val = trim($val);
  981. if ($val !== '')
  982. {
  983. $val = array('field' => $val, 'escape' => $escape);
  984. $this->qb_groupby[] = $val;
  985. if ($this->qb_caching === TRUE)
  986. {
  987. $this->qb_cache_groupby[] = $val;
  988. $this->qb_cache_exists[] = 'groupby';
  989. }
  990. }
  991. }
  992. return $this;
  993. }
  994. // --------------------------------------------------------------------
  995. /**
  996. * HAVING
  997. *
  998. * Separates multiple calls with 'AND'.
  999. *
  1000. * @param string $key
  1001. * @param string $value
  1002. * @param bool $escape
  1003. * @return CI_DB_query_builder
  1004. */
  1005. public function having($key, $value = NULL, $escape = NULL)
  1006. {
  1007. return $this->_wh('qb_having', $key, $value, 'AND ', $escape);
  1008. }
  1009. // --------------------------------------------------------------------
  1010. /**
  1011. * OR HAVING
  1012. *
  1013. * Separates multiple calls with 'OR'.
  1014. *
  1015. * @param string $key
  1016. * @param string $value
  1017. * @param bool $escape
  1018. * @return CI_DB_query_builder
  1019. */
  1020. public function or_having($key, $value = NULL, $escape = NULL)
  1021. {
  1022. return $this->_wh('qb_having', $key, $value, 'OR ', $escape);
  1023. }
  1024. // --------------------------------------------------------------------
  1025. /**
  1026. * ORDER BY
  1027. *
  1028. * @param string $orderby
  1029. * @param string $direction ASC, DESC or RANDOM
  1030. * @param bool $escape
  1031. * @return CI_DB_query_builder
  1032. */
  1033. public function order_by($orderby, $direction = '', $escape = NULL)
  1034. {
  1035. $direction = strtoupper(trim($direction));
  1036. if ($direction === 'RANDOM')
  1037. {
  1038. $direction = '';
  1039. // Do we have a seed value?
  1040. $orderby = ctype_digit((string) $orderby)
  1041. ? sprintf($this->_random_keyword[1], $orderby)
  1042. : $this->_random_keyword[0];
  1043. }
  1044. elseif (empty($orderby))
  1045. {
  1046. return $this;
  1047. }
  1048. elseif ($direction !== '')
  1049. {
  1050. $direction = in_array($direction, array('ASC', 'DESC'), TRUE) ? ' '.$direction : '';
  1051. }
  1052. is_bool($escape) OR $escape = $this->_protect_identifiers;
  1053. if ($escape === FALSE)
  1054. {
  1055. $qb_orderby[] = array('field' => $orderby, 'direction' => $direction, 'escape' => FALSE);
  1056. }
  1057. else
  1058. {
  1059. $qb_orderby = array();
  1060. foreach (explode(',', $orderby) as $field)
  1061. {
  1062. $qb_orderby[] = ($direction === '' && preg_match('/\s+(ASC|DESC)$/i', rtrim($field), $match, PREG_OFFSET_CAPTURE))
  1063. ? array('field' => ltrim(substr($field, 0, $match[0][1])), 'direction' => ' '.$match[1][0], 'escape' => TRUE)
  1064. : array('field' => trim($field), 'direction' => $direction, 'escape' => TRUE);
  1065. }
  1066. }
  1067. $this->qb_orderby = array_merge($this->qb_orderby, $qb_orderby);
  1068. if ($this->qb_caching === TRUE)
  1069. {
  1070. $this->qb_cache_orderby = array_merge($this->qb_cache_orderby, $qb_orderby);
  1071. $this->qb_cache_exists[] = 'orderby';
  1072. }
  1073. return $this;
  1074. }
  1075. // --------------------------------------------------------------------
  1076. /**
  1077. * LIMIT
  1078. *
  1079. * @param int $value LIMIT value
  1080. * @param int $offset OFFSET value
  1081. * @return CI_DB_query_builder
  1082. */
  1083. public function limit($value, $offset = 0)
  1084. {
  1085. is_null($value) OR $this->qb_limit = (int) $value;
  1086. empty($offset) OR $this->qb_offset = (int) $offset;
  1087. return $this;
  1088. }
  1089. // --------------------------------------------------------------------
  1090. /**
  1091. * Sets the OFFSET value
  1092. *
  1093. * @param int $offset OFFSET value
  1094. * @return CI_DB_query_builder
  1095. */
  1096. public function offset($offset)
  1097. {
  1098. empty($offset) OR $this->qb_offset = (int) $offset;
  1099. return $this;
  1100. }
  1101. // --------------------------------------------------------------------
  1102. /**
  1103. * LIMIT string
  1104. *
  1105. * Generates a platform-specific LIMIT clause.
  1106. *
  1107. * @param string $sql SQL Query
  1108. * @return string
  1109. */
  1110. protected function _limit($sql)
  1111. {
  1112. return $sql.' LIMIT '.($this->qb_offset ? $this->qb_offset.', ' : '').(int) $this->qb_limit;
  1113. }
  1114. // --------------------------------------------------------------------
  1115. /**
  1116. * The "set" function.
  1117. *
  1118. * Allows key/value pairs to be set for inserting or updating
  1119. *
  1120. * @param mixed
  1121. * @param string
  1122. * @param bool
  1123. * @return CI_DB_query_builder
  1124. */
  1125. public function set($key, $value = '', $escape = NULL)
  1126. {
  1127. $key = $this->_object_to_array($key);
  1128. if ( ! is_array($key))
  1129. {
  1130. $key = array($key => $value);
  1131. }
  1132. is_bool($escape) OR $escape = $this->_protect_identifiers;
  1133. foreach ($key as $k => $v)
  1134. {
  1135. $this->qb_set[$this->protect_identifiers($k, FALSE, $escape)] = ($escape)
  1136. ? $this->escape($v) : $v;
  1137. }
  1138. return $this;
  1139. }
  1140. // --------------------------------------------------------------------
  1141. /**
  1142. * Get SELECT query string
  1143. *
  1144. * Compiles a SELECT query string and returns the sql.
  1145. *
  1146. * @param string the table name to select from (optional)
  1147. * @param bool TRUE: resets QB values; FALSE: leave QB values alone
  1148. * @return string
  1149. */
  1150. public function get_compiled_select($table = '', $reset = TRUE)
  1151. {
  1152. if ($table !== '')
  1153. {
  1154. $this->_track_aliases($table);
  1155. $this->from($table);
  1156. }
  1157. $select = $this->_compile_select();
  1158. if ($reset === TRUE)
  1159. {
  1160. $this->_reset_select();
  1161. }
  1162. return $select;
  1163. }
  1164. // --------------------------------------------------------------------
  1165. /**
  1166. * Get
  1167. *
  1168. * Compiles the select statement based on the other functions called
  1169. * and runs the query
  1170. *
  1171. * @param string the table
  1172. * @param string the limit clause
  1173. * @param string the offset clause
  1174. * @return CI_DB_result
  1175. */
  1176. public function get($table = '', $limit = NULL, $offset = NULL)
  1177. {
  1178. if ($table !== '')
  1179. {
  1180. $this->_track_aliases($table);
  1181. $this->from($table);
  1182. }
  1183. if ( ! empty($limit))
  1184. {
  1185. $this->limit($limit, $offset);
  1186. }
  1187. $result = $this->query($this->_compile_select());
  1188. $this->_reset_select();
  1189. return $result;
  1190. }
  1191. // --------------------------------------------------------------------
  1192. /**
  1193. * "Count All Results" query
  1194. *
  1195. * Generates a platform-specific query string that counts all records
  1196. * returned by an Query Builder query.
  1197. *
  1198. * @param string
  1199. * @param bool the reset clause
  1200. * @return int
  1201. */
  1202. public function count_all_results($table = '', $reset = TRUE)
  1203. {
  1204. if ($table !== '')
  1205. {
  1206. $this->_track_aliases($table);
  1207. $this->from($table);
  1208. }
  1209. // ORDER BY usage is often problematic here (most notably
  1210. // on Microsoft SQL Server) and ultimately unnecessary
  1211. // for selecting COUNT(*) ...
  1212. $qb_orderby = $this->qb_orderby;
  1213. $qb_cache_orderby = $this->qb_cache_orderby;
  1214. $this->qb_orderby = $this->qb_cache_orderby = NULL;
  1215. $result = ($this->qb_distinct === TRUE OR ! empty($this->qb_groupby) OR ! empty($this->qb_cache_groupby) OR $this->qb_limit OR $this->qb_offset)
  1216. ? $this->query($this->_count_string.$this->protect_identifiers('numrows')."\nFROM (\n".$this->_compile_select()."\n) CI_count_all_results")
  1217. : $this->query($this->_compile_select($this->_count_string.$this->protect_identifiers('numrows')));
  1218. if ($reset === TRUE)
  1219. {
  1220. $this->_reset_select();
  1221. }
  1222. else
  1223. {
  1224. $this->qb_orderby = $qb_orderby;
  1225. $this->qb_cache_orderby = $qb_cache_orderby;
  1226. }
  1227. if ($result->num_rows() === 0)
  1228. {
  1229. return 0;
  1230. }
  1231. $row = $result->row();
  1232. return (int) $row->numrows;
  1233. }
  1234. // --------------------------------------------------------------------
  1235. /**
  1236. * Get_Where
  1237. *
  1238. * Allows the where clause, limit and offset to be added directly
  1239. *
  1240. * @param string $table
  1241. * @param string $where
  1242. * @param int $limit
  1243. * @param int $offset
  1244. * @return CI_DB_result
  1245. */
  1246. public function get_where($table = '', $where = NULL, $limit = NULL, $offset = NULL)
  1247. {
  1248. if ($table !== '')
  1249. {
  1250. $this->from($table);
  1251. }
  1252. if ($where !== NULL)
  1253. {
  1254. $this->where($where);
  1255. }
  1256. if ( ! empty($limit))
  1257. {
  1258. $this->limit($limit, $offset);
  1259. }
  1260. $result = $this->query($this->_compile_select());
  1261. $this->_reset_select();
  1262. return $result;
  1263. }
  1264. // --------------------------------------------------------------------
  1265. /**
  1266. * Insert_Batch
  1267. *
  1268. * Compiles batch insert strings and runs the queries
  1269. *
  1270. * @param string $table Table to insert into
  1271. * @param array $set An associative array of insert values
  1272. * @param bool $escape Whether to escape values and identifiers
  1273. * @return int Number of rows inserted or FALSE on failure
  1274. */
  1275. public function insert_batch($table, $set = NULL, $escape = NULL, $batch_size = 100)
  1276. {
  1277. if ($set === NULL)
  1278. {
  1279. if (empty($this->qb_set))
  1280. {
  1281. return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
  1282. }
  1283. }
  1284. else
  1285. {
  1286. if (empty($set))
  1287. {
  1288. return ($this->db_debug) ? $this->display_error('insert_batch() called with no data') : FALSE;
  1289. }
  1290. $this->set_insert_batch($set, '', $escape);
  1291. }
  1292. if (strlen($table) === 0)
  1293. {
  1294. if ( ! isset($this->qb_from[0]))
  1295. {
  1296. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1297. }
  1298. $table = $this->qb_from[0];
  1299. }
  1300. // Batch this baby
  1301. $affected_rows = 0;
  1302. for ($i = 0, $total = count($this->qb_set); $i < $total; $i += $batch_size)
  1303. {
  1304. if ($this->query($this->_insert_batch($this->protect_identifiers($table, TRUE, $escape, FALSE), $this->qb_keys, array_slice($this->qb_set, $i, $batch_size))))
  1305. {
  1306. $affected_rows += $this->affected_rows();
  1307. }
  1308. }
  1309. $this->_reset_write();
  1310. return $affected_rows;
  1311. }
  1312. // --------------------------------------------------------------------
  1313. /**
  1314. * Insert batch statement
  1315. *
  1316. * Generates a platform-specific insert string from the supplied data.
  1317. *
  1318. * @param string $table Table name
  1319. * @param array $keys INSERT keys
  1320. * @param array $values INSERT values
  1321. * @return string
  1322. */
  1323. protected function _insert_batch($table, $keys, $values)
  1324. {
  1325. return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES '.implode(', ', $values);
  1326. }
  1327. // --------------------------------------------------------------------
  1328. /**
  1329. * The "set_insert_batch" function. Allows key/value pairs to be set for batch inserts
  1330. *
  1331. * @param mixed
  1332. * @param string
  1333. * @param bool
  1334. * @return CI_DB_query_builder
  1335. */
  1336. public function set_insert_batch($key, $value = '', $escape = NULL)
  1337. {
  1338. $key = $this->_object_to_array_batch($key);
  1339. if ( ! is_array($key))
  1340. {
  1341. $key = array($key => $value);
  1342. }
  1343. is_bool($escape) OR $escape = $this->_protect_identifiers;
  1344. $keys = array_keys($this->_object_to_array(reset($key)));
  1345. sort($keys);
  1346. foreach ($key as $row)
  1347. {
  1348. $row = $this->_object_to_array($row);
  1349. if (count(array_diff($keys, array_keys($row))) > 0 OR count(array_diff(array_keys($row), $keys)) > 0)
  1350. {
  1351. // batch function above returns an error on an empty array
  1352. $this->qb_set[] = array();
  1353. return;
  1354. }
  1355. ksort($row); // puts $row in the same order as our keys
  1356. if ($escape !== FALSE)
  1357. {
  1358. $clean = array();
  1359. foreach ($row as $value)
  1360. {
  1361. $clean[] = $this->escape($value);
  1362. }
  1363. $row = $clean;
  1364. }
  1365. $this->qb_set[] = '('.implode(',', $row).')';
  1366. }
  1367. foreach ($keys as $k)
  1368. {
  1369. $this->qb_keys[] = $this->protect_identifiers($k, FALSE, $escape);
  1370. }
  1371. return $this;
  1372. }
  1373. // --------------------------------------------------------------------
  1374. /**
  1375. * Get INSERT query string
  1376. *
  1377. * Compiles an insert query and returns the sql
  1378. *
  1379. * @param string the table to insert into
  1380. * @param bool TRUE: reset QB values; FALSE: leave QB values alone
  1381. * @return string
  1382. */
  1383. public function get_compiled_insert($table = '', $reset = TRUE)
  1384. {
  1385. if ($this->_validate_insert($table) === FALSE)
  1386. {
  1387. return FALSE;
  1388. }
  1389. $sql = $this->_insert(
  1390. $this->protect_identifiers(
  1391. $this->qb_from[0], TRUE, NULL, FALSE
  1392. ),
  1393. array_keys($this->qb_set),
  1394. array_values($this->qb_set)
  1395. );
  1396. if ($reset === TRUE)
  1397. {
  1398. $this->_reset_write();
  1399. }
  1400. return $sql;
  1401. }
  1402. // --------------------------------------------------------------------
  1403. /**
  1404. * Insert
  1405. *
  1406. * Compiles an insert string and runs the query
  1407. *
  1408. * @param string the table to insert data into
  1409. * @param array an associative array of insert values
  1410. * @param bool $escape Whether to escape values and identifiers
  1411. * @return bool TRUE on success, FALSE on failure
  1412. */
  1413. public function insert($table = '', $set = NULL, $escape = NULL)
  1414. {
  1415. if ($set !== NULL)
  1416. {
  1417. $this->set($set, '', $escape);
  1418. }
  1419. if ($this->_validate_insert($table) === FALSE)
  1420. {
  1421. return FALSE;
  1422. }
  1423. $sql = $this->_insert(
  1424. $this->protect_identifiers(
  1425. $this->qb_from[0], TRUE, $escape, FALSE
  1426. ),
  1427. array_keys($this->qb_set),
  1428. array_values($this->qb_set)
  1429. );
  1430. $this->_reset_write();
  1431. return $this->query($sql);
  1432. }
  1433. // --------------------------------------------------------------------
  1434. /**
  1435. * Validate Insert
  1436. *
  1437. * This method is used by both insert() and get_compiled_insert() to
  1438. * validate that the there data is actually being set and that table
  1439. * has been chosen to be inserted into.
  1440. *
  1441. * @param string the table to insert data into
  1442. * @return string
  1443. */
  1444. protected function _validate_insert($table = '')
  1445. {
  1446. if (count($this->qb_set) === 0)
  1447. {
  1448. return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
  1449. }
  1450. if ($table !== '')
  1451. {
  1452. $this->qb_from[0] = $table;
  1453. }
  1454. elseif ( ! isset($this->qb_from[0]))
  1455. {
  1456. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1457. }
  1458. return TRUE;
  1459. }
  1460. // --------------------------------------------------------------------
  1461. /**
  1462. * Replace
  1463. *
  1464. * Compiles an replace into string and runs the query
  1465. *
  1466. * @param string the table to replace data into
  1467. * @param array an associative array of insert values
  1468. * @return bool TRUE on success, FALSE on failure
  1469. */
  1470. public function replace($table = '', $set = NULL)
  1471. {
  1472. if ($set !== NULL)
  1473. {
  1474. $this->set($set);
  1475. }
  1476. if (count($this->qb_set) === 0)
  1477. {
  1478. return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
  1479. }
  1480. if ($table === '')
  1481. {
  1482. if ( ! isset($this->qb_from[0]))
  1483. {
  1484. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1485. }
  1486. $table = $this->qb_from[0];
  1487. }
  1488. $sql = $this->_replace($this->protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->qb_set), array_values($this->qb_set));
  1489. $this->_reset_write();
  1490. return $this->query($sql);
  1491. }
  1492. // --------------------------------------------------------------------
  1493. /**
  1494. * Replace statement
  1495. *
  1496. * Generates a platform-specific replace string from the supplied data
  1497. *
  1498. * @param string the table name
  1499. * @param array the insert keys
  1500. * @param array the insert values
  1501. * @return string
  1502. */
  1503. protected function _replace($table, $keys, $values)
  1504. {
  1505. return 'REPLACE INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
  1506. }
  1507. // --------------------------------------------------------------------
  1508. /**
  1509. * FROM tables
  1510. *
  1511. * Groups tables in FROM clauses if needed, so there is no confusion
  1512. * about operator precedence.
  1513. *
  1514. * Note: This is only used (and overridden) by MySQL and CUBRID.
  1515. *
  1516. * @return string
  1517. */
  1518. protected function _from_tables()
  1519. {
  1520. return implode(', ', $this->qb_from);
  1521. }
  1522. // --------------------------------------------------------------------
  1523. /**
  1524. * Get UPDATE query string
  1525. *
  1526. * Compiles an update query and returns the sql
  1527. *
  1528. * @param string the table to update
  1529. * @param bool TRUE: reset QB values; FALSE: leave QB values alone
  1530. * @return string
  1531. */
  1532. public function get_compiled_update($table = '', $reset = TRUE)
  1533. {
  1534. // Combine any cached components with the current statements
  1535. $this->_merge_cache();
  1536. if ($this->_validate_update($table) === FALSE)
  1537. {
  1538. return FALSE;
  1539. }
  1540. $sql = $this->_update($this->qb_from[0], $this->qb_set);
  1541. if ($reset === TRUE)
  1542. {
  1543. $this->_reset_write();
  1544. }
  1545. return $sql;
  1546. }
  1547. // --------------------------------------------------------------------
  1548. /**
  1549. * UPDATE
  1550. *
  1551. * Compiles an update string and runs the query.
  1552. *
  1553. * @param string $table
  1554. * @param array $set An associative array of update values
  1555. * @param mixed $where
  1556. * @param int $limit
  1557. * @return bool TRUE on success, FALSE on failure
  1558. */
  1559. public function update($table = '', $set = NULL, $where = NULL, $limit = NULL)
  1560. {
  1561. // Combine any cached components with the current statements
  1562. $this->_merge_cache();
  1563. if ($set !== NULL)
  1564. {
  1565. $this->set($set);
  1566. }
  1567. if ($this->_validate_update($table) === FALSE)
  1568. {
  1569. return FALSE;
  1570. }
  1571. if ($where !== NULL)
  1572. {
  1573. $this->where($where);
  1574. }
  1575. if ( ! empty($limit))
  1576. {
  1577. $this->limit($limit);
  1578. }
  1579. $sql = $this->_update($this->qb_from[0], $this->qb_set);
  1580. $this->_reset_write();
  1581. return $this->query($sql);
  1582. }
  1583. // --------------------------------------------------------------------
  1584. /**
  1585. * Validate Update
  1586. *
  1587. * This method is used by both update() and get_compiled_update() to
  1588. * validate that data is actually being set and that a table has been
  1589. * chosen to be update.
  1590. *
  1591. * @param string the table to update data on
  1592. * @return bool
  1593. */
  1594. protected function _validate_update($table)
  1595. {
  1596. if (count($this->qb_set) === 0)
  1597. {
  1598. return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
  1599. }
  1600. if ($table !== '')
  1601. {
  1602. $this->qb_from = array($this->protect_identifiers($table, TRUE, NULL, FALSE));
  1603. }
  1604. elseif ( ! isset($this->qb_from[0]))
  1605. {
  1606. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1607. }
  1608. return TRUE;
  1609. }
  1610. // --------------------------------------------------------------------
  1611. /**
  1612. * Update_Batch
  1613. *
  1614. * Compiles an update string and runs the query
  1615. *
  1616. * @param string the table to retrieve the results from
  1617. * @param array an associative array of update values
  1618. * @param string the where key
  1619. * @return int number of rows affected or FALSE on failure
  1620. */
  1621. public function update_batch($table, $set = NULL, $index = NULL, $batch_size = 100)
  1622. {
  1623. // Combine any cached components with the current statements
  1624. $this->_merge_cache();
  1625. if ($index === NULL)
  1626. {
  1627. return ($this->db_debug) ? $this->display_error('db_must_use_index') : FALSE;
  1628. }
  1629. if ($set === NULL)
  1630. {
  1631. if (empty($this->qb_set_ub))
  1632. {
  1633. return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
  1634. }
  1635. }
  1636. else
  1637. {
  1638. if (empty($set))
  1639. {
  1640. return ($this->db_debug) ? $this->display_error('update_batch() called with no data') : FALSE;
  1641. }
  1642. $this->set_update_batch($set, $index);
  1643. }
  1644. if (strlen($table) === 0)
  1645. {
  1646. if ( ! isset($this->qb_from[0]))
  1647. {
  1648. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1649. }
  1650. $table = $this->qb_from[0];
  1651. }
  1652. // Batch this baby
  1653. $affected_rows = 0;
  1654. for ($i = 0, $total = count($this->qb_set_ub); $i < $total; $i += $batch_size)
  1655. {
  1656. if ($this->query($this->_update_batch($this->protect_identifiers($table, TRUE, NULL, FALSE), array_slice($this->qb_set_ub, $i, $batch_size), $index)))
  1657. {
  1658. $affected_rows += $this->affected_rows();
  1659. }
  1660. $this->qb_where = array();
  1661. }
  1662. $this->_reset_write();
  1663. return $affected_rows;
  1664. }
  1665. // --------------------------------------------------------------------
  1666. /**
  1667. * Update_Batch statement
  1668. *
  1669. * Generates a platform-specific batch update string from the supplied data
  1670. *
  1671. * @param string $table Table name
  1672. * @param array $values Update data
  1673. * @param string $index WHERE key
  1674. * @return string
  1675. */
  1676. protected function _update_batch($table, $values, $index)
  1677. {
  1678. $ids = array();
  1679. foreach ($values as $key => $val)
  1680. {
  1681. $ids[] = $val[$index]['value'];
  1682. foreach (array_keys($val) as $field)
  1683. {
  1684. if ($field !== $index)
  1685. {
  1686. $final[$val[$field]['field']][] = 'WHEN '.$val[$index]['field'].' = '.$val[$index]['value'].' THEN '.$val[$field]['value'];
  1687. }
  1688. }
  1689. }
  1690. $cases = '';
  1691. foreach ($final as $k => $v)
  1692. {
  1693. $cases .= $k." = CASE \n"
  1694. .implode("\n", $v)."\n"
  1695. .'ELSE '.$k.' END, ';
  1696. }
  1697. $this->where($val[$index]['field'].' IN('.implode(',', $ids).')', NULL, FALSE);
  1698. return 'UPDATE '.$table.' SET '.substr($cases, 0, -2).$this->_compile_wh('qb_where');
  1699. }
  1700. // --------------------------------------------------------------------
  1701. /**
  1702. * The "set_update_batch" function. Allows key/value pairs to be set for batch updating
  1703. *
  1704. * @param array
  1705. * @param string
  1706. * @param bool
  1707. * @return CI_DB_query_builder
  1708. */
  1709. public function set_update_batch($key, $index = '', $escape = NULL)
  1710. {
  1711. $key = $this->_object_to_array_batch($key);
  1712. if ( ! is_array($key))
  1713. {
  1714. // @todo error
  1715. }
  1716. is_bool($escape) OR $escape = $this->_protect_identifiers;
  1717. foreach ($key as $k => $v)
  1718. {
  1719. $index_set = FALSE;
  1720. $clean = array();
  1721. foreach ($v as $k2 => $v2)
  1722. {
  1723. if ($k2 === $index)
  1724. {
  1725. $index_set = TRUE;
  1726. }
  1727. $clean[$k2] = array(
  1728. 'field' => $this->protect_identifiers($k2, FALSE, $escape),
  1729. 'value' => ($escape === FALSE ? $v2 : $this->escape($v2))
  1730. );
  1731. }
  1732. if ($index_set === FALSE)
  1733. {
  1734. return $this->display_error('db_batch_missing_index');
  1735. }
  1736. $this->qb_set_ub[] = $clean;
  1737. }
  1738. return $this;
  1739. }
  1740. // --------------------------------------------------------------------
  1741. /**
  1742. * Empty Table
  1743. *
  1744. * Compiles a delete string and runs "DELETE FROM table"
  1745. *
  1746. * @param string the table to empty
  1747. * @return bool TRUE on success, FALSE on failure
  1748. */
  1749. public function empty_table($table = '')
  1750. {
  1751. if ($table === '')
  1752. {
  1753. if ( ! isset($this->qb_from[0]))
  1754. {
  1755. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1756. }
  1757. $table = $this->qb_from[0];
  1758. }
  1759. else
  1760. {
  1761. $table = $this->protect_identifiers($table, TRUE, NULL, FALSE);
  1762. }
  1763. $sql = $this->_delete($table);
  1764. $this->_reset_write();
  1765. return $this->query($sql);
  1766. }
  1767. // --------------------------------------------------------------------
  1768. /**
  1769. * Truncate
  1770. *
  1771. * Compiles a truncate string and runs the query
  1772. * If the database does not support the truncate() command
  1773. * This function maps to "DELETE FROM table"
  1774. *
  1775. * @param string the table to truncate
  1776. * @return bool TRUE on success, FALSE on failure
  1777. */
  1778. public function truncate($table = '')
  1779. {
  1780. if ($table === '')
  1781. {
  1782. if ( ! isset($this->qb_from[0]))
  1783. {
  1784. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1785. }
  1786. $table = $this->qb_from[0];
  1787. }
  1788. else
  1789. {
  1790. $table = $this->protect_identifiers($table, TRUE, NULL, FALSE);
  1791. }
  1792. $sql = $this->_truncate($table);
  1793. $this->_reset_write();
  1794. return $this->query($sql);
  1795. }
  1796. // --------------------------------------------------------------------
  1797. /**
  1798. * Truncate statement
  1799. *
  1800. * Generates a platform-specific truncate string from the supplied data
  1801. *
  1802. * If the database does not support the truncate() command,
  1803. * then this method maps to 'DELETE FROM table'
  1804. *
  1805. * @param string the table name
  1806. * @return string
  1807. */
  1808. protected function _truncate($table)
  1809. {
  1810. return 'TRUNCATE '.$table;
  1811. }
  1812. // --------------------------------------------------------------------
  1813. /**
  1814. * Get DELETE query string
  1815. *
  1816. * Compiles a delete query string and returns the sql
  1817. *
  1818. * @param string the table to delete from
  1819. * @param bool TRUE: reset QB values; FALSE: leave QB values alone
  1820. * @return string
  1821. */
  1822. public function get_compiled_delete($table = '', $reset = TRUE)
  1823. {
  1824. $this->return_delete_sql = TRUE;
  1825. $sql = $this->delete($table, '', NULL, $reset);
  1826. $this->return_delete_sql = FALSE;
  1827. return $sql;
  1828. }
  1829. // --------------------------------------------------------------------
  1830. /**
  1831. * Delete
  1832. *
  1833. * Compiles a delete string and runs the query
  1834. *
  1835. * @param mixed the table(s) to delete from. String or array
  1836. * @param mixed the where clause
  1837. * @param mixed the limit clause
  1838. * @param bool
  1839. * @return mixed
  1840. */
  1841. public function delete($table = '', $where = '', $limit = NULL, $reset_data = TRUE)
  1842. {
  1843. // Combine any cached components with the current statements
  1844. $this->_merge_cache();
  1845. if ($table === '')
  1846. {
  1847. if ( ! isset($this->qb_from[0]))
  1848. {
  1849. return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
  1850. }
  1851. $table = $this->qb_from[0];
  1852. }
  1853. elseif (is_array($table))
  1854. {
  1855. empty($where) && $reset_data = FALSE;
  1856. foreach ($table as $single_table)
  1857. {
  1858. $this->delete($single_table, $where, $limit, $reset_data);
  1859. }
  1860. return;
  1861. }
  1862. else
  1863. {
  1864. $table = $this->protect_identifiers($table, TRUE, NULL, FALSE);
  1865. }
  1866. if ($where !== '')
  1867. {
  1868. $this->where($where);
  1869. }
  1870. if ( ! empty($limit))
  1871. {
  1872. $this->limit($limit);
  1873. }
  1874. if (count($this->qb_where) === 0)
  1875. {
  1876. return ($this->db_debug) ? $this->display_error('db_del_must_use_where') : FALSE;
  1877. }
  1878. $sql = $this->_delete($table);
  1879. if ($reset_data)
  1880. {
  1881. $this->_reset_write();
  1882. }
  1883. return ($this->return_delete_sql === TRUE) ? $sql : $this->query($sql);
  1884. }
  1885. // --------------------------------------------------------------------
  1886. /**
  1887. * Delete statement
  1888. *
  1889. * Generates a platform-specific delete string from the supplied data
  1890. *
  1891. * @param string the table name
  1892. * @return string
  1893. */
  1894. protected function _delete($table)
  1895. {
  1896. return 'DELETE FROM '.$table.$this->_compile_wh('qb_where')
  1897. .($this->qb_limit ? ' LIMIT '.$this->qb_limit : '');
  1898. }
  1899. // --------------------------------------------------------------------
  1900. /**
  1901. * DB Prefix
  1902. *
  1903. * Prepends a database prefix if one exists in configuration
  1904. *
  1905. * @param string the table
  1906. * @return string
  1907. */
  1908. public function dbprefix($table = '')
  1909. {
  1910. if ($table === '')
  1911. {
  1912. $this->display_error('db_table_name_required');
  1913. }
  1914. return $this->dbprefix.$table;
  1915. }
  1916. // --------------------------------------------------------------------
  1917. /**
  1918. * Set DB Prefix
  1919. *
  1920. * Set's the DB Prefix to something new without needing to reconnect
  1921. *
  1922. * @param string the prefix
  1923. * @return string
  1924. */
  1925. public function set_dbprefix($prefix = '')
  1926. {
  1927. return $this->dbprefix = $prefix;
  1928. }
  1929. // --------------------------------------------------------------------
  1930. /**
  1931. * Track Aliases
  1932. *
  1933. * Used to track SQL statements written with aliased tables.
  1934. *
  1935. * @param string The table to inspect
  1936. * @return string
  1937. */
  1938. protected function _track_aliases($table)
  1939. {
  1940. if (is_array($table))
  1941. {
  1942. foreach ($table as $t)
  1943. {
  1944. $this->_track_aliases($t);
  1945. }
  1946. return;
  1947. }
  1948. // Does the string contain a comma? If so, we need to separate
  1949. // the string into discreet statements
  1950. if (strpos($table, ',') !== FALSE)
  1951. {
  1952. return $this->_track_aliases(explode(',', $table));
  1953. }
  1954. // if a table alias is used we can recognize it by a space
  1955. if (strpos($table, ' ') !== FALSE)
  1956. {
  1957. // if the alias is written with the AS keyword, remove it
  1958. $table = preg_replace('/\s+AS\s+/i', ' ', $table);
  1959. // Grab the alias
  1960. $table = trim(strrchr($table, ' '));
  1961. // Store the alias, if it doesn't already exist
  1962. if ( ! in_array($table, $this->qb_aliased_tables, TRUE))
  1963. {
  1964. $this->qb_aliased_tables[] = $table;
  1965. if ($this->qb_caching === TRUE && ! in_array($table, $this->qb_cache_aliased_tables, TRUE))
  1966. {
  1967. $this->qb_cache_aliased_tables[] = $table;
  1968. $this->qb_cache_exists[] = 'aliased_tables';
  1969. }
  1970. }
  1971. }
  1972. }
  1973. // --------------------------------------------------------------------
  1974. /**
  1975. * Compile the SELECT statement
  1976. *
  1977. * Generates a query string based on which functions were used.
  1978. * Should not be called directly.
  1979. *
  1980. * @param bool $select_override
  1981. * @return string
  1982. */
  1983. protected function _compile_select($select_override = FALSE)
  1984. {
  1985. // Combine any cached components with the current statements
  1986. $this->_merge_cache();
  1987. // Write the "select" portion of the query
  1988. if ($select_override !== FALSE)
  1989. {
  1990. $sql = $select_override;
  1991. }
  1992. else
  1993. {
  1994. $sql = ( ! $this->qb_distinct) ? 'SELECT ' : 'SELECT DISTINCT ';
  1995. if (count($this->qb_select) === 0)
  1996. {
  1997. $sql .= '*';
  1998. }
  1999. else
  2000. {
  2001. // Cycle through the "select" portion of the query and prep each column name.
  2002. // The reason we protect identifiers here rather than in the select() function
  2003. // is because until the user calls the from() function we don't know if there are aliases
  2004. foreach ($this->qb_select as $key => $val)
  2005. {
  2006. $no_escape = isset($this->qb_no_escape[$key]) ? $this->qb_no_escape[$key] : NULL;
  2007. $this->qb_select[$key] = $this->protect_identifiers($val, FALSE, $no_escape);
  2008. }
  2009. $sql .= implode(', ', $this->qb_select);
  2010. }
  2011. }
  2012. // Write the "FROM" portion of the query
  2013. if (count($this->qb_from) > 0)
  2014. {
  2015. $sql .= "\nFROM ".$this->_from_tables();
  2016. }
  2017. // Write the "JOIN" portion of the query
  2018. if (count($this->qb_join) > 0)
  2019. {
  2020. $sql .= "\n".implode("\n", $this->qb_join);
  2021. }
  2022. $sql .= $this->_compile_wh('qb_where')
  2023. .$this->_compile_group_by()
  2024. .$this->_compile_wh('qb_having')
  2025. .$this->_compile_order_by(); // ORDER BY
  2026. // LIMIT
  2027. if ($this->qb_limit OR $this->qb_offset)
  2028. {
  2029. return $this->_limit($sql."\n");
  2030. }
  2031. return $sql;
  2032. }
  2033. // --------------------------------------------------------------------
  2034. /**
  2035. * Compile WHERE, HAVING statements
  2036. *
  2037. * Escapes identifiers in WHERE and HAVING statements at execution time.
  2038. *
  2039. * Required so that aliases are tracked properly, regardless of whether
  2040. * where(), or_where(), having(), or_having are called prior to from(),
  2041. * join() and dbprefix is added only if needed.
  2042. *
  2043. * @param string $qb_key 'qb_where' or 'qb_having'
  2044. * @return string SQL statement
  2045. */
  2046. protected function _compile_wh($qb_key)
  2047. {
  2048. if (count($this->$qb_key) > 0)
  2049. {
  2050. for ($i = 0, $c = count($this->$qb_key); $i < $c; $i++)
  2051. {
  2052. // Is this condition already compiled?
  2053. if (is_string($this->{$qb_key}[$i]))
  2054. {
  2055. continue;
  2056. }
  2057. elseif ($this->{$qb_key}[$i]['escape'] === FALSE)
  2058. {
  2059. $this->{$qb_key}[$i] = $this->{$qb_key}[$i]['condition'];
  2060. continue;
  2061. }
  2062. // Split multiple conditions
  2063. $conditions = preg_split(
  2064. '/((?:^|\s+)AND\s+|(?:^|\s+)OR\s+)/i',
  2065. $this->{$qb_key}[$i]['condition'],
  2066. -1,
  2067. PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
  2068. );
  2069. for ($ci = 0, $cc = count($conditions); $ci < $cc; $ci++)
  2070. {
  2071. if (($op = $this->_get_operator($conditions[$ci])) === FALSE
  2072. OR ! preg_match('/^(\(?)(.*)('.preg_quote($op, '/').')\s*(.*(?<!\)))?(\)?)$/i', $conditions[$ci], $matches))
  2073. {
  2074. continue;
  2075. }
  2076. // $matches = array(
  2077. // 0 => '(test <= foo)', /* the whole thing */
  2078. // 1 => '(', /* optional */
  2079. // 2 => 'test', /* the field name */
  2080. // 3 => ' <= ', /* $op */
  2081. // 4 => 'foo', /* optional, if $op is e.g. 'IS NULL' */
  2082. // 5 => ')' /* optional */
  2083. // );
  2084. if ( ! empty($matches[4]))
  2085. {
  2086. $this->_is_literal($matches[4]) OR $matches[4] = $this->protect_identifiers(trim($matches[4]));
  2087. $matches[4] = ' '.$matches[4];
  2088. }
  2089. $conditions[$ci] = $matches[1].$this->protect_identifiers(trim($matches[2]))
  2090. .' '.trim($matches[3]).$matches[4].$matches[5];
  2091. }
  2092. $this->{$qb_key}[$i] = implode('', $conditions);
  2093. }
  2094. return ($qb_key === 'qb_having' ? "\nHAVING " : "\nWHERE ")
  2095. .implode("\n", $this->$qb_key);
  2096. }
  2097. return '';
  2098. }
  2099. // --------------------------------------------------------------------
  2100. /**
  2101. * Compile GROUP BY
  2102. *
  2103. * Escapes identifiers in GROUP BY statements at execution time.
  2104. *
  2105. * Required so that aliases are tracked properly, regardless of whether
  2106. * group_by() is called prior to from(), join() and dbprefix is added
  2107. * only if needed.
  2108. *
  2109. * @return string SQL statement
  2110. */
  2111. protected function _compile_group_by()
  2112. {
  2113. if (count($this->qb_groupby) > 0)
  2114. {
  2115. for ($i = 0, $c = count($this->qb_groupby); $i < $c; $i++)
  2116. {
  2117. // Is it already compiled?
  2118. if (is_string($this->qb_groupby[$i]))
  2119. {
  2120. continue;
  2121. }
  2122. $this->qb_groupby[$i] = ($this->qb_groupby[$i]['escape'] === FALSE OR $this->_is_literal($this->qb_groupby[$i]['field']))
  2123. ? $this->qb_groupby[$i]['field']
  2124. : $this->protect_identifiers($this->qb_groupby[$i]['field']);
  2125. }
  2126. return "\nGROUP BY ".implode(', ', $this->qb_groupby);
  2127. }
  2128. return '';
  2129. }
  2130. // --------------------------------------------------------------------
  2131. /**
  2132. * Compile ORDER BY
  2133. *
  2134. * Escapes identifiers in ORDER BY statements at execution time.
  2135. *
  2136. * Required so that aliases are tracked properly, regardless of whether
  2137. * order_by() is called prior to from(), join() and dbprefix is added
  2138. * only if needed.
  2139. *
  2140. * @return string SQL statement
  2141. */
  2142. protected function _compile_order_by()
  2143. {
  2144. if (empty($this->qb_orderby))
  2145. {
  2146. return '';
  2147. }
  2148. for ($i = 0, $c = count($this->qb_orderby); $i < $c; $i++)
  2149. {
  2150. if (is_string($this->qb_orderby[$i]))
  2151. {
  2152. continue;
  2153. }
  2154. if ($this->qb_orderby[$i]['escape'] !== FALSE && ! $this->_is_literal($this->qb_orderby[$i]['field']))
  2155. {
  2156. $this->qb_orderby[$i]['field'] = $this->protect_identifiers($this->qb_orderby[$i]['field']);
  2157. }
  2158. $this->qb_orderby[$i] = $this->qb_orderby[$i]['field'].$this->qb_orderby[$i]['direction'];
  2159. }
  2160. return "\nORDER BY ".implode(', ', $this->qb_orderby);
  2161. }
  2162. // --------------------------------------------------------------------
  2163. /**
  2164. * Object to Array
  2165. *
  2166. * Takes an object as input and converts the class variables to array key/vals
  2167. *
  2168. * @param object
  2169. * @return array
  2170. */
  2171. protected function _object_to_array($object)
  2172. {
  2173. if ( ! is_object($object))
  2174. {
  2175. return $object;
  2176. }
  2177. $array = array();
  2178. foreach (get_object_vars($object) as $key => $val)
  2179. {
  2180. // There are some built in keys we need to ignore for this conversion
  2181. if ( ! is_object($val) && ! is_array($val) && $key !== '_parent_name')
  2182. {
  2183. $array[$key] = $val;
  2184. }
  2185. }
  2186. return $array;
  2187. }
  2188. // --------------------------------------------------------------------
  2189. /**
  2190. * Object to Array
  2191. *
  2192. * Takes an object as input and converts the class variables to array key/vals
  2193. *
  2194. * @param object
  2195. * @return array
  2196. */
  2197. protected function _object_to_array_batch($object)
  2198. {
  2199. if ( ! is_object($object))
  2200. {
  2201. return $object;
  2202. }
  2203. $array = array();
  2204. $out = get_object_vars($object);
  2205. $fields = array_keys($out);
  2206. foreach ($fields as $val)
  2207. {
  2208. // There are some built in keys we need to ignore for this conversion
  2209. if ($val !== '_parent_name')
  2210. {
  2211. $i = 0;
  2212. foreach ($out[$val] as $data)
  2213. {
  2214. $array[$i++][$val] = $data;
  2215. }
  2216. }
  2217. }
  2218. return $array;
  2219. }
  2220. // --------------------------------------------------------------------
  2221. /**
  2222. * Start Cache
  2223. *
  2224. * Starts QB caching
  2225. *
  2226. * @return CI_DB_query_builder
  2227. */
  2228. public function start_cache()
  2229. {
  2230. $this->qb_caching = TRUE;
  2231. return $this;
  2232. }
  2233. // --------------------------------------------------------------------
  2234. /**
  2235. * Stop Cache
  2236. *
  2237. * Stops QB caching
  2238. *
  2239. * @return CI_DB_query_builder
  2240. */
  2241. public function stop_cache()
  2242. {
  2243. $this->qb_caching = FALSE;
  2244. return $this;
  2245. }
  2246. // --------------------------------------------------------------------
  2247. /**
  2248. * Flush Cache
  2249. *
  2250. * Empties the QB cache
  2251. *
  2252. * @return CI_DB_query_builder
  2253. */
  2254. public function flush_cache()
  2255. {
  2256. $this->_reset_run(array(
  2257. 'qb_cache_select' => array(),
  2258. 'qb_cache_from' => array(),
  2259. 'qb_cache_join' => array(),
  2260. 'qb_cache_where' => array(),
  2261. 'qb_cache_groupby' => array(),
  2262. 'qb_cache_having' => array(),
  2263. 'qb_cache_orderby' => array(),
  2264. 'qb_cache_set' => array(),
  2265. 'qb_cache_exists' => array(),
  2266. 'qb_cache_no_escape' => array(),
  2267. 'qb_cache_aliased_tables' => array()
  2268. ));
  2269. return $this;
  2270. }
  2271. // --------------------------------------------------------------------
  2272. /**
  2273. * Merge Cache
  2274. *
  2275. * When called, this function merges any cached QB arrays with
  2276. * locally called ones.
  2277. *
  2278. * @return void
  2279. */
  2280. protected function _merge_cache()
  2281. {
  2282. if (count($this->qb_cache_exists) === 0)
  2283. {
  2284. return;
  2285. }
  2286. elseif (in_array('select', $this->qb_cache_exists, TRUE))
  2287. {
  2288. $qb_no_escape = $this->qb_cache_no_escape;
  2289. }
  2290. foreach (array_unique($this->qb_cache_exists) as $val) // select, from, etc.
  2291. {
  2292. $qb_variable = 'qb_'.$val;
  2293. $qb_cache_var = 'qb_cache_'.$val;
  2294. $qb_new = $this->$qb_cache_var;
  2295. for ($i = 0, $c = count($this->$qb_variable); $i < $c; $i++)
  2296. {
  2297. if ( ! in_array($this->{$qb_variable}[$i], $qb_new, TRUE))
  2298. {
  2299. $qb_new[] = $this->{$qb_variable}[$i];
  2300. if ($val === 'select')
  2301. {
  2302. $qb_no_escape[] = $this->qb_no_escape[$i];
  2303. }
  2304. }
  2305. }
  2306. $this->$qb_variable = $qb_new;
  2307. if ($val === 'select')
  2308. {
  2309. $this->qb_no_escape = $qb_no_escape;
  2310. }
  2311. }
  2312. }
  2313. // --------------------------------------------------------------------
  2314. /**
  2315. * Is literal
  2316. *
  2317. * Determines if a string represents a literal value or a field name
  2318. *
  2319. * @param string $str
  2320. * @return bool
  2321. */
  2322. protected function _is_literal($str)
  2323. {
  2324. $str = trim($str);
  2325. if (empty($str) OR ctype_digit($str) OR (string) (float) $str === $str OR in_array(strtoupper($str), array('TRUE', 'FALSE'), TRUE))
  2326. {
  2327. return TRUE;
  2328. }
  2329. static $_str;
  2330. if (empty($_str))
  2331. {
  2332. $_str = ($this->_escape_char !== '"')
  2333. ? array('"', "'") : array("'");
  2334. }
  2335. return in_array($str[0], $_str, TRUE);
  2336. }
  2337. // --------------------------------------------------------------------
  2338. /**
  2339. * Reset Query Builder values.
  2340. *
  2341. * Publicly-visible method to reset the QB values.
  2342. *
  2343. * @return CI_DB_query_builder
  2344. */
  2345. public function reset_query()
  2346. {
  2347. $this->_reset_select();
  2348. $this->_reset_write();
  2349. return $this;
  2350. }
  2351. // --------------------------------------------------------------------
  2352. /**
  2353. * Resets the query builder values. Called by the get() function
  2354. *
  2355. * @param array An array of fields to reset
  2356. * @return void
  2357. */
  2358. protected function _reset_run($qb_reset_items)
  2359. {
  2360. foreach ($qb_reset_items as $item => $default_value)
  2361. {
  2362. $this->$item = $default_value;
  2363. }
  2364. }
  2365. // --------------------------------------------------------------------
  2366. /**
  2367. * Resets the query builder values. Called by the get() function
  2368. *
  2369. * @return void
  2370. */
  2371. protected function _reset_select()
  2372. {
  2373. $this->_reset_run(array(
  2374. 'qb_select' => array(),
  2375. 'qb_from' => array(),
  2376. 'qb_join' => array(),
  2377. 'qb_where' => array(),
  2378. 'qb_groupby' => array(),
  2379. 'qb_having' => array(),
  2380. 'qb_orderby' => array(),
  2381. 'qb_aliased_tables' => array(),
  2382. 'qb_no_escape' => array(),
  2383. 'qb_distinct' => FALSE,
  2384. 'qb_limit' => FALSE,
  2385. 'qb_offset' => FALSE
  2386. ));
  2387. }
  2388. // --------------------------------------------------------------------
  2389. /**
  2390. * Resets the query builder "write" values.
  2391. *
  2392. * Called by the insert() update() insert_batch() update_batch() and delete() functions
  2393. *
  2394. * @return void
  2395. */
  2396. protected function _reset_write()
  2397. {
  2398. $this->_reset_run(array(
  2399. 'qb_set' => array(),
  2400. 'qb_set_ub' => array(),
  2401. 'qb_from' => array(),
  2402. 'qb_join' => array(),
  2403. 'qb_where' => array(),
  2404. 'qb_orderby' => array(),
  2405. 'qb_keys' => array(),
  2406. 'qb_limit' => FALSE
  2407. ));
  2408. }
  2409. }