DboSource.php 95 KB

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