DboSource.php 94 KB

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