DboSource.php 100 KB

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