DboSource.php 95 KB

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