DboSource.php 100 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547
  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 bool
  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 bool
  68. */
  69. public $useNestedTransactions = false;
  70. /**
  71. * Print full query debug info?
  72. *
  73. * @var bool
  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 int
  86. */
  87. public $numRows = null;
  88. /**
  89. * Time the last query took
  90. *
  91. * @var int
  92. */
  93. public $took = null;
  94. /**
  95. * Result
  96. *
  97. * @var array
  98. */
  99. protected $_result = null;
  100. /**
  101. * Queries count.
  102. *
  103. * @var int
  104. */
  105. protected $_queriesCnt = 0;
  106. /**
  107. * Total duration of all queries.
  108. *
  109. * @var int
  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 int
  124. */
  125. protected $_queriesLogMax = 200;
  126. /**
  127. * Caches serialized results of executed queries
  128. *
  129. * @var array
  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 int
  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 bool
  207. */
  208. protected $_methodCacheChange = false;
  209. /**
  210. * Constructor
  211. *
  212. * @param array $config Array of configuration information for the Datasource.
  213. * @param bool $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 bool 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 bool 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 bool
  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 The options for executing the query.
  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 The source to check.
  453. * @return int 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 int 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|bool $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 bool|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 bool
  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 bool 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 bool 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 bool $sorted Get the queries sorted by time taken, defaults to false.
  792. * @param bool $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 bool $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 bool $quote Whether you want the table name quoted.
  855. * @param bool $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 bool 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 int $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. $originalJoins = $queryData['joins'];
  966. $queryData['joins'] = array();
  967. // Generate hasOne and belongsTo associations inside $queryData
  968. $linkedModels = array();
  969. foreach ($associations as $type) {
  970. if ($type !== 'hasOne' && $type !== 'belongsTo') {
  971. continue;
  972. }
  973. foreach ($Model->{$type} as $assoc => $assocData) {
  974. $LinkModel = $Model->{$assoc};
  975. if ($Model->useDbConfig !== $LinkModel->useDbConfig) {
  976. continue;
  977. }
  978. if ($noAssocFields) {
  979. $assocData['fields'] = false;
  980. }
  981. $external = isset($assocData['external']);
  982. if ($this->generateAssociationQuery($Model, $LinkModel, $type, $assoc, $assocData, $queryData, $external) === true) {
  983. $linkedModels[$type . '/' . $assoc] = true;
  984. }
  985. }
  986. }
  987. if (!empty($originalJoins)) {
  988. $queryData['joins'] = array_merge($queryData['joins'], $originalJoins);
  989. }
  990. // Build SQL statement with the primary model, plus hasOne and belongsTo associations
  991. $query = $this->buildAssociationQuery($Model, $queryData);
  992. $resultSet = $this->fetchAll($query, $Model->cacheQueries);
  993. unset($query);
  994. if ($resultSet === false) {
  995. $Model->onError();
  996. return false;
  997. }
  998. $filtered = array();
  999. // Filter hasOne and belongsTo associations
  1000. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  1001. $filtered = $this->_filterResults($resultSet, $Model);
  1002. }
  1003. // Deep associations
  1004. if ($Model->recursive > -1) {
  1005. $joined = array();
  1006. if (isset($queryData['joins'][0]['alias'])) {
  1007. $joined[$Model->alias] = (array)Hash::extract($queryData['joins'], '{n}.alias');
  1008. }
  1009. foreach ($associations as $type) {
  1010. foreach ($Model->{$type} as $assoc => $assocData) {
  1011. $LinkModel = $Model->{$assoc};
  1012. if (!isset($linkedModels[$type . '/' . $assoc])) {
  1013. $db = $Model->useDbConfig === $LinkModel->useDbConfig ? $this : $LinkModel->getDataSource();
  1014. } elseif ($Model->recursive > 1) {
  1015. $db = $this;
  1016. }
  1017. if (isset($db) && method_exists($db, 'queryAssociation')) {
  1018. $stack = array($assoc);
  1019. $stack['_joined'] = $joined;
  1020. $db->queryAssociation($Model, $LinkModel, $type, $assoc, $assocData, $array, true, $resultSet, $Model->recursive - 1, $stack);
  1021. unset($db);
  1022. if ($type === 'hasMany' || $type === 'hasAndBelongsToMany') {
  1023. $filtered[] = $assoc;
  1024. }
  1025. }
  1026. }
  1027. }
  1028. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  1029. $this->_filterResults($resultSet, $Model, $filtered);
  1030. }
  1031. }
  1032. if ($recursive !== null) {
  1033. $Model->recursive = $modelRecursive;
  1034. }
  1035. return $resultSet;
  1036. }
  1037. /**
  1038. * Passes association results through afterFind filters of the corresponding model.
  1039. *
  1040. * The primary model is always excluded, because the filtering is later done by Model::_filterResults().
  1041. *
  1042. * @param array &$resultSet Reference of resultset to be filtered.
  1043. * @param Model $Model Instance of model to operate against.
  1044. * @param array $filtered List of classes already filtered, to be skipped.
  1045. * @return array Array of results that have been filtered through $Model->afterFind.
  1046. */
  1047. protected function _filterResults(&$resultSet, Model $Model, $filtered = array()) {
  1048. if (!is_array($resultSet)) {
  1049. return array();
  1050. }
  1051. $current = reset($resultSet);
  1052. if (!is_array($current)) {
  1053. return array();
  1054. }
  1055. $keys = array_diff(array_keys($current), $filtered, array($Model->alias));
  1056. $filtering = array();
  1057. foreach ($keys as $className) {
  1058. if (!isset($Model->{$className}) || !is_object($Model->{$className})) {
  1059. continue;
  1060. }
  1061. $LinkedModel = $Model->{$className};
  1062. $filtering[] = $className;
  1063. foreach ($resultSet as $key => &$result) {
  1064. $data = $LinkedModel->afterFind(array(array($className => $result[$className])), false);
  1065. if (isset($data[0][$className])) {
  1066. $result[$className] = $data[0][$className];
  1067. } else {
  1068. unset($resultSet[$key]);
  1069. }
  1070. }
  1071. }
  1072. return $filtering;
  1073. }
  1074. /**
  1075. * Queries associations.
  1076. *
  1077. * Used to fetch results on recursive models.
  1078. *
  1079. * - 'hasMany' associations with no limit set:
  1080. * Fetch, filter and merge is done recursively for every level.
  1081. *
  1082. * - 'hasAndBelongsToMany' associations:
  1083. * Fetch and filter is done unaffected by the (recursive) level set.
  1084. *
  1085. * @param Model $Model Primary Model object.
  1086. * @param Model $LinkModel Linked model object.
  1087. * @param string $type Association type, one of the model association types ie. hasMany.
  1088. * @param string $association Association name.
  1089. * @param array $assocData Association data.
  1090. * @param array &$queryData An array of queryData information containing keys similar to Model::find().
  1091. * @param bool $external Whether or not the association query is on an external datasource.
  1092. * @param array &$resultSet Existing results.
  1093. * @param int $recursive Number of levels of association.
  1094. * @param array $stack A list with joined models.
  1095. * @return mixed
  1096. * @throws CakeException when results cannot be created.
  1097. */
  1098. public function queryAssociation(Model $Model, Model $LinkModel, $type, $association, $assocData, &$queryData, $external, &$resultSet, $recursive, $stack) {
  1099. if (isset($stack['_joined'])) {
  1100. $joined = $stack['_joined'];
  1101. unset($stack['_joined']);
  1102. }
  1103. $queryTemplate = $this->generateAssociationQuery($Model, $LinkModel, $type, $association, $assocData, $queryData, $external);
  1104. if (empty($queryTemplate)) {
  1105. return;
  1106. }
  1107. if (!is_array($resultSet)) {
  1108. throw new CakeException(__d('cake_dev', 'Error in Model %s', get_class($Model)));
  1109. }
  1110. if ($type === 'hasMany' && empty($assocData['limit']) && !empty($assocData['foreignKey'])) {
  1111. // 'hasMany' associations with no limit set.
  1112. $assocIds = array();
  1113. foreach ($resultSet as $result) {
  1114. $assocIds[] = $this->insertQueryData('{$__cakeID__$}', $result, $association, $Model, $stack);
  1115. }
  1116. $assocIds = array_filter($assocIds);
  1117. // Fetch
  1118. $assocResultSet = array();
  1119. if (!empty($assocIds)) {
  1120. $assocResultSet = $this->_fetchHasMany($Model, $queryTemplate, $assocIds);
  1121. }
  1122. // Recursively query associations
  1123. if ($recursive > 0 && !empty($assocResultSet) && is_array($assocResultSet)) {
  1124. foreach ($LinkModel->associations() as $type1) {
  1125. foreach ($LinkModel->{$type1} as $assoc1 => $assocData1) {
  1126. $DeepModel = $LinkModel->{$assoc1};
  1127. $tmpStack = $stack;
  1128. $tmpStack[] = $assoc1;
  1129. $db = $LinkModel->useDbConfig === $DeepModel->useDbConfig ? $this : $DeepModel->getDataSource();
  1130. $db->queryAssociation($LinkModel, $DeepModel, $type1, $assoc1, $assocData1, $queryData, true, $assocResultSet, $recursive - 1, $tmpStack);
  1131. }
  1132. }
  1133. }
  1134. // Filter
  1135. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  1136. $this->_filterResults($assocResultSet, $Model);
  1137. }
  1138. // Merge
  1139. return $this->_mergeHasMany($resultSet, $assocResultSet, $association, $Model);
  1140. } elseif ($type === 'hasAndBelongsToMany') {
  1141. // 'hasAndBelongsToMany' associations.
  1142. $assocIds = array();
  1143. foreach ($resultSet as $result) {
  1144. $assocIds[] = $this->insertQueryData('{$__cakeID__$}', $result, $association, $Model, $stack);
  1145. }
  1146. $assocIds = array_filter($assocIds);
  1147. // Fetch
  1148. $assocResultSet = array();
  1149. if (!empty($assocIds)) {
  1150. $assocResultSet = $this->_fetchHasAndBelongsToMany($Model, $queryTemplate, $assocIds, $association);
  1151. }
  1152. $habtmAssocData = $Model->hasAndBelongsToMany[$association];
  1153. $foreignKey = $habtmAssocData['foreignKey'];
  1154. $joinKeys = array($foreignKey, $habtmAssocData['associationForeignKey']);
  1155. list($with, $habtmFields) = $Model->joinModel($habtmAssocData['with'], $joinKeys);
  1156. $habtmFieldsCount = count($habtmFields);
  1157. // Filter
  1158. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  1159. $this->_filterResults($assocResultSet, $Model);
  1160. }
  1161. }
  1162. $modelAlias = $Model->alias;
  1163. $primaryKey = $Model->primaryKey;
  1164. $selfJoin = ($Model->name === $LinkModel->name);
  1165. foreach ($resultSet as &$row) {
  1166. if ($type === 'hasOne' || $type === 'belongsTo' || $type === 'hasMany') {
  1167. $assocResultSet = array();
  1168. $prefetched = false;
  1169. if (
  1170. ($type === 'hasOne' || $type === 'belongsTo') &&
  1171. isset($row[$LinkModel->alias], $joined[$Model->alias]) &&
  1172. in_array($LinkModel->alias, $joined[$Model->alias])
  1173. ) {
  1174. $joinedData = Hash::filter($row[$LinkModel->alias]);
  1175. if (!empty($joinedData)) {
  1176. $assocResultSet[0] = array($LinkModel->alias => $row[$LinkModel->alias]);
  1177. }
  1178. $prefetched = true;
  1179. } else {
  1180. $query = $this->insertQueryData($queryTemplate, $row, $association, $Model, $stack);
  1181. if ($query !== false) {
  1182. $assocResultSet = $this->fetchAll($query, $Model->cacheQueries);
  1183. }
  1184. }
  1185. }
  1186. if (!empty($assocResultSet) && is_array($assocResultSet)) {
  1187. if ($recursive > 0) {
  1188. foreach ($LinkModel->associations() as $type1) {
  1189. foreach ($LinkModel->{$type1} as $assoc1 => $assocData1) {
  1190. $DeepModel = $LinkModel->{$assoc1};
  1191. if (
  1192. $type1 === 'belongsTo' ||
  1193. ($type === 'belongsTo' && $DeepModel->alias === $modelAlias) ||
  1194. ($DeepModel->alias !== $modelAlias)
  1195. ) {
  1196. $tmpStack = $stack;
  1197. $tmpStack[] = $assoc1;
  1198. $db = $LinkModel->useDbConfig === $DeepModel->useDbConfig ? $this : $DeepModel->getDataSource();
  1199. $db->queryAssociation($LinkModel, $DeepModel, $type1, $assoc1, $assocData1, $queryData, true, $assocResultSet, $recursive - 1, $tmpStack);
  1200. }
  1201. }
  1202. }
  1203. }
  1204. if ($type === 'hasAndBelongsToMany') {
  1205. $merge = array();
  1206. foreach ($assocResultSet as $data) {
  1207. if (isset($data[$with]) && $data[$with][$foreignKey] === $row[$modelAlias][$primaryKey]) {
  1208. if ($habtmFieldsCount <= 2) {
  1209. unset($data[$with]);
  1210. }
  1211. $merge[] = $data;
  1212. }
  1213. }
  1214. if (empty($merge) && !isset($row[$association])) {
  1215. $row[$association] = $merge;
  1216. } else {
  1217. $this->_mergeAssociation($row, $merge, $association, $type);
  1218. }
  1219. } else {
  1220. $this->_mergeAssociation($row, $assocResultSet, $association, $type, $selfJoin);
  1221. }
  1222. if ($type !== 'hasAndBelongsToMany' && isset($row[$association]) && !$prefetched) {
  1223. $row[$association] = $LinkModel->afterFind($row[$association], false);
  1224. }
  1225. } else {
  1226. $tempArray[0][$association] = false;
  1227. $this->_mergeAssociation($row, $tempArray, $association, $type, $selfJoin);
  1228. }
  1229. }
  1230. }
  1231. /**
  1232. * Fetch 'hasMany' associations.
  1233. *
  1234. * This is just a proxy to maintain BC.
  1235. *
  1236. * @param Model $Model Primary model object.
  1237. * @param string $query Association query template.
  1238. * @param array $ids Array of IDs of associated records.
  1239. * @return array Association results.
  1240. * @see DboSource::_fetchHasMany()
  1241. */
  1242. public function fetchAssociated(Model $Model, $query, $ids) {
  1243. return $this->_fetchHasMany($Model, $query, $ids);
  1244. }
  1245. /**
  1246. * Fetch 'hasMany' associations.
  1247. *
  1248. * @param Model $Model Primary model object.
  1249. * @param string $query Association query template.
  1250. * @param array $ids Array of IDs of associated records.
  1251. * @return array Association results.
  1252. */
  1253. protected function _fetchHasMany(Model $Model, $query, $ids) {
  1254. $ids = array_unique($ids);
  1255. $query = str_replace('{$__cakeID__$}', implode(', ', $ids), $query);
  1256. if (count($ids) > 1) {
  1257. $query = str_replace('= (', 'IN (', $query);
  1258. }
  1259. return $this->fetchAll($query, $Model->cacheQueries);
  1260. }
  1261. /**
  1262. * Fetch 'hasAndBelongsToMany' associations.
  1263. *
  1264. * @param Model $Model Primary model object.
  1265. * @param string $query Association query.
  1266. * @param array $ids Array of IDs of associated records.
  1267. * @param string $association Association name.
  1268. * @return array Association results.
  1269. */
  1270. protected function _fetchHasAndBelongsToMany(Model $Model, $query, $ids, $association) {
  1271. $ids = array_unique($ids);
  1272. if (count($ids) > 1) {
  1273. $query = str_replace('{$__cakeID__$}', '(' . implode(', ', $ids) . ')', $query);
  1274. $query = str_replace('= (', 'IN (', $query);
  1275. } else {
  1276. $query = str_replace('{$__cakeID__$}', $ids[0], $query);
  1277. }
  1278. $query = str_replace(' WHERE 1 = 1', '', $query);
  1279. return $this->fetchAll($query, $Model->cacheQueries);
  1280. }
  1281. /**
  1282. * Merge the results of 'hasMany' associations.
  1283. *
  1284. * Note: this function also deals with the formatting of the data.
  1285. *
  1286. * @param array &$resultSet Data to merge into.
  1287. * @param array $assocResultSet Data to merge.
  1288. * @param string $association Name of Model being merged.
  1289. * @param Model $Model Model being merged onto.
  1290. * @return void
  1291. */
  1292. protected function _mergeHasMany(&$resultSet, $assocResultSet, $association, Model $Model) {
  1293. $modelAlias = $Model->alias;
  1294. $primaryKey = $Model->primaryKey;
  1295. $foreignKey = $Model->hasMany[$association]['foreignKey'];
  1296. foreach ($resultSet as &$result) {
  1297. if (!isset($result[$modelAlias])) {
  1298. continue;
  1299. }
  1300. $resultPrimaryKey = $result[$modelAlias][$primaryKey];
  1301. $merged = array();
  1302. foreach ($assocResultSet as $data) {
  1303. if ($resultPrimaryKey !== $data[$association][$foreignKey]) {
  1304. continue;
  1305. }
  1306. if (count($data) > 1) {
  1307. $data = array_merge($data[$association], $data);
  1308. unset($data[$association]);
  1309. foreach ($data as $key => $name) {
  1310. if (is_numeric($key)) {
  1311. $data[$association][] = $name;
  1312. unset($data[$key]);
  1313. }
  1314. }
  1315. $merged[] = $data;
  1316. } else {
  1317. $merged[] = $data[$association];
  1318. }
  1319. }
  1320. $result = Hash::mergeDiff($result, array($association => $merged));
  1321. }
  1322. }
  1323. /**
  1324. * Merge association of merge into data
  1325. *
  1326. * @param array &$data The data to merge.
  1327. * @param array &$merge The data to merge.
  1328. * @param string $association The association name to merge.
  1329. * @param string $type The type of association
  1330. * @param bool $selfJoin Whether or not this is a self join.
  1331. * @return void
  1332. */
  1333. protected function _mergeAssociation(&$data, &$merge, $association, $type, $selfJoin = false) {
  1334. if (isset($merge[0]) && !isset($merge[0][$association])) {
  1335. $association = Inflector::pluralize($association);
  1336. }
  1337. $dataAssociation =& $data[$association];
  1338. if ($type === 'belongsTo' || $type === 'hasOne') {
  1339. if (isset($merge[$association])) {
  1340. $dataAssociation = $merge[$association][0];
  1341. } else {
  1342. if (!empty($merge[0][$association])) {
  1343. foreach ($merge[0] as $assoc => $data2) {
  1344. if ($assoc !== $association) {
  1345. $merge[0][$association][$assoc] = $data2;
  1346. }
  1347. }
  1348. }
  1349. if (!isset($dataAssociation)) {
  1350. $dataAssociation = array();
  1351. if ($merge[0][$association]) {
  1352. $dataAssociation = $merge[0][$association];
  1353. }
  1354. } else {
  1355. if (is_array($merge[0][$association])) {
  1356. foreach ($dataAssociation as $k => $v) {
  1357. if (!is_array($v)) {
  1358. $dataAssocTmp[$k] = $v;
  1359. }
  1360. }
  1361. foreach ($merge[0][$association] as $k => $v) {
  1362. if (!is_array($v)) {
  1363. $mergeAssocTmp[$k] = $v;
  1364. }
  1365. }
  1366. $dataKeys = array_keys($data);
  1367. $mergeKeys = array_keys($merge[0]);
  1368. if ($mergeKeys[0] === $dataKeys[0] || $mergeKeys === $dataKeys) {
  1369. $dataAssociation[$association] = $merge[0][$association];
  1370. } else {
  1371. $diff = Hash::diff($dataAssocTmp, $mergeAssocTmp);
  1372. $dataAssociation = array_merge($merge[0][$association], $diff);
  1373. }
  1374. } elseif ($selfJoin && array_key_exists($association, $merge[0])) {
  1375. $dataAssociation = array_merge($dataAssociation, array($association => array()));
  1376. }
  1377. }
  1378. }
  1379. } else {
  1380. if (isset($merge[0][$association]) && $merge[0][$association] === false) {
  1381. if (!isset($dataAssociation)) {
  1382. $dataAssociation = array();
  1383. }
  1384. } else {
  1385. foreach ($merge as $row) {
  1386. $insert = array();
  1387. if (count($row) === 1) {
  1388. $insert = $row[$association];
  1389. } elseif (isset($row[$association])) {
  1390. $insert = array_merge($row[$association], $row);
  1391. unset($insert[$association]);
  1392. }
  1393. if (empty($dataAssociation) || (isset($dataAssociation) && !in_array($insert, $dataAssociation, true))) {
  1394. $dataAssociation[] = $insert;
  1395. }
  1396. }
  1397. }
  1398. }
  1399. }
  1400. /**
  1401. * Prepares fields required by an SQL statement.
  1402. *
  1403. * When no fields are set, all the $Model fields are returned.
  1404. *
  1405. * @param Model $Model The model to prepare.
  1406. * @param array $queryData An array of queryData information containing keys similar to Model::find().
  1407. * @return array Array containing SQL fields.
  1408. */
  1409. public function prepareFields(Model $Model, $queryData) {
  1410. if (empty($queryData['fields'])) {
  1411. $queryData['fields'] = $this->fields($Model);
  1412. } elseif (!empty($Model->hasMany) && $Model->recursive > -1) {
  1413. // hasMany relationships need the $Model primary key.
  1414. $assocFields = $this->fields($Model, null, "{$Model->alias}.{$Model->primaryKey}");
  1415. $passedFields = $queryData['fields'];
  1416. if (
  1417. count($passedFields) > 1 ||
  1418. (strpos($passedFields[0], $assocFields[0]) === false && !preg_match('/^[a-z]+\(/i', $passedFields[0]))
  1419. ) {
  1420. $queryData['fields'] = array_merge($passedFields, $assocFields);
  1421. }
  1422. }
  1423. return array_unique($queryData['fields']);
  1424. }
  1425. /**
  1426. * Builds an SQL statement.
  1427. *
  1428. * This is merely a convenient wrapper to DboSource::buildStatement().
  1429. *
  1430. * @param Model $Model The model to build an association query for.
  1431. * @param array $queryData An array of queryData information containing keys similar to Model::find().
  1432. * @return string String containing an SQL statement.
  1433. * @see DboSource::buildStatement()
  1434. */
  1435. public function buildAssociationQuery(Model $Model, $queryData) {
  1436. $queryData = $this->_scrubQueryData($queryData);
  1437. return $this->buildStatement(
  1438. array(
  1439. 'fields' => $this->prepareFields($Model, $queryData),
  1440. 'table' => $this->fullTableName($Model),
  1441. 'alias' => $Model->alias,
  1442. 'limit' => $queryData['limit'],
  1443. 'offset' => $queryData['offset'],
  1444. 'joins' => $queryData['joins'],
  1445. 'conditions' => $queryData['conditions'],
  1446. 'order' => $queryData['order'],
  1447. 'group' => $queryData['group']
  1448. ),
  1449. $Model
  1450. );
  1451. }
  1452. /**
  1453. * Generates a query or part of a query from a single model or two associated models.
  1454. *
  1455. * Builds a string containing an SQL statement template.
  1456. *
  1457. * @param Model $Model Primary Model object.
  1458. * @param Model|null $LinkModel Linked model object.
  1459. * @param string $type Association type, one of the model association types ie. hasMany.
  1460. * @param string $association Association name.
  1461. * @param array $assocData Association data.
  1462. * @param array &$queryData An array of queryData information containing keys similar to Model::find().
  1463. * @param bool $external Whether or not the association query is on an external datasource.
  1464. * @return mixed
  1465. * String representing a query.
  1466. * True, when $external is false and association $type is 'hasOne' or 'belongsTo'.
  1467. */
  1468. public function generateAssociationQuery(Model $Model, $LinkModel, $type, $association, $assocData, &$queryData, $external) {
  1469. $assocData = $this->_scrubQueryData($assocData);
  1470. $queryData = $this->_scrubQueryData($queryData);
  1471. if ($LinkModel === null) {
  1472. return $this->buildStatement(
  1473. array(
  1474. 'fields' => array_unique($queryData['fields']),
  1475. 'table' => $this->fullTableName($Model),
  1476. 'alias' => $Model->alias,
  1477. 'limit' => $queryData['limit'],
  1478. 'offset' => $queryData['offset'],
  1479. 'joins' => $queryData['joins'],
  1480. 'conditions' => $queryData['conditions'],
  1481. 'order' => $queryData['order'],
  1482. 'group' => $queryData['group']
  1483. ),
  1484. $Model
  1485. );
  1486. }
  1487. if ($external && !empty($assocData['finderQuery'])) {
  1488. return $assocData['finderQuery'];
  1489. }
  1490. if ($type === 'hasMany' || $type === 'hasAndBelongsToMany') {
  1491. if (empty($assocData['offset']) && !empty($assocData['page'])) {
  1492. $assocData['offset'] = ($assocData['page'] - 1) * $assocData['limit'];
  1493. }
  1494. }
  1495. switch ($type) {
  1496. case 'hasOne':
  1497. case 'belongsTo':
  1498. $conditions = $this->_mergeConditions(
  1499. $assocData['conditions'],
  1500. $this->getConstraint($type, $Model, $LinkModel, $association, array_merge($assocData, compact('external')))
  1501. );
  1502. if ($external) {
  1503. // Not self join
  1504. if ($Model->name !== $LinkModel->name) {
  1505. $modelAlias = $Model->alias;
  1506. foreach ($conditions as $key => $condition) {
  1507. if (is_numeric($key) && strpos($condition, $modelAlias . '.') !== false) {
  1508. unset($conditions[$key]);
  1509. }
  1510. }
  1511. }
  1512. $query = array_merge($assocData, array(
  1513. 'conditions' => $conditions,
  1514. 'table' => $this->fullTableName($LinkModel),
  1515. 'fields' => $this->fields($LinkModel, $association, $assocData['fields']),
  1516. 'alias' => $association,
  1517. 'group' => null
  1518. ));
  1519. } else {
  1520. $join = array(
  1521. 'table' => $LinkModel,
  1522. 'alias' => $association,
  1523. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1524. 'conditions' => trim($this->conditions($conditions, true, false, $Model))
  1525. );
  1526. $fields = array();
  1527. if ($assocData['fields'] !== false) {
  1528. $fields = $this->fields($LinkModel, $association, $assocData['fields']);
  1529. }
  1530. $queryData['fields'] = array_merge($this->prepareFields($Model, $queryData), $fields);
  1531. if (!empty($assocData['order'])) {
  1532. $queryData['order'][] = $assocData['order'];
  1533. }
  1534. if (!in_array($join, $queryData['joins'], true)) {
  1535. $queryData['joins'][] = $join;
  1536. }
  1537. return true;
  1538. }
  1539. break;
  1540. case 'hasMany':
  1541. $assocData['fields'] = $this->fields($LinkModel, $association, $assocData['fields']);
  1542. if (!empty($assocData['foreignKey'])) {
  1543. $assocData['fields'] = array_merge($assocData['fields'], $this->fields($LinkModel, $association, array("{$association}.{$assocData['foreignKey']}")));
  1544. }
  1545. $query = array(
  1546. 'conditions' => $this->_mergeConditions($this->getConstraint('hasMany', $Model, $LinkModel, $association, $assocData), $assocData['conditions']),
  1547. 'fields' => array_unique($assocData['fields']),
  1548. 'table' => $this->fullTableName($LinkModel),
  1549. 'alias' => $association,
  1550. 'order' => $assocData['order'],
  1551. 'limit' => $assocData['limit'],
  1552. 'offset' => $assocData['offset'],
  1553. 'group' => null
  1554. );
  1555. break;
  1556. case 'hasAndBelongsToMany':
  1557. $joinFields = array();
  1558. $joinAssoc = null;
  1559. if (isset($assocData['with']) && !empty($assocData['with'])) {
  1560. $joinKeys = array($assocData['foreignKey'], $assocData['associationForeignKey']);
  1561. list($with, $joinFields) = $Model->joinModel($assocData['with'], $joinKeys);
  1562. $joinTbl = $Model->{$with};
  1563. $joinAlias = $joinTbl;
  1564. if (is_array($joinFields) && !empty($joinFields)) {
  1565. $joinAssoc = $joinAlias = $joinTbl->alias;
  1566. $joinFields = $this->fields($joinTbl, $joinAlias, $joinFields);
  1567. } else {
  1568. $joinFields = array();
  1569. }
  1570. } else {
  1571. $joinTbl = $assocData['joinTable'];
  1572. $joinAlias = $this->fullTableName($assocData['joinTable']);
  1573. }
  1574. $query = array(
  1575. 'conditions' => $assocData['conditions'],
  1576. 'limit' => $assocData['limit'],
  1577. 'offset' => $assocData['offset'],
  1578. 'table' => $this->fullTableName($LinkModel),
  1579. 'alias' => $association,
  1580. 'fields' => array_merge($this->fields($LinkModel, $association, $assocData['fields']), $joinFields),
  1581. 'order' => $assocData['order'],
  1582. 'group' => null,
  1583. 'joins' => array(array(
  1584. 'table' => $joinTbl,
  1585. 'alias' => $joinAssoc,
  1586. 'conditions' => $this->getConstraint('hasAndBelongsToMany', $Model, $LinkModel, $joinAlias, $assocData, $association)
  1587. ))
  1588. );
  1589. break;
  1590. }
  1591. if (isset($query)) {
  1592. return $this->buildStatement($query, $Model);
  1593. }
  1594. return null;
  1595. }
  1596. /**
  1597. * Returns a conditions array for the constraint between two models.
  1598. *
  1599. * @param string $type Association type.
  1600. * @param Model $Model Primary Model object.
  1601. * @param Model $LinkModel Linked model object.
  1602. * @param string $association Association name.
  1603. * @param array $assocData Association data.
  1604. * @param string $association2 HABTM association name.
  1605. * @return array Conditions array defining the constraint between $Model and $LinkModel.
  1606. */
  1607. public function getConstraint($type, Model $Model, Model $LinkModel, $association, $assocData, $association2 = null) {
  1608. $assocData += array('external' => false);
  1609. if (empty($assocData['foreignKey'])) {
  1610. return array();
  1611. }
  1612. switch ($type) {
  1613. case 'hasOne':
  1614. if ($assocData['external']) {
  1615. return array(
  1616. "{$association}.{$assocData['foreignKey']}" => '{$__cakeID__$}'
  1617. );
  1618. } else {
  1619. return array(
  1620. "{$association}.{$assocData['foreignKey']}" => $this->identifier("{$Model->alias}.{$Model->primaryKey}")
  1621. );
  1622. }
  1623. case 'belongsTo':
  1624. if ($assocData['external']) {
  1625. return array(
  1626. "{$association}.{$LinkModel->primaryKey}" => '{$__cakeForeignKey__$}'
  1627. );
  1628. } else {
  1629. return array(
  1630. "{$Model->alias}.{$assocData['foreignKey']}" => $this->identifier("{$association}.{$LinkModel->primaryKey}")
  1631. );
  1632. }
  1633. case 'hasMany':
  1634. return array("{$association}.{$assocData['foreignKey']}" => array('{$__cakeID__$}'));
  1635. case 'hasAndBelongsToMany':
  1636. return array(
  1637. array(
  1638. "{$association}.{$assocData['foreignKey']}" => '{$__cakeID__$}'
  1639. ),
  1640. array(
  1641. "{$association}.{$assocData['associationForeignKey']}" => $this->identifier("{$association2}.{$LinkModel->primaryKey}")
  1642. )
  1643. );
  1644. }
  1645. return array();
  1646. }
  1647. /**
  1648. * Builds and generates a JOIN condition from an array. Handles final clean-up before conversion.
  1649. *
  1650. * @param array $join An array defining a JOIN condition in a query.
  1651. * @return string An SQL JOIN condition to be used in a query.
  1652. * @see DboSource::renderJoinStatement()
  1653. * @see DboSource::buildStatement()
  1654. */
  1655. public function buildJoinStatement($join) {
  1656. $data = array_merge(array(
  1657. 'type' => null,
  1658. 'alias' => null,
  1659. 'table' => 'join_table',
  1660. 'conditions' => array()
  1661. ), $join);
  1662. if (!empty($data['alias'])) {
  1663. $data['alias'] = $this->alias . $this->name($data['alias']);
  1664. }
  1665. if (!empty($data['conditions'])) {
  1666. $data['conditions'] = trim($this->conditions($data['conditions'], true, false));
  1667. }
  1668. if (!empty($data['table']) && (!is_string($data['table']) || strpos($data['table'], '(') !== 0)) {
  1669. $data['table'] = $this->fullTableName($data['table']);
  1670. }
  1671. return $this->renderJoinStatement($data);
  1672. }
  1673. /**
  1674. * Builds and generates an SQL statement from an array. Handles final clean-up before conversion.
  1675. *
  1676. * @param array $query An array defining an SQL query.
  1677. * @param Model $Model The model object which initiated the query.
  1678. * @return string An executable SQL statement.
  1679. * @see DboSource::renderStatement()
  1680. */
  1681. public function buildStatement($query, Model $Model) {
  1682. $query = array_merge($this->_queryDefaults, $query);
  1683. if (!empty($query['joins'])) {
  1684. $count = count($query['joins']);
  1685. for ($i = 0; $i < $count; $i++) {
  1686. if (is_array($query['joins'][$i])) {
  1687. $query['joins'][$i] = $this->buildJoinStatement($query['joins'][$i]);
  1688. }
  1689. }
  1690. }
  1691. return $this->renderStatement('select', array(
  1692. 'conditions' => $this->conditions($query['conditions'], true, true, $Model),
  1693. 'fields' => implode(', ', $query['fields']),
  1694. 'table' => $query['table'],
  1695. 'alias' => $this->alias . $this->name($query['alias']),
  1696. 'order' => $this->order($query['order'], 'ASC', $Model),
  1697. 'limit' => $this->limit($query['limit'], $query['offset']),
  1698. 'joins' => implode(' ', $query['joins']),
  1699. 'group' => $this->group($query['group'], $Model)
  1700. ));
  1701. }
  1702. /**
  1703. * Renders a final SQL JOIN statement
  1704. *
  1705. * @param array $data The data to generate a join statement for.
  1706. * @return string
  1707. */
  1708. public function renderJoinStatement($data) {
  1709. if (strtoupper($data['type']) === 'CROSS') {
  1710. return "{$data['type']} JOIN {$data['table']} {$data['alias']}";
  1711. }
  1712. return trim("{$data['type']} JOIN {$data['table']} {$data['alias']} ON ({$data['conditions']})");
  1713. }
  1714. /**
  1715. * Renders a final SQL statement by putting together the component parts in the correct order
  1716. *
  1717. * @param string $type type of query being run. e.g select, create, update, delete, schema, alter.
  1718. * @param array $data Array of data to insert into the query.
  1719. * @return string Rendered SQL expression to be run.
  1720. */
  1721. public function renderStatement($type, $data) {
  1722. extract($data);
  1723. $aliases = null;
  1724. switch (strtolower($type)) {
  1725. case 'select':
  1726. return trim("SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}");
  1727. case 'create':
  1728. return "INSERT INTO {$table} ({$fields}) VALUES ({$values})";
  1729. case 'update':
  1730. if (!empty($alias)) {
  1731. $aliases = "{$this->alias}{$alias} {$joins} ";
  1732. }
  1733. return trim("UPDATE {$table} {$aliases}SET {$fields} {$conditions}");
  1734. case 'delete':
  1735. if (!empty($alias)) {
  1736. $aliases = "{$this->alias}{$alias} {$joins} ";
  1737. }
  1738. return trim("DELETE {$alias} FROM {$table} {$aliases}{$conditions}");
  1739. case 'schema':
  1740. foreach (array('columns', 'indexes', 'tableParameters') as $var) {
  1741. if (is_array(${$var})) {
  1742. ${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
  1743. } else {
  1744. ${$var} = '';
  1745. }
  1746. }
  1747. if (trim($indexes) !== '') {
  1748. $columns .= ',';
  1749. }
  1750. return "CREATE TABLE {$table} (\n{$columns}{$indexes}) {$tableParameters};";
  1751. case 'alter':
  1752. return;
  1753. }
  1754. }
  1755. /**
  1756. * Merges a mixed set of string/array conditions.
  1757. *
  1758. * @param mixed $query The query to merge conditions for.
  1759. * @param mixed $assoc The association names.
  1760. * @return array
  1761. */
  1762. protected function _mergeConditions($query, $assoc) {
  1763. if (empty($assoc)) {
  1764. return $query;
  1765. }
  1766. if (is_array($query)) {
  1767. return array_merge((array)$assoc, $query);
  1768. }
  1769. if (!empty($query)) {
  1770. $query = array($query);
  1771. if (is_array($assoc)) {
  1772. $query = array_merge($query, $assoc);
  1773. } else {
  1774. $query[] = $assoc;
  1775. }
  1776. return $query;
  1777. }
  1778. return $assoc;
  1779. }
  1780. /**
  1781. * Generates and executes an SQL UPDATE statement for given model, fields, and values.
  1782. * For databases that do not support aliases in UPDATE queries.
  1783. *
  1784. * @param Model $Model The model to update.
  1785. * @param array $fields The fields to update
  1786. * @param array $values The values fo the fields.
  1787. * @param mixed $conditions The conditions for the update. When non-empty $values will not be quoted.
  1788. * @return bool Success
  1789. */
  1790. public function update(Model $Model, $fields = array(), $values = null, $conditions = null) {
  1791. if (!$values) {
  1792. $combined = $fields;
  1793. } else {
  1794. $combined = array_combine($fields, $values);
  1795. }
  1796. $fields = implode(', ', $this->_prepareUpdateFields($Model, $combined, empty($conditions)));
  1797. $alias = $joins = null;
  1798. $table = $this->fullTableName($Model);
  1799. $conditions = $this->_matchRecords($Model, $conditions);
  1800. if ($conditions === false) {
  1801. return false;
  1802. }
  1803. $query = compact('table', 'alias', 'joins', 'fields', 'conditions');
  1804. if (!$this->execute($this->renderStatement('update', $query))) {
  1805. $Model->onError();
  1806. return false;
  1807. }
  1808. return true;
  1809. }
  1810. /**
  1811. * Quotes and prepares fields and values for an SQL UPDATE statement
  1812. *
  1813. * @param Model $Model The model to prepare fields for.
  1814. * @param array $fields The fields to update.
  1815. * @param bool $quoteValues If values should be quoted, or treated as SQL snippets
  1816. * @param bool $alias Include the model alias in the field name
  1817. * @return array Fields and values, quoted and prepared
  1818. */
  1819. protected function _prepareUpdateFields(Model $Model, $fields, $quoteValues = true, $alias = false) {
  1820. $quotedAlias = $this->startQuote . $Model->alias . $this->endQuote;
  1821. $updates = array();
  1822. foreach ($fields as $field => $value) {
  1823. if ($alias && strpos($field, '.') === false) {
  1824. $quoted = $Model->escapeField($field);
  1825. } elseif (!$alias && strpos($field, '.') !== false) {
  1826. $quoted = $this->name(str_replace($quotedAlias . '.', '', str_replace(
  1827. $Model->alias . '.', '', $field
  1828. )));
  1829. } else {
  1830. $quoted = $this->name($field);
  1831. }
  1832. if ($value === null) {
  1833. $updates[] = $quoted . ' = NULL';
  1834. continue;
  1835. }
  1836. $update = $quoted . ' = ';
  1837. if ($quoteValues) {
  1838. $update .= $this->value($value, $Model->getColumnType($field));
  1839. } elseif ($Model->getColumnType($field) === 'boolean' && (is_int($value) || is_bool($value))) {
  1840. $update .= $this->boolean($value, true);
  1841. } elseif (!$alias) {
  1842. $update .= str_replace($quotedAlias . '.', '', str_replace(
  1843. $Model->alias . '.', '', $value
  1844. ));
  1845. } else {
  1846. $update .= $value;
  1847. }
  1848. $updates[] = $update;
  1849. }
  1850. return $updates;
  1851. }
  1852. /**
  1853. * Generates and executes an SQL DELETE statement.
  1854. * For databases that do not support aliases in UPDATE queries.
  1855. *
  1856. * @param Model $Model The model to delete from
  1857. * @param mixed $conditions The conditions to use. If empty the model's primary key will be used.
  1858. * @return bool Success
  1859. */
  1860. public function delete(Model $Model, $conditions = null) {
  1861. $alias = $joins = null;
  1862. $table = $this->fullTableName($Model);
  1863. $conditions = $this->_matchRecords($Model, $conditions);
  1864. if ($conditions === false) {
  1865. return false;
  1866. }
  1867. if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
  1868. $Model->onError();
  1869. return false;
  1870. }
  1871. return true;
  1872. }
  1873. /**
  1874. * Gets a list of record IDs for the given conditions. Used for multi-record updates and deletes
  1875. * in databases that do not support aliases in UPDATE/DELETE queries.
  1876. *
  1877. * @param Model $Model The model to find matching records for.
  1878. * @param mixed $conditions The conditions to match against.
  1879. * @return array List of record IDs
  1880. */
  1881. protected function _matchRecords(Model $Model, $conditions = null) {
  1882. if ($conditions === true) {
  1883. $conditions = $this->conditions(true);
  1884. } elseif ($conditions === null) {
  1885. $conditions = $this->conditions($this->defaultConditions($Model, $conditions, false), true, true, $Model);
  1886. } else {
  1887. $noJoin = true;
  1888. foreach ($conditions as $field => $value) {
  1889. $originalField = $field;
  1890. if (strpos($field, '.') !== false) {
  1891. list(, $field) = explode('.', $field);
  1892. $field = ltrim($field, $this->startQuote);
  1893. $field = rtrim($field, $this->endQuote);
  1894. }
  1895. if (!$Model->hasField($field)) {
  1896. $noJoin = false;
  1897. break;
  1898. }
  1899. if ($field !== $originalField) {
  1900. $conditions[$field] = $value;
  1901. unset($conditions[$originalField]);
  1902. }
  1903. }
  1904. if ($noJoin === true) {
  1905. return $this->conditions($conditions);
  1906. }
  1907. $idList = $Model->find('all', array(
  1908. 'fields' => "{$Model->alias}.{$Model->primaryKey}",
  1909. 'conditions' => $conditions
  1910. ));
  1911. if (empty($idList)) {
  1912. return false;
  1913. }
  1914. $conditions = $this->conditions(array(
  1915. $Model->primaryKey => Hash::extract($idList, "{n}.{$Model->alias}.{$Model->primaryKey}")
  1916. ));
  1917. }
  1918. return $conditions;
  1919. }
  1920. /**
  1921. * Returns an array of SQL JOIN conditions from a model's associations.
  1922. *
  1923. * @param Model $Model The model to get joins for.2
  1924. * @return array
  1925. */
  1926. protected function _getJoins(Model $Model) {
  1927. $join = array();
  1928. $joins = array_merge($Model->getAssociated('hasOne'), $Model->getAssociated('belongsTo'));
  1929. foreach ($joins as $assoc) {
  1930. if (!isset($Model->{$assoc})) {
  1931. continue;
  1932. }
  1933. $LinkModel = $Model->{$assoc};
  1934. if ($Model->useDbConfig !== $LinkModel->useDbConfig) {
  1935. continue;
  1936. }
  1937. $assocData = $Model->getAssociated($assoc);
  1938. $join[] = $this->buildJoinStatement(array(
  1939. 'table' => $LinkModel,
  1940. 'alias' => $assoc,
  1941. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1942. 'conditions' => trim($this->conditions(
  1943. $this->_mergeConditions($assocData['conditions'], $this->getConstraint($assocData['association'], $Model, $LinkModel, $assoc, $assocData)),
  1944. true,
  1945. false,
  1946. $Model
  1947. ))
  1948. ));
  1949. }
  1950. return $join;
  1951. }
  1952. /**
  1953. * Returns an SQL calculation, i.e. COUNT() or MAX()
  1954. *
  1955. * @param Model $Model The model to get a calculated field for.
  1956. * @param string $func Lowercase name of SQL function, i.e. 'count' or 'max'
  1957. * @param array $params Function parameters (any values must be quoted manually)
  1958. * @return string An SQL calculation function
  1959. */
  1960. public function calculate(Model $Model, $func, $params = array()) {
  1961. $params = (array)$params;
  1962. switch (strtolower($func)) {
  1963. case 'count':
  1964. if (!isset($params[0])) {
  1965. $params[0] = '*';
  1966. }
  1967. if (!isset($params[1])) {
  1968. $params[1] = 'count';
  1969. }
  1970. if ($Model->isVirtualField($params[0])) {
  1971. $arg = $this->_quoteFields($Model->getVirtualField($params[0]));
  1972. } else {
  1973. $arg = $this->name($params[0]);
  1974. }
  1975. return 'COUNT(' . $arg . ') AS ' . $this->name($params[1]);
  1976. case 'max':
  1977. case 'min':
  1978. if (!isset($params[1])) {
  1979. $params[1] = $params[0];
  1980. }
  1981. if ($Model->isVirtualField($params[0])) {
  1982. $arg = $this->_quoteFields($Model->getVirtualField($params[0]));
  1983. } else {
  1984. $arg = $this->name($params[0]);
  1985. }
  1986. return strtoupper($func) . '(' . $arg . ') AS ' . $this->name($params[1]);
  1987. }
  1988. }
  1989. /**
  1990. * Deletes all the records in a table and resets the count of the auto-incrementing
  1991. * primary key, where applicable.
  1992. *
  1993. * @param Model|string $table A string or model class representing the table to be truncated
  1994. * @return bool SQL TRUNCATE TABLE statement, false if not applicable.
  1995. */
  1996. public function truncate($table) {
  1997. return $this->execute('TRUNCATE TABLE ' . $this->fullTableName($table));
  1998. }
  1999. /**
  2000. * Check if the server support nested transactions
  2001. *
  2002. * @return bool
  2003. */
  2004. public function nestedTransactionSupported() {
  2005. return false;
  2006. }
  2007. /**
  2008. * Begin a transaction
  2009. *
  2010. * @return bool True on success, false on fail
  2011. * (i.e. if the database/model does not support transactions,
  2012. * or a transaction has not started).
  2013. */
  2014. public function begin() {
  2015. if ($this->_transactionStarted) {
  2016. if ($this->nestedTransactionSupported()) {
  2017. return $this->_beginNested();
  2018. }
  2019. $this->_transactionNesting++;
  2020. return $this->_transactionStarted;
  2021. }
  2022. $this->_transactionNesting = 0;
  2023. if ($this->fullDebug) {
  2024. $this->logQuery('BEGIN');
  2025. }
  2026. return $this->_transactionStarted = $this->_connection->beginTransaction();
  2027. }
  2028. /**
  2029. * Begin a nested transaction
  2030. *
  2031. * @return bool
  2032. */
  2033. protected function _beginNested() {
  2034. $query = 'SAVEPOINT LEVEL' . ++$this->_transactionNesting;
  2035. if ($this->fullDebug) {
  2036. $this->logQuery($query);
  2037. }
  2038. $this->_connection->exec($query);
  2039. return true;
  2040. }
  2041. /**
  2042. * Commit a transaction
  2043. *
  2044. * @return bool True on success, false on fail
  2045. * (i.e. if the database/model does not support transactions,
  2046. * or a transaction has not started).
  2047. */
  2048. public function commit() {
  2049. if (!$this->_transactionStarted) {
  2050. return false;
  2051. }
  2052. if ($this->_transactionNesting === 0) {
  2053. if ($this->fullDebug) {
  2054. $this->logQuery('COMMIT');
  2055. }
  2056. $this->_transactionStarted = false;
  2057. return $this->_connection->commit();
  2058. }
  2059. if ($this->nestedTransactionSupported()) {
  2060. return $this->_commitNested();
  2061. }
  2062. $this->_transactionNesting--;
  2063. return true;
  2064. }
  2065. /**
  2066. * Commit a nested transaction
  2067. *
  2068. * @return bool
  2069. */
  2070. protected function _commitNested() {
  2071. $query = 'RELEASE SAVEPOINT LEVEL' . $this->_transactionNesting--;
  2072. if ($this->fullDebug) {
  2073. $this->logQuery($query);
  2074. }
  2075. $this->_connection->exec($query);
  2076. return true;
  2077. }
  2078. /**
  2079. * Rollback a transaction
  2080. *
  2081. * @return bool True on success, false on fail
  2082. * (i.e. if the database/model does not support transactions,
  2083. * or a transaction has not started).
  2084. */
  2085. public function rollback() {
  2086. if (!$this->_transactionStarted) {
  2087. return false;
  2088. }
  2089. if ($this->_transactionNesting === 0) {
  2090. if ($this->fullDebug) {
  2091. $this->logQuery('ROLLBACK');
  2092. }
  2093. $this->_transactionStarted = false;
  2094. return $this->_connection->rollBack();
  2095. }
  2096. if ($this->nestedTransactionSupported()) {
  2097. return $this->_rollbackNested();
  2098. }
  2099. $this->_transactionNesting--;
  2100. return true;
  2101. }
  2102. /**
  2103. * Rollback a nested transaction
  2104. *
  2105. * @return bool
  2106. */
  2107. protected function _rollbackNested() {
  2108. $query = 'ROLLBACK TO SAVEPOINT LEVEL' . $this->_transactionNesting--;
  2109. if ($this->fullDebug) {
  2110. $this->logQuery($query);
  2111. }
  2112. $this->_connection->exec($query);
  2113. return true;
  2114. }
  2115. /**
  2116. * Returns the ID generated from the previous INSERT operation.
  2117. *
  2118. * @param mixed $source The source to get an id for.
  2119. * @return mixed
  2120. */
  2121. public function lastInsertId($source = null) {
  2122. return $this->_connection->lastInsertId();
  2123. }
  2124. /**
  2125. * Creates a default set of conditions from the model if $conditions is null/empty.
  2126. * If conditions are supplied then they will be returned. If a model doesn't exist and no conditions
  2127. * were provided either null or false will be returned based on what was input.
  2128. *
  2129. * @param Model $Model The model to get conditions for.
  2130. * @param string|array|bool $conditions Array of conditions, conditions string, null or false. If an array of conditions,
  2131. * or string conditions those conditions will be returned. With other values the model's existence will be checked.
  2132. * If the model doesn't exist a null or false will be returned depending on the input value.
  2133. * @param bool $useAlias Use model aliases rather than table names when generating conditions
  2134. * @return mixed Either null, false, $conditions or an array of default conditions to use.
  2135. * @see DboSource::update()
  2136. * @see DboSource::conditions()
  2137. */
  2138. public function defaultConditions(Model $Model, $conditions, $useAlias = true) {
  2139. if (!empty($conditions)) {
  2140. return $conditions;
  2141. }
  2142. $exists = $Model->exists();
  2143. if (!$exists && ($conditions !== null || !empty($Model->__safeUpdateMode))) {
  2144. return false;
  2145. } elseif (!$exists) {
  2146. return null;
  2147. }
  2148. $alias = $Model->alias;
  2149. if (!$useAlias) {
  2150. $alias = $this->fullTableName($Model, false);
  2151. }
  2152. return array("{$alias}.{$Model->primaryKey}" => $Model->getID());
  2153. }
  2154. /**
  2155. * Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name)
  2156. *
  2157. * @param Model $Model The model to get a key for.
  2158. * @param string $key The key field.
  2159. * @param string $assoc The association name.
  2160. * @return string
  2161. */
  2162. public function resolveKey(Model $Model, $key, $assoc = null) {
  2163. if (strpos('.', $key) !== false) {
  2164. return $this->name($Model->alias) . '.' . $this->name($key);
  2165. }
  2166. return $key;
  2167. }
  2168. /**
  2169. * Private helper method to remove query metadata in given data array.
  2170. *
  2171. * @param array $data The data to scrub.
  2172. * @return array
  2173. */
  2174. protected function _scrubQueryData($data) {
  2175. static $base = null;
  2176. if ($base === null) {
  2177. $base = array_fill_keys(array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group'), array());
  2178. $base['callbacks'] = null;
  2179. }
  2180. return (array)$data + $base;
  2181. }
  2182. /**
  2183. * Converts model virtual fields into sql expressions to be fetched later
  2184. *
  2185. * @param Model $Model The model to get virtual fields for.
  2186. * @param string $alias Alias table name
  2187. * @param array $fields virtual fields to be used on query
  2188. * @return array
  2189. */
  2190. protected function _constructVirtualFields(Model $Model, $alias, $fields) {
  2191. $virtual = array();
  2192. foreach ($fields as $field) {
  2193. $virtualField = $this->name($alias . $this->virtualFieldSeparator . $field);
  2194. $expression = $this->_quoteFields($Model->getVirtualField($field));
  2195. $virtual[] = '(' . $expression . ") {$this->alias} {$virtualField}";
  2196. }
  2197. return $virtual;
  2198. }
  2199. /**
  2200. * Generates the fields list of an SQL query.
  2201. *
  2202. * @param Model $Model The model to get fields for.
  2203. * @param string $alias Alias table name
  2204. * @param mixed $fields The provided list of fields.
  2205. * @param bool $quote If false, returns fields array unquoted
  2206. * @return array
  2207. */
  2208. public function fields(Model $Model, $alias = null, $fields = array(), $quote = true) {
  2209. if (empty($alias)) {
  2210. $alias = $Model->alias;
  2211. }
  2212. $virtualFields = $Model->getVirtualField();
  2213. $cacheKey = array(
  2214. $alias,
  2215. get_class($Model),
  2216. $Model->alias,
  2217. $virtualFields,
  2218. $fields,
  2219. $quote,
  2220. ConnectionManager::getSourceName($this),
  2221. $Model->schemaName,
  2222. $Model->table
  2223. );
  2224. $cacheKey = md5(serialize($cacheKey));
  2225. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  2226. return $return;
  2227. }
  2228. $allFields = empty($fields);
  2229. if ($allFields) {
  2230. $fields = array_keys($Model->schema());
  2231. } elseif (!is_array($fields)) {
  2232. $fields = String::tokenize($fields);
  2233. }
  2234. $fields = array_values(array_filter($fields));
  2235. $allFields = $allFields || in_array('*', $fields) || in_array($Model->alias . '.*', $fields);
  2236. $virtual = array();
  2237. if (!empty($virtualFields)) {
  2238. $virtualKeys = array_keys($virtualFields);
  2239. foreach ($virtualKeys as $field) {
  2240. $virtualKeys[] = $Model->alias . '.' . $field;
  2241. }
  2242. $virtual = ($allFields) ? $virtualKeys : array_intersect($virtualKeys, $fields);
  2243. foreach ($virtual as $i => $field) {
  2244. if (strpos($field, '.') !== false) {
  2245. $virtual[$i] = str_replace($Model->alias . '.', '', $field);
  2246. }
  2247. $fields = array_diff($fields, array($field));
  2248. }
  2249. $fields = array_values($fields);
  2250. }
  2251. if (!$quote) {
  2252. if (!empty($virtual)) {
  2253. $fields = array_merge($fields, $this->_constructVirtualFields($Model, $alias, $virtual));
  2254. }
  2255. return $fields;
  2256. }
  2257. $count = count($fields);
  2258. if ($count >= 1 && !in_array($fields[0], array('*', 'COUNT(*)'))) {
  2259. for ($i = 0; $i < $count; $i++) {
  2260. if (is_string($fields[$i]) && in_array($fields[$i], $virtual)) {
  2261. unset($fields[$i]);
  2262. continue;
  2263. }
  2264. if (is_object($fields[$i]) && isset($fields[$i]->type) && $fields[$i]->type === 'expression') {
  2265. $fields[$i] = $fields[$i]->value;
  2266. } elseif (preg_match('/^\(.*\)\s' . $this->alias . '.*/i', $fields[$i])) {
  2267. continue;
  2268. } elseif (!preg_match('/^.+\\(.*\\)/', $fields[$i])) {
  2269. $prepend = '';
  2270. if (strpos($fields[$i], 'DISTINCT') !== false) {
  2271. $prepend = 'DISTINCT ';
  2272. $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
  2273. }
  2274. $dot = strpos($fields[$i], '.');
  2275. if ($dot === false) {
  2276. $prefix = !(
  2277. strpos($fields[$i], ' ') !== false ||
  2278. strpos($fields[$i], '(') !== false
  2279. );
  2280. $fields[$i] = $this->name(($prefix ? $alias . '.' : '') . $fields[$i]);
  2281. } else {
  2282. if (strpos($fields[$i], ',') === false) {
  2283. $build = explode('.', $fields[$i]);
  2284. if (!Hash::numeric($build)) {
  2285. $fields[$i] = $this->name(implode('.', $build));
  2286. }
  2287. }
  2288. }
  2289. $fields[$i] = $prepend . $fields[$i];
  2290. } elseif (preg_match('/\(([\.\w]+)\)/', $fields[$i], $field)) {
  2291. if (isset($field[1])) {
  2292. if (strpos($field[1], '.') === false) {
  2293. $field[1] = $this->name($alias . '.' . $field[1]);
  2294. } else {
  2295. $field[0] = explode('.', $field[1]);
  2296. if (!Hash::numeric($field[0])) {
  2297. $field[0] = implode('.', array_map(array(&$this, 'name'), $field[0]));
  2298. $fields[$i] = preg_replace('/\(' . $field[1] . '\)/', '(' . $field[0] . ')', $fields[$i], 1);
  2299. }
  2300. }
  2301. }
  2302. }
  2303. }
  2304. }
  2305. if (!empty($virtual)) {
  2306. $fields = array_merge($fields, $this->_constructVirtualFields($Model, $alias, $virtual));
  2307. }
  2308. return $this->cacheMethod(__FUNCTION__, $cacheKey, array_unique($fields));
  2309. }
  2310. /**
  2311. * Creates a WHERE clause by parsing given conditions data. If an array or string
  2312. * conditions are provided those conditions will be parsed and quoted. If a boolean
  2313. * is given it will be integer cast as condition. Null will return 1 = 1.
  2314. *
  2315. * Results of this method are stored in a memory cache. This improves performance, but
  2316. * because the method uses a hashing algorithm it can have collisions.
  2317. * Setting DboSource::$cacheMethods to false will disable the memory cache.
  2318. *
  2319. * @param mixed $conditions Array or string of conditions, or any value.
  2320. * @param bool $quoteValues If true, values should be quoted
  2321. * @param bool $where If true, "WHERE " will be prepended to the return value
  2322. * @param Model $Model A reference to the Model instance making the query
  2323. * @return string SQL fragment
  2324. */
  2325. public function conditions($conditions, $quoteValues = true, $where = true, Model $Model = null) {
  2326. $clause = $out = '';
  2327. if ($where) {
  2328. $clause = ' WHERE ';
  2329. }
  2330. if (is_array($conditions) && !empty($conditions)) {
  2331. $out = $this->conditionKeysToString($conditions, $quoteValues, $Model);
  2332. if (empty($out)) {
  2333. return $clause . ' 1 = 1';
  2334. }
  2335. return $clause . implode(' AND ', $out);
  2336. }
  2337. if (is_bool($conditions)) {
  2338. return $clause . (int)$conditions . ' = 1';
  2339. }
  2340. if (empty($conditions) || trim($conditions) === '') {
  2341. return $clause . '1 = 1';
  2342. }
  2343. $clauses = '/^WHERE\\x20|^GROUP\\x20BY\\x20|^HAVING\\x20|^ORDER\\x20BY\\x20/i';
  2344. if (preg_match($clauses, $conditions)) {
  2345. $clause = '';
  2346. }
  2347. $conditions = $this->_quoteFields($conditions);
  2348. return $clause . $conditions;
  2349. }
  2350. /**
  2351. * Creates a WHERE clause by parsing given conditions array. Used by DboSource::conditions().
  2352. *
  2353. * @param array $conditions Array or string of conditions
  2354. * @param bool $quoteValues If true, values should be quoted
  2355. * @param Model $Model A reference to the Model instance making the query
  2356. * @return string SQL fragment
  2357. */
  2358. public function conditionKeysToString($conditions, $quoteValues = true, Model $Model = null) {
  2359. $out = array();
  2360. $data = $columnType = null;
  2361. $bool = array('and', 'or', 'not', 'and not', 'or not', 'xor', '||', '&&');
  2362. foreach ($conditions as $key => $value) {
  2363. $join = ' AND ';
  2364. $not = null;
  2365. if (is_array($value)) {
  2366. $valueInsert = (
  2367. !empty($value) &&
  2368. (substr_count($key, '?') === count($value) || substr_count($key, ':') === count($value))
  2369. );
  2370. }
  2371. if (is_numeric($key) && empty($value)) {
  2372. continue;
  2373. } elseif (is_numeric($key) && is_string($value)) {
  2374. $out[] = $this->_quoteFields($value);
  2375. } elseif ((is_numeric($key) && is_array($value)) || in_array(strtolower(trim($key)), $bool)) {
  2376. if (in_array(strtolower(trim($key)), $bool)) {
  2377. $join = ' ' . strtoupper($key) . ' ';
  2378. } else {
  2379. $key = $join;
  2380. }
  2381. $value = $this->conditionKeysToString($value, $quoteValues, $Model);
  2382. if (strpos($join, 'NOT') !== false) {
  2383. if (strtoupper(trim($key)) === 'NOT') {
  2384. $key = 'AND ' . trim($key);
  2385. }
  2386. $not = 'NOT ';
  2387. }
  2388. if (empty($value)) {
  2389. continue;
  2390. }
  2391. if (empty($value[1])) {
  2392. if ($not) {
  2393. $out[] = $not . '(' . $value[0] . ')';
  2394. } else {
  2395. $out[] = $value[0];
  2396. }
  2397. } else {
  2398. $out[] = '(' . $not . '(' . implode(') ' . strtoupper($key) . ' (', $value) . '))';
  2399. }
  2400. } else {
  2401. if (is_object($value) && isset($value->type)) {
  2402. if ($value->type === 'identifier') {
  2403. $data .= $this->name($key) . ' = ' . $this->name($value->value);
  2404. } elseif ($value->type === 'expression') {
  2405. if (is_numeric($key)) {
  2406. $data .= $value->value;
  2407. } else {
  2408. $data .= $this->name($key) . ' = ' . $value->value;
  2409. }
  2410. }
  2411. } elseif (is_array($value) && !empty($value) && !$valueInsert) {
  2412. $keys = array_keys($value);
  2413. if ($keys === array_values($keys)) {
  2414. $count = count($value);
  2415. if ($count === 1 && !preg_match('/\s+(?:NOT|\!=)$/', $key)) {
  2416. $data = $this->_quoteFields($key) . ' = (';
  2417. if ($quoteValues) {
  2418. if ($Model !== null) {
  2419. $columnType = $Model->getColumnType($key);
  2420. }
  2421. $data .= implode(', ', $this->value($value, $columnType));
  2422. }
  2423. $data .= ')';
  2424. } else {
  2425. $data = $this->_parseKey($key, $value, $Model);
  2426. }
  2427. } else {
  2428. $ret = $this->conditionKeysToString($value, $quoteValues, $Model);
  2429. if (count($ret) > 1) {
  2430. $data = '(' . implode(') AND (', $ret) . ')';
  2431. } elseif (isset($ret[0])) {
  2432. $data = $ret[0];
  2433. }
  2434. }
  2435. } elseif (is_numeric($key) && !empty($value)) {
  2436. $data = $this->_quoteFields($value);
  2437. } else {
  2438. $data = $this->_parseKey(trim($key), $value, $Model);
  2439. }
  2440. if ($data) {
  2441. $out[] = $data;
  2442. $data = null;
  2443. }
  2444. }
  2445. }
  2446. return $out;
  2447. }
  2448. /**
  2449. * Extracts a Model.field identifier and an SQL condition operator from a string, formats
  2450. * and inserts values, and composes them into an SQL snippet.
  2451. *
  2452. * @param string $key An SQL key snippet containing a field and optional SQL operator
  2453. * @param mixed $value The value(s) to be inserted in the string
  2454. * @param Model $Model Model object initiating the query
  2455. * @return string
  2456. */
  2457. protected function _parseKey($key, $value, Model $Model = null) {
  2458. $operatorMatch = '/^(((' . implode(')|(', $this->_sqlOps);
  2459. $operatorMatch .= ')\\x20?)|<[>=]?(?![^>]+>)\\x20?|[>=!]{1,3}(?!<)\\x20?)/is';
  2460. $bound = (strpos($key, '?') !== false || (is_array($value) && strpos($key, ':') !== false));
  2461. if (strpos($key, ' ') === false) {
  2462. $operator = '=';
  2463. } else {
  2464. list($key, $operator) = explode(' ', trim($key), 2);
  2465. if (!preg_match($operatorMatch, trim($operator)) && strpos($operator, ' ') !== false) {
  2466. $key = $key . ' ' . $operator;
  2467. $split = strrpos($key, ' ');
  2468. $operator = substr($key, $split);
  2469. $key = substr($key, 0, $split);
  2470. }
  2471. }
  2472. $virtual = false;
  2473. $type = null;
  2474. if ($Model !== null) {
  2475. if ($Model->isVirtualField($key)) {
  2476. $key = $this->_quoteFields($Model->getVirtualField($key));
  2477. $virtual = true;
  2478. }
  2479. $type = $Model->getColumnType($key);
  2480. }
  2481. $null = $value === null || (is_array($value) && empty($value));
  2482. if (strtolower($operator) === 'not') {
  2483. $data = $this->conditionKeysToString(
  2484. array($operator => array($key => $value)), true, $Model
  2485. );
  2486. return $data[0];
  2487. }
  2488. $value = $this->value($value, $type);
  2489. if (!$virtual && $key !== '?') {
  2490. $isKey = (
  2491. strpos($key, '(') !== false ||
  2492. strpos($key, ')') !== false ||
  2493. strpos($key, '|') !== false
  2494. );
  2495. $key = $isKey ? $this->_quoteFields($key) : $this->name($key);
  2496. }
  2497. if ($bound) {
  2498. return String::insert($key . ' ' . trim($operator), $value);
  2499. }
  2500. if (!preg_match($operatorMatch, trim($operator))) {
  2501. $operator .= is_array($value) ? ' IN' : ' =';
  2502. }
  2503. $operator = trim($operator);
  2504. if (is_array($value)) {
  2505. $value = implode(', ', $value);
  2506. switch ($operator) {
  2507. case '=':
  2508. $operator = 'IN';
  2509. break;
  2510. case '!=':
  2511. case '<>':
  2512. $operator = 'NOT IN';
  2513. break;
  2514. }
  2515. $value = "({$value})";
  2516. } elseif ($null || $value === 'NULL') {
  2517. switch ($operator) {
  2518. case '=':
  2519. $operator = 'IS';
  2520. break;
  2521. case '!=':
  2522. case '<>':
  2523. $operator = 'IS NOT';
  2524. break;
  2525. }
  2526. }
  2527. if ($virtual) {
  2528. return "({$key}) {$operator} {$value}";
  2529. }
  2530. return "{$key} {$operator} {$value}";
  2531. }
  2532. /**
  2533. * Quotes Model.fields
  2534. *
  2535. * @param string $conditions The conditions to quote.
  2536. * @return string or false if no match
  2537. */
  2538. protected function _quoteFields($conditions) {
  2539. $start = $end = null;
  2540. $original = $conditions;
  2541. if (!empty($this->startQuote)) {
  2542. $start = preg_quote($this->startQuote);
  2543. }
  2544. if (!empty($this->endQuote)) {
  2545. $end = preg_quote($this->endQuote);
  2546. }
  2547. $conditions = str_replace(array($start, $end), '', $conditions);
  2548. $conditions = preg_replace_callback(
  2549. '/(?:[\'\"][^\'\"\\\]*(?:\\\.[^\'\"\\\]*)*[\'\"])|([a-z0-9_][a-z0-9\\-_]*\\.[a-z0-9_][a-z0-9_\\-]*)/i',
  2550. array(&$this, '_quoteMatchedField'),
  2551. $conditions
  2552. );
  2553. if ($conditions !== null) {
  2554. return $conditions;
  2555. }
  2556. return $original;
  2557. }
  2558. /**
  2559. * Auxiliary function to quote matches `Model.fields` from a preg_replace_callback call
  2560. *
  2561. * @param string $match matched string
  2562. * @return string quoted string
  2563. */
  2564. protected function _quoteMatchedField($match) {
  2565. if (is_numeric($match[0])) {
  2566. return $match[0];
  2567. }
  2568. return $this->name($match[0]);
  2569. }
  2570. /**
  2571. * Returns a limit statement in the correct format for the particular database.
  2572. *
  2573. * @param int $limit Limit of results returned
  2574. * @param int $offset Offset from which to start results
  2575. * @return string SQL limit/offset statement
  2576. */
  2577. public function limit($limit, $offset = null) {
  2578. if ($limit) {
  2579. $rt = ' LIMIT';
  2580. if ($offset) {
  2581. $rt .= sprintf(' %u,', $offset);
  2582. }
  2583. $rt .= sprintf(' %u', $limit);
  2584. return $rt;
  2585. }
  2586. return null;
  2587. }
  2588. /**
  2589. * Returns an ORDER BY clause as a string.
  2590. *
  2591. * @param array|string $keys Field reference, as a key (i.e. Post.title)
  2592. * @param string $direction Direction (ASC or DESC)
  2593. * @param Model $Model Model reference (used to look for virtual field)
  2594. * @return string ORDER BY clause
  2595. */
  2596. public function order($keys, $direction = 'ASC', Model $Model = null) {
  2597. if (!is_array($keys)) {
  2598. $keys = array($keys);
  2599. }
  2600. $keys = array_filter($keys);
  2601. $result = array();
  2602. while (!empty($keys)) {
  2603. list($key, $dir) = each($keys);
  2604. array_shift($keys);
  2605. if (is_numeric($key)) {
  2606. $key = $dir;
  2607. $dir = $direction;
  2608. }
  2609. if (is_string($key) && strpos($key, ',') !== false && !preg_match('/\(.+\,.+\)/', $key)) {
  2610. $key = array_map('trim', explode(',', $key));
  2611. }
  2612. if (is_array($key)) {
  2613. //Flatten the array
  2614. $key = array_reverse($key, true);
  2615. foreach ($key as $k => $v) {
  2616. if (is_numeric($k)) {
  2617. array_unshift($keys, $v);
  2618. } else {
  2619. $keys = array($k => $v) + $keys;
  2620. }
  2621. }
  2622. continue;
  2623. } elseif (is_object($key) && isset($key->type) && $key->type === 'expression') {
  2624. $result[] = $key->value;
  2625. continue;
  2626. }
  2627. if (preg_match('/\\x20(ASC|DESC).*/i', $key, $_dir)) {
  2628. $dir = $_dir[0];
  2629. $key = preg_replace('/\\x20(ASC|DESC).*/i', '', $key);
  2630. }
  2631. $key = trim($key);
  2632. if ($Model !== null) {
  2633. if ($Model->isVirtualField($key)) {
  2634. $key = '(' . $this->_quoteFields($Model->getVirtualField($key)) . ')';
  2635. }
  2636. list($alias) = pluginSplit($key);
  2637. if ($alias !== $Model->alias && is_object($Model->{$alias}) && $Model->{$alias}->isVirtualField($key)) {
  2638. $key = '(' . $this->_quoteFields($Model->{$alias}->getVirtualField($key)) . ')';
  2639. }
  2640. }
  2641. if (strpos($key, '.')) {
  2642. $key = preg_replace_callback('/([a-zA-Z0-9_-]{1,})\\.([a-zA-Z0-9_-]{1,})/', array(&$this, '_quoteMatchedField'), $key);
  2643. }
  2644. if (!preg_match('/\s/', $key) && strpos($key, '.') === false) {
  2645. $key = $this->name($key);
  2646. }
  2647. $key .= ' ' . trim($dir);
  2648. $result[] = $key;
  2649. }
  2650. if (!empty($result)) {
  2651. return ' ORDER BY ' . implode(', ', $result);
  2652. }
  2653. return '';
  2654. }
  2655. /**
  2656. * Create a GROUP BY SQL clause.
  2657. *
  2658. * @param string|array $fields Group By fields
  2659. * @param Model $Model The model to get group by fields for.
  2660. * @return string Group By clause or null.
  2661. */
  2662. public function group($fields, Model $Model = null) {
  2663. if (empty($fields)) {
  2664. return null;
  2665. }
  2666. if (!is_array($fields)) {
  2667. $fields = array($fields);
  2668. }
  2669. if ($Model !== null) {
  2670. foreach ($fields as $index => $key) {
  2671. if ($Model->isVirtualField($key)) {
  2672. $fields[$index] = '(' . $Model->getVirtualField($key) . ')';
  2673. }
  2674. }
  2675. }
  2676. $fields = implode(', ', $fields);
  2677. return ' GROUP BY ' . $this->_quoteFields($fields);
  2678. }
  2679. /**
  2680. * Disconnects database, kills the connection and says the connection is closed.
  2681. *
  2682. * @return void
  2683. */
  2684. public function close() {
  2685. $this->disconnect();
  2686. }
  2687. /**
  2688. * Checks if the specified table contains any record matching specified SQL
  2689. *
  2690. * @param Model $Model Model to search
  2691. * @param string $sql SQL WHERE clause (condition only, not the "WHERE" part)
  2692. * @return bool True if the table has a matching record, else false
  2693. */
  2694. public function hasAny(Model $Model, $sql) {
  2695. $sql = $this->conditions($sql);
  2696. $table = $this->fullTableName($Model);
  2697. $alias = $this->alias . $this->name($Model->alias);
  2698. $where = $sql ? "{$sql}" : ' WHERE 1 = 1';
  2699. $id = $Model->escapeField();
  2700. $out = $this->fetchRow("SELECT COUNT({$id}) {$this->alias}count FROM {$table} {$alias}{$where}");
  2701. if (is_array($out)) {
  2702. return $out[0]['count'];
  2703. }
  2704. return false;
  2705. }
  2706. /**
  2707. * Gets the length of a database-native column description, or null if no length
  2708. *
  2709. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  2710. * @return mixed An integer or string representing the length of the column, or null for unknown length.
  2711. */
  2712. public function length($real) {
  2713. if (!preg_match_all('/([\w\s]+)(?:\((\d+)(?:,(\d+))?\))?(\sunsigned)?(\szerofill)?/', $real, $result)) {
  2714. $col = str_replace(array(')', 'unsigned'), '', $real);
  2715. $limit = null;
  2716. if (strpos($col, '(') !== false) {
  2717. list($col, $limit) = explode('(', $col);
  2718. }
  2719. if ($limit !== null) {
  2720. return intval($limit);
  2721. }
  2722. return null;
  2723. }
  2724. $types = array(
  2725. 'int' => 1, 'tinyint' => 1, 'smallint' => 1, 'mediumint' => 1, 'integer' => 1, 'bigint' => 1
  2726. );
  2727. list($real, $type, $length, $offset, $sign) = $result;
  2728. $typeArr = $type;
  2729. $type = $type[0];
  2730. $length = $length[0];
  2731. $offset = $offset[0];
  2732. $isFloat = in_array($type, array('dec', 'decimal', 'float', 'numeric', 'double'));
  2733. if ($isFloat && $offset) {
  2734. return $length . ',' . $offset;
  2735. }
  2736. if (($real[0] == $type) && (count($real) === 1)) {
  2737. return null;
  2738. }
  2739. if (isset($types[$type])) {
  2740. $length += $types[$type];
  2741. if (!empty($sign)) {
  2742. $length--;
  2743. }
  2744. } elseif (in_array($type, array('enum', 'set'))) {
  2745. $length = 0;
  2746. foreach ($typeArr as $key => $enumValue) {
  2747. if ($key === 0) {
  2748. continue;
  2749. }
  2750. $tmpLength = strlen($enumValue);
  2751. if ($tmpLength > $length) {
  2752. $length = $tmpLength;
  2753. }
  2754. }
  2755. }
  2756. return intval($length);
  2757. }
  2758. /**
  2759. * Translates between PHP boolean values and Database (faked) boolean values
  2760. *
  2761. * @param mixed $data Value to be translated
  2762. * @param bool $quote Whether or not the field should be cast to a string.
  2763. * @return string|bool Converted boolean value
  2764. */
  2765. public function boolean($data, $quote = false) {
  2766. if ($quote) {
  2767. return !empty($data) ? '1' : '0';
  2768. }
  2769. return !empty($data);
  2770. }
  2771. /**
  2772. * Inserts multiple values into a table
  2773. *
  2774. * @param string $table The table being inserted into.
  2775. * @param array $fields The array of field/column names being inserted.
  2776. * @param array $values The array of values to insert. The values should
  2777. * be an array of rows. Each row should have values keyed by the column name.
  2778. * Each row must have the values in the same order as $fields.
  2779. * @return bool
  2780. */
  2781. public function insertMulti($table, $fields, $values) {
  2782. $table = $this->fullTableName($table);
  2783. $holder = implode(',', array_fill(0, count($fields), '?'));
  2784. $fields = implode(', ', array_map(array(&$this, 'name'), $fields));
  2785. $pdoMap = array(
  2786. 'integer' => PDO::PARAM_INT,
  2787. 'float' => PDO::PARAM_STR,
  2788. 'boolean' => PDO::PARAM_BOOL,
  2789. 'string' => PDO::PARAM_STR,
  2790. 'text' => PDO::PARAM_STR
  2791. );
  2792. $columnMap = array();
  2793. $sql = "INSERT INTO {$table} ({$fields}) VALUES ({$holder})";
  2794. $statement = $this->_connection->prepare($sql);
  2795. $this->begin();
  2796. foreach ($values[key($values)] as $key => $val) {
  2797. $type = $this->introspectType($val);
  2798. $columnMap[$key] = $pdoMap[$type];
  2799. }
  2800. foreach ($values as $value) {
  2801. $i = 1;
  2802. foreach ($value as $col => $val) {
  2803. $statement->bindValue($i, $val, $columnMap[$col]);
  2804. $i += 1;
  2805. }
  2806. $statement->execute();
  2807. $statement->closeCursor();
  2808. if ($this->fullDebug) {
  2809. $this->logQuery($sql, $value);
  2810. }
  2811. }
  2812. return $this->commit();
  2813. }
  2814. /**
  2815. * Reset a sequence based on the MAX() value of $column. Useful
  2816. * for resetting sequences after using insertMulti().
  2817. *
  2818. * This method should be implemented by datasources that require sequences to be used.
  2819. *
  2820. * @param string $table The name of the table to update.
  2821. * @param string $column The column to use when resetting the sequence value.
  2822. * @return bool|void success.
  2823. */
  2824. public function resetSequence($table, $column) {
  2825. }
  2826. /**
  2827. * Returns an array of the indexes in given datasource name.
  2828. *
  2829. * @param string $model Name of model to inspect
  2830. * @return array Fields in table. Keys are column and unique
  2831. */
  2832. public function index($model) {
  2833. return array();
  2834. }
  2835. /**
  2836. * Generate a database-native schema for the given Schema object
  2837. *
  2838. * @param CakeSchema $schema An instance of a subclass of CakeSchema
  2839. * @param string $tableName Optional. If specified only the table name given will be generated.
  2840. * Otherwise, all tables defined in the schema are generated.
  2841. * @return string
  2842. */
  2843. public function createSchema($schema, $tableName = null) {
  2844. if (!$schema instanceof CakeSchema) {
  2845. trigger_error(__d('cake_dev', 'Invalid schema object'), E_USER_WARNING);
  2846. return null;
  2847. }
  2848. $out = '';
  2849. foreach ($schema->tables as $curTable => $columns) {
  2850. if (!$tableName || $tableName === $curTable) {
  2851. $cols = $indexes = $tableParameters = array();
  2852. $primary = null;
  2853. $table = $this->fullTableName($curTable);
  2854. $primaryCount = 0;
  2855. foreach ($columns as $col) {
  2856. if (isset($col['key']) && $col['key'] === 'primary') {
  2857. $primaryCount++;
  2858. }
  2859. }
  2860. foreach ($columns as $name => $col) {
  2861. if (is_string($col)) {
  2862. $col = array('type' => $col);
  2863. }
  2864. $isPrimary = isset($col['key']) && $col['key'] === 'primary';
  2865. // Multi-column primary keys are not supported.
  2866. if ($isPrimary && $primaryCount > 1) {
  2867. unset($col['key']);
  2868. $isPrimary = false;
  2869. }
  2870. if ($isPrimary) {
  2871. $primary = $name;
  2872. }
  2873. if ($name !== 'indexes' && $name !== 'tableParameters') {
  2874. $col['name'] = $name;
  2875. if (!isset($col['type'])) {
  2876. $col['type'] = 'string';
  2877. }
  2878. $cols[] = $this->buildColumn($col);
  2879. } elseif ($name === 'indexes') {
  2880. $indexes = array_merge($indexes, $this->buildIndex($col, $table));
  2881. } elseif ($name === 'tableParameters') {
  2882. $tableParameters = array_merge($tableParameters, $this->buildTableParameters($col, $table));
  2883. }
  2884. }
  2885. if (!isset($columns['indexes']['PRIMARY']) && !empty($primary)) {
  2886. $col = array('PRIMARY' => array('column' => $primary, 'unique' => 1));
  2887. $indexes = array_merge($indexes, $this->buildIndex($col, $table));
  2888. }
  2889. $columns = $cols;
  2890. $out .= $this->renderStatement('schema', compact('table', 'columns', 'indexes', 'tableParameters')) . "\n\n";
  2891. }
  2892. }
  2893. return $out;
  2894. }
  2895. /**
  2896. * Generate an alter syntax from CakeSchema::compare()
  2897. *
  2898. * @param mixed $compare The comparison data.
  2899. * @param string $table The table name.
  2900. * @return bool
  2901. */
  2902. public function alterSchema($compare, $table = null) {
  2903. return false;
  2904. }
  2905. /**
  2906. * Generate a "drop table" statement for the given Schema object
  2907. *
  2908. * @param CakeSchema $schema An instance of a subclass of CakeSchema
  2909. * @param string $table Optional. If specified only the table name given will be generated.
  2910. * Otherwise, all tables defined in the schema are generated.
  2911. * @return string
  2912. */
  2913. public function dropSchema(CakeSchema $schema, $table = null) {
  2914. $out = '';
  2915. if ($table && array_key_exists($table, $schema->tables)) {
  2916. return $this->_dropTable($table) . "\n";
  2917. } elseif ($table) {
  2918. return $out;
  2919. }
  2920. foreach (array_keys($schema->tables) as $curTable) {
  2921. $out .= $this->_dropTable($curTable) . "\n";
  2922. }
  2923. return $out;
  2924. }
  2925. /**
  2926. * Generate a "drop table" statement for a single table
  2927. *
  2928. * @param type $table Name of the table to drop
  2929. * @return string Drop table SQL statement
  2930. */
  2931. protected function _dropTable($table) {
  2932. return 'DROP TABLE ' . $this->fullTableName($table) . ";";
  2933. }
  2934. /**
  2935. * Generate a database-native column schema string
  2936. *
  2937. * @param array $column An array structured like the following: array('name' => 'value', 'type' => 'value'[, options]),
  2938. * where options can be 'default', 'length', or 'key'.
  2939. * @return string
  2940. */
  2941. public function buildColumn($column) {
  2942. $name = $type = null;
  2943. extract(array_merge(array('null' => true), $column));
  2944. if (empty($name) || empty($type)) {
  2945. trigger_error(__d('cake_dev', 'Column name or type not defined in schema'), E_USER_WARNING);
  2946. return null;
  2947. }
  2948. if (!isset($this->columns[$type])) {
  2949. trigger_error(__d('cake_dev', 'Column type %s does not exist', $type), E_USER_WARNING);
  2950. return null;
  2951. }
  2952. $real = $this->columns[$type];
  2953. $out = $this->name($name) . ' ' . $real['name'];
  2954. if (isset($column['length'])) {
  2955. $length = $column['length'];
  2956. } elseif (isset($column['limit'])) {
  2957. $length = $column['limit'];
  2958. } elseif (isset($real['length'])) {
  2959. $length = $real['length'];
  2960. } elseif (isset($real['limit'])) {
  2961. $length = $real['limit'];
  2962. }
  2963. if (isset($length)) {
  2964. $out .= '(' . $length . ')';
  2965. }
  2966. if (($column['type'] === 'integer' || $column['type'] === 'float') && isset($column['default']) && $column['default'] === '') {
  2967. $column['default'] = null;
  2968. }
  2969. $out = $this->_buildFieldParameters($out, $column, 'beforeDefault');
  2970. if (isset($column['key']) && $column['key'] === 'primary' && ($type === 'integer' || $type === 'biginteger')) {
  2971. $out .= ' ' . $this->columns['primary_key']['name'];
  2972. } elseif (isset($column['key']) && $column['key'] === 'primary') {
  2973. $out .= ' NOT NULL';
  2974. } elseif (isset($column['default']) && isset($column['null']) && $column['null'] === false) {
  2975. $out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL';
  2976. } elseif (isset($column['default'])) {
  2977. $out .= ' DEFAULT ' . $this->value($column['default'], $type);
  2978. } elseif ($type !== 'timestamp' && !empty($column['null'])) {
  2979. $out .= ' DEFAULT NULL';
  2980. } elseif ($type === 'timestamp' && !empty($column['null'])) {
  2981. $out .= ' NULL';
  2982. } elseif (isset($column['null']) && $column['null'] === false) {
  2983. $out .= ' NOT NULL';
  2984. }
  2985. if ($type === 'timestamp' && isset($column['default']) && strtolower($column['default']) === 'current_timestamp') {
  2986. $out = str_replace(array("'CURRENT_TIMESTAMP'", "'current_timestamp'"), 'CURRENT_TIMESTAMP', $out);
  2987. }
  2988. return $this->_buildFieldParameters($out, $column, 'afterDefault');
  2989. }
  2990. /**
  2991. * Build the field parameters, in a position
  2992. *
  2993. * @param string $columnString The partially built column string
  2994. * @param array $columnData The array of column data.
  2995. * @param string $position The position type to use. 'beforeDefault' or 'afterDefault' are common
  2996. * @return string a built column with the field parameters added.
  2997. */
  2998. protected function _buildFieldParameters($columnString, $columnData, $position) {
  2999. foreach ($this->fieldParameters as $paramName => $value) {
  3000. if (isset($columnData[$paramName]) && $value['position'] == $position) {
  3001. if (isset($value['options']) && !in_array($columnData[$paramName], $value['options'], true)) {
  3002. continue;
  3003. }
  3004. if (isset($value['types']) && !in_array($columnData['type'], $value['types'], true)) {
  3005. continue;
  3006. }
  3007. $val = $columnData[$paramName];
  3008. if ($value['quote']) {
  3009. $val = $this->value($val);
  3010. }
  3011. $columnString .= ' ' . $value['value'] . (empty($value['noVal']) ? $value['join'] . $val : '');
  3012. }
  3013. }
  3014. return $columnString;
  3015. }
  3016. /**
  3017. * Format indexes for create table.
  3018. *
  3019. * @param array $indexes The indexes to build
  3020. * @param string $table The table name.
  3021. * @return array
  3022. */
  3023. public function buildIndex($indexes, $table = null) {
  3024. $join = array();
  3025. foreach ($indexes as $name => $value) {
  3026. $out = '';
  3027. if ($name === 'PRIMARY') {
  3028. $out .= 'PRIMARY ';
  3029. $name = null;
  3030. } else {
  3031. if (!empty($value['unique'])) {
  3032. $out .= 'UNIQUE ';
  3033. }
  3034. $name = $this->startQuote . $name . $this->endQuote;
  3035. }
  3036. if (is_array($value['column'])) {
  3037. $out .= 'KEY ' . $name . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
  3038. } else {
  3039. $out .= 'KEY ' . $name . ' (' . $this->name($value['column']) . ')';
  3040. }
  3041. $join[] = $out;
  3042. }
  3043. return $join;
  3044. }
  3045. /**
  3046. * Read additional table parameters
  3047. *
  3048. * @param string $name The table name to read.
  3049. * @return array
  3050. */
  3051. public function readTableParameters($name) {
  3052. $parameters = array();
  3053. if (method_exists($this, 'listDetailedSources')) {
  3054. $currentTableDetails = $this->listDetailedSources($name);
  3055. foreach ($this->tableParameters as $paramName => $parameter) {
  3056. if (!empty($parameter['column']) && !empty($currentTableDetails[$parameter['column']])) {
  3057. $parameters[$paramName] = $currentTableDetails[$parameter['column']];
  3058. }
  3059. }
  3060. }
  3061. return $parameters;
  3062. }
  3063. /**
  3064. * Format parameters for create table
  3065. *
  3066. * @param array $parameters The parameters to create SQL for.
  3067. * @param string $table The table name.
  3068. * @return array
  3069. */
  3070. public function buildTableParameters($parameters, $table = null) {
  3071. $result = array();
  3072. foreach ($parameters as $name => $value) {
  3073. if (isset($this->tableParameters[$name])) {
  3074. if ($this->tableParameters[$name]['quote']) {
  3075. $value = $this->value($value);
  3076. }
  3077. $result[] = $this->tableParameters[$name]['value'] . $this->tableParameters[$name]['join'] . $value;
  3078. }
  3079. }
  3080. return $result;
  3081. }
  3082. /**
  3083. * Guesses the data type of an array
  3084. *
  3085. * @param string $value The value to introspect for type data.
  3086. * @return string
  3087. */
  3088. public function introspectType($value) {
  3089. if (!is_array($value)) {
  3090. if (is_bool($value)) {
  3091. return 'boolean';
  3092. }
  3093. if (is_float($value) && floatval($value) === $value) {
  3094. return 'float';
  3095. }
  3096. if (is_int($value) && intval($value) === $value) {
  3097. return 'integer';
  3098. }
  3099. if (is_string($value) && strlen($value) > 255) {
  3100. return 'text';
  3101. }
  3102. return 'string';
  3103. }
  3104. $isAllFloat = $isAllInt = true;
  3105. $containsInt = $containsString = false;
  3106. foreach ($value as $valElement) {
  3107. $valElement = trim($valElement);
  3108. if (!is_float($valElement) && !preg_match('/^[\d]+\.[\d]+$/', $valElement)) {
  3109. $isAllFloat = false;
  3110. } else {
  3111. continue;
  3112. }
  3113. if (!is_int($valElement) && !preg_match('/^[\d]+$/', $valElement)) {
  3114. $isAllInt = false;
  3115. } else {
  3116. $containsInt = true;
  3117. continue;
  3118. }
  3119. $containsString = true;
  3120. }
  3121. if ($isAllFloat) {
  3122. return 'float';
  3123. }
  3124. if ($isAllInt) {
  3125. return 'integer';
  3126. }
  3127. if ($containsInt && !$containsString) {
  3128. return 'integer';
  3129. }
  3130. return 'string';
  3131. }
  3132. /**
  3133. * Writes a new key for the in memory sql query cache
  3134. *
  3135. * @param string $sql SQL query
  3136. * @param mixed $data result of $sql query
  3137. * @param array $params query params bound as values
  3138. * @return void
  3139. */
  3140. protected function _writeQueryCache($sql, $data, $params = array()) {
  3141. if (preg_match('/^\s*select/i', $sql)) {
  3142. $this->_queryCache[$sql][serialize($params)] = $data;
  3143. }
  3144. }
  3145. /**
  3146. * Returns the result for a sql query if it is already cached
  3147. *
  3148. * @param string $sql SQL query
  3149. * @param array $params query params bound as values
  3150. * @return mixed results for query if it is cached, false otherwise
  3151. */
  3152. public function getQueryCache($sql, $params = array()) {
  3153. if (isset($this->_queryCache[$sql]) && preg_match('/^\s*select/i', $sql)) {
  3154. $serialized = serialize($params);
  3155. if (isset($this->_queryCache[$sql][$serialized])) {
  3156. return $this->_queryCache[$sql][$serialized];
  3157. }
  3158. }
  3159. return false;
  3160. }
  3161. /**
  3162. * Used for storing in cache the results of the in-memory methodCache
  3163. */
  3164. public function __destruct() {
  3165. if ($this->_methodCacheChange) {
  3166. Cache::write('method_cache', self::$methodCache, '_cake_core_');
  3167. }
  3168. }
  3169. }