DboSource.php 84 KB

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