DboSource.php 98 KB

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