DboSource.php 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149
  1. <?php
  2. /**
  3. * Dbo Source
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package cake.libs.model.datasources
  16. * @since CakePHP(tm) v 0.10.0.1076
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('DataSource', 'Model/Datasource');
  20. App::uses('String', 'Utility');
  21. App::uses('View', 'View');
  22. /**
  23. * DboSource
  24. *
  25. * Creates DBO-descendant objects from a given db connection configuration
  26. *
  27. * @package cake.libs.model.datasources
  28. */
  29. class DboSource extends DataSource {
  30. /**
  31. * Description string for this Database Data Source.
  32. *
  33. * @var string
  34. * @access public
  35. */
  36. public $description = "Database Data Source";
  37. /**
  38. * index definition, standard cake, primary, index, unique
  39. *
  40. * @var array
  41. */
  42. public $index = array('PRI' => 'primary', 'MUL' => 'index', 'UNI' => 'unique');
  43. /**
  44. * Database keyword used to assign aliases to identifiers.
  45. *
  46. * @var string
  47. * @access public
  48. */
  49. public $alias = 'AS ';
  50. /**
  51. * Caches result from query parsing operations. Cached results for both DboSource::name() and
  52. * DboSource::conditions() will be stored here. Method caching uses `crc32()` which is
  53. * fast but can collisions more easily than other hashing algorithms. If you have problems
  54. * with collisions, set DboSource::$cacheMethods to false.
  55. *
  56. * @var array
  57. * @access public
  58. */
  59. public $methodCache = array();
  60. /**
  61. * Whether or not to cache the results of DboSource::name() and DboSource::conditions()
  62. * into the memory cache. Set to false to disable the use of the memory cache.
  63. *
  64. * @var boolean.
  65. * @access public
  66. */
  67. public $cacheMethods = true;
  68. /**
  69. * Print full query debug info?
  70. *
  71. * @var boolean
  72. * @access public
  73. */
  74. public $fullDebug = false;
  75. /**
  76. * Error description of last query
  77. *
  78. * @var unknown_type
  79. * @access public
  80. */
  81. public $error = null;
  82. /**
  83. * String to hold how many rows were affected by the last SQL operation.
  84. *
  85. * @var string
  86. * @access public
  87. */
  88. public $affected = null;
  89. /**
  90. * Number of rows in current resultset
  91. *
  92. * @var int
  93. * @access public
  94. */
  95. public $numRows = null;
  96. /**
  97. * Time the last query took
  98. *
  99. * @var int
  100. * @access public
  101. */
  102. public $took = null;
  103. /**
  104. * Result
  105. *
  106. * @var array
  107. * @access protected
  108. */
  109. protected $_result = null;
  110. /**
  111. * Queries count.
  112. *
  113. * @var int
  114. * @access protected
  115. */
  116. protected $_queriesCnt = 0;
  117. /**
  118. * Total duration of all queries.
  119. *
  120. * @var unknown_type
  121. * @access protected
  122. */
  123. protected $_queriesTime = null;
  124. /**
  125. * Log of queries executed by this DataSource
  126. *
  127. * @var unknown_type
  128. * @access protected
  129. */
  130. protected $_queriesLog = array();
  131. /**
  132. * Maximum number of items in query log
  133. *
  134. * This is to prevent query log taking over too much memory.
  135. *
  136. * @var int Maximum number of queries in the queries log.
  137. * @access protected
  138. */
  139. protected $_queriesLogMax = 200;
  140. /**
  141. * Caches serialzed results of executed queries
  142. *
  143. * @var array Maximum number of queries in the queries log.
  144. * @access protected
  145. */
  146. protected $_queryCache = array();
  147. /**
  148. * A reference to the physical connection of this DataSource
  149. *
  150. * @var array
  151. * @access public
  152. */
  153. public $connection = null;
  154. /**
  155. * The DataSource configuration key name
  156. *
  157. * @var string
  158. * @access public
  159. */
  160. public $configKeyName = null;
  161. /**
  162. * The starting character that this DataSource uses for quoted identifiers.
  163. *
  164. * @var string
  165. * @access public
  166. */
  167. public $startQuote = null;
  168. /**
  169. * The ending character that this DataSource uses for quoted identifiers.
  170. *
  171. * @var string
  172. * @access public
  173. */
  174. public $endQuote = null;
  175. /**
  176. * Bypass automatic adding of joined fields/associations.
  177. *
  178. * @var boolean
  179. * @access private
  180. */
  181. private $__bypass = false;
  182. /**
  183. * The set of valid SQL operations usable in a WHERE statement
  184. *
  185. * @var array
  186. * @access private
  187. */
  188. private $__sqlOps = array('like', 'ilike', 'or', 'not', 'in', 'between', 'regexp', 'similar to');
  189. /**
  190. * Indicates the level of nested transactions
  191. *
  192. * @var integer
  193. * @access protected
  194. */
  195. protected $_transactionNesting = 0;
  196. /**
  197. * Index of basic SQL commands
  198. *
  199. * @var array
  200. * @access protected
  201. */
  202. protected $_commands = array(
  203. 'begin' => 'BEGIN',
  204. 'commit' => 'COMMIT',
  205. 'rollback' => 'ROLLBACK'
  206. );
  207. /**
  208. * Separator string for virtualField composition
  209. *
  210. * @var string
  211. */
  212. public $virtualFieldSeparator = '__';
  213. /**
  214. * List of table engine specific parameters used on table creating
  215. *
  216. * @var array
  217. * @access public
  218. */
  219. public $tableParameters = array();
  220. /**
  221. * List of engine specific additional field parameters used on table creating
  222. *
  223. * @var array
  224. * @access public
  225. */
  226. public $fieldParameters = array();
  227. /**
  228. * Constructor
  229. *
  230. * @param array $config Array of configuration information for the Datasource.
  231. * @param boolean $autoConnect Whether or not the datasource should automatically connect.
  232. */
  233. public function __construct($config = null, $autoConnect = true) {
  234. if (!isset($config['prefix'])) {
  235. $config['prefix'] = '';
  236. }
  237. parent::__construct($config);
  238. $this->fullDebug = Configure::read('debug') > 1;
  239. if (!$this->enabled()) {
  240. return;
  241. }
  242. if ($autoConnect) {
  243. $this->connect();
  244. }
  245. }
  246. /**
  247. * Reconnects to database server with optional new settings
  248. *
  249. * @param array $config An array defining the new configuration settings
  250. * @return boolean True on success, false on failure
  251. */
  252. function reconnect($config = array()) {
  253. $this->disconnect();
  254. $this->setConfig($config);
  255. $this->_sources = null;
  256. return $this->connect();
  257. }
  258. /**
  259. * Disconnects from database.
  260. *
  261. * @return boolean True if the database could be disconnected, else false
  262. */
  263. function disconnect() {
  264. if ($this->_result instanceof PDOStatement) {
  265. $this->_result->closeCursor();
  266. }
  267. unset($this->_connection);
  268. $this->connected = false;
  269. return true;
  270. }
  271. /**
  272. * Get the underlying connection object.
  273. *
  274. * @return PDOConnection
  275. */
  276. public function getConnection() {
  277. return $this->_connection;
  278. }
  279. /**
  280. * Returns a quoted and escaped string of $data for use in an SQL statement.
  281. *
  282. * @param string $data String to be prepared for use in an SQL statement
  283. * @param string $column The column into which this data will be inserted
  284. * @return string Quoted and escaped data
  285. */
  286. function value($data, $column = null) {
  287. if (is_array($data) && !empty($data)) {
  288. return array_map(
  289. array(&$this, 'value'),
  290. $data, array_fill(0, count($data), $column)
  291. );
  292. } elseif (is_object($data) && isset($data->type, $data->value)) {
  293. if ($data->type == 'identifier') {
  294. return $this->name($data->value);
  295. } elseif ($data->type == 'expression') {
  296. return $data->value;
  297. }
  298. } elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
  299. return $data;
  300. }
  301. if ($data === null || (is_array($data) && empty($data))) {
  302. return 'NULL';
  303. }
  304. if (empty($column)) {
  305. $column = $this->introspectType($data);
  306. }
  307. switch ($column) {
  308. case 'binary':
  309. return $this->_connection->quote($data, PDO::PARAM_LOB);
  310. break;
  311. case 'boolean':
  312. return $this->_connection->quote($this->boolean($data, true), PDO::PARAM_BOOL);
  313. break;
  314. case 'string':
  315. case 'text':
  316. return $this->_connection->quote($data, PDO::PARAM_STR);
  317. default:
  318. if ($data === '') {
  319. return 'NULL';
  320. }
  321. if (is_float($data)) {
  322. return sprintf('%F', $data);
  323. }
  324. if ((is_int($data) || $data === '0') || (
  325. is_numeric($data) && strpos($data, ',') === false &&
  326. $data[0] != '0' && strpos($data, 'e') === false)
  327. ) {
  328. return $data;
  329. }
  330. return $this->_connection->quote($data);
  331. break;
  332. }
  333. }
  334. /**
  335. * Returns an object to represent a database identifier in a query. Expression objects
  336. * are not sanitized or esacped.
  337. *
  338. * @param string $identifier A SQL expression to be used as an identifier
  339. * @return object An object representing a database identifier to be used in a query
  340. */
  341. public function identifier($identifier) {
  342. $obj = new stdClass();
  343. $obj->type = 'identifier';
  344. $obj->value = $identifier;
  345. return $obj;
  346. }
  347. /**
  348. * Returns an object to represent a database expression in a query. Expression objects
  349. * are not sanitized or esacped.
  350. *
  351. * @param string $expression An arbitrary SQL expression to be inserted into a query.
  352. * @return object An object representing a database expression to be used in a query
  353. */
  354. public function expression($expression) {
  355. $obj = new stdClass();
  356. $obj->type = 'expression';
  357. $obj->value = $expression;
  358. return $obj;
  359. }
  360. /**
  361. * Executes given SQL statement.
  362. *
  363. * @param string $sql SQL statement
  364. * @param array $params Additional options for the query.
  365. * @return boolean
  366. */
  367. public function rawQuery($sql, $params = array()) {
  368. $this->took = $this->error = $this->numRows = false;
  369. return $this->execute($sql, $params);
  370. }
  371. /**
  372. * Queries the database with given SQL statement, and obtains some metadata about the result
  373. * (rows affected, timing, any errors, number of rows in resultset). The query is also logged.
  374. * If Configure::read('debug') is set, the log is shown all the time, else it is only shown on errors.
  375. *
  376. * ### Options
  377. *
  378. * - log - Whether or not the query should be logged to the memory log.
  379. *
  380. * @param string $sql
  381. * @param array $options
  382. * @param array $params values to be bided to the query
  383. * @return mixed Resource or object representing the result set, or false on failure
  384. */
  385. public function execute($sql, $options = array(), $params = array()) {
  386. $options += array('log' => $this->fullDebug);
  387. $this->error = null;
  388. $t = microtime(true);
  389. $this->_result = $this->_execute($sql, $params);
  390. if ($options['log']) {
  391. $this->took = round((microtime(true) - $t) * 1000, 0);
  392. $this->numRows = $this->affected = $this->lastAffected();
  393. $this->logQuery($sql);
  394. }
  395. if ($this->error) {
  396. $this->showQuery($sql);
  397. return false;
  398. }
  399. return $this->_result;
  400. }
  401. /**
  402. * Executes given SQL statement.
  403. *
  404. * @param string $sql SQL statement
  405. * @param array $params list of params to be bound to query
  406. * @return PDOStatement if query executes with no problem, true as the result of a succesfull
  407. * query returning no rows, suchs as a CREATE statement, false otherwise
  408. */
  409. protected function _execute($sql, $params = array()) {
  410. $sql = trim($sql);
  411. if (preg_match('/^(?:CREATE|ALTER|DROP)/i', $sql)) {
  412. $statements = array_filter(explode(';', $sql));
  413. if (count($statements) > 1) {
  414. $result = array_map(array($this, '_execute'), $statements);
  415. return array_search(false, $result) === false;
  416. }
  417. }
  418. try {
  419. $query = $this->_connection->prepare($sql);
  420. $query->setFetchMode(PDO::FETCH_LAZY);
  421. if (!$query->execute($params)) {
  422. $this->_results = $query;
  423. $this->error = $this->lastError($query);
  424. $query->closeCursor();
  425. return false;
  426. }
  427. if (!$query->columnCount()) {
  428. $query->closeCursor();
  429. return true;
  430. }
  431. return $query;
  432. } catch (PDOException $e) {
  433. $this->_results = null;
  434. $this->error = $e->getMessage();
  435. return false;
  436. }
  437. }
  438. /**
  439. * Returns a formatted error message from previous database operation.
  440. *
  441. * @param PDOStatement $query the query to extract the error from if any
  442. * @return string Error message with error number
  443. */
  444. function lastError(PDOStatement $query = null) {
  445. $error = $query->errorInfo();
  446. if (empty($error[2])) {
  447. return null;
  448. }
  449. return $error[1] . ': ' . $error[2];
  450. }
  451. /**
  452. * Returns number of affected rows in previous database operation. If no previous operation exists,
  453. * this returns false.
  454. *
  455. * @return integer Number of affected rows
  456. */
  457. function lastAffected() {
  458. if ($this->hasResult()) {
  459. return $this->_result->rowCount();
  460. }
  461. return null;
  462. }
  463. /**
  464. * Returns number of rows in previous resultset. If no previous resultset exists,
  465. * this returns false.
  466. *
  467. * @return integer Number of rows in resultset
  468. */
  469. function lastNumRows() {
  470. return $this->lastAffected();
  471. }
  472. /**
  473. * DataSource Query abstraction
  474. *
  475. * @return resource Result resource identifier.
  476. */
  477. public function query() {
  478. $args = func_get_args();
  479. $fields = null;
  480. $order = null;
  481. $limit = null;
  482. $page = null;
  483. $recursive = null;
  484. if (count($args) === 1) {
  485. return $this->fetchAll($args[0]);
  486. } elseif (count($args) > 1 && (strpos($args[0], 'findBy') === 0 || strpos($args[0], 'findAllBy') === 0)) {
  487. $params = $args[1];
  488. if (substr($args[0], 0, 6) === 'findBy') {
  489. $all = false;
  490. $field = Inflector::underscore(substr($args[0], 6));
  491. } else {
  492. $all = true;
  493. $field = Inflector::underscore(substr($args[0], 9));
  494. }
  495. $or = (strpos($field, '_or_') !== false);
  496. if ($or) {
  497. $field = explode('_or_', $field);
  498. } else {
  499. $field = explode('_and_', $field);
  500. }
  501. $off = count($field) - 1;
  502. if (isset($params[1 + $off])) {
  503. $fields = $params[1 + $off];
  504. }
  505. if (isset($params[2 + $off])) {
  506. $order = $params[2 + $off];
  507. }
  508. if (!array_key_exists(0, $params)) {
  509. return false;
  510. }
  511. $c = 0;
  512. $conditions = array();
  513. foreach ($field as $f) {
  514. $conditions[$args[2]->alias . '.' . $f] = $params[$c++];
  515. }
  516. if ($or) {
  517. $conditions = array('OR' => $conditions);
  518. }
  519. if ($all) {
  520. if (isset($params[3 + $off])) {
  521. $limit = $params[3 + $off];
  522. }
  523. if (isset($params[4 + $off])) {
  524. $page = $params[4 + $off];
  525. }
  526. if (isset($params[5 + $off])) {
  527. $recursive = $params[5 + $off];
  528. }
  529. return $args[2]->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
  530. } else {
  531. if (isset($params[3 + $off])) {
  532. $recursive = $params[3 + $off];
  533. }
  534. return $args[2]->find('first', compact('conditions', 'fields', 'order', 'recursive'));
  535. }
  536. } else {
  537. if (isset($args[1]) && $args[1] === true) {
  538. return $this->fetchAll($args[0], true);
  539. } else if (isset($args[1]) && !is_array($args[1]) ) {
  540. return $this->fetchAll($args[0], false);
  541. } else if (isset($args[1]) && is_array($args[1])) {
  542. $offset = 0;
  543. if (isset($args[2])) {
  544. $cache = $args[2];
  545. } else {
  546. $cache = true;
  547. }
  548. return $this->fetchAll($args[0], $args[1], array('cache' => $cache));
  549. }
  550. }
  551. }
  552. /**
  553. * Returns a row from current resultset as an array
  554. *
  555. * @param string $sql Some SQL to be executed.
  556. * @return array The fetched row as an array
  557. */
  558. public function fetchRow($sql = null) {
  559. if (is_string($sql) && strlen($sql) > 5 && !$this->execute($sql)) {
  560. return null;
  561. }
  562. if ($this->hasResult()) {
  563. $this->resultSet($this->_result);
  564. $resultRow = $this->fetchResult();
  565. if (isset($resultRow[0])) {
  566. $this->fetchVirtualField($resultRow);
  567. }
  568. return $resultRow;
  569. } else {
  570. return null;
  571. }
  572. }
  573. /**
  574. * Returns an array of all result rows for a given SQL query.
  575. * Returns false if no rows matched.
  576. *
  577. *
  578. * ### Options
  579. *
  580. * - cache - Returns the cached version of the query, if exists and stores the result in cache
  581. *
  582. * @param string $sql SQL statement
  583. * @param array $params parameters to be bound as values for the SQL statement
  584. * @param array $options additional options for the query.
  585. * @return array Array of resultset rows, or false if no rows matched
  586. */
  587. public function fetchAll($sql, $params = array(), $options = array()) {
  588. if (is_string($options)) {
  589. $options = array('modelName' => $options);
  590. }
  591. if (is_bool($params)) {
  592. $options['cache'] = $params;
  593. $params = array();
  594. }
  595. $options += array('cache' => true);
  596. $cache = $options['cache'];
  597. if ($cache && ($cached = $this->getQueryCache($sql, $params)) !== false) {
  598. return $cached;
  599. }
  600. if ($result = $this->execute($sql, array(), $params)) {
  601. $out = array();
  602. if ($this->hasResult()) {
  603. $first = $this->fetchRow();
  604. if ($first != null) {
  605. $out[] = $first;
  606. }
  607. while ($item = $this->fetchResult()) {
  608. if (isset($item[0])) {
  609. $this->fetchVirtualField($item);
  610. }
  611. $out[] = $item;
  612. }
  613. }
  614. if (!is_bool($result) && $cache) {
  615. $this->_writeQueryCache($sql, $out, $params);
  616. }
  617. if (empty($out) && is_bool($this->_result)) {
  618. return $this->_result;
  619. }
  620. return $out;
  621. }
  622. return false;
  623. }
  624. /**
  625. * Fetches the next row from the current result set
  626. *
  627. * @return boolean
  628. */
  629. public function fetchResult() {
  630. return false;
  631. }
  632. /**
  633. * Modifies $result array to place virtual fields in model entry where they belongs to
  634. *
  635. * @param array $resut Reference to the fetched row
  636. * @return void
  637. */
  638. public function fetchVirtualField(&$result) {
  639. if (isset($result[0]) && is_array($result[0])) {
  640. foreach ($result[0] as $field => $value) {
  641. if (strpos($field, $this->virtualFieldSeparator) === false) {
  642. continue;
  643. }
  644. list($alias, $virtual) = explode($this->virtualFieldSeparator, $field);
  645. if (!ClassRegistry::isKeySet($alias)) {
  646. return;
  647. }
  648. $model = ClassRegistry::getObject($alias);
  649. if ($model->isVirtualField($virtual)) {
  650. $result[$alias][$virtual] = $value;
  651. unset($result[0][$field]);
  652. }
  653. }
  654. if (empty($result[0])) {
  655. unset($result[0]);
  656. }
  657. }
  658. }
  659. /**
  660. * Returns a single field of the first of query results for a given SQL query, or false if empty.
  661. *
  662. * @param string $name Name of the field
  663. * @param string $sql SQL query
  664. * @return mixed Value of field read.
  665. */
  666. public function field($name, $sql) {
  667. $data = $this->fetchRow($sql);
  668. if (empty($data[$name])) {
  669. return false;
  670. }
  671. return $data[$name];
  672. }
  673. /**
  674. * Empties the method caches.
  675. * These caches are used by DboSource::name() and DboSource::conditions()
  676. *
  677. * @return void
  678. */
  679. public function flushMethodCache() {
  680. $this->methodCache = array();
  681. }
  682. /**
  683. * Cache a value into the methodCaches. Will respect the value of DboSource::$cacheMethods.
  684. * Will retrieve a value from the cache if $value is null.
  685. *
  686. * If caching is disabled and a write is attempted, the $value will be returned.
  687. * A read will either return the value or null.
  688. *
  689. * @param string $method Name of the method being cached.
  690. * @param string $key The keyname for the cache operation.
  691. * @param mixed $value The value to cache into memory.
  692. * @return mixed Either null on failure, or the value if its set.
  693. */
  694. public function cacheMethod($method, $key, $value = null) {
  695. if ($this->cacheMethods === false) {
  696. return $value;
  697. }
  698. if ($value === null) {
  699. return (isset($this->methodCache[$method][$key])) ? $this->methodCache[$method][$key] : null;
  700. }
  701. return $this->methodCache[$method][$key] = $value;
  702. }
  703. /**
  704. * Returns a quoted name of $data for use in an SQL statement.
  705. * Strips fields out of SQL functions before quoting.
  706. *
  707. * Results of this method are stored in a memory cache. This improves performance, but
  708. * because the method uses a simple hashing algorithm it can infrequently have collisions.
  709. * Setting DboSource::$cacheMethods to false will disable the memory cache.
  710. *
  711. * @param mixed $data Either a string with a column to quote. An array of columns to quote or an
  712. * object from DboSource::expression() or DboSource::identifier()
  713. * @return string SQL field
  714. */
  715. public function name($data) {
  716. if (is_object($data) && isset($data->type)) {
  717. return $data->value;
  718. }
  719. if ($data === '*') {
  720. return '*';
  721. }
  722. if (is_array($data)) {
  723. foreach ($data as $i => $dataItem) {
  724. $data[$i] = $this->name($dataItem);
  725. }
  726. return $data;
  727. }
  728. $cacheKey = crc32($this->startQuote.$data.$this->endQuote);
  729. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  730. return $return;
  731. }
  732. $data = trim($data);
  733. if (preg_match('/^[\w-]+(?:\.[^ \*]*)*$/', $data)) { // string, string.string
  734. if (strpos($data, '.') === false) { // string
  735. return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
  736. }
  737. $items = explode('.', $data);
  738. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  739. $this->startQuote . implode($this->endQuote . '.' . $this->startQuote, $items) . $this->endQuote
  740. );
  741. }
  742. if (preg_match('/^[\w-]+\.\*$/', $data)) { // string.*
  743. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  744. $this->startQuote . str_replace('.*', $this->endQuote . '.*', $data)
  745. );
  746. }
  747. if (preg_match('/^([\w-]+)\((.*)\)$/', $data, $matches)) { // Functions
  748. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  749. $matches[1] . '(' . $this->name($matches[2]) . ')'
  750. );
  751. }
  752. if (
  753. preg_match('/^([\w-]+(\.[\w-]+|\(.*\))*)\s+' . preg_quote($this->alias) . '\s*([\w-]+)$/i', $data, $matches
  754. )) {
  755. return $this->cacheMethod(
  756. __FUNCTION__, $cacheKey,
  757. preg_replace(
  758. '/\s{2,}/', ' ', $this->name($matches[1]) . ' ' . $this->alias . ' ' . $this->name($matches[3])
  759. )
  760. );
  761. }
  762. if (preg_match('/^[\w-_\s]*[\w-_]+/', $data)) {
  763. return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
  764. }
  765. return $this->cacheMethod(__FUNCTION__, $cacheKey, $data);
  766. }
  767. /**
  768. * Checks if the source is connected to the database.
  769. *
  770. * @return boolean True if the database is connected, else false
  771. */
  772. public function isConnected() {
  773. return $this->connected;
  774. }
  775. /**
  776. * Checks if the result is valid
  777. *
  778. * @return boolean True if the result is valid else false
  779. */
  780. public function hasResult() {
  781. return is_a($this->_result, 'PDOStatement');
  782. }
  783. /**
  784. * Get the query log as an array.
  785. *
  786. * @param boolean $sorted Get the queries sorted by time taken, defaults to false.
  787. * @param boolean $clear If True the existing log will cleared.
  788. * @return array Array of queries run as an array
  789. */
  790. public function getLog($sorted = false, $clear = true) {
  791. if ($sorted) {
  792. $log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC);
  793. } else {
  794. $log = $this->_queriesLog;
  795. }
  796. if ($clear) {
  797. $this->_queriesLog = array();
  798. }
  799. return array('log' => $log, 'count' => $this->_queriesCnt, 'time' => $this->_queriesTime);
  800. }
  801. /**
  802. * Outputs the contents of the queries log. If in a non-CLI environment the sql_log element
  803. * will be rendered and output. If in a CLI environment, a plain text log is generated.
  804. *
  805. * @param boolean $sorted Get the queries sorted by time taken, defaults to false.
  806. * @return void
  807. */
  808. public function showLog($sorted = false) {
  809. $log = $this->getLog($sorted, false);
  810. if (empty($log['log'])) {
  811. return;
  812. }
  813. if (PHP_SAPI != 'cli') {
  814. $controller = null;
  815. $View = new View($controller, false);
  816. $View->set('logs', array($this->configKeyName => $log));
  817. echo $View->element('sql_dump', array('_forced_from_dbo_' => true));
  818. } else {
  819. foreach ($log['log'] as $k => $i) {
  820. print (($k + 1) . ". {$i['query']} {$i['error']}\n");
  821. }
  822. }
  823. }
  824. /**
  825. * Log given SQL query.
  826. *
  827. * @param string $sql SQL statement
  828. * @todo: Add hook to log errors instead of returning false
  829. */
  830. public function logQuery($sql) {
  831. $this->_queriesCnt++;
  832. $this->_queriesTime += $this->took;
  833. $this->_queriesLog[] = array(
  834. 'query' => $sql,
  835. 'error' => $this->error,
  836. 'affected' => $this->affected,
  837. 'numRows' => $this->numRows,
  838. 'took' => $this->took
  839. );
  840. if (count($this->_queriesLog) > $this->_queriesLogMax) {
  841. array_pop($this->_queriesLog);
  842. }
  843. if ($this->error) {
  844. return false;
  845. }
  846. }
  847. /**
  848. * Output information about an SQL query. The SQL statement, number of rows in resultset,
  849. * and execution time in microseconds. If the query fails, an error is output instead.
  850. *
  851. * @param string $sql Query to show information on.
  852. */
  853. public function showQuery($sql) {
  854. $error = $this->error;
  855. if (strlen($sql) > 200 && !$this->fullDebug && Configure::read('debug') > 1) {
  856. $sql = substr($sql, 0, 200) . '[...]';
  857. }
  858. if (Configure::read('debug') > 0) {
  859. $out = null;
  860. if ($error) {
  861. trigger_error('<span style="color:Red;text-align:left"><b>' . __d('cake_dev', 'SQL Error:') . "</b> {$this->error}</span>", E_USER_WARNING);
  862. } else {
  863. $out = ('<small>[' . __d('cake_dev', 'Aff:%s Num:%s Took:%sms', $this->affected, $this->numRows, $this->took) . ']</small>');
  864. }
  865. pr(sprintf('<p style="text-align:left"><b>' . __d('cake_dev', 'Query:') . '</b> %s %s</p>', $sql, $out));
  866. }
  867. }
  868. /**
  869. * Gets full table name including prefix
  870. *
  871. * @param mixed $model Either a Model object or a string table name.
  872. * @param boolean $quote Whether you want the table name quoted.
  873. * @return string Full quoted table name
  874. */
  875. public function fullTableName($model, $quote = true) {
  876. if (is_object($model)) {
  877. $table = $model->tablePrefix . $model->table;
  878. } elseif (isset($this->config['prefix'])) {
  879. $table = $this->config['prefix'] . strval($model);
  880. } else {
  881. $table = strval($model);
  882. }
  883. if ($quote) {
  884. return $this->name($table);
  885. }
  886. return $table;
  887. }
  888. /**
  889. * The "C" in CRUD
  890. *
  891. * Creates new records in the database.
  892. *
  893. * @param Model $model Model object that the record is for.
  894. * @param array $fields An array of field names to insert. If null, $model->data will be
  895. * used to generate field names.
  896. * @param array $values An array of values with keys matching the fields. If null, $model->data will
  897. * be used to generate values.
  898. * @return boolean Success
  899. */
  900. public function create($model, $fields = null, $values = null) {
  901. $id = null;
  902. if ($fields == null) {
  903. unset($fields, $values);
  904. $fields = array_keys($model->data);
  905. $values = array_values($model->data);
  906. }
  907. $count = count($fields);
  908. for ($i = 0; $i < $count; $i++) {
  909. $valueInsert[] = $this->value($values[$i], $model->getColumnType($fields[$i]), false);
  910. }
  911. for ($i = 0; $i < $count; $i++) {
  912. $fieldInsert[] = $this->name($fields[$i]);
  913. if ($fields[$i] == $model->primaryKey) {
  914. $id = $values[$i];
  915. }
  916. }
  917. $query = array(
  918. 'table' => $this->fullTableName($model),
  919. 'fields' => implode(', ', $fieldInsert),
  920. 'values' => implode(', ', $valueInsert)
  921. );
  922. if ($this->execute($this->renderStatement('create', $query))) {
  923. if (empty($id)) {
  924. $id = $this->lastInsertId($this->fullTableName($model, false), $model->primaryKey);
  925. }
  926. $model->setInsertID($id);
  927. $model->id = $id;
  928. return true;
  929. }
  930. $model->onError();
  931. return false;
  932. }
  933. /**
  934. * The "R" in CRUD
  935. *
  936. * Reads record(s) from the database.
  937. *
  938. * @param Model $model A Model object that the query is for.
  939. * @param array $queryData An array of queryData information containing keys similar to Model::find()
  940. * @param integer $recursive Number of levels of association
  941. * @return mixed boolean false on error/failure. An array of results on success.
  942. */
  943. public function read($model, $queryData = array(), $recursive = null) {
  944. $queryData = $this->__scrubQueryData($queryData);
  945. $null = null;
  946. $array = array();
  947. $linkedModels = array();
  948. $this->__bypass = false;
  949. if ($recursive === null && isset($queryData['recursive'])) {
  950. $recursive = $queryData['recursive'];
  951. }
  952. if (!is_null($recursive)) {
  953. $_recursive = $model->recursive;
  954. $model->recursive = $recursive;
  955. }
  956. if (!empty($queryData['fields'])) {
  957. $this->__bypass = true;
  958. $queryData['fields'] = $this->fields($model, null, $queryData['fields']);
  959. } else {
  960. $queryData['fields'] = $this->fields($model);
  961. }
  962. $_associations = $model->associations();
  963. if ($model->recursive == -1) {
  964. $_associations = array();
  965. } elseif ($model->recursive == 0) {
  966. unset($_associations[2], $_associations[3]);
  967. }
  968. foreach ($_associations as $type) {
  969. foreach ($model->{$type} as $assoc => $assocData) {
  970. $linkModel = $model->{$assoc};
  971. $external = isset($assocData['external']);
  972. $linkModel->getDataSource();
  973. if ($model->useDbConfig === $linkModel->useDbConfig) {
  974. if (true === $this->generateAssociationQuery($model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null)) {
  975. $linkedModels[$type . '/' . $assoc] = true;
  976. }
  977. }
  978. }
  979. }
  980. $query = trim($this->generateAssociationQuery($model, null, null, null, null, $queryData, false, $null));
  981. $resultSet = $this->fetchAll($query, $model->cacheQueries);
  982. if ($resultSet === false) {
  983. $model->onError();
  984. return false;
  985. }
  986. $filtered = $this->_filterResults($resultSet, $model);
  987. if ($model->recursive > -1) {
  988. foreach ($_associations as $type) {
  989. foreach ($model->{$type} as $assoc => $assocData) {
  990. $linkModel = $model->{$assoc};
  991. if (!isset($linkedModels[$type . '/' . $assoc])) {
  992. if ($model->useDbConfig === $linkModel->useDbConfig) {
  993. $db = $this;
  994. } else {
  995. $db = ConnectionManager::getDataSource($linkModel->useDbConfig);
  996. }
  997. } elseif ($model->recursive > 1 && ($type === 'belongsTo' || $type === 'hasOne')) {
  998. $db = $this;
  999. }
  1000. if (isset($db) && method_exists($db, 'queryAssociation')) {
  1001. $stack = array($assoc);
  1002. $db->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $array, true, $resultSet, $model->recursive - 1, $stack);
  1003. unset($db);
  1004. if ($type === 'hasMany') {
  1005. $filtered[] = $assoc;
  1006. }
  1007. }
  1008. }
  1009. }
  1010. $this->_filterResults($resultSet, $model, $filtered);
  1011. }
  1012. if (!is_null($recursive)) {
  1013. $model->recursive = $_recursive;
  1014. }
  1015. return $resultSet;
  1016. }
  1017. /**
  1018. * Passes association results thru afterFind filters of corresponding model
  1019. *
  1020. * @param array $results Reference of resultset to be filtered
  1021. * @param object $model Instance of model to operate against
  1022. * @param array $filtered List of classes already filtered, to be skipped
  1023. * @return array Array of results that have been filtered through $model->afterFind
  1024. */
  1025. protected function _filterResults(&$results, Model $model, $filtered = array()) {
  1026. $current = current($results);
  1027. if (!is_array($current)) {
  1028. return array();
  1029. }
  1030. $keys = array_diff(array_keys($current), $filtered, array($model->alias));
  1031. $filtering = array();
  1032. foreach ($keys as $className) {
  1033. if (!isset($model->{$className}) || !is_object($model->{$className})) {
  1034. continue;
  1035. }
  1036. $linkedModel = $model->{$className};
  1037. $filtering[] = $className;
  1038. foreach ($results as &$result) {
  1039. $data = $linkedModel->afterFind(array(array($className => $result[$className])), false);
  1040. if (isset($data[0][$className])) {
  1041. $result[$className] = $data[0][$className];
  1042. }
  1043. }
  1044. }
  1045. return $filtering;
  1046. }
  1047. /**
  1048. * Queries associations. Used to fetch results on recursive models.
  1049. *
  1050. * @param Model $model Primary Model object
  1051. * @param Model $linkModel Linked model that
  1052. * @param string $type Association type, one of the model association types ie. hasMany
  1053. * @param unknown_type $association
  1054. * @param unknown_type $assocData
  1055. * @param array $queryData
  1056. * @param boolean $external Whether or not the association query is on an external datasource.
  1057. * @param array $resultSet Existing results
  1058. * @param integer $recursive Number of levels of association
  1059. * @param array $stack
  1060. */
  1061. public function queryAssociation($model, &$linkModel, $type, $association, $assocData, &$queryData, $external = false, &$resultSet, $recursive, $stack) {
  1062. if ($query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet)) {
  1063. if (!is_array($resultSet)) {
  1064. if (Configure::read('debug') > 0) {
  1065. echo '<div style = "font: Verdana bold 12px; color: #FF0000">' . __d('cake_dev', 'SQL Error in model %s:', $model->alias) . ' ';
  1066. if (isset($this->error) && $this->error != null) {
  1067. echo $this->error;
  1068. }
  1069. echo '</div>';
  1070. }
  1071. return null;
  1072. }
  1073. if ($type === 'hasMany' && empty($assocData['limit']) && !empty($assocData['foreignKey'])) {
  1074. $ins = $fetch = array();
  1075. foreach ($resultSet as &$result) {
  1076. if ($in = $this->insertQueryData('{$__cakeID__$}', $result, $association, $assocData, $model, $linkModel, $stack)) {
  1077. $ins[] = $in;
  1078. }
  1079. }
  1080. if (!empty($ins)) {
  1081. $ins = array_unique($ins);
  1082. $fetch = $this->fetchAssociated($model, $query, $ins);
  1083. }
  1084. if (!empty($fetch) && is_array($fetch)) {
  1085. if ($recursive > 0) {
  1086. foreach ($linkModel->associations() as $type1) {
  1087. foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
  1088. $deepModel = $linkModel->{$assoc1};
  1089. $tmpStack = $stack;
  1090. $tmpStack[] = $assoc1;
  1091. if ($linkModel->useDbConfig === $deepModel->useDbConfig) {
  1092. $db = $this;
  1093. } else {
  1094. $db = ConnectionManager::getDataSource($deepModel->useDbConfig);
  1095. }
  1096. $db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
  1097. }
  1098. }
  1099. }
  1100. }
  1101. $this->_filterResults($fetch, $model);
  1102. return $this->__mergeHasMany($resultSet, $fetch, $association, $model, $linkModel);
  1103. } elseif ($type === 'hasAndBelongsToMany') {
  1104. $ins = $fetch = array();
  1105. foreach ($resultSet as &$result) {
  1106. if ($in = $this->insertQueryData('{$__cakeID__$}', $result, $association, $assocData, $model, $linkModel, $stack)) {
  1107. $ins[] = $in;
  1108. }
  1109. }
  1110. if (!empty($ins)) {
  1111. $ins = array_unique($ins);
  1112. if (count($ins) > 1) {
  1113. $query = str_replace('{$__cakeID__$}', '(' .implode(', ', $ins) .')', $query);
  1114. $query = str_replace('= (', 'IN (', $query);
  1115. } else {
  1116. $query = str_replace('{$__cakeID__$}', $ins[0], $query);
  1117. }
  1118. $query = str_replace(' WHERE 1 = 1', '', $query);
  1119. }
  1120. $foreignKey = $model->hasAndBelongsToMany[$association]['foreignKey'];
  1121. $joinKeys = array($foreignKey, $model->hasAndBelongsToMany[$association]['associationForeignKey']);
  1122. list($with, $habtmFields) = $model->joinModel($model->hasAndBelongsToMany[$association]['with'], $joinKeys);
  1123. $habtmFieldsCount = count($habtmFields);
  1124. $q = $this->insertQueryData($query, null, $association, $assocData, $model, $linkModel, $stack);
  1125. if ($q !== false) {
  1126. $fetch = $this->fetchAll($q, $model->cacheQueries);
  1127. } else {
  1128. $fetch = null;
  1129. }
  1130. }
  1131. $modelAlias = $model->alias;
  1132. $modelPK = $model->primaryKey;
  1133. foreach ($resultSet as &$row) {
  1134. if ($type !== 'hasAndBelongsToMany') {
  1135. $q = $this->insertQueryData($query, $row, $association, $assocData, $model, $linkModel, $stack);
  1136. if ($q !== false) {
  1137. $fetch = $this->fetchAll($q, $model->cacheQueries);
  1138. } else {
  1139. $fetch = null;
  1140. }
  1141. }
  1142. $selfJoin = $linkModel->name === $model->name;
  1143. if (!empty($fetch) && is_array($fetch)) {
  1144. if ($recursive > 0) {
  1145. foreach ($linkModel->associations() as $type1) {
  1146. foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
  1147. $deepModel = $linkModel->{$assoc1};
  1148. if ($type1 === 'belongsTo' || ($deepModel->alias === $modelAlias && $type === 'belongsTo') || ($deepModel->alias !== $modelAlias)) {
  1149. $tmpStack = $stack;
  1150. $tmpStack[] = $assoc1;
  1151. if ($linkModel->useDbConfig == $deepModel->useDbConfig) {
  1152. $db = $this;
  1153. } else {
  1154. $db = ConnectionManager::getDataSource($deepModel->useDbConfig);
  1155. }
  1156. $db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
  1157. }
  1158. }
  1159. }
  1160. }
  1161. if ($type === 'hasAndBelongsToMany') {
  1162. $uniqueIds = $merge = array();
  1163. foreach ($fetch as $j => $data) {
  1164. if (isset($data[$with]) && $data[$with][$foreignKey] === $row[$modelAlias][$modelPK]) {
  1165. if ($habtmFieldsCount <= 2) {
  1166. unset($data[$with]);
  1167. }
  1168. $merge[] = $data;
  1169. }
  1170. }
  1171. if (empty($merge) && !isset($row[$association])) {
  1172. $row[$association] = $merge;
  1173. } else {
  1174. $this->__mergeAssociation($row, $merge, $association, $type);
  1175. }
  1176. } else {
  1177. $this->__mergeAssociation($row, $fetch, $association, $type, $selfJoin);
  1178. }
  1179. if (isset($row[$association])) {
  1180. $row[$association] = $linkModel->afterFind($row[$association], false);
  1181. }
  1182. } else {
  1183. $tempArray[0][$association] = false;
  1184. $this->__mergeAssociation($row, $tempArray, $association, $type, $selfJoin);
  1185. }
  1186. }
  1187. }
  1188. }
  1189. /**
  1190. * A more efficient way to fetch associations. Woohoo!
  1191. *
  1192. * @param model $model Primary model object
  1193. * @param string $query Association query
  1194. * @param array $ids Array of IDs of associated records
  1195. * @return array Association results
  1196. */
  1197. public function fetchAssociated($model, $query, $ids) {
  1198. $query = str_replace('{$__cakeID__$}', implode(', ', $ids), $query);
  1199. if (count($ids) > 1) {
  1200. $query = str_replace('= (', 'IN (', $query);
  1201. }
  1202. return $this->fetchAll($query, $model->cacheQueries);
  1203. }
  1204. /**
  1205. * mergeHasMany - Merge the results of hasMany relations.
  1206. *
  1207. *
  1208. * @param array $resultSet Data to merge into
  1209. * @param array $merge Data to merge
  1210. * @param string $association Name of Model being Merged
  1211. * @param object $model Model being merged onto
  1212. * @param object $linkModel Model being merged
  1213. * @return void
  1214. */
  1215. function __mergeHasMany(&$resultSet, $merge, $association, $model, $linkModel) {
  1216. $modelAlias = $model->alias;
  1217. $modelPK = $model->primaryKey;
  1218. $modelFK = $model->hasMany[$association]['foreignKey'];
  1219. foreach ($resultSet as &$result) {
  1220. if (!isset($result[$modelAlias])) {
  1221. continue;
  1222. }
  1223. $merged = array();
  1224. foreach ($merge as $data) {
  1225. if ($result[$modelAlias][$modelPK] === $data[$association][$modelFK]) {
  1226. if (count($data) > 1) {
  1227. $data = array_merge($data[$association], $data);
  1228. unset($data[$association]);
  1229. foreach ($data as $key => $name) {
  1230. if (is_numeric($key)) {
  1231. $data[$association][] = $name;
  1232. unset($data[$key]);
  1233. }
  1234. }
  1235. $merged[] = $data;
  1236. } else {
  1237. $merged[] = $data[$association];
  1238. }
  1239. }
  1240. }
  1241. $result = Set::pushDiff($result, array($association => $merged));
  1242. }
  1243. }
  1244. /**
  1245. * Enter description here...
  1246. *
  1247. * @param unknown_type $data
  1248. * @param unknown_type $merge
  1249. * @param unknown_type $association
  1250. * @param unknown_type $type
  1251. * @param boolean $selfJoin
  1252. * @access private
  1253. */
  1254. function __mergeAssociation(&$data, &$merge, $association, $type, $selfJoin = false) {
  1255. if (isset($merge[0]) && !isset($merge[0][$association])) {
  1256. $association = Inflector::pluralize($association);
  1257. }
  1258. if ($type === 'belongsTo' || $type === 'hasOne') {
  1259. if (isset($merge[$association])) {
  1260. $data[$association] = $merge[$association][0];
  1261. } else {
  1262. if (count($merge[0][$association]) > 1) {
  1263. foreach ($merge[0] as $assoc => $data2) {
  1264. if ($assoc !== $association) {
  1265. $merge[0][$association][$assoc] = $data2;
  1266. }
  1267. }
  1268. }
  1269. if (!isset($data[$association])) {
  1270. if ($merge[0][$association] != null) {
  1271. $data[$association] = $merge[0][$association];
  1272. } else {
  1273. $data[$association] = array();
  1274. }
  1275. } else {
  1276. if (is_array($merge[0][$association])) {
  1277. foreach ($data[$association] as $k => $v) {
  1278. if (!is_array($v)) {
  1279. $dataAssocTmp[$k] = $v;
  1280. }
  1281. }
  1282. foreach ($merge[0][$association] as $k => $v) {
  1283. if (!is_array($v)) {
  1284. $mergeAssocTmp[$k] = $v;
  1285. }
  1286. }
  1287. $dataKeys = array_keys($data);
  1288. $mergeKeys = array_keys($merge[0]);
  1289. if ($mergeKeys[0] === $dataKeys[0] || $mergeKeys === $dataKeys) {
  1290. $data[$association][$association] = $merge[0][$association];
  1291. } else {
  1292. $diff = Set::diff($dataAssocTmp, $mergeAssocTmp);
  1293. $data[$association] = array_merge($merge[0][$association], $diff);
  1294. }
  1295. } elseif ($selfJoin && array_key_exists($association, $merge[0])) {
  1296. $data[$association] = array_merge($data[$association], array($association => array()));
  1297. }
  1298. }
  1299. }
  1300. } else {
  1301. if (isset($merge[0][$association]) && $merge[0][$association] === false) {
  1302. if (!isset($data[$association])) {
  1303. $data[$association] = array();
  1304. }
  1305. } else {
  1306. foreach ($merge as $i => $row) {
  1307. if (count($row) === 1) {
  1308. if (empty($data[$association]) || (isset($data[$association]) && !in_array($row[$association], $data[$association]))) {
  1309. $data[$association][] = $row[$association];
  1310. }
  1311. } elseif (!empty($row)) {
  1312. $tmp = array_merge($row[$association], $row);
  1313. unset($tmp[$association]);
  1314. $data[$association][] = $tmp;
  1315. }
  1316. }
  1317. }
  1318. }
  1319. }
  1320. /**
  1321. * Generates an array representing a query or part of a query from a single model or two associated models
  1322. *
  1323. * @param Model $model
  1324. * @param Model $linkModel
  1325. * @param string $type
  1326. * @param string $association
  1327. * @param array $assocData
  1328. * @param array $queryData
  1329. * @param boolean $external
  1330. * @param array $resultSet
  1331. * @return mixed
  1332. */
  1333. public function generateAssociationQuery($model, $linkModel, $type, $association = null, $assocData = array(), &$queryData, $external = false, &$resultSet) {
  1334. $queryData = $this->__scrubQueryData($queryData);
  1335. $assocData = $this->__scrubQueryData($assocData);
  1336. $modelAlias = $model->alias;
  1337. if (empty($queryData['fields'])) {
  1338. $queryData['fields'] = $this->fields($model, $modelAlias);
  1339. } elseif (!empty($model->hasMany) && $model->recursive > -1) {
  1340. $assocFields = $this->fields($model, $modelAlias, array("{$modelAlias}.{$model->primaryKey}"));
  1341. $passedFields = $this->fields($model, $modelAlias, $queryData['fields']);
  1342. if (count($passedFields) === 1) {
  1343. if (strpos($passedFields[0], $assocFields[0]) === false && !preg_match('/^[a-z]+\(/i', $passedFields[0])) {
  1344. $queryData['fields'] = array_merge($passedFields, $assocFields);
  1345. } else {
  1346. $queryData['fields'] = $passedFields;
  1347. }
  1348. } else {
  1349. $queryData['fields'] = array_merge($passedFields, $assocFields);
  1350. }
  1351. unset($assocFields, $passedFields);
  1352. }
  1353. if ($linkModel === null) {
  1354. return $this->buildStatement(
  1355. array(
  1356. 'fields' => array_unique($queryData['fields']),
  1357. 'table' => $this->fullTableName($model),
  1358. 'alias' => $modelAlias,
  1359. 'limit' => $queryData['limit'],
  1360. 'offset' => $queryData['offset'],
  1361. 'joins' => $queryData['joins'],
  1362. 'conditions' => $queryData['conditions'],
  1363. 'order' => $queryData['order'],
  1364. 'group' => $queryData['group']
  1365. ),
  1366. $model
  1367. );
  1368. }
  1369. if ($external && !empty($assocData['finderQuery'])) {
  1370. return $assocData['finderQuery'];
  1371. }
  1372. $self = $model->name === $linkModel->name;
  1373. $fields = array();
  1374. if ($external || (in_array($type, array('hasOne', 'belongsTo')) && $this->__bypass === false)) {
  1375. $fields = $this->fields($linkModel, $association, $assocData['fields']);
  1376. }
  1377. if (empty($assocData['offset']) && !empty($assocData['page'])) {
  1378. $assocData['offset'] = ($assocData['page'] - 1) * $assocData['limit'];
  1379. }
  1380. $assocData['limit'] = $this->limit($assocData['limit'], $assocData['offset']);
  1381. switch ($type) {
  1382. case 'hasOne':
  1383. case 'belongsTo':
  1384. $conditions = $this->__mergeConditions(
  1385. $assocData['conditions'],
  1386. $this->getConstraint($type, $model, $linkModel, $association, array_merge($assocData, compact('external', 'self')))
  1387. );
  1388. if (!$self && $external) {
  1389. foreach ($conditions as $key => $condition) {
  1390. if (is_numeric($key) && strpos($condition, $modelAlias . '.') !== false) {
  1391. unset($conditions[$key]);
  1392. }
  1393. }
  1394. }
  1395. if ($external) {
  1396. $query = array_merge($assocData, array(
  1397. 'conditions' => $conditions,
  1398. 'table' => $this->fullTableName($linkModel),
  1399. 'fields' => $fields,
  1400. 'alias' => $association,
  1401. 'group' => null
  1402. ));
  1403. $query += array('order' => $assocData['order'], 'limit' => $assocData['limit']);
  1404. } else {
  1405. $join = array(
  1406. 'table' => $this->fullTableName($linkModel),
  1407. 'alias' => $association,
  1408. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1409. 'conditions' => trim($this->conditions($conditions, true, false, $model))
  1410. );
  1411. $queryData['fields'] = array_merge($queryData['fields'], $fields);
  1412. if (!empty($assocData['order'])) {
  1413. $queryData['order'][] = $assocData['order'];
  1414. }
  1415. if (!in_array($join, $queryData['joins'])) {
  1416. $queryData['joins'][] = $join;
  1417. }
  1418. return true;
  1419. }
  1420. break;
  1421. case 'hasMany':
  1422. $assocData['fields'] = $this->fields($linkModel, $association, $assocData['fields']);
  1423. if (!empty($assocData['foreignKey'])) {
  1424. $assocData['fields'] = array_merge($assocData['fields'], $this->fields($linkModel, $association, array("{$association}.{$assocData['foreignKey']}")));
  1425. }
  1426. $query = array(
  1427. 'conditions' => $this->__mergeConditions($this->getConstraint('hasMany', $model, $linkModel, $association, $assocData), $assocData['conditions']),
  1428. 'fields' => array_unique($assocData['fields']),
  1429. 'table' => $this->fullTableName($linkModel),
  1430. 'alias' => $association,
  1431. 'order' => $assocData['order'],
  1432. 'limit' => $assocData['limit'],
  1433. 'group' => null
  1434. );
  1435. break;
  1436. case 'hasAndBelongsToMany':
  1437. $joinFields = array();
  1438. $joinAssoc = null;
  1439. if (isset($assocData['with']) && !empty($assocData['with'])) {
  1440. $joinKeys = array($assocData['foreignKey'], $assocData['associationForeignKey']);
  1441. list($with, $joinFields) = $model->joinModel($assocData['with'], $joinKeys);
  1442. $joinTbl = $this->fullTableName($model->{$with});
  1443. $joinAlias = $joinTbl;
  1444. if (is_array($joinFields) && !empty($joinFields)) {
  1445. $joinAssoc = $joinAlias = $model->{$with}->alias;
  1446. $joinFields = $this->fields($model->{$with}, $joinAlias, $joinFields);
  1447. } else {
  1448. $joinFields = array();
  1449. }
  1450. } else {
  1451. $joinTbl = $this->fullTableName($assocData['joinTable']);
  1452. $joinAlias = $joinTbl;
  1453. }
  1454. $query = array(
  1455. 'conditions' => $assocData['conditions'],
  1456. 'limit' => $assocData['limit'],
  1457. 'table' => $this->fullTableName($linkModel),
  1458. 'alias' => $association,
  1459. 'fields' => array_merge($this->fields($linkModel, $association, $assocData['fields']), $joinFields),
  1460. 'order' => $assocData['order'],
  1461. 'group' => null,
  1462. 'joins' => array(array(
  1463. 'table' => $joinTbl,
  1464. 'alias' => $joinAssoc,
  1465. 'conditions' => $this->getConstraint('hasAndBelongsToMany', $model, $linkModel, $joinAlias, $assocData, $association)
  1466. ))
  1467. );
  1468. break;
  1469. }
  1470. if (isset($query)) {
  1471. return $this->buildStatement($query, $model);
  1472. }
  1473. return null;
  1474. }
  1475. /**
  1476. * Returns a conditions array for the constraint between two models
  1477. *
  1478. * @param string $type Association type
  1479. * @param object $model Model object
  1480. * @param array $association Association array
  1481. * @return array Conditions array defining the constraint between $model and $association
  1482. */
  1483. public function getConstraint($type, $model, $linkModel, $alias, $assoc, $alias2 = null) {
  1484. $assoc += array('external' => false, 'self' => false);
  1485. if (empty($assoc['foreignKey'])) {
  1486. return array();
  1487. }
  1488. switch (true) {
  1489. case ($assoc['external'] && $type === 'hasOne'):
  1490. return array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}');
  1491. case ($assoc['external'] && $type === 'belongsTo'):
  1492. return array("{$alias}.{$linkModel->primaryKey}" => '{$__cakeForeignKey__$}');
  1493. case (!$assoc['external'] && $type === 'hasOne'):
  1494. return array("{$alias}.{$assoc['foreignKey']}" => $this->identifier("{$model->alias}.{$model->primaryKey}"));
  1495. case (!$assoc['external'] && $type === 'belongsTo'):
  1496. return array("{$model->alias}.{$assoc['foreignKey']}" => $this->identifier("{$alias}.{$linkModel->primaryKey}"));
  1497. case ($type === 'hasMany'):
  1498. return array("{$alias}.{$assoc['foreignKey']}" => array('{$__cakeID__$}'));
  1499. case ($type === 'hasAndBelongsToMany'):
  1500. return array(
  1501. array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}'),
  1502. array("{$alias}.{$assoc['associationForeignKey']}" => $this->identifier("{$alias2}.{$linkModel->primaryKey}"))
  1503. );
  1504. }
  1505. return array();
  1506. }
  1507. /**
  1508. * Builds and generates a JOIN statement from an array. Handles final clean-up before conversion.
  1509. *
  1510. * @param array $join An array defining a JOIN statement in a query
  1511. * @return string An SQL JOIN statement to be used in a query
  1512. * @access public
  1513. * @see DboSource::renderJoinStatement()
  1514. * @see DboSource::buildStatement()
  1515. */
  1516. public function buildJoinStatement($join) {
  1517. $data = array_merge(array(
  1518. 'type' => null,
  1519. 'alias' => null,
  1520. 'table' => 'join_table',
  1521. 'conditions' => array()
  1522. ), $join);
  1523. if (!empty($data['alias'])) {
  1524. $data['alias'] = $this->alias . $this->name($data['alias']);
  1525. }
  1526. if (!empty($data['conditions'])) {
  1527. $data['conditions'] = trim($this->conditions($data['conditions'], true, false));
  1528. }
  1529. return $this->renderJoinStatement($data);
  1530. }
  1531. /**
  1532. * Builds and generates an SQL statement from an array. Handles final clean-up before conversion.
  1533. *
  1534. * @param array $query An array defining an SQL query
  1535. * @param object $model The model object which initiated the query
  1536. * @return string An executable SQL statement
  1537. * @access public
  1538. * @see DboSource::renderStatement()
  1539. */
  1540. public function buildStatement($query, $model) {
  1541. $query = array_merge(array('offset' => null, 'joins' => array()), $query);
  1542. if (!empty($query['joins'])) {
  1543. $count = count($query['joins']);
  1544. for ($i = 0; $i < $count; $i++) {
  1545. if (is_array($query['joins'][$i])) {
  1546. $query['joins'][$i] = $this->buildJoinStatement($query['joins'][$i]);
  1547. }
  1548. }
  1549. }
  1550. return $this->renderStatement('select', array(
  1551. 'conditions' => $this->conditions($query['conditions'], true, true, $model),
  1552. 'fields' => implode(', ', $query['fields']),
  1553. 'table' => $query['table'],
  1554. 'alias' => $this->alias . $this->name($query['alias']),
  1555. 'order' => $this->order($query['order'], 'ASC', $model),
  1556. 'limit' => $this->limit($query['limit'], $query['offset']),
  1557. 'joins' => implode(' ', $query['joins']),
  1558. 'group' => $this->group($query['group'], $model)
  1559. ));
  1560. }
  1561. /**
  1562. * Renders a final SQL JOIN statement
  1563. *
  1564. * @param array $data
  1565. * @return string
  1566. */
  1567. public function renderJoinStatement($data) {
  1568. extract($data);
  1569. return trim("{$type} JOIN {$table} {$alias} ON ({$conditions})");
  1570. }
  1571. /**
  1572. * Renders a final SQL statement by putting together the component parts in the correct order
  1573. *
  1574. * @param string $type type of query being run. e.g select, create, update, delete, schema, alter.
  1575. * @param array $data Array of data to insert into the query.
  1576. * @return string Rendered SQL expression to be run.
  1577. */
  1578. public function renderStatement($type, $data) {
  1579. extract($data);
  1580. $aliases = null;
  1581. switch (strtolower($type)) {
  1582. case 'select':
  1583. return "SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}";
  1584. case 'create':
  1585. return "INSERT INTO {$table} ({$fields}) VALUES ({$values})";
  1586. case 'update':
  1587. if (!empty($alias)) {
  1588. $aliases = "{$this->alias}{$alias} {$joins} ";
  1589. }
  1590. return "UPDATE {$table} {$aliases}SET {$fields} {$conditions}";
  1591. case 'delete':
  1592. if (!empty($alias)) {
  1593. $aliases = "{$this->alias}{$alias} {$joins} ";
  1594. }
  1595. return "DELETE {$alias} FROM {$table} {$aliases}{$conditions}";
  1596. case 'schema':
  1597. foreach (array('columns', 'indexes', 'tableParameters') as $var) {
  1598. if (is_array(${$var})) {
  1599. ${$var} = "\t" . join(",\n\t", array_filter(${$var}));
  1600. } else {
  1601. ${$var} = '';
  1602. }
  1603. }
  1604. if (trim($indexes) !== '') {
  1605. $columns .= ',';
  1606. }
  1607. return "CREATE TABLE {$table} (\n{$columns}{$indexes}){$tableParameters};";
  1608. case 'alter':
  1609. return;
  1610. }
  1611. }
  1612. /**
  1613. * Merges a mixed set of string/array conditions
  1614. *
  1615. * @param mixed $query
  1616. * @param mixed $assoc
  1617. * @return array
  1618. */
  1619. private function __mergeConditions($query, $assoc) {
  1620. if (empty($assoc)) {
  1621. return $query;
  1622. }
  1623. if (is_array($query)) {
  1624. return array_merge((array)$assoc, $query);
  1625. }
  1626. if (!empty($query)) {
  1627. $query = array($query);
  1628. if (is_array($assoc)) {
  1629. $query = array_merge($query, $assoc);
  1630. } else {
  1631. $query[] = $assoc;
  1632. }
  1633. return $query;
  1634. }
  1635. return $assoc;
  1636. }
  1637. /**
  1638. * Generates and executes an SQL UPDATE statement for given model, fields, and values.
  1639. * For databases that do not support aliases in UPDATE queries.
  1640. *
  1641. * @param Model $model
  1642. * @param array $fields
  1643. * @param array $values
  1644. * @param mixed $conditions
  1645. * @return boolean Success
  1646. */
  1647. public function update($model, $fields = array(), $values = null, $conditions = null) {
  1648. if ($values == null) {
  1649. $combined = $fields;
  1650. } else {
  1651. $combined = array_combine($fields, $values);
  1652. }
  1653. $fields = implode(', ', $this->_prepareUpdateFields($model, $combined, empty($conditions)));
  1654. $alias = $joins = null;
  1655. $table = $this->fullTableName($model);
  1656. $conditions = $this->_matchRecords($model, $conditions);
  1657. if ($conditions === false) {
  1658. return false;
  1659. }
  1660. $query = compact('table', 'alias', 'joins', 'fields', 'conditions');
  1661. if (!$this->execute($this->renderStatement('update', $query))) {
  1662. $model->onError();
  1663. return false;
  1664. }
  1665. return true;
  1666. }
  1667. /**
  1668. * Quotes and prepares fields and values for an SQL UPDATE statement
  1669. *
  1670. * @param Model $model
  1671. * @param array $fields
  1672. * @param boolean $quoteValues If values should be quoted, or treated as SQL snippets
  1673. * @param boolean $alias Include the model alias in the field name
  1674. * @return array Fields and values, quoted and preparted
  1675. */
  1676. protected function _prepareUpdateFields($model, $fields, $quoteValues = true, $alias = false) {
  1677. $quotedAlias = $this->startQuote . $model->alias . $this->endQuote;
  1678. $updates = array();
  1679. foreach ($fields as $field => $value) {
  1680. if ($alias && strpos($field, '.') === false) {
  1681. $quoted = $model->escapeField($field);
  1682. } elseif (!$alias && strpos($field, '.') !== false) {
  1683. $quoted = $this->name(str_replace($quotedAlias . '.', '', str_replace(
  1684. $model->alias . '.', '', $field
  1685. )));
  1686. } else {
  1687. $quoted = $this->name($field);
  1688. }
  1689. if ($value === null) {
  1690. $updates[] = $quoted . ' = NULL';
  1691. continue;
  1692. }
  1693. $update = $quoted . ' = ';
  1694. if ($quoteValues) {
  1695. $update .= $this->value($value, $model->getColumnType($field), false);
  1696. } elseif (!$alias) {
  1697. $update .= str_replace($quotedAlias . '.', '', str_replace(
  1698. $model->alias . '.', '', $value
  1699. ));
  1700. } else {
  1701. $update .= $value;
  1702. }
  1703. $updates[] = $update;
  1704. }
  1705. return $updates;
  1706. }
  1707. /**
  1708. * Generates and executes an SQL DELETE statement.
  1709. * For databases that do not support aliases in UPDATE queries.
  1710. *
  1711. * @param Model $model
  1712. * @param mixed $conditions
  1713. * @return boolean Success
  1714. */
  1715. public function delete($model, $conditions = null) {
  1716. $alias = $joins = null;
  1717. $table = $this->fullTableName($model);
  1718. $conditions = $this->_matchRecords($model, $conditions);
  1719. if ($conditions === false) {
  1720. return false;
  1721. }
  1722. if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
  1723. $model->onError();
  1724. return false;
  1725. }
  1726. return true;
  1727. }
  1728. /**
  1729. * Gets a list of record IDs for the given conditions. Used for multi-record updates and deletes
  1730. * in databases that do not support aliases in UPDATE/DELETE queries.
  1731. *
  1732. * @param Model $model
  1733. * @param mixed $conditions
  1734. * @return array List of record IDs
  1735. */
  1736. protected function _matchRecords($model, $conditions = null) {
  1737. if ($conditions === true) {
  1738. $conditions = $this->conditions(true);
  1739. } elseif ($conditions === null) {
  1740. $conditions = $this->conditions($this->defaultConditions($model, $conditions, false), true, true, $model);
  1741. } else {
  1742. $noJoin = true;
  1743. foreach ($conditions as $field => $value) {
  1744. $originalField = $field;
  1745. if (strpos($field, '.') !== false) {
  1746. list($alias, $field) = explode('.', $field);
  1747. $field = ltrim($field, $this->startQuote);
  1748. $field = rtrim($field, $this->endQuote);
  1749. }
  1750. if (!$model->hasField($field)) {
  1751. $noJoin = false;
  1752. break;
  1753. }
  1754. if ($field !== $originalField) {
  1755. $conditions[$field] = $value;
  1756. unset($conditions[$originalField]);
  1757. }
  1758. }
  1759. if ($noJoin === true) {
  1760. return $this->conditions($conditions);
  1761. }
  1762. $idList = $model->find('all', array(
  1763. 'fields' => "{$model->alias}.{$model->primaryKey}",
  1764. 'conditions' => $conditions
  1765. ));
  1766. if (empty($idList)) {
  1767. return false;
  1768. }
  1769. $conditions = $this->conditions(array(
  1770. $model->primaryKey => Set::extract($idList, "{n}.{$model->alias}.{$model->primaryKey}")
  1771. ));
  1772. }
  1773. return $conditions;
  1774. }
  1775. /**
  1776. * Returns an array of SQL JOIN fragments from a model's associations
  1777. *
  1778. * @param object $model
  1779. * @return array
  1780. */
  1781. protected function _getJoins($model) {
  1782. $join = array();
  1783. $joins = array_merge($model->getAssociated('hasOne'), $model->getAssociated('belongsTo'));
  1784. foreach ($joins as $assoc) {
  1785. if (isset($model->{$assoc}) && $model->useDbConfig == $model->{$assoc}->useDbConfig && $model->{$assoc}->getDataSource()) {
  1786. $assocData = $model->getAssociated($assoc);
  1787. $join[] = $this->buildJoinStatement(array(
  1788. 'table' => $this->fullTableName($model->{$assoc}),
  1789. 'alias' => $assoc,
  1790. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1791. 'conditions' => trim($this->conditions(
  1792. $this->__mergeConditions($assocData['conditions'], $this->getConstraint($assocData['association'], $model, $model->{$assoc}, $assoc, $assocData)),
  1793. true, false, $model
  1794. ))
  1795. ));
  1796. }
  1797. }
  1798. return $join;
  1799. }
  1800. /**
  1801. * Returns an SQL calculation, i.e. COUNT() or MAX()
  1802. *
  1803. * @param model $model
  1804. * @param string $func Lowercase name of SQL function, i.e. 'count' or 'max'
  1805. * @param array $params Function parameters (any values must be quoted manually)
  1806. * @return string An SQL calculation function
  1807. */
  1808. public function calculate($model, $func, $params = array()) {
  1809. $params = (array)$params;
  1810. switch (strtolower($func)) {
  1811. case 'count':
  1812. if (!isset($params[0])) {
  1813. $params[0] = '*';
  1814. }
  1815. if (!isset($params[1])) {
  1816. $params[1] = 'count';
  1817. }
  1818. if (is_object($model) && $model->isVirtualField($params[0])){
  1819. $arg = $this->__quoteFields($model->getVirtualField($params[0]));
  1820. } else {
  1821. $arg = $this->name($params[0]);
  1822. }
  1823. return 'COUNT(' . $arg . ') AS ' . $this->name($params[1]);
  1824. case 'max':
  1825. case 'min':
  1826. if (!isset($params[1])) {
  1827. $params[1] = $params[0];
  1828. }
  1829. if (is_object($model) && $model->isVirtualField($params[0])) {
  1830. $arg = $this->__quoteFields($model->getVirtualField($params[0]));
  1831. } else {
  1832. $arg = $this->name($params[0]);
  1833. }
  1834. return strtoupper($func) . '(' . $arg . ') AS ' . $this->name($params[1]);
  1835. break;
  1836. }
  1837. }
  1838. /**
  1839. * Deletes all the records in a table and resets the count of the auto-incrementing
  1840. * primary key, where applicable.
  1841. *
  1842. * @param mixed $table A string or model class representing the table to be truncated
  1843. * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
  1844. */
  1845. public function truncate($table) {
  1846. return $this->execute('TRUNCATE TABLE ' . $this->fullTableName($table));
  1847. }
  1848. /**
  1849. * Begin a transaction
  1850. *
  1851. * @return boolean True on success, false on fail
  1852. * (i.e. if the database/model does not support transactions,
  1853. * or a transaction has not started).
  1854. */
  1855. public function begin() {
  1856. if ($this->_transactionStarted || $this->_connection->beginTransaction()) {
  1857. $this->_transactionStarted = true;
  1858. $this->_transactionNesting++;
  1859. return true;
  1860. }
  1861. return false;
  1862. }
  1863. /**
  1864. * Commit a transaction
  1865. *
  1866. * @return boolean True on success, false on fail
  1867. * (i.e. if the database/model does not support transactions,
  1868. * or a transaction has not started).
  1869. */
  1870. public function commit() {
  1871. if ($this->_transactionStarted) {
  1872. $this->_transactionNesting--;
  1873. if ($this->_transactionNesting <= 0) {
  1874. $this->_transactionStarted = false;
  1875. $this->_transactionNesting = 0;
  1876. return $this->_connection->commit();
  1877. }
  1878. return true;
  1879. }
  1880. return false;
  1881. }
  1882. /**
  1883. * Rollback a transaction
  1884. *
  1885. * @return boolean True on success, false on fail
  1886. * (i.e. if the database/model does not support transactions,
  1887. * or a transaction has not started).
  1888. */
  1889. public function rollback() {
  1890. if ($this->_transactionStarted && $this->_connection->rollBack()) {
  1891. $this->_transactionStarted = false;
  1892. $this->_transactionNesting = 0;
  1893. return true;
  1894. }
  1895. return false;
  1896. }
  1897. /**
  1898. * Returns the ID generated from the previous INSERT operation.
  1899. *
  1900. * @param unknown_type $source
  1901. * @return in
  1902. */
  1903. function lastInsertId($source = null) {
  1904. return $this->_connection->lastInsertId();
  1905. }
  1906. /**
  1907. * Creates a default set of conditions from the model if $conditions is null/empty.
  1908. * If conditions are supplied then they will be returned. If a model doesn't exist and no conditions
  1909. * were provided either null or false will be returned based on what was input.
  1910. *
  1911. * @param object $model
  1912. * @param mixed $conditions Array of conditions, conditions string, null or false. If an array of conditions,
  1913. * or string conditions those conditions will be returned. With other values the model's existance will be checked.
  1914. * If the model doesn't exist a null or false will be returned depending on the input value.
  1915. * @param boolean $useAlias Use model aliases rather than table names when generating conditions
  1916. * @return mixed Either null, false, $conditions or an array of default conditions to use.
  1917. * @see DboSource::update()
  1918. * @see DboSource::conditions()
  1919. */
  1920. public function defaultConditions($model, $conditions, $useAlias = true) {
  1921. if (!empty($conditions)) {
  1922. return $conditions;
  1923. }
  1924. $exists = $model->exists();
  1925. if (!$exists && $conditions !== null) {
  1926. return false;
  1927. } elseif (!$exists) {
  1928. return null;
  1929. }
  1930. $alias = $model->alias;
  1931. if (!$useAlias) {
  1932. $alias = $this->fullTableName($model, false);
  1933. }
  1934. return array("{$alias}.{$model->primaryKey}" => $model->getID());
  1935. }
  1936. /**
  1937. * Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name)
  1938. *
  1939. * @param unknown_type $model
  1940. * @param unknown_type $key
  1941. * @param unknown_type $assoc
  1942. * @return string
  1943. */
  1944. public function resolveKey($model, $key, $assoc = null) {
  1945. if (empty($assoc)) {
  1946. $assoc = $model->alias;
  1947. }
  1948. if (strpos('.', $key) !== false) {
  1949. return $this->name($model->alias) . '.' . $this->name($key);
  1950. }
  1951. return $key;
  1952. }
  1953. /**
  1954. * Private helper method to remove query metadata in given data array.
  1955. *
  1956. * @param array $data
  1957. * @return array
  1958. */
  1959. public function __scrubQueryData($data) {
  1960. static $base = null;
  1961. if ($base === null) {
  1962. $base = array_fill_keys(array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group'), array());
  1963. }
  1964. return (array)$data + $base;
  1965. }
  1966. /**
  1967. * Converts model virtual fields into sql expressions to be fetched later
  1968. *
  1969. * @param Model $model
  1970. * @param string $alias Alias tablename
  1971. * @param mixed $fields virtual fields to be used on query
  1972. * @return array
  1973. */
  1974. protected function _constructVirtualFields($model, $alias, $fields) {
  1975. $virtual = array();
  1976. foreach ($fields as $field) {
  1977. $virtualField = $this->name($alias . $this->virtualFieldSeparator . $field);
  1978. $expression = $this->__quoteFields($model->getVirtualField($field));
  1979. $virtual[] = '(' . $expression . ") {$this->alias} {$virtualField}";
  1980. }
  1981. return $virtual;
  1982. }
  1983. /**
  1984. * Generates the fields list of an SQL query.
  1985. *
  1986. * @param Model $model
  1987. * @param string $alias Alias tablename
  1988. * @param mixed $fields
  1989. * @param boolean $quote If false, returns fields array unquoted
  1990. * @return array
  1991. */
  1992. public function fields($model, $alias = null, $fields = array(), $quote = true) {
  1993. if (empty($alias)) {
  1994. $alias = $model->alias;
  1995. }
  1996. $cacheKey = array(
  1997. $model->useDbConfig,
  1998. $model->table,
  1999. array_keys($model->schema()),
  2000. $model->name,
  2001. $model->getVirtualField(),
  2002. $alias,
  2003. $fields,
  2004. $quote
  2005. );
  2006. $cacheKey = crc32(serialize($cacheKey));
  2007. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  2008. return $return;
  2009. }
  2010. $allFields = empty($fields);
  2011. if ($allFields) {
  2012. $fields = array_keys($model->schema());
  2013. } elseif (!is_array($fields)) {
  2014. $fields = String::tokenize($fields);
  2015. }
  2016. $fields = array_values(array_filter($fields));
  2017. $allFields = $allFields || in_array('*', $fields) || in_array($model->alias . '.*', $fields);
  2018. $virtual = array();
  2019. $virtualFields = $model->getVirtualField();
  2020. if (!empty($virtualFields)) {
  2021. $virtualKeys = array_keys($virtualFields);
  2022. foreach ($virtualKeys as $field) {
  2023. $virtualKeys[] = $model->alias . '.' . $field;
  2024. }
  2025. $virtual = ($allFields) ? $virtualKeys : array_intersect($virtualKeys, $fields);
  2026. foreach ($virtual as $i => $field) {
  2027. if (strpos($field, '.') !== false) {
  2028. $virtual[$i] = str_replace($model->alias . '.', '', $field);
  2029. }
  2030. $fields = array_diff($fields, array($field));
  2031. }
  2032. $fields = array_values($fields);
  2033. }
  2034. if (!$quote) {
  2035. if (!empty($virtual)) {
  2036. $fields = array_merge($fields, $this->_constructVirtualFields($model, $alias, $virtual));
  2037. }
  2038. return $fields;
  2039. }
  2040. $count = count($fields);
  2041. if ($count >= 1 && !in_array($fields[0], array('*', 'COUNT(*)'))) {
  2042. for ($i = 0; $i < $count; $i++) {
  2043. if (is_string($fields[$i]) && in_array($fields[$i], $virtual)) {
  2044. unset($fields[$i]);
  2045. continue;
  2046. }
  2047. if (is_object($fields[$i]) && isset($fields[$i]->type) && $fields[$i]->type === 'expression') {
  2048. $fields[$i] = $fields[$i]->value;
  2049. } elseif (preg_match('/^\(.*\)\s' . $this->alias . '.*/i', $fields[$i])){
  2050. continue;
  2051. } elseif (!preg_match('/^.+\\(.*\\)/', $fields[$i])) {
  2052. $prepend = '';
  2053. if (strpos($fields[$i], 'DISTINCT') !== false) {
  2054. $prepend = 'DISTINCT ';
  2055. $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
  2056. }
  2057. $dot = strpos($fields[$i], '.');
  2058. if ($dot === false) {
  2059. $prefix = !(
  2060. strpos($fields[$i], ' ') !== false ||
  2061. strpos($fields[$i], '(') !== false
  2062. );
  2063. $fields[$i] = $this->name(($prefix ? $alias . '.' : '') . $fields[$i]);
  2064. } else {
  2065. $value = array();
  2066. if (strpos($fields[$i], ',') === false) {
  2067. $build = explode('.', $fields[$i]);
  2068. if (!Set::numeric($build)) {
  2069. $fields[$i] = $this->name(implode('.', $build));
  2070. }
  2071. }
  2072. }
  2073. $fields[$i] = $prepend . $fields[$i];
  2074. } elseif (preg_match('/\(([\.\w]+)\)/', $fields[$i], $field)) {
  2075. if (isset($field[1])) {
  2076. if (strpos($field[1], '.') === false) {
  2077. $field[1] = $this->name($alias . '.' . $field[1]);
  2078. } else {
  2079. $field[0] = explode('.', $field[1]);
  2080. if (!Set::numeric($field[0])) {
  2081. $field[0] = implode('.', array_map(array(&$this, 'name'), $field[0]));
  2082. $fields[$i] = preg_replace('/\(' . $field[1] . '\)/', '(' . $field[0] . ')', $fields[$i], 1);
  2083. }
  2084. }
  2085. }
  2086. }
  2087. }
  2088. }
  2089. if (!empty($virtual)) {
  2090. $fields = array_merge($fields, $this->_constructVirtualFields($model, $alias, $virtual));
  2091. }
  2092. return $this->cacheMethod(__FUNCTION__, $cacheKey, array_unique($fields));
  2093. }
  2094. /**
  2095. * Creates a WHERE clause by parsing given conditions data. If an array or string
  2096. * conditions are provided those conditions will be parsed and quoted. If a boolean
  2097. * is given it will be integer cast as condition. Null will return 1 = 1.
  2098. *
  2099. * Results of this method are stored in a memory cache. This improves performance, but
  2100. * because the method uses a simple hashing algorithm it can infrequently have collisions.
  2101. * Setting DboSource::$cacheMethods to false will disable the memory cache.
  2102. *
  2103. * @param mixed $conditions Array or string of conditions, or any value.
  2104. * @param boolean $quoteValues If true, values should be quoted
  2105. * @param boolean $where If true, "WHERE " will be prepended to the return value
  2106. * @param Model $model A reference to the Model instance making the query
  2107. * @return string SQL fragment
  2108. */
  2109. public function conditions($conditions, $quoteValues = true, $where = true, $model = null) {
  2110. if (is_object($model)) {
  2111. $cacheKey = array(
  2112. $model->useDbConfig,
  2113. $model->table,
  2114. $model->schema(),
  2115. $model->name,
  2116. $model->getVirtualField(),
  2117. $conditions,
  2118. $quoteValues,
  2119. $where
  2120. );
  2121. } else {
  2122. $cacheKey = array($conditions, $quoteValues, $where);
  2123. }
  2124. $cacheKey = crc32(serialize($cacheKey));
  2125. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  2126. return $return;
  2127. }
  2128. $clause = $out = '';
  2129. if ($where) {
  2130. $clause = ' WHERE ';
  2131. }
  2132. if (is_array($conditions) && !empty($conditions)) {
  2133. $out = $this->conditionKeysToString($conditions, $quoteValues, $model);
  2134. if (empty($out)) {
  2135. return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . ' 1 = 1');
  2136. }
  2137. return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . implode(' AND ', $out));
  2138. }
  2139. if (is_bool($conditions)) {
  2140. return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . (int)$conditions . ' = 1');
  2141. }
  2142. if (empty($conditions) || trim($conditions) === '') {
  2143. return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . '1 = 1');
  2144. }
  2145. $clauses = '/^WHERE\\x20|^GROUP\\x20BY\\x20|^HAVING\\x20|^ORDER\\x20BY\\x20/i';
  2146. if (preg_match($clauses, $conditions, $match)) {
  2147. $clause = '';
  2148. }
  2149. $conditions = $this->__quoteFields($conditions);
  2150. return $this->cacheMethod(__FUNCTION__, $cacheKey, $clause . $conditions);
  2151. }
  2152. /**
  2153. * Creates a WHERE clause by parsing given conditions array. Used by DboSource::conditions().
  2154. *
  2155. * @param array $conditions Array or string of conditions
  2156. * @param boolean $quoteValues If true, values should be quoted
  2157. * @param Model $model A reference to the Model instance making the query
  2158. * @return string SQL fragment
  2159. */
  2160. public function conditionKeysToString($conditions, $quoteValues = true, $model = null) {
  2161. $out = array();
  2162. $data = $columnType = null;
  2163. $bool = array('and', 'or', 'not', 'and not', 'or not', 'xor', '||', '&&');
  2164. foreach ($conditions as $key => $value) {
  2165. $join = ' AND ';
  2166. $not = null;
  2167. if (is_array($value)) {
  2168. $valueInsert = (
  2169. !empty($value) &&
  2170. (substr_count($key, '?') === count($value) || substr_count($key, ':') === count($value))
  2171. );
  2172. }
  2173. if (is_numeric($key) && empty($value)) {
  2174. continue;
  2175. } elseif (is_numeric($key) && is_string($value)) {
  2176. $out[] = $not . $this->__quoteFields($value);
  2177. } elseif ((is_numeric($key) && is_array($value)) || in_array(strtolower(trim($key)), $bool)) {
  2178. if (in_array(strtolower(trim($key)), $bool)) {
  2179. $join = ' ' . strtoupper($key) . ' ';
  2180. } else {
  2181. $key = $join;
  2182. }
  2183. $value = $this->conditionKeysToString($value, $quoteValues, $model);
  2184. if (strpos($join, 'NOT') !== false) {
  2185. if (strtoupper(trim($key)) === 'NOT') {
  2186. $key = 'AND ' . trim($key);
  2187. }
  2188. $not = 'NOT ';
  2189. }
  2190. if (empty($value[1])) {
  2191. if ($not) {
  2192. $out[] = $not . '(' . $value[0] . ')';
  2193. } else {
  2194. $out[] = $value[0] ;
  2195. }
  2196. } else {
  2197. $out[] = '(' . $not . '(' . implode(') ' . strtoupper($key) . ' (', $value) . '))';
  2198. }
  2199. } else {
  2200. if (is_object($value) && isset($value->type)) {
  2201. if ($value->type === 'identifier') {
  2202. $data .= $this->name($key) . ' = ' . $this->name($value->value);
  2203. } elseif ($value->type === 'expression') {
  2204. if (is_numeric($key)) {
  2205. $data .= $value->value;
  2206. } else {
  2207. $data .= $this->name($key) . ' = ' . $value->value;
  2208. }
  2209. }
  2210. } elseif (is_array($value) && !empty($value) && !$valueInsert) {
  2211. $keys = array_keys($value);
  2212. if ($keys === array_values($keys)) {
  2213. $count = count($value);
  2214. if ($count === 1) {
  2215. $data = $this->__quoteFields($key) . ' = (';
  2216. } else {
  2217. $data = $this->__quoteFields($key) . ' IN (';
  2218. }
  2219. if ($quoteValues) {
  2220. if (is_object($model)) {
  2221. $columnType = $model->getColumnType($key);
  2222. }
  2223. $data .= implode(', ', $this->value($value, $columnType));
  2224. }
  2225. $data .= ')';
  2226. } else {
  2227. $ret = $this->conditionKeysToString($value, $quoteValues, $model);
  2228. if (count($ret) > 1) {
  2229. $data = '(' . implode(') AND (', $ret) . ')';
  2230. } elseif (isset($ret[0])) {
  2231. $data = $ret[0];
  2232. }
  2233. }
  2234. } elseif (is_numeric($key) && !empty($value)) {
  2235. $data = $this->__quoteFields($value);
  2236. } else {
  2237. $data = $this->__parseKey($model, trim($key), $value);
  2238. }
  2239. if ($data != null) {
  2240. $out[] = $data;
  2241. $data = null;
  2242. }
  2243. }
  2244. }
  2245. return $out;
  2246. }
  2247. /**
  2248. * Extracts a Model.field identifier and an SQL condition operator from a string, formats
  2249. * and inserts values, and composes them into an SQL snippet.
  2250. *
  2251. * @param Model $model Model object initiating the query
  2252. * @param string $key An SQL key snippet containing a field and optional SQL operator
  2253. * @param mixed $value The value(s) to be inserted in the string
  2254. * @return string
  2255. * @access private
  2256. */
  2257. function __parseKey($model, $key, $value) {
  2258. $operatorMatch = '/^((' . implode(')|(', $this->__sqlOps);
  2259. $operatorMatch .= '\\x20)|<[>=]?(?![^>]+>)\\x20?|[>=!]{1,3}(?!<)\\x20?)/is';
  2260. $bound = (strpos($key, '?') !== false || (is_array($value) && strpos($key, ':') !== false));
  2261. if (strpos($key, ' ') === false) {
  2262. $operator = '=';
  2263. } else {
  2264. list($key, $operator) = explode(' ', trim($key), 2);
  2265. if (!preg_match($operatorMatch, trim($operator)) && strpos($operator, ' ') !== false) {
  2266. $key = $key . ' ' . $operator;
  2267. $split = strrpos($key, ' ');
  2268. $operator = substr($key, $split);
  2269. $key = substr($key, 0, $split);
  2270. }
  2271. }
  2272. $virtual = false;
  2273. if (is_object($model) && $model->isVirtualField($key)) {
  2274. $key = $this->__quoteFields($model->getVirtualField($key));
  2275. $virtual = true;
  2276. }
  2277. $type = is_object($model) ? $model->getColumnType($key) : null;
  2278. $null = $value === null || (is_array($value) && empty($value));
  2279. if (strtolower($operator) === 'not') {
  2280. $data = $this->conditionKeysToString(
  2281. array($operator => array($key => $value)), true, $model
  2282. );
  2283. return $data[0];
  2284. }
  2285. $value = $this->value($value, $type);
  2286. if (!$virtual && $key !== '?') {
  2287. $isKey = (strpos($key, '(') !== false || strpos($key, ')') !== false);
  2288. $key = $isKey ? $this->__quoteFields($key) : $this->name($key);
  2289. }
  2290. if ($bound) {
  2291. return String::insert($key . ' ' . trim($operator), $value);
  2292. }
  2293. if (!preg_match($operatorMatch, trim($operator))) {
  2294. $operator .= ' =';
  2295. }
  2296. $operator = trim($operator);
  2297. if (is_array($value)) {
  2298. $value = implode(', ', $value);
  2299. switch ($operator) {
  2300. case '=':
  2301. $operator = 'IN';
  2302. break;
  2303. case '!=':
  2304. case '<>':
  2305. $operator = 'NOT IN';
  2306. break;
  2307. }
  2308. $value = "({$value})";
  2309. } elseif ($null) {
  2310. switch ($operator) {
  2311. case '=':
  2312. $operator = 'IS';
  2313. break;
  2314. case '!=':
  2315. case '<>':
  2316. $operator = 'IS NOT';
  2317. break;
  2318. }
  2319. }
  2320. if ($virtual) {
  2321. return "({$key}) {$operator} {$value}";
  2322. }
  2323. return "{$key} {$operator} {$value}";
  2324. }
  2325. /**
  2326. * Quotes Model.fields
  2327. *
  2328. * @param string $conditions
  2329. * @return string or false if no match
  2330. * @access private
  2331. */
  2332. function __quoteFields($conditions) {
  2333. $start = $end = null;
  2334. $original = $conditions;
  2335. if (!empty($this->startQuote)) {
  2336. $start = preg_quote($this->startQuote);
  2337. }
  2338. if (!empty($this->endQuote)) {
  2339. $end = preg_quote($this->endQuote);
  2340. }
  2341. $conditions = str_replace(array($start, $end), '', $conditions);
  2342. $conditions = preg_replace_callback('/(?:[\'\"][^\'\"\\\]*(?:\\\.[^\'\"\\\]*)*[\'\"])|([a-z0-9_' . $start . $end . ']*\\.[a-z0-9_' . $start . $end . ']*)/i', array(&$this, '__quoteMatchedField'), $conditions);
  2343. if ($conditions !== null) {
  2344. return $conditions;
  2345. }
  2346. return $original;
  2347. }
  2348. /**
  2349. * Auxiliary function to quote matches `Model.fields` from a preg_replace_callback call
  2350. *
  2351. * @param string matched string
  2352. * @return string quoted strig
  2353. * @access private
  2354. */
  2355. function __quoteMatchedField($match) {
  2356. if (is_numeric($match[0])) {
  2357. return $match[0];
  2358. }
  2359. return $this->name($match[0]);
  2360. }
  2361. /**
  2362. * Returns a limit statement in the correct format for the particular database.
  2363. *
  2364. * @param integer $limit Limit of results returned
  2365. * @param integer $offset Offset from which to start results
  2366. * @return string SQL limit/offset statement
  2367. */
  2368. public function limit($limit, $offset = null) {
  2369. if ($limit) {
  2370. $rt = '';
  2371. if (!strpos(strtolower($limit), 'limit')) {
  2372. $rt = ' LIMIT';
  2373. }
  2374. if ($offset) {
  2375. $rt .= ' ' . $offset . ',';
  2376. }
  2377. $rt .= ' ' . $limit;
  2378. return $rt;
  2379. }
  2380. return null;
  2381. }
  2382. /**
  2383. * Returns an ORDER BY clause as a string.
  2384. *
  2385. * @param string $key Field reference, as a key (i.e. Post.title)
  2386. * @param string $direction Direction (ASC or DESC)
  2387. * @param object $model model reference (used to look for virtual field)
  2388. * @return string ORDER BY clause
  2389. */
  2390. public function order($keys, $direction = 'ASC', $model = null) {
  2391. if (!is_array($keys)) {
  2392. $keys = array($keys);
  2393. }
  2394. $keys = array_filter($keys);
  2395. $result = array();
  2396. while (!empty($keys)) {
  2397. list($key, $dir) = each($keys);
  2398. array_shift($keys);
  2399. if (is_numeric($key)) {
  2400. $key = $dir;
  2401. $dir = $direction;
  2402. }
  2403. if (is_string($key) && strpos($key, ',') !== false && !preg_match('/\(.+\,.+\)/', $key)) {
  2404. $key = array_map('trim', explode(',', $key));
  2405. }
  2406. if (is_array($key)) {
  2407. //Flatten the array
  2408. $key = array_reverse($key, true);
  2409. foreach ($key as $k => $v) {
  2410. if (is_numeric($k)) {
  2411. array_unshift($keys, $v);
  2412. } else {
  2413. $keys = array($k => $v) + $keys;
  2414. }
  2415. }
  2416. continue;
  2417. } elseif (is_object($key) && isset($key->type) && $key->type === 'expression') {
  2418. $result[] = $key->value;
  2419. continue;
  2420. }
  2421. if (preg_match('/\\x20(ASC|DESC).*/i', $key, $_dir)) {
  2422. $dir = $_dir[0];
  2423. $key = preg_replace('/\\x20(ASC|DESC).*/i', '', $key);
  2424. }
  2425. $key = trim($key);
  2426. if (is_object($model) && $model->isVirtualField($key)) {
  2427. $key = '(' . $this->__quoteFields($model->getVirtualField($key)) . ')';
  2428. }
  2429. if (strpos($key, '.')) {
  2430. $key = preg_replace_callback('/([a-zA-Z0-9_-]{1,})\\.([a-zA-Z0-9_-]{1,})/', array(&$this, '__quoteMatchedField'), $key);
  2431. }
  2432. if (!preg_match('/\s/', $key) && strpos($key, '.') === false) {
  2433. $key = $this->name($key);
  2434. }
  2435. $key .= ' ' . trim($dir);
  2436. $result[] = $key;
  2437. }
  2438. if (!empty($result)) {
  2439. return ' ORDER BY ' . implode(', ', $result);
  2440. }
  2441. return '';
  2442. }
  2443. /**
  2444. * Create a GROUP BY SQL clause
  2445. *
  2446. * @param string $group Group By Condition
  2447. * @return mixed string condition or null
  2448. */
  2449. public function group($group, $model = null) {
  2450. if ($group) {
  2451. if (!is_array($group)) {
  2452. $group = array($group);
  2453. }
  2454. foreach($group as $index => $key) {
  2455. if ($model->isVirtualField($key)) {
  2456. $group[$index] = '(' . $model->getVirtualField($key) . ')';
  2457. }
  2458. }
  2459. $group = implode(', ', $group);
  2460. return ' GROUP BY ' . $this->__quoteFields($group);
  2461. }
  2462. return null;
  2463. }
  2464. /**
  2465. * Disconnects database, kills the connection and says the connection is closed.
  2466. *
  2467. * @return void
  2468. */
  2469. public function close() {
  2470. $this->disconnect();
  2471. }
  2472. /**
  2473. * Checks if the specified table contains any record matching specified SQL
  2474. *
  2475. * @param Model $model Model to search
  2476. * @param string $sql SQL WHERE clause (condition only, not the "WHERE" part)
  2477. * @return boolean True if the table has a matching record, else false
  2478. */
  2479. public function hasAny($Model, $sql) {
  2480. $sql = $this->conditions($sql);
  2481. $table = $this->fullTableName($Model);
  2482. $alias = $this->alias . $this->name($Model->alias);
  2483. $where = $sql ? "{$sql}" : ' WHERE 1 = 1';
  2484. $id = $Model->escapeField();
  2485. $out = $this->fetchRow("SELECT COUNT({$id}) {$this->alias}count FROM {$table} {$alias}{$where}");
  2486. if (is_array($out)) {
  2487. return $out[0]['count'];
  2488. }
  2489. return false;
  2490. }
  2491. /**
  2492. * Gets the length of a database-native column description, or null if no length
  2493. *
  2494. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  2495. * @return mixed An integer or string representing the length of the column
  2496. */
  2497. public function length($real) {
  2498. if (!preg_match_all('/([\w\s]+)(?:\((\d+)(?:,(\d+))?\))?(\sunsigned)?(\szerofill)?/', $real, $result)) {
  2499. trigger_error(__d('cake_dev', "FIXME: Can't parse field: " . $real), E_USER_WARNING);
  2500. $col = str_replace(array(')', 'unsigned'), '', $real);
  2501. $limit = null;
  2502. if (strpos($col, '(') !== false) {
  2503. list($col, $limit) = explode('(', $col);
  2504. }
  2505. if ($limit !== null) {
  2506. return intval($limit);
  2507. }
  2508. return null;
  2509. }
  2510. $types = array(
  2511. 'int' => 1, 'tinyint' => 1, 'smallint' => 1, 'mediumint' => 1, 'integer' => 1, 'bigint' => 1
  2512. );
  2513. list($real, $type, $length, $offset, $sign, $zerofill) = $result;
  2514. $typeArr = $type;
  2515. $type = $type[0];
  2516. $length = $length[0];
  2517. $offset = $offset[0];
  2518. $isFloat = in_array($type, array('dec', 'decimal', 'float', 'numeric', 'double'));
  2519. if ($isFloat && $offset) {
  2520. return $length . ',' . $offset;
  2521. }
  2522. if (($real[0] == $type) && (count($real) === 1)) {
  2523. return null;
  2524. }
  2525. if (isset($types[$type])) {
  2526. $length += $types[$type];
  2527. if (!empty($sign)) {
  2528. $length--;
  2529. }
  2530. } elseif (in_array($type, array('enum', 'set'))) {
  2531. $length = 0;
  2532. foreach ($typeArr as $key => $enumValue) {
  2533. if ($key === 0) {
  2534. continue;
  2535. }
  2536. $tmpLength = strlen($enumValue);
  2537. if ($tmpLength > $length) {
  2538. $length = $tmpLength;
  2539. }
  2540. }
  2541. }
  2542. return intval($length);
  2543. }
  2544. /**
  2545. * Translates between PHP boolean values and Database (faked) boolean values
  2546. *
  2547. * @param mixed $data Value to be translated
  2548. * @return int Converted boolean value
  2549. */
  2550. public function boolean($data, $quote = false) {
  2551. if ($quote) {
  2552. return !empty($data) ? '1' : '0';
  2553. }
  2554. return !empty($data);
  2555. }
  2556. /**
  2557. * Inserts multiple values into a table
  2558. *
  2559. * @param string $table
  2560. * @param string $fields
  2561. * @param array $values
  2562. */
  2563. public function insertMulti($table, $fields, $values) {
  2564. $table = $this->fullTableName($table);
  2565. $holder = implode(',', array_fill(0, count($fields), '?'));
  2566. $fields = implode(', ', array_map(array(&$this, 'name'), $fields));
  2567. $count = count($values);
  2568. $sql = "INSERT INTO {$table} ({$fields}) VALUES ({$holder})";
  2569. $statement = $this->_connection->prepare($sql);
  2570. $this->begin();
  2571. for ($x = 0; $x < $count; $x++) {
  2572. $statement->execute($values[$x]);
  2573. $statement->closeCursor();
  2574. }
  2575. return $this->commit();
  2576. }
  2577. /**
  2578. * Returns an array of the indexes in given datasource name.
  2579. *
  2580. * @param string $model Name of model to inspect
  2581. * @return array Fields in table. Keys are column and unique
  2582. */
  2583. public function index($model) {
  2584. return false;
  2585. }
  2586. /**
  2587. * Generate a database-native schema for the given Schema object
  2588. *
  2589. * @param object $schema An instance of a subclass of CakeSchema
  2590. * @param string $tableName Optional. If specified only the table name given will be generated.
  2591. * Otherwise, all tables defined in the schema are generated.
  2592. * @return string
  2593. */
  2594. public function createSchema($schema, $tableName = null) {
  2595. if (!is_a($schema, 'CakeSchema')) {
  2596. trigger_error(__d('cake_dev', 'Invalid schema object'), E_USER_WARNING);
  2597. return null;
  2598. }
  2599. $out = '';
  2600. foreach ($schema->tables as $curTable => $columns) {
  2601. if (!$tableName || $tableName == $curTable) {
  2602. $cols = $colList = $indexes = $tableParameters = array();
  2603. $primary = null;
  2604. $table = $this->fullTableName($curTable);
  2605. foreach ($columns as $name => $col) {
  2606. if (is_string($col)) {
  2607. $col = array('type' => $col);
  2608. }
  2609. if (isset($col['key']) && $col['key'] === 'primary') {
  2610. $primary = $name;
  2611. }
  2612. if ($name !== 'indexes' && $name !== 'tableParameters') {
  2613. $col['name'] = $name;
  2614. if (!isset($col['type'])) {
  2615. $col['type'] = 'string';
  2616. }
  2617. $cols[] = $this->buildColumn($col);
  2618. } elseif ($name === 'indexes') {
  2619. $indexes = array_merge($indexes, $this->buildIndex($col, $table));
  2620. } elseif ($name === 'tableParameters') {
  2621. $tableParameters = array_merge($tableParameters, $this->buildTableParameters($col, $table));
  2622. }
  2623. }
  2624. if (empty($indexes) && !empty($primary)) {
  2625. $col = array('PRIMARY' => array('column' => $primary, 'unique' => 1));
  2626. $indexes = array_merge($indexes, $this->buildIndex($col, $table));
  2627. }
  2628. $columns = $cols;
  2629. $out .= $this->renderStatement('schema', compact('table', 'columns', 'indexes', 'tableParameters')) . "\n\n";
  2630. }
  2631. }
  2632. return $out;
  2633. }
  2634. /**
  2635. * Generate a alter syntax from CakeSchema::compare()
  2636. *
  2637. * @param unknown_type $schema
  2638. * @return boolean
  2639. */
  2640. function alterSchema($compare, $table = null) {
  2641. return false;
  2642. }
  2643. /**
  2644. * Generate a "drop table" statement for the given Schema object
  2645. *
  2646. * @param CakeSchema $schema An instance of a subclass of CakeSchema
  2647. * @param string $table Optional. If specified only the table name given will be generated.
  2648. * Otherwise, all tables defined in the schema are generated.
  2649. * @return string
  2650. */
  2651. public function dropSchema(CakeSchema $schema, $table = null) {
  2652. $out = '';
  2653. foreach ($schema->tables as $curTable => $columns) {
  2654. if (!$table || $table == $curTable) {
  2655. $out .= 'DROP TABLE ' . $this->fullTableName($curTable) . ";\n";
  2656. }
  2657. }
  2658. return $out;
  2659. }
  2660. /**
  2661. * Generate a database-native column schema string
  2662. *
  2663. * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
  2664. * where options can be 'default', 'length', or 'key'.
  2665. * @return string
  2666. */
  2667. public function buildColumn($column) {
  2668. $name = $type = null;
  2669. extract(array_merge(array('null' => true), $column));
  2670. if (empty($name) || empty($type)) {
  2671. trigger_error(__d('cake_dev', 'Column name or type not defined in schema'), E_USER_WARNING);
  2672. return null;
  2673. }
  2674. if (!isset($this->columns[$type])) {
  2675. trigger_error(__d('cake_dev', 'Column type %s does not exist', $type), E_USER_WARNING);
  2676. return null;
  2677. }
  2678. $real = $this->columns[$type];
  2679. $out = $this->name($name) . ' ' . $real['name'];
  2680. if (isset($column['length'])) {
  2681. $length = $column['length'];
  2682. } elseif (isset($column['limit'])) {
  2683. $length = $column['limit'];
  2684. } elseif (isset($real['length'])) {
  2685. $length = $real['length'];
  2686. } elseif (isset($real['limit'])) {
  2687. $length = $real['limit'];
  2688. }
  2689. if (isset($length)) {
  2690. $out .= '(' . $length . ')';
  2691. }
  2692. if (($column['type'] === 'integer' || $column['type'] === 'float' ) && isset($column['default']) && $column['default'] === '') {
  2693. $column['default'] = null;
  2694. }
  2695. $out = $this->_buildFieldParameters($out, $column, 'beforeDefault');
  2696. if (isset($column['key']) && $column['key'] === 'primary' && $type === 'integer') {
  2697. $out .= ' ' . $this->columns['primary_key']['name'];
  2698. } elseif (isset($column['key']) && $column['key'] === 'primary') {
  2699. $out .= ' NOT NULL';
  2700. } elseif (isset($column['default']) && isset($column['null']) && $column['null'] === false) {
  2701. $out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL';
  2702. } elseif (isset($column['default'])) {
  2703. $out .= ' DEFAULT ' . $this->value($column['default'], $type);
  2704. } elseif ($type !== 'timestamp' && !empty($column['null'])) {
  2705. $out .= ' DEFAULT NULL';
  2706. } elseif ($type === 'timestamp' && !empty($column['null'])) {
  2707. $out .= ' NULL';
  2708. } elseif (isset($column['null']) && $column['null'] === false) {
  2709. $out .= ' NOT NULL';
  2710. }
  2711. if ($type === 'timestamp' && isset($column['default']) && strtolower($column['default']) === 'current_timestamp') {
  2712. $out = str_replace(array("'CURRENT_TIMESTAMP'", "'current_timestamp'"), 'CURRENT_TIMESTAMP', $out);
  2713. }
  2714. return $this->_buildFieldParameters($out, $column, 'afterDefault');
  2715. }
  2716. /**
  2717. * Build the field parameters, in a position
  2718. *
  2719. * @param string $columnString The partially built column string
  2720. * @param array $columnData The array of column data.
  2721. * @param string $position The position type to use. 'beforeDefault' or 'afterDefault' are common
  2722. * @return string a built column with the field parameters added.
  2723. */
  2724. public function _buildFieldParameters($columnString, $columnData, $position) {
  2725. foreach ($this->fieldParameters as $paramName => $value) {
  2726. if (isset($columnData[$paramName]) && $value['position'] == $position) {
  2727. if (isset($value['options']) && !in_array($columnData[$paramName], $value['options'])) {
  2728. continue;
  2729. }
  2730. $val = $columnData[$paramName];
  2731. if ($value['quote']) {
  2732. $val = $this->value($val);
  2733. }
  2734. $columnString .= ' ' . $value['value'] . $value['join'] . $val;
  2735. }
  2736. }
  2737. return $columnString;
  2738. }
  2739. /**
  2740. * Format indexes for create table
  2741. *
  2742. * @param array $indexes
  2743. * @param string $table
  2744. * @return array
  2745. */
  2746. public function buildIndex($indexes, $table = null) {
  2747. $join = array();
  2748. foreach ($indexes as $name => $value) {
  2749. $out = '';
  2750. if ($name === 'PRIMARY') {
  2751. $out .= 'PRIMARY ';
  2752. $name = null;
  2753. } else {
  2754. if (!empty($value['unique'])) {
  2755. $out .= 'UNIQUE ';
  2756. }
  2757. $name = $this->startQuote . $name . $this->endQuote;
  2758. }
  2759. if (is_array($value['column'])) {
  2760. $out .= 'KEY ' . $name . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
  2761. } else {
  2762. $out .= 'KEY ' . $name . ' (' . $this->name($value['column']) . ')';
  2763. }
  2764. $join[] = $out;
  2765. }
  2766. return $join;
  2767. }
  2768. /**
  2769. * Read additional table parameters
  2770. *
  2771. * @param array $parameters
  2772. * @param string $table
  2773. * @return array
  2774. */
  2775. public function readTableParameters($name) {
  2776. $parameters = array();
  2777. if (method_exists($this, 'listDetailedSources')) {
  2778. $currentTableDetails = $this->listDetailedSources($name);
  2779. foreach ($this->tableParameters as $paramName => $parameter) {
  2780. if (!empty($parameter['column']) && !empty($currentTableDetails[$parameter['column']])) {
  2781. $parameters[$paramName] = $currentTableDetails[$parameter['column']];
  2782. }
  2783. }
  2784. }
  2785. return $parameters;
  2786. }
  2787. /**
  2788. * Format parameters for create table
  2789. *
  2790. * @param array $parameters
  2791. * @param string $table
  2792. * @return array
  2793. */
  2794. public function buildTableParameters($parameters, $table = null) {
  2795. $result = array();
  2796. foreach ($parameters as $name => $value) {
  2797. if (isset($this->tableParameters[$name])) {
  2798. if ($this->tableParameters[$name]['quote']) {
  2799. $value = $this->value($value);
  2800. }
  2801. $result[] = $this->tableParameters[$name]['value'] . $this->tableParameters[$name]['join'] . $value;
  2802. }
  2803. }
  2804. return $result;
  2805. }
  2806. /**
  2807. * Guesses the data type of an array
  2808. *
  2809. * @param string $value
  2810. * @return void
  2811. */
  2812. public function introspectType($value) {
  2813. if (!is_array($value)) {
  2814. if (is_bool($value)) {
  2815. return 'boolean';
  2816. }
  2817. if (is_float($value) && floatval($value) === $value) {
  2818. return 'float';
  2819. }
  2820. if (is_int($value) && intval($value) === $value) {
  2821. return 'integer';
  2822. }
  2823. if (is_string($value) && strlen($value) > 255) {
  2824. return 'text';
  2825. }
  2826. return 'string';
  2827. }
  2828. $isAllFloat = $isAllInt = true;
  2829. $containsFloat = $containsInt = $containsString = false;
  2830. foreach ($value as $key => $valElement) {
  2831. $valElement = trim($valElement);
  2832. if (!is_float($valElement) && !preg_match('/^[\d]+\.[\d]+$/', $valElement)) {
  2833. $isAllFloat = false;
  2834. } else {
  2835. $containsFloat = true;
  2836. continue;
  2837. }
  2838. if (!is_int($valElement) && !preg_match('/^[\d]+$/', $valElement)) {
  2839. $isAllInt = false;
  2840. } else {
  2841. $containsInt = true;
  2842. continue;
  2843. }
  2844. $containsString = true;
  2845. }
  2846. if ($isAllFloat) {
  2847. return 'float';
  2848. }
  2849. if ($isAllInt) {
  2850. return 'integer';
  2851. }
  2852. if ($containsInt && !$containsString) {
  2853. return 'integer';
  2854. }
  2855. return 'string';
  2856. }
  2857. /**
  2858. * Writes a new key for the in memory sql query cache
  2859. *
  2860. * @param string $sql SQL query
  2861. * @param mixed $data result of $sql query
  2862. * @param array $params query params bound as values
  2863. * @return void
  2864. */
  2865. protected function _writeQueryCache($sql, $data, $params = array()) {
  2866. if (preg_match('/^\s*select/i', $sql)) {
  2867. $this->_queryCache[$sql][serialize($params)] = $data;
  2868. }
  2869. }
  2870. /**
  2871. * Returns the result for a sql query if it is already cached
  2872. *
  2873. * @param string $sql SQL query
  2874. * @param array $params query params bound as values
  2875. * @return mixed results for query if it is cached, false otherwise
  2876. */
  2877. public function getQueryCache($sql, $params = array()) {
  2878. if (isset($this->_queryCache[$sql]) && preg_match('/^\s*select/i', $sql)) {
  2879. $serialized = serialize($params);
  2880. if (isset($this->_queryCache[$sql][$serialized])) {
  2881. return $this->_queryCache[$sql][$serialized];
  2882. }
  2883. }
  2884. return false;
  2885. }
  2886. }