DboSource.php 90 KB

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