DboSource.php 95 KB

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