DboSource.php 95 KB

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