DB_query_builder.php 60 KB

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