DboSource.php 89 KB

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