DboSource.php 91 KB

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