DboSource.php 94 KB

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