DboSource.php 98 KB

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