DboSource.php 91 KB

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