DboSource.php 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526
  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, $LinkModel, $type, $association, $assocData, &$queryData, $external) {
  1461. $assocData = $this->_scrubQueryData($assocData);
  1462. if ($LinkModel === null) {
  1463. return '';
  1464. }
  1465. if ($external && !empty($assocData['finderQuery'])) {
  1466. return $assocData['finderQuery'];
  1467. }
  1468. if ($type === 'hasMany' || $type === 'hasAndBelongsToMany') {
  1469. if (empty($assocData['offset']) && !empty($assocData['page'])) {
  1470. $assocData['offset'] = ($assocData['page'] - 1) * $assocData['limit'];
  1471. }
  1472. }
  1473. switch ($type) {
  1474. case 'hasOne':
  1475. case 'belongsTo':
  1476. $conditions = $this->_mergeConditions(
  1477. $assocData['conditions'],
  1478. $this->getConstraint($type, $Model, $LinkModel, $association, array_merge($assocData, compact('external')))
  1479. );
  1480. if ($external) {
  1481. // Not self join
  1482. if ($Model->name !== $LinkModel->name) {
  1483. $modelAlias = $Model->alias;
  1484. foreach ($conditions as $key => $condition) {
  1485. if (is_numeric($key) && strpos($condition, $modelAlias . '.') !== false) {
  1486. unset($conditions[$key]);
  1487. }
  1488. }
  1489. }
  1490. $query = array_merge($assocData, array(
  1491. 'conditions' => $conditions,
  1492. 'table' => $this->fullTableName($LinkModel),
  1493. 'fields' => $this->fields($LinkModel, $association, $assocData['fields']),
  1494. 'alias' => $association,
  1495. 'group' => null
  1496. ));
  1497. } else {
  1498. $join = array(
  1499. 'table' => $LinkModel,
  1500. 'alias' => $association,
  1501. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1502. 'conditions' => trim($this->conditions($conditions, true, false, $Model))
  1503. );
  1504. $queryData = $this->_scrubQueryData($queryData);
  1505. $fields = array();
  1506. if ($assocData['fields'] !== false) {
  1507. $fields = $this->fields($LinkModel, $association, $assocData['fields']);
  1508. }
  1509. $queryData['fields'] = array_merge($this->prepareFields($Model, $queryData), $fields);
  1510. if (!empty($assocData['order'])) {
  1511. $queryData['order'][] = $assocData['order'];
  1512. }
  1513. if (!in_array($join, $queryData['joins'])) {
  1514. $queryData['joins'][] = $join;
  1515. }
  1516. return true;
  1517. }
  1518. break;
  1519. case 'hasMany':
  1520. $assocData['fields'] = $this->fields($LinkModel, $association, $assocData['fields']);
  1521. if (!empty($assocData['foreignKey'])) {
  1522. $assocData['fields'] = array_merge($assocData['fields'], $this->fields($LinkModel, $association, array("{$association}.{$assocData['foreignKey']}")));
  1523. }
  1524. $query = array(
  1525. 'conditions' => $this->_mergeConditions($this->getConstraint('hasMany', $Model, $LinkModel, $association, $assocData), $assocData['conditions']),
  1526. 'fields' => array_unique($assocData['fields']),
  1527. 'table' => $this->fullTableName($LinkModel),
  1528. 'alias' => $association,
  1529. 'order' => $assocData['order'],
  1530. 'limit' => $assocData['limit'],
  1531. 'offset' => $assocData['offset'],
  1532. 'group' => null
  1533. );
  1534. break;
  1535. case 'hasAndBelongsToMany':
  1536. $joinFields = array();
  1537. $joinAssoc = null;
  1538. if (isset($assocData['with']) && !empty($assocData['with'])) {
  1539. $joinKeys = array($assocData['foreignKey'], $assocData['associationForeignKey']);
  1540. list($with, $joinFields) = $Model->joinModel($assocData['with'], $joinKeys);
  1541. $joinTbl = $Model->{$with};
  1542. $joinAlias = $joinTbl;
  1543. if (is_array($joinFields) && !empty($joinFields)) {
  1544. $joinAssoc = $joinAlias = $joinTbl->alias;
  1545. $joinFields = $this->fields($joinTbl, $joinAlias, $joinFields);
  1546. } else {
  1547. $joinFields = array();
  1548. }
  1549. } else {
  1550. $joinTbl = $assocData['joinTable'];
  1551. $joinAlias = $this->fullTableName($assocData['joinTable']);
  1552. }
  1553. $query = array(
  1554. 'conditions' => $assocData['conditions'],
  1555. 'limit' => $assocData['limit'],
  1556. 'offset' => $assocData['offset'],
  1557. 'table' => $this->fullTableName($LinkModel),
  1558. 'alias' => $association,
  1559. 'fields' => array_merge($this->fields($LinkModel, $association, $assocData['fields']), $joinFields),
  1560. 'order' => $assocData['order'],
  1561. 'group' => null,
  1562. 'joins' => array(array(
  1563. 'table' => $joinTbl,
  1564. 'alias' => $joinAssoc,
  1565. 'conditions' => $this->getConstraint('hasAndBelongsToMany', $Model, $LinkModel, $joinAlias, $assocData, $association)
  1566. ))
  1567. );
  1568. break;
  1569. }
  1570. if (isset($query)) {
  1571. return $this->buildStatement($query, $Model);
  1572. }
  1573. return null;
  1574. }
  1575. /**
  1576. * Returns a conditions array for the constraint between two models.
  1577. *
  1578. * @param string $type Association type.
  1579. * @param Model $Model Primary Model object.
  1580. * @param Model $LinkModel Linked model object.
  1581. * @param string $association Association name.
  1582. * @param array $assocData Association data.
  1583. * @param string $association2 HABTM association name.
  1584. * @return array Conditions array defining the constraint between $Model and $LinkModel.
  1585. */
  1586. public function getConstraint($type, Model $Model, Model $LinkModel, $association, $assocData, $association2 = null) {
  1587. $assocData += array('external' => false);
  1588. if (empty($assocData['foreignKey'])) {
  1589. return array();
  1590. }
  1591. switch ($type) {
  1592. case 'hasOne':
  1593. if ($assocData['external']) {
  1594. return array(
  1595. "{$association}.{$assocData['foreignKey']}" => '{$__cakeID__$}'
  1596. );
  1597. } else {
  1598. return array(
  1599. "{$association}.{$assocData['foreignKey']}" => $this->identifier("{$Model->alias}.{$Model->primaryKey}")
  1600. );
  1601. }
  1602. case 'belongsTo':
  1603. if ($assocData['external']) {
  1604. return array(
  1605. "{$association}.{$LinkModel->primaryKey}" => '{$__cakeForeignKey__$}'
  1606. );
  1607. } else {
  1608. return array(
  1609. "{$Model->alias}.{$assocData['foreignKey']}" => $this->identifier("{$association}.{$LinkModel->primaryKey}")
  1610. );
  1611. }
  1612. case 'hasMany':
  1613. return array("{$association}.{$assocData['foreignKey']}" => array('{$__cakeID__$}'));
  1614. case 'hasAndBelongsToMany':
  1615. return array(
  1616. array(
  1617. "{$association}.{$assocData['foreignKey']}" => '{$__cakeID__$}'
  1618. ),
  1619. array(
  1620. "{$association}.{$assocData['associationForeignKey']}" => $this->identifier("{$association2}.{$LinkModel->primaryKey}")
  1621. )
  1622. );
  1623. }
  1624. return array();
  1625. }
  1626. /**
  1627. * Builds and generates a JOIN condition from an array. Handles final clean-up before conversion.
  1628. *
  1629. * @param array $join An array defining a JOIN condition in a query.
  1630. * @return string An SQL JOIN condition to be used in a query.
  1631. * @see DboSource::renderJoinStatement()
  1632. * @see DboSource::buildStatement()
  1633. */
  1634. public function buildJoinStatement($join) {
  1635. $data = array_merge(array(
  1636. 'type' => null,
  1637. 'alias' => null,
  1638. 'table' => 'join_table',
  1639. 'conditions' => array()
  1640. ), $join);
  1641. if (!empty($data['alias'])) {
  1642. $data['alias'] = $this->alias . $this->name($data['alias']);
  1643. }
  1644. if (!empty($data['conditions'])) {
  1645. $data['conditions'] = trim($this->conditions($data['conditions'], true, false));
  1646. }
  1647. if (!empty($data['table']) && (!is_string($data['table']) || strpos($data['table'], '(') !== 0)) {
  1648. $data['table'] = $this->fullTableName($data['table']);
  1649. }
  1650. return $this->renderJoinStatement($data);
  1651. }
  1652. /**
  1653. * Builds and generates an SQL statement from an array. Handles final clean-up before conversion.
  1654. *
  1655. * @param array $query An array defining an SQL query.
  1656. * @param Model $Model The model object which initiated the query.
  1657. * @return string An executable SQL statement.
  1658. * @see DboSource::renderStatement()
  1659. */
  1660. public function buildStatement($query, Model $Model) {
  1661. $query = array_merge($this->_queryDefaults, $query);
  1662. if (!empty($query['joins'])) {
  1663. $count = count($query['joins']);
  1664. for ($i = 0; $i < $count; $i++) {
  1665. if (is_array($query['joins'][$i])) {
  1666. $query['joins'][$i] = $this->buildJoinStatement($query['joins'][$i]);
  1667. }
  1668. }
  1669. }
  1670. return $this->renderStatement('select', array(
  1671. 'conditions' => $this->conditions($query['conditions'], true, true, $Model),
  1672. 'fields' => implode(', ', $query['fields']),
  1673. 'table' => $query['table'],
  1674. 'alias' => $this->alias . $this->name($query['alias']),
  1675. 'order' => $this->order($query['order'], 'ASC', $Model),
  1676. 'limit' => $this->limit($query['limit'], $query['offset']),
  1677. 'joins' => implode(' ', $query['joins']),
  1678. 'group' => $this->group($query['group'], $Model)
  1679. ));
  1680. }
  1681. /**
  1682. * Renders a final SQL JOIN statement
  1683. *
  1684. * @param array $data
  1685. * @return string
  1686. */
  1687. public function renderJoinStatement($data) {
  1688. if (strtoupper($data['type']) === 'CROSS') {
  1689. return "{$data['type']} JOIN {$data['table']} {$data['alias']}";
  1690. }
  1691. return trim("{$data['type']} JOIN {$data['table']} {$data['alias']} ON ({$data['conditions']})");
  1692. }
  1693. /**
  1694. * Renders a final SQL statement by putting together the component parts in the correct order
  1695. *
  1696. * @param string $type type of query being run. e.g select, create, update, delete, schema, alter.
  1697. * @param array $data Array of data to insert into the query.
  1698. * @return string Rendered SQL expression to be run.
  1699. */
  1700. public function renderStatement($type, $data) {
  1701. extract($data);
  1702. $aliases = null;
  1703. switch (strtolower($type)) {
  1704. case 'select':
  1705. return trim("SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}");
  1706. case 'create':
  1707. return "INSERT INTO {$table} ({$fields}) VALUES ({$values})";
  1708. case 'update':
  1709. if (!empty($alias)) {
  1710. $aliases = "{$this->alias}{$alias} {$joins} ";
  1711. }
  1712. return trim("UPDATE {$table} {$aliases}SET {$fields} {$conditions}");
  1713. case 'delete':
  1714. if (!empty($alias)) {
  1715. $aliases = "{$this->alias}{$alias} {$joins} ";
  1716. }
  1717. return trim("DELETE {$alias} FROM {$table} {$aliases}{$conditions}");
  1718. case 'schema':
  1719. foreach (array('columns', 'indexes', 'tableParameters') as $var) {
  1720. if (is_array(${$var})) {
  1721. ${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
  1722. } else {
  1723. ${$var} = '';
  1724. }
  1725. }
  1726. if (trim($indexes) !== '') {
  1727. $columns .= ',';
  1728. }
  1729. return "CREATE TABLE {$table} (\n{$columns}{$indexes}) {$tableParameters};";
  1730. case 'alter':
  1731. return;
  1732. }
  1733. }
  1734. /**
  1735. * Merges a mixed set of string/array conditions.
  1736. *
  1737. * @param mixed $query
  1738. * @param mixed $assoc
  1739. * @return array
  1740. */
  1741. protected function _mergeConditions($query, $assoc) {
  1742. if (empty($assoc)) {
  1743. return $query;
  1744. }
  1745. if (is_array($query)) {
  1746. return array_merge((array)$assoc, $query);
  1747. }
  1748. if (!empty($query)) {
  1749. $query = array($query);
  1750. if (is_array($assoc)) {
  1751. $query = array_merge($query, $assoc);
  1752. } else {
  1753. $query[] = $assoc;
  1754. }
  1755. return $query;
  1756. }
  1757. return $assoc;
  1758. }
  1759. /**
  1760. * Generates and executes an SQL UPDATE statement for given model, fields, and values.
  1761. * For databases that do not support aliases in UPDATE queries.
  1762. *
  1763. * @param Model $Model
  1764. * @param array $fields
  1765. * @param array $values
  1766. * @param mixed $conditions
  1767. * @return boolean Success
  1768. */
  1769. public function update(Model $Model, $fields = array(), $values = null, $conditions = null) {
  1770. if (!$values) {
  1771. $combined = $fields;
  1772. } else {
  1773. $combined = array_combine($fields, $values);
  1774. }
  1775. $fields = implode(', ', $this->_prepareUpdateFields($Model, $combined, empty($conditions)));
  1776. $alias = $joins = null;
  1777. $table = $this->fullTableName($Model);
  1778. $conditions = $this->_matchRecords($Model, $conditions);
  1779. if ($conditions === false) {
  1780. return false;
  1781. }
  1782. $query = compact('table', 'alias', 'joins', 'fields', 'conditions');
  1783. if (!$this->execute($this->renderStatement('update', $query))) {
  1784. $Model->onError();
  1785. return false;
  1786. }
  1787. return true;
  1788. }
  1789. /**
  1790. * Quotes and prepares fields and values for an SQL UPDATE statement
  1791. *
  1792. * @param Model $Model
  1793. * @param array $fields
  1794. * @param boolean $quoteValues If values should be quoted, or treated as SQL snippets
  1795. * @param boolean $alias Include the model alias in the field name
  1796. * @return array Fields and values, quoted and prepared
  1797. */
  1798. protected function _prepareUpdateFields(Model $Model, $fields, $quoteValues = true, $alias = false) {
  1799. $quotedAlias = $this->startQuote . $Model->alias . $this->endQuote;
  1800. $updates = array();
  1801. foreach ($fields as $field => $value) {
  1802. if ($alias && strpos($field, '.') === false) {
  1803. $quoted = $Model->escapeField($field);
  1804. } elseif (!$alias && strpos($field, '.') !== false) {
  1805. $quoted = $this->name(str_replace($quotedAlias . '.', '', str_replace(
  1806. $Model->alias . '.', '', $field
  1807. )));
  1808. } else {
  1809. $quoted = $this->name($field);
  1810. }
  1811. if ($value === null) {
  1812. $updates[] = $quoted . ' = NULL';
  1813. continue;
  1814. }
  1815. $update = $quoted . ' = ';
  1816. if ($quoteValues) {
  1817. $update .= $this->value($value, $Model->getColumnType($field));
  1818. } elseif ($Model->getColumnType($field) === 'boolean' && (is_int($value) || is_bool($value))) {
  1819. $update .= $this->boolean($value, true);
  1820. } elseif (!$alias) {
  1821. $update .= str_replace($quotedAlias . '.', '', str_replace(
  1822. $Model->alias . '.', '', $value
  1823. ));
  1824. } else {
  1825. $update .= $value;
  1826. }
  1827. $updates[] = $update;
  1828. }
  1829. return $updates;
  1830. }
  1831. /**
  1832. * Generates and executes an SQL DELETE statement.
  1833. * For databases that do not support aliases in UPDATE queries.
  1834. *
  1835. * @param Model $Model
  1836. * @param mixed $conditions
  1837. * @return boolean Success
  1838. */
  1839. public function delete(Model $Model, $conditions = null) {
  1840. $alias = $joins = null;
  1841. $table = $this->fullTableName($Model);
  1842. $conditions = $this->_matchRecords($Model, $conditions);
  1843. if ($conditions === false) {
  1844. return false;
  1845. }
  1846. if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
  1847. $Model->onError();
  1848. return false;
  1849. }
  1850. return true;
  1851. }
  1852. /**
  1853. * Gets a list of record IDs for the given conditions. Used for multi-record updates and deletes
  1854. * in databases that do not support aliases in UPDATE/DELETE queries.
  1855. *
  1856. * @param Model $Model
  1857. * @param mixed $conditions
  1858. * @return array List of record IDs
  1859. */
  1860. protected function _matchRecords(Model $Model, $conditions = null) {
  1861. if ($conditions === true) {
  1862. $conditions = $this->conditions(true);
  1863. } elseif ($conditions === null) {
  1864. $conditions = $this->conditions($this->defaultConditions($Model, $conditions, false), true, true, $Model);
  1865. } else {
  1866. $noJoin = true;
  1867. foreach ($conditions as $field => $value) {
  1868. $originalField = $field;
  1869. if (strpos($field, '.') !== false) {
  1870. list(, $field) = explode('.', $field);
  1871. $field = ltrim($field, $this->startQuote);
  1872. $field = rtrim($field, $this->endQuote);
  1873. }
  1874. if (!$Model->hasField($field)) {
  1875. $noJoin = false;
  1876. break;
  1877. }
  1878. if ($field !== $originalField) {
  1879. $conditions[$field] = $value;
  1880. unset($conditions[$originalField]);
  1881. }
  1882. }
  1883. if ($noJoin === true) {
  1884. return $this->conditions($conditions);
  1885. }
  1886. $idList = $Model->find('all', array(
  1887. 'fields' => "{$Model->alias}.{$Model->primaryKey}",
  1888. 'conditions' => $conditions
  1889. ));
  1890. if (empty($idList)) {
  1891. return false;
  1892. }
  1893. $conditions = $this->conditions(array(
  1894. $Model->primaryKey => Hash::extract($idList, "{n}.{$Model->alias}.{$Model->primaryKey}")
  1895. ));
  1896. }
  1897. return $conditions;
  1898. }
  1899. /**
  1900. * Returns an array of SQL JOIN conditions from a model's associations.
  1901. *
  1902. * @param Model $Model
  1903. * @return array
  1904. */
  1905. protected function _getJoins(Model $Model) {
  1906. $join = array();
  1907. $joins = array_merge($Model->getAssociated('hasOne'), $Model->getAssociated('belongsTo'));
  1908. foreach ($joins as $assoc) {
  1909. if (!isset($Model->{$assoc})) {
  1910. continue;
  1911. }
  1912. $LinkModel = $Model->{$assoc};
  1913. if ($Model->useDbConfig !== $LinkModel->useDbConfig) {
  1914. continue;
  1915. }
  1916. $assocData = $Model->getAssociated($assoc);
  1917. $join[] = $this->buildJoinStatement(array(
  1918. 'table' => $LinkModel,
  1919. 'alias' => $assoc,
  1920. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1921. 'conditions' => trim($this->conditions(
  1922. $this->_mergeConditions($assocData['conditions'], $this->getConstraint($assocData['association'], $Model, $LinkModel, $assoc, $assocData)),
  1923. true,
  1924. false,
  1925. $Model
  1926. ))
  1927. ));
  1928. }
  1929. return $join;
  1930. }
  1931. /**
  1932. * Returns an SQL calculation, i.e. COUNT() or MAX()
  1933. *
  1934. * @param Model $Model
  1935. * @param string $func Lowercase name of SQL function, i.e. 'count' or 'max'
  1936. * @param array $params Function parameters (any values must be quoted manually)
  1937. * @return string An SQL calculation function
  1938. */
  1939. public function calculate(Model $Model, $func, $params = array()) {
  1940. $params = (array)$params;
  1941. switch (strtolower($func)) {
  1942. case 'count':
  1943. if (!isset($params[0])) {
  1944. $params[0] = '*';
  1945. }
  1946. if (!isset($params[1])) {
  1947. $params[1] = 'count';
  1948. }
  1949. if ($Model->isVirtualField($params[0])) {
  1950. $arg = $this->_quoteFields($Model->getVirtualField($params[0]));
  1951. } else {
  1952. $arg = $this->name($params[0]);
  1953. }
  1954. return 'COUNT(' . $arg . ') AS ' . $this->name($params[1]);
  1955. case 'max':
  1956. case 'min':
  1957. if (!isset($params[1])) {
  1958. $params[1] = $params[0];
  1959. }
  1960. if ($Model->isVirtualField($params[0])) {
  1961. $arg = $this->_quoteFields($Model->getVirtualField($params[0]));
  1962. } else {
  1963. $arg = $this->name($params[0]);
  1964. }
  1965. return strtoupper($func) . '(' . $arg . ') AS ' . $this->name($params[1]);
  1966. }
  1967. }
  1968. /**
  1969. * Deletes all the records in a table and resets the count of the auto-incrementing
  1970. * primary key, where applicable.
  1971. *
  1972. * @param Model|string $table A string or model class representing the table to be truncated
  1973. * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
  1974. */
  1975. public function truncate($table) {
  1976. return $this->execute('TRUNCATE TABLE ' . $this->fullTableName($table));
  1977. }
  1978. /**
  1979. * Check if the server support nested transactions
  1980. *
  1981. * @return boolean
  1982. */
  1983. public function nestedTransactionSupported() {
  1984. return false;
  1985. }
  1986. /**
  1987. * Begin a transaction
  1988. *
  1989. * @return boolean True on success, false on fail
  1990. * (i.e. if the database/model does not support transactions,
  1991. * or a transaction has not started).
  1992. */
  1993. public function begin() {
  1994. if ($this->_transactionStarted) {
  1995. if ($this->nestedTransactionSupported()) {
  1996. return $this->_beginNested();
  1997. }
  1998. $this->_transactionNesting++;
  1999. return $this->_transactionStarted;
  2000. }
  2001. $this->_transactionNesting = 0;
  2002. if ($this->fullDebug) {
  2003. $this->logQuery('BEGIN');
  2004. }
  2005. return $this->_transactionStarted = $this->_connection->beginTransaction();
  2006. }
  2007. /**
  2008. * Begin a nested transaction
  2009. *
  2010. * @return boolean
  2011. */
  2012. protected function _beginNested() {
  2013. $query = 'SAVEPOINT LEVEL' . ++$this->_transactionNesting;
  2014. if ($this->fullDebug) {
  2015. $this->logQuery($query);
  2016. }
  2017. $this->_connection->exec($query);
  2018. return true;
  2019. }
  2020. /**
  2021. * Commit a transaction
  2022. *
  2023. * @return boolean True on success, false on fail
  2024. * (i.e. if the database/model does not support transactions,
  2025. * or a transaction has not started).
  2026. */
  2027. public function commit() {
  2028. if (!$this->_transactionStarted) {
  2029. return false;
  2030. }
  2031. if ($this->_transactionNesting === 0) {
  2032. if ($this->fullDebug) {
  2033. $this->logQuery('COMMIT');
  2034. }
  2035. $this->_transactionStarted = false;
  2036. return $this->_connection->commit();
  2037. }
  2038. if ($this->nestedTransactionSupported()) {
  2039. return $this->_commitNested();
  2040. }
  2041. $this->_transactionNesting--;
  2042. return true;
  2043. }
  2044. /**
  2045. * Commit a nested transaction
  2046. *
  2047. * @return boolean
  2048. */
  2049. protected function _commitNested() {
  2050. $query = 'RELEASE SAVEPOINT LEVEL' . $this->_transactionNesting--;
  2051. if ($this->fullDebug) {
  2052. $this->logQuery($query);
  2053. }
  2054. $this->_connection->exec($query);
  2055. return true;
  2056. }
  2057. /**
  2058. * Rollback a transaction
  2059. *
  2060. * @return boolean True on success, false on fail
  2061. * (i.e. if the database/model does not support transactions,
  2062. * or a transaction has not started).
  2063. */
  2064. public function rollback() {
  2065. if (!$this->_transactionStarted) {
  2066. return false;
  2067. }
  2068. if ($this->_transactionNesting === 0) {
  2069. if ($this->fullDebug) {
  2070. $this->logQuery('ROLLBACK');
  2071. }
  2072. $this->_transactionStarted = false;
  2073. return $this->_connection->rollBack();
  2074. }
  2075. if ($this->nestedTransactionSupported()) {
  2076. return $this->_rollbackNested();
  2077. }
  2078. $this->_transactionNesting--;
  2079. return true;
  2080. }
  2081. /**
  2082. * Rollback a nested transaction
  2083. *
  2084. * @return boolean
  2085. */
  2086. protected function _rollbackNested() {
  2087. $query = 'ROLLBACK TO SAVEPOINT LEVEL' . $this->_transactionNesting--;
  2088. if ($this->fullDebug) {
  2089. $this->logQuery($query);
  2090. }
  2091. $this->_connection->exec($query);
  2092. return true;
  2093. }
  2094. /**
  2095. * Returns the ID generated from the previous INSERT operation.
  2096. *
  2097. * @param mixed $source
  2098. * @return mixed
  2099. */
  2100. public function lastInsertId($source = null) {
  2101. return $this->_connection->lastInsertId();
  2102. }
  2103. /**
  2104. * Creates a default set of conditions from the model if $conditions is null/empty.
  2105. * If conditions are supplied then they will be returned. If a model doesn't exist and no conditions
  2106. * were provided either null or false will be returned based on what was input.
  2107. *
  2108. * @param Model $Model
  2109. * @param string|array|boolean $conditions Array of conditions, conditions string, null or false. If an array of conditions,
  2110. * or string conditions those conditions will be returned. With other values the model's existence will be checked.
  2111. * If the model doesn't exist a null or false will be returned depending on the input value.
  2112. * @param boolean $useAlias Use model aliases rather than table names when generating conditions
  2113. * @return mixed Either null, false, $conditions or an array of default conditions to use.
  2114. * @see DboSource::update()
  2115. * @see DboSource::conditions()
  2116. */
  2117. public function defaultConditions(Model $Model, $conditions, $useAlias = true) {
  2118. if (!empty($conditions)) {
  2119. return $conditions;
  2120. }
  2121. $exists = $Model->exists();
  2122. if (!$exists && $conditions !== null) {
  2123. return false;
  2124. } elseif (!$exists) {
  2125. return null;
  2126. }
  2127. $alias = $Model->alias;
  2128. if (!$useAlias) {
  2129. $alias = $this->fullTableName($Model, false);
  2130. }
  2131. return array("{$alias}.{$Model->primaryKey}" => $Model->getID());
  2132. }
  2133. /**
  2134. * Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name)
  2135. *
  2136. * @param Model $Model
  2137. * @param string $key
  2138. * @param string $assoc
  2139. * @return string
  2140. */
  2141. public function resolveKey(Model $Model, $key, $assoc = null) {
  2142. if (strpos('.', $key) !== false) {
  2143. return $this->name($Model->alias) . '.' . $this->name($key);
  2144. }
  2145. return $key;
  2146. }
  2147. /**
  2148. * Private helper method to remove query metadata in given data array.
  2149. *
  2150. * @param array $data
  2151. * @return array
  2152. */
  2153. protected function _scrubQueryData($data) {
  2154. static $base = null;
  2155. if ($base === null) {
  2156. $base = array_fill_keys(array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group'), array());
  2157. $base['callbacks'] = null;
  2158. }
  2159. return (array)$data + $base;
  2160. }
  2161. /**
  2162. * Converts model virtual fields into sql expressions to be fetched later
  2163. *
  2164. * @param Model $Model
  2165. * @param string $alias Alias table name
  2166. * @param array $fields virtual fields to be used on query
  2167. * @return array
  2168. */
  2169. protected function _constructVirtualFields(Model $Model, $alias, $fields) {
  2170. $virtual = array();
  2171. foreach ($fields as $field) {
  2172. $virtualField = $this->name($alias . $this->virtualFieldSeparator . $field);
  2173. $expression = $this->_quoteFields($Model->getVirtualField($field));
  2174. $virtual[] = '(' . $expression . ") {$this->alias} {$virtualField}";
  2175. }
  2176. return $virtual;
  2177. }
  2178. /**
  2179. * Generates the fields list of an SQL query.
  2180. *
  2181. * @param Model $Model
  2182. * @param string $alias Alias table name
  2183. * @param mixed $fields
  2184. * @param boolean $quote If false, returns fields array unquoted
  2185. * @return array
  2186. */
  2187. public function fields(Model $Model, $alias = null, $fields = array(), $quote = true) {
  2188. if (empty($alias)) {
  2189. $alias = $Model->alias;
  2190. }
  2191. $virtualFields = $Model->getVirtualField();
  2192. $cacheKey = array(
  2193. $alias,
  2194. get_class($Model),
  2195. $Model->alias,
  2196. $virtualFields,
  2197. $fields,
  2198. $quote,
  2199. ConnectionManager::getSourceName($this),
  2200. $Model->schemaName,
  2201. $Model->table
  2202. );
  2203. $cacheKey = md5(serialize($cacheKey));
  2204. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  2205. return $return;
  2206. }
  2207. $allFields = empty($fields);
  2208. if ($allFields) {
  2209. $fields = array_keys($Model->schema());
  2210. } elseif (!is_array($fields)) {
  2211. $fields = String::tokenize($fields);
  2212. }
  2213. $fields = array_values(array_filter($fields));
  2214. $allFields = $allFields || in_array('*', $fields) || in_array($Model->alias . '.*', $fields);
  2215. $virtual = array();
  2216. if (!empty($virtualFields)) {
  2217. $virtualKeys = array_keys($virtualFields);
  2218. foreach ($virtualKeys as $field) {
  2219. $virtualKeys[] = $Model->alias . '.' . $field;
  2220. }
  2221. $virtual = ($allFields) ? $virtualKeys : array_intersect($virtualKeys, $fields);
  2222. foreach ($virtual as $i => $field) {
  2223. if (strpos($field, '.') !== false) {
  2224. $virtual[$i] = str_replace($Model->alias . '.', '', $field);
  2225. }
  2226. $fields = array_diff($fields, array($field));
  2227. }
  2228. $fields = array_values($fields);
  2229. }
  2230. if (!$quote) {
  2231. if (!empty($virtual)) {
  2232. $fields = array_merge($fields, $this->_constructVirtualFields($Model, $alias, $virtual));
  2233. }
  2234. return $fields;
  2235. }
  2236. $count = count($fields);
  2237. if ($count >= 1 && !in_array($fields[0], array('*', 'COUNT(*)'))) {
  2238. for ($i = 0; $i < $count; $i++) {
  2239. if (is_string($fields[$i]) && in_array($fields[$i], $virtual)) {
  2240. unset($fields[$i]);
  2241. continue;
  2242. }
  2243. if (is_object($fields[$i]) && isset($fields[$i]->type) && $fields[$i]->type === 'expression') {
  2244. $fields[$i] = $fields[$i]->value;
  2245. } elseif (preg_match('/^\(.*\)\s' . $this->alias . '.*/i', $fields[$i])) {
  2246. continue;
  2247. } elseif (!preg_match('/^.+\\(.*\\)/', $fields[$i])) {
  2248. $prepend = '';
  2249. if (strpos($fields[$i], 'DISTINCT') !== false) {
  2250. $prepend = 'DISTINCT ';
  2251. $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
  2252. }
  2253. $dot = strpos($fields[$i], '.');
  2254. if ($dot === false) {
  2255. $prefix = !(
  2256. strpos($fields[$i], ' ') !== false ||
  2257. strpos($fields[$i], '(') !== false
  2258. );
  2259. $fields[$i] = $this->name(($prefix ? $alias . '.' : '') . $fields[$i]);
  2260. } else {
  2261. if (strpos($fields[$i], ',') === false) {
  2262. $build = explode('.', $fields[$i]);
  2263. if (!Hash::numeric($build)) {
  2264. $fields[$i] = $this->name(implode('.', $build));
  2265. }
  2266. }
  2267. }
  2268. $fields[$i] = $prepend . $fields[$i];
  2269. } elseif (preg_match('/\(([\.\w]+)\)/', $fields[$i], $field)) {
  2270. if (isset($field[1])) {
  2271. if (strpos($field[1], '.') === false) {
  2272. $field[1] = $this->name($alias . '.' . $field[1]);
  2273. } else {
  2274. $field[0] = explode('.', $field[1]);
  2275. if (!Hash::numeric($field[0])) {
  2276. $field[0] = implode('.', array_map(array(&$this, 'name'), $field[0]));
  2277. $fields[$i] = preg_replace('/\(' . $field[1] . '\)/', '(' . $field[0] . ')', $fields[$i], 1);
  2278. }
  2279. }
  2280. }
  2281. }
  2282. }
  2283. }
  2284. if (!empty($virtual)) {
  2285. $fields = array_merge($fields, $this->_constructVirtualFields($Model, $alias, $virtual));
  2286. }
  2287. return $this->cacheMethod(__FUNCTION__, $cacheKey, array_unique($fields));
  2288. }
  2289. /**
  2290. * Creates a WHERE clause by parsing given conditions data. If an array or string
  2291. * conditions are provided those conditions will be parsed and quoted. If a boolean
  2292. * is given it will be integer cast as condition. Null will return 1 = 1.
  2293. *
  2294. * Results of this method are stored in a memory cache. This improves performance, but
  2295. * because the method uses a hashing algorithm it can have collisions.
  2296. * Setting DboSource::$cacheMethods to false will disable the memory cache.
  2297. *
  2298. * @param mixed $conditions Array or string of conditions, or any value.
  2299. * @param boolean $quoteValues If true, values should be quoted
  2300. * @param boolean $where If true, "WHERE " will be prepended to the return value
  2301. * @param Model $Model A reference to the Model instance making the query
  2302. * @return string SQL fragment
  2303. */
  2304. public function conditions($conditions, $quoteValues = true, $where = true, Model $Model = null) {
  2305. $clause = $out = '';
  2306. if ($where) {
  2307. $clause = ' WHERE ';
  2308. }
  2309. if (is_array($conditions) && !empty($conditions)) {
  2310. $out = $this->conditionKeysToString($conditions, $quoteValues, $Model);
  2311. if (empty($out)) {
  2312. return $clause . ' 1 = 1';
  2313. }
  2314. return $clause . implode(' AND ', $out);
  2315. }
  2316. if (is_bool($conditions)) {
  2317. return $clause . (int)$conditions . ' = 1';
  2318. }
  2319. if (empty($conditions) || trim($conditions) === '') {
  2320. return $clause . '1 = 1';
  2321. }
  2322. $clauses = '/^WHERE\\x20|^GROUP\\x20BY\\x20|^HAVING\\x20|^ORDER\\x20BY\\x20/i';
  2323. if (preg_match($clauses, $conditions)) {
  2324. $clause = '';
  2325. }
  2326. $conditions = $this->_quoteFields($conditions);
  2327. return $clause . $conditions;
  2328. }
  2329. /**
  2330. * Creates a WHERE clause by parsing given conditions array. Used by DboSource::conditions().
  2331. *
  2332. * @param array $conditions Array or string of conditions
  2333. * @param boolean $quoteValues If true, values should be quoted
  2334. * @param Model $Model A reference to the Model instance making the query
  2335. * @return string SQL fragment
  2336. */
  2337. public function conditionKeysToString($conditions, $quoteValues = true, Model $Model = null) {
  2338. $out = array();
  2339. $data = $columnType = null;
  2340. $bool = array('and', 'or', 'not', 'and not', 'or not', 'xor', '||', '&&');
  2341. foreach ($conditions as $key => $value) {
  2342. $join = ' AND ';
  2343. $not = null;
  2344. if (is_array($value)) {
  2345. $valueInsert = (
  2346. !empty($value) &&
  2347. (substr_count($key, '?') === count($value) || substr_count($key, ':') === count($value))
  2348. );
  2349. }
  2350. if (is_numeric($key) && empty($value)) {
  2351. continue;
  2352. } elseif (is_numeric($key) && is_string($value)) {
  2353. $out[] = $this->_quoteFields($value);
  2354. } elseif ((is_numeric($key) && is_array($value)) || in_array(strtolower(trim($key)), $bool)) {
  2355. if (in_array(strtolower(trim($key)), $bool)) {
  2356. $join = ' ' . strtoupper($key) . ' ';
  2357. } else {
  2358. $key = $join;
  2359. }
  2360. $value = $this->conditionKeysToString($value, $quoteValues, $Model);
  2361. if (strpos($join, 'NOT') !== false) {
  2362. if (strtoupper(trim($key)) === 'NOT') {
  2363. $key = 'AND ' . trim($key);
  2364. }
  2365. $not = 'NOT ';
  2366. }
  2367. if (empty($value)) {
  2368. continue;
  2369. }
  2370. if (empty($value[1])) {
  2371. if ($not) {
  2372. $out[] = $not . '(' . $value[0] . ')';
  2373. } else {
  2374. $out[] = $value[0];
  2375. }
  2376. } else {
  2377. $out[] = '(' . $not . '(' . implode(') ' . strtoupper($key) . ' (', $value) . '))';
  2378. }
  2379. } else {
  2380. if (is_object($value) && isset($value->type)) {
  2381. if ($value->type === 'identifier') {
  2382. $data .= $this->name($key) . ' = ' . $this->name($value->value);
  2383. } elseif ($value->type === 'expression') {
  2384. if (is_numeric($key)) {
  2385. $data .= $value->value;
  2386. } else {
  2387. $data .= $this->name($key) . ' = ' . $value->value;
  2388. }
  2389. }
  2390. } elseif (is_array($value) && !empty($value) && !$valueInsert) {
  2391. $keys = array_keys($value);
  2392. if ($keys === array_values($keys)) {
  2393. $count = count($value);
  2394. if ($count === 1 && !preg_match('/\s+(?:NOT|\!=)$/', $key)) {
  2395. $data = $this->_quoteFields($key) . ' = (';
  2396. if ($quoteValues) {
  2397. if ($Model !== null) {
  2398. $columnType = $Model->getColumnType($key);
  2399. }
  2400. $data .= implode(', ', $this->value($value, $columnType));
  2401. }
  2402. $data .= ')';
  2403. } else {
  2404. $data = $this->_parseKey($key, $value, $Model);
  2405. }
  2406. } else {
  2407. $ret = $this->conditionKeysToString($value, $quoteValues, $Model);
  2408. if (count($ret) > 1) {
  2409. $data = '(' . implode(') AND (', $ret) . ')';
  2410. } elseif (isset($ret[0])) {
  2411. $data = $ret[0];
  2412. }
  2413. }
  2414. } elseif (is_numeric($key) && !empty($value)) {
  2415. $data = $this->_quoteFields($value);
  2416. } else {
  2417. $data = $this->_parseKey(trim($key), $value, $Model);
  2418. }
  2419. if ($data) {
  2420. $out[] = $data;
  2421. $data = null;
  2422. }
  2423. }
  2424. }
  2425. return $out;
  2426. }
  2427. /**
  2428. * Extracts a Model.field identifier and an SQL condition operator from a string, formats
  2429. * and inserts values, and composes them into an SQL snippet.
  2430. *
  2431. * @param string $key An SQL key snippet containing a field and optional SQL operator
  2432. * @param mixed $value The value(s) to be inserted in the string
  2433. * @param Model $Model Model object initiating the query
  2434. * @return string
  2435. */
  2436. protected function _parseKey($key, $value, Model $Model = null) {
  2437. $operatorMatch = '/^(((' . implode(')|(', $this->_sqlOps);
  2438. $operatorMatch .= ')\\x20?)|<[>=]?(?![^>]+>)\\x20?|[>=!]{1,3}(?!<)\\x20?)/is';
  2439. $bound = (strpos($key, '?') !== false || (is_array($value) && strpos($key, ':') !== false));
  2440. if (strpos($key, ' ') === false) {
  2441. $operator = '=';
  2442. } else {
  2443. list($key, $operator) = explode(' ', trim($key), 2);
  2444. if (!preg_match($operatorMatch, trim($operator)) && strpos($operator, ' ') !== false) {
  2445. $key = $key . ' ' . $operator;
  2446. $split = strrpos($key, ' ');
  2447. $operator = substr($key, $split);
  2448. $key = substr($key, 0, $split);
  2449. }
  2450. }
  2451. $virtual = false;
  2452. $type = null;
  2453. if ($Model !== null) {
  2454. if ($Model->isVirtualField($key)) {
  2455. $key = $this->_quoteFields($Model->getVirtualField($key));
  2456. $virtual = true;
  2457. }
  2458. $type = $Model->getColumnType($key);
  2459. }
  2460. $null = $value === null || (is_array($value) && empty($value));
  2461. if (strtolower($operator) === 'not') {
  2462. $data = $this->conditionKeysToString(
  2463. array($operator => array($key => $value)), true, $Model
  2464. );
  2465. return $data[0];
  2466. }
  2467. $value = $this->value($value, $type);
  2468. if (!$virtual && $key !== '?') {
  2469. $isKey = (
  2470. strpos($key, '(') !== false ||
  2471. strpos($key, ')') !== false ||
  2472. strpos($key, '|') !== false
  2473. );
  2474. $key = $isKey ? $this->_quoteFields($key) : $this->name($key);
  2475. }
  2476. if ($bound) {
  2477. return String::insert($key . ' ' . trim($operator), $value);
  2478. }
  2479. if (!preg_match($operatorMatch, trim($operator))) {
  2480. $operator .= is_array($value) ? ' IN' : ' =';
  2481. }
  2482. $operator = trim($operator);
  2483. if (is_array($value)) {
  2484. $value = implode(', ', $value);
  2485. switch ($operator) {
  2486. case '=':
  2487. $operator = 'IN';
  2488. break;
  2489. case '!=':
  2490. case '<>':
  2491. $operator = 'NOT IN';
  2492. break;
  2493. }
  2494. $value = "({$value})";
  2495. } elseif ($null || $value === 'NULL') {
  2496. switch ($operator) {
  2497. case '=':
  2498. $operator = 'IS';
  2499. break;
  2500. case '!=':
  2501. case '<>':
  2502. $operator = 'IS NOT';
  2503. break;
  2504. }
  2505. }
  2506. if ($virtual) {
  2507. return "({$key}) {$operator} {$value}";
  2508. }
  2509. return "{$key} {$operator} {$value}";
  2510. }
  2511. /**
  2512. * Quotes Model.fields
  2513. *
  2514. * @param string $conditions
  2515. * @return string or false if no match
  2516. */
  2517. protected function _quoteFields($conditions) {
  2518. $start = $end = null;
  2519. $original = $conditions;
  2520. if (!empty($this->startQuote)) {
  2521. $start = preg_quote($this->startQuote);
  2522. }
  2523. if (!empty($this->endQuote)) {
  2524. $end = preg_quote($this->endQuote);
  2525. }
  2526. $conditions = str_replace(array($start, $end), '', $conditions);
  2527. $conditions = preg_replace_callback(
  2528. '/(?:[\'\"][^\'\"\\\]*(?:\\\.[^\'\"\\\]*)*[\'\"])|([a-z0-9_][a-z0-9\\-_]*\\.[a-z0-9_][a-z0-9_\\-]*)/i',
  2529. array(&$this, '_quoteMatchedField'),
  2530. $conditions
  2531. );
  2532. if ($conditions !== null) {
  2533. return $conditions;
  2534. }
  2535. return $original;
  2536. }
  2537. /**
  2538. * Auxiliary function to quote matches `Model.fields` from a preg_replace_callback call
  2539. *
  2540. * @param string $match matched string
  2541. * @return string quoted string
  2542. */
  2543. protected function _quoteMatchedField($match) {
  2544. if (is_numeric($match[0])) {
  2545. return $match[0];
  2546. }
  2547. return $this->name($match[0]);
  2548. }
  2549. /**
  2550. * Returns a limit statement in the correct format for the particular database.
  2551. *
  2552. * @param integer $limit Limit of results returned
  2553. * @param integer $offset Offset from which to start results
  2554. * @return string SQL limit/offset statement
  2555. */
  2556. public function limit($limit, $offset = null) {
  2557. if ($limit) {
  2558. $rt = ' LIMIT';
  2559. if ($offset) {
  2560. $rt .= sprintf(' %u,', $offset);
  2561. }
  2562. $rt .= sprintf(' %u', $limit);
  2563. return $rt;
  2564. }
  2565. return null;
  2566. }
  2567. /**
  2568. * Returns an ORDER BY clause as a string.
  2569. *
  2570. * @param array|string $keys Field reference, as a key (i.e. Post.title)
  2571. * @param string $direction Direction (ASC or DESC)
  2572. * @param Model $Model Model reference (used to look for virtual field)
  2573. * @return string ORDER BY clause
  2574. */
  2575. public function order($keys, $direction = 'ASC', Model $Model = null) {
  2576. if (!is_array($keys)) {
  2577. $keys = array($keys);
  2578. }
  2579. $keys = array_filter($keys);
  2580. $result = array();
  2581. while (!empty($keys)) {
  2582. list($key, $dir) = each($keys);
  2583. array_shift($keys);
  2584. if (is_numeric($key)) {
  2585. $key = $dir;
  2586. $dir = $direction;
  2587. }
  2588. if (is_string($key) && strpos($key, ',') !== false && !preg_match('/\(.+\,.+\)/', $key)) {
  2589. $key = array_map('trim', explode(',', $key));
  2590. }
  2591. if (is_array($key)) {
  2592. //Flatten the array
  2593. $key = array_reverse($key, true);
  2594. foreach ($key as $k => $v) {
  2595. if (is_numeric($k)) {
  2596. array_unshift($keys, $v);
  2597. } else {
  2598. $keys = array($k => $v) + $keys;
  2599. }
  2600. }
  2601. continue;
  2602. } elseif (is_object($key) && isset($key->type) && $key->type === 'expression') {
  2603. $result[] = $key->value;
  2604. continue;
  2605. }
  2606. if (preg_match('/\\x20(ASC|DESC).*/i', $key, $_dir)) {
  2607. $dir = $_dir[0];
  2608. $key = preg_replace('/\\x20(ASC|DESC).*/i', '', $key);
  2609. }
  2610. $key = trim($key);
  2611. if ($Model !== null) {
  2612. if ($Model->isVirtualField($key)) {
  2613. $key = '(' . $this->_quoteFields($Model->getVirtualField($key)) . ')';
  2614. }
  2615. list($alias) = pluginSplit($key);
  2616. if ($alias !== $Model->alias && is_object($Model->{$alias}) && $Model->{$alias}->isVirtualField($key)) {
  2617. $key = '(' . $this->_quoteFields($Model->{$alias}->getVirtualField($key)) . ')';
  2618. }
  2619. }
  2620. if (strpos($key, '.')) {
  2621. $key = preg_replace_callback('/([a-zA-Z0-9_-]{1,})\\.([a-zA-Z0-9_-]{1,})/', array(&$this, '_quoteMatchedField'), $key);
  2622. }
  2623. if (!preg_match('/\s/', $key) && strpos($key, '.') === false) {
  2624. $key = $this->name($key);
  2625. }
  2626. $key .= ' ' . trim($dir);
  2627. $result[] = $key;
  2628. }
  2629. if (!empty($result)) {
  2630. return ' ORDER BY ' . implode(', ', $result);
  2631. }
  2632. return '';
  2633. }
  2634. /**
  2635. * Create a GROUP BY SQL clause.
  2636. *
  2637. * @param string|array $fields Group By fields
  2638. * @param Model $Model
  2639. * @return string Group By clause or null.
  2640. */
  2641. public function group($fields, Model $Model = null) {
  2642. if (empty($fields)) {
  2643. return null;
  2644. }
  2645. if (!is_array($fields)) {
  2646. $fields = array($fields);
  2647. }
  2648. if ($Model !== null) {
  2649. foreach ($fields as $index => $key) {
  2650. if ($Model->isVirtualField($key)) {
  2651. $fields[$index] = '(' . $Model->getVirtualField($key) . ')';
  2652. }
  2653. }
  2654. }
  2655. $fields = implode(', ', $fields);
  2656. return ' GROUP BY ' . $this->_quoteFields($fields);
  2657. }
  2658. /**
  2659. * Disconnects database, kills the connection and says the connection is closed.
  2660. *
  2661. * @return void
  2662. */
  2663. public function close() {
  2664. $this->disconnect();
  2665. }
  2666. /**
  2667. * Checks if the specified table contains any record matching specified SQL
  2668. *
  2669. * @param Model $Model Model to search
  2670. * @param string $sql SQL WHERE clause (condition only, not the "WHERE" part)
  2671. * @return boolean True if the table has a matching record, else false
  2672. */
  2673. public function hasAny(Model $Model, $sql) {
  2674. $sql = $this->conditions($sql);
  2675. $table = $this->fullTableName($Model);
  2676. $alias = $this->alias . $this->name($Model->alias);
  2677. $where = $sql ? "{$sql}" : ' WHERE 1 = 1';
  2678. $id = $Model->escapeField();
  2679. $out = $this->fetchRow("SELECT COUNT({$id}) {$this->alias}count FROM {$table} {$alias}{$where}");
  2680. if (is_array($out)) {
  2681. return $out[0]['count'];
  2682. }
  2683. return false;
  2684. }
  2685. /**
  2686. * Gets the length of a database-native column description, or null if no length
  2687. *
  2688. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  2689. * @return mixed An integer or string representing the length of the column, or null for unknown length.
  2690. */
  2691. public function length($real) {
  2692. if (!preg_match_all('/([\w\s]+)(?:\((\d+)(?:,(\d+))?\))?(\sunsigned)?(\szerofill)?/', $real, $result)) {
  2693. $col = str_replace(array(')', 'unsigned'), '', $real);
  2694. $limit = null;
  2695. if (strpos($col, '(') !== false) {
  2696. list($col, $limit) = explode('(', $col);
  2697. }
  2698. if ($limit !== null) {
  2699. return intval($limit);
  2700. }
  2701. return null;
  2702. }
  2703. $types = array(
  2704. 'int' => 1, 'tinyint' => 1, 'smallint' => 1, 'mediumint' => 1, 'integer' => 1, 'bigint' => 1
  2705. );
  2706. list($real, $type, $length, $offset, $sign) = $result;
  2707. $typeArr = $type;
  2708. $type = $type[0];
  2709. $length = $length[0];
  2710. $offset = $offset[0];
  2711. $isFloat = in_array($type, array('dec', 'decimal', 'float', 'numeric', 'double'));
  2712. if ($isFloat && $offset) {
  2713. return $length . ',' . $offset;
  2714. }
  2715. if (($real[0] == $type) && (count($real) === 1)) {
  2716. return null;
  2717. }
  2718. if (isset($types[$type])) {
  2719. $length += $types[$type];
  2720. if (!empty($sign)) {
  2721. $length--;
  2722. }
  2723. } elseif (in_array($type, array('enum', 'set'))) {
  2724. $length = 0;
  2725. foreach ($typeArr as $key => $enumValue) {
  2726. if ($key === 0) {
  2727. continue;
  2728. }
  2729. $tmpLength = strlen($enumValue);
  2730. if ($tmpLength > $length) {
  2731. $length = $tmpLength;
  2732. }
  2733. }
  2734. }
  2735. return intval($length);
  2736. }
  2737. /**
  2738. * Translates between PHP boolean values and Database (faked) boolean values
  2739. *
  2740. * @param mixed $data Value to be translated
  2741. * @param boolean $quote
  2742. * @return string|boolean Converted boolean value
  2743. */
  2744. public function boolean($data, $quote = false) {
  2745. if ($quote) {
  2746. return !empty($data) ? '1' : '0';
  2747. }
  2748. return !empty($data);
  2749. }
  2750. /**
  2751. * Inserts multiple values into a table
  2752. *
  2753. * @param string $table The table being inserted into.
  2754. * @param array $fields The array of field/column names being inserted.
  2755. * @param array $values The array of values to insert. The values should
  2756. * be an array of rows. Each row should have values keyed by the column name.
  2757. * Each row must have the values in the same order as $fields.
  2758. * @return boolean
  2759. */
  2760. public function insertMulti($table, $fields, $values) {
  2761. $table = $this->fullTableName($table);
  2762. $holder = implode(',', array_fill(0, count($fields), '?'));
  2763. $fields = implode(', ', array_map(array(&$this, 'name'), $fields));
  2764. $pdoMap = array(
  2765. 'integer' => PDO::PARAM_INT,
  2766. 'float' => PDO::PARAM_STR,
  2767. 'boolean' => PDO::PARAM_BOOL,
  2768. 'string' => PDO::PARAM_STR,
  2769. 'text' => PDO::PARAM_STR
  2770. );
  2771. $columnMap = array();
  2772. $sql = "INSERT INTO {$table} ({$fields}) VALUES ({$holder})";
  2773. $statement = $this->_connection->prepare($sql);
  2774. $this->begin();
  2775. foreach ($values[key($values)] as $key => $val) {
  2776. $type = $this->introspectType($val);
  2777. $columnMap[$key] = $pdoMap[$type];
  2778. }
  2779. foreach ($values as $value) {
  2780. $i = 1;
  2781. foreach ($value as $col => $val) {
  2782. $statement->bindValue($i, $val, $columnMap[$col]);
  2783. $i += 1;
  2784. }
  2785. $statement->execute();
  2786. $statement->closeCursor();
  2787. if ($this->fullDebug) {
  2788. $this->logQuery($sql, $value);
  2789. }
  2790. }
  2791. return $this->commit();
  2792. }
  2793. /**
  2794. * Reset a sequence based on the MAX() value of $column. Useful
  2795. * for resetting sequences after using insertMulti().
  2796. *
  2797. * This method should be implemented by datasources that require sequences to be used.
  2798. *
  2799. * @param string $table The name of the table to update.
  2800. * @param string $column The column to use when resetting the sequence value.
  2801. * @return boolean|void success.
  2802. */
  2803. public function resetSequence($table, $column) {
  2804. }
  2805. /**
  2806. * Returns an array of the indexes in given datasource name.
  2807. *
  2808. * @param string $model Name of model to inspect
  2809. * @return array Fields in table. Keys are column and unique
  2810. */
  2811. public function index($model) {
  2812. return array();
  2813. }
  2814. /**
  2815. * Generate a database-native schema for the given Schema object
  2816. *
  2817. * @param CakeSchema $schema An instance of a subclass of CakeSchema
  2818. * @param string $tableName Optional. If specified only the table name given will be generated.
  2819. * Otherwise, all tables defined in the schema are generated.
  2820. * @return string
  2821. */
  2822. public function createSchema($schema, $tableName = null) {
  2823. if (!$schema instanceof CakeSchema) {
  2824. trigger_error(__d('cake_dev', 'Invalid schema object'), E_USER_WARNING);
  2825. return null;
  2826. }
  2827. $out = '';
  2828. foreach ($schema->tables as $curTable => $columns) {
  2829. if (!$tableName || $tableName == $curTable) {
  2830. $cols = $indexes = $tableParameters = array();
  2831. $primary = null;
  2832. $table = $this->fullTableName($curTable);
  2833. $primaryCount = 0;
  2834. foreach ($columns as $col) {
  2835. if (isset($col['key']) && $col['key'] === 'primary') {
  2836. $primaryCount++;
  2837. }
  2838. }
  2839. foreach ($columns as $name => $col) {
  2840. if (is_string($col)) {
  2841. $col = array('type' => $col);
  2842. }
  2843. $isPrimary = isset($col['key']) && $col['key'] === 'primary';
  2844. // Multi-column primary keys are not supported.
  2845. if ($isPrimary && $primaryCount > 1) {
  2846. unset($col['key']);
  2847. $isPrimary = false;
  2848. }
  2849. if ($isPrimary) {
  2850. $primary = $name;
  2851. }
  2852. if ($name !== 'indexes' && $name !== 'tableParameters') {
  2853. $col['name'] = $name;
  2854. if (!isset($col['type'])) {
  2855. $col['type'] = 'string';
  2856. }
  2857. $cols[] = $this->buildColumn($col);
  2858. } elseif ($name === 'indexes') {
  2859. $indexes = array_merge($indexes, $this->buildIndex($col, $table));
  2860. } elseif ($name === 'tableParameters') {
  2861. $tableParameters = array_merge($tableParameters, $this->buildTableParameters($col, $table));
  2862. }
  2863. }
  2864. if (!isset($columns['indexes']['PRIMARY']) && !empty($primary)) {
  2865. $col = array('PRIMARY' => array('column' => $primary, 'unique' => 1));
  2866. $indexes = array_merge($indexes, $this->buildIndex($col, $table));
  2867. }
  2868. $columns = $cols;
  2869. $out .= $this->renderStatement('schema', compact('table', 'columns', 'indexes', 'tableParameters')) . "\n\n";
  2870. }
  2871. }
  2872. return $out;
  2873. }
  2874. /**
  2875. * Generate a alter syntax from CakeSchema::compare()
  2876. *
  2877. * @param mixed $compare
  2878. * @param string $table
  2879. * @return boolean
  2880. */
  2881. public function alterSchema($compare, $table = null) {
  2882. return false;
  2883. }
  2884. /**
  2885. * Generate a "drop table" statement for the given Schema object
  2886. *
  2887. * @param CakeSchema $schema An instance of a subclass of CakeSchema
  2888. * @param string $table Optional. If specified only the table name given will be generated.
  2889. * Otherwise, all tables defined in the schema are generated.
  2890. * @return string
  2891. */
  2892. public function dropSchema(CakeSchema $schema, $table = null) {
  2893. $out = '';
  2894. if ($table && array_key_exists($table, $schema->tables)) {
  2895. return $this->_dropTable($table) . "\n";
  2896. } elseif ($table) {
  2897. return $out;
  2898. }
  2899. foreach (array_keys($schema->tables) as $curTable) {
  2900. $out .= $this->_dropTable($curTable) . "\n";
  2901. }
  2902. return $out;
  2903. }
  2904. /**
  2905. * Generate a "drop table" statement for a single table
  2906. *
  2907. * @param type $table Name of the table to drop
  2908. * @return string Drop table SQL statement
  2909. */
  2910. protected function _dropTable($table) {
  2911. return 'DROP TABLE ' . $this->fullTableName($table) . ";";
  2912. }
  2913. /**
  2914. * Generate a database-native column schema string
  2915. *
  2916. * @param array $column An array structured like the following: array('name' => 'value', 'type' => 'value'[, options]),
  2917. * where options can be 'default', 'length', or 'key'.
  2918. * @return string
  2919. */
  2920. public function buildColumn($column) {
  2921. $name = $type = null;
  2922. extract(array_merge(array('null' => true), $column));
  2923. if (empty($name) || empty($type)) {
  2924. trigger_error(__d('cake_dev', 'Column name or type not defined in schema'), E_USER_WARNING);
  2925. return null;
  2926. }
  2927. if (!isset($this->columns[$type])) {
  2928. trigger_error(__d('cake_dev', 'Column type %s does not exist', $type), E_USER_WARNING);
  2929. return null;
  2930. }
  2931. $real = $this->columns[$type];
  2932. $out = $this->name($name) . ' ' . $real['name'];
  2933. if (isset($column['length'])) {
  2934. $length = $column['length'];
  2935. } elseif (isset($column['limit'])) {
  2936. $length = $column['limit'];
  2937. } elseif (isset($real['length'])) {
  2938. $length = $real['length'];
  2939. } elseif (isset($real['limit'])) {
  2940. $length = $real['limit'];
  2941. }
  2942. if (isset($length)) {
  2943. $out .= '(' . $length . ')';
  2944. }
  2945. if (($column['type'] === 'integer' || $column['type'] === 'float') && isset($column['default']) && $column['default'] === '') {
  2946. $column['default'] = null;
  2947. }
  2948. $out = $this->_buildFieldParameters($out, $column, 'beforeDefault');
  2949. if (isset($column['key']) && $column['key'] === 'primary' && ($type === 'integer' || $type === 'biginteger')) {
  2950. $out .= ' ' . $this->columns['primary_key']['name'];
  2951. } elseif (isset($column['key']) && $column['key'] === 'primary') {
  2952. $out .= ' NOT NULL';
  2953. } elseif (isset($column['default']) && isset($column['null']) && $column['null'] === false) {
  2954. $out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL';
  2955. } elseif (isset($column['default'])) {
  2956. $out .= ' DEFAULT ' . $this->value($column['default'], $type);
  2957. } elseif ($type !== 'timestamp' && !empty($column['null'])) {
  2958. $out .= ' DEFAULT NULL';
  2959. } elseif ($type === 'timestamp' && !empty($column['null'])) {
  2960. $out .= ' NULL';
  2961. } elseif (isset($column['null']) && $column['null'] === false) {
  2962. $out .= ' NOT NULL';
  2963. }
  2964. if ($type === 'timestamp' && isset($column['default']) && strtolower($column['default']) === 'current_timestamp') {
  2965. $out = str_replace(array("'CURRENT_TIMESTAMP'", "'current_timestamp'"), 'CURRENT_TIMESTAMP', $out);
  2966. }
  2967. return $this->_buildFieldParameters($out, $column, 'afterDefault');
  2968. }
  2969. /**
  2970. * Build the field parameters, in a position
  2971. *
  2972. * @param string $columnString The partially built column string
  2973. * @param array $columnData The array of column data.
  2974. * @param string $position The position type to use. 'beforeDefault' or 'afterDefault' are common
  2975. * @return string a built column with the field parameters added.
  2976. */
  2977. protected function _buildFieldParameters($columnString, $columnData, $position) {
  2978. foreach ($this->fieldParameters as $paramName => $value) {
  2979. if (isset($columnData[$paramName]) && $value['position'] == $position) {
  2980. if (isset($value['options']) && !in_array($columnData[$paramName], $value['options'], true)) {
  2981. continue;
  2982. }
  2983. if (isset($value['types']) && !in_array($columnData['type'], $value['types'], true)) {
  2984. continue;
  2985. }
  2986. $val = $columnData[$paramName];
  2987. if ($value['quote']) {
  2988. $val = $this->value($val);
  2989. }
  2990. $columnString .= ' ' . $value['value'] . (empty($value['noVal']) ? $value['join'] . $val : '');
  2991. }
  2992. }
  2993. return $columnString;
  2994. }
  2995. /**
  2996. * Format indexes for create table.
  2997. *
  2998. * @param array $indexes
  2999. * @param string $table
  3000. * @return array
  3001. */
  3002. public function buildIndex($indexes, $table = null) {
  3003. $join = array();
  3004. foreach ($indexes as $name => $value) {
  3005. $out = '';
  3006. if ($name === 'PRIMARY') {
  3007. $out .= 'PRIMARY ';
  3008. $name = null;
  3009. } else {
  3010. if (!empty($value['unique'])) {
  3011. $out .= 'UNIQUE ';
  3012. }
  3013. $name = $this->startQuote . $name . $this->endQuote;
  3014. }
  3015. if (is_array($value['column'])) {
  3016. $out .= 'KEY ' . $name . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
  3017. } else {
  3018. $out .= 'KEY ' . $name . ' (' . $this->name($value['column']) . ')';
  3019. }
  3020. $join[] = $out;
  3021. }
  3022. return $join;
  3023. }
  3024. /**
  3025. * Read additional table parameters
  3026. *
  3027. * @param string $name
  3028. * @return array
  3029. */
  3030. public function readTableParameters($name) {
  3031. $parameters = array();
  3032. if (method_exists($this, 'listDetailedSources')) {
  3033. $currentTableDetails = $this->listDetailedSources($name);
  3034. foreach ($this->tableParameters as $paramName => $parameter) {
  3035. if (!empty($parameter['column']) && !empty($currentTableDetails[$parameter['column']])) {
  3036. $parameters[$paramName] = $currentTableDetails[$parameter['column']];
  3037. }
  3038. }
  3039. }
  3040. return $parameters;
  3041. }
  3042. /**
  3043. * Format parameters for create table
  3044. *
  3045. * @param array $parameters
  3046. * @param string $table
  3047. * @return array
  3048. */
  3049. public function buildTableParameters($parameters, $table = null) {
  3050. $result = array();
  3051. foreach ($parameters as $name => $value) {
  3052. if (isset($this->tableParameters[$name])) {
  3053. if ($this->tableParameters[$name]['quote']) {
  3054. $value = $this->value($value);
  3055. }
  3056. $result[] = $this->tableParameters[$name]['value'] . $this->tableParameters[$name]['join'] . $value;
  3057. }
  3058. }
  3059. return $result;
  3060. }
  3061. /**
  3062. * Guesses the data type of an array
  3063. *
  3064. * @param string $value
  3065. * @return void
  3066. */
  3067. public function introspectType($value) {
  3068. if (!is_array($value)) {
  3069. if (is_bool($value)) {
  3070. return 'boolean';
  3071. }
  3072. if (is_float($value) && floatval($value) === $value) {
  3073. return 'float';
  3074. }
  3075. if (is_int($value) && intval($value) === $value) {
  3076. return 'integer';
  3077. }
  3078. if (is_string($value) && strlen($value) > 255) {
  3079. return 'text';
  3080. }
  3081. return 'string';
  3082. }
  3083. $isAllFloat = $isAllInt = true;
  3084. $containsInt = $containsString = false;
  3085. foreach ($value as $valElement) {
  3086. $valElement = trim($valElement);
  3087. if (!is_float($valElement) && !preg_match('/^[\d]+\.[\d]+$/', $valElement)) {
  3088. $isAllFloat = false;
  3089. } else {
  3090. continue;
  3091. }
  3092. if (!is_int($valElement) && !preg_match('/^[\d]+$/', $valElement)) {
  3093. $isAllInt = false;
  3094. } else {
  3095. $containsInt = true;
  3096. continue;
  3097. }
  3098. $containsString = true;
  3099. }
  3100. if ($isAllFloat) {
  3101. return 'float';
  3102. }
  3103. if ($isAllInt) {
  3104. return 'integer';
  3105. }
  3106. if ($containsInt && !$containsString) {
  3107. return 'integer';
  3108. }
  3109. return 'string';
  3110. }
  3111. /**
  3112. * Writes a new key for the in memory sql query cache
  3113. *
  3114. * @param string $sql SQL query
  3115. * @param mixed $data result of $sql query
  3116. * @param array $params query params bound as values
  3117. * @return void
  3118. */
  3119. protected function _writeQueryCache($sql, $data, $params = array()) {
  3120. if (preg_match('/^\s*select/i', $sql)) {
  3121. $this->_queryCache[$sql][serialize($params)] = $data;
  3122. }
  3123. }
  3124. /**
  3125. * Returns the result for a sql query if it is already cached
  3126. *
  3127. * @param string $sql SQL query
  3128. * @param array $params query params bound as values
  3129. * @return mixed results for query if it is cached, false otherwise
  3130. */
  3131. public function getQueryCache($sql, $params = array()) {
  3132. if (isset($this->_queryCache[$sql]) && preg_match('/^\s*select/i', $sql)) {
  3133. $serialized = serialize($params);
  3134. if (isset($this->_queryCache[$sql][$serialized])) {
  3135. return $this->_queryCache[$sql][$serialized];
  3136. }
  3137. }
  3138. return false;
  3139. }
  3140. /**
  3141. * Used for storing in cache the results of the in-memory methodCache
  3142. */
  3143. public function __destruct() {
  3144. if ($this->_methodCacheChange) {
  3145. Cache::write('method_cache', self::$methodCache, '_cake_core_');
  3146. }
  3147. }
  3148. }