DB_query_builder.php 62 KB

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