Sin descripción

idiorm.php 95KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555
  1. <?php
  2. namespace MailPoetVendor\Idiorm;
  3. if (!defined('ABSPATH')) exit;
  4. use ArrayAccess;
  5. use ArrayIterator;
  6. use Countable;
  7. use Exception;
  8. use InvalidArgumentException;
  9. use IteratorAggregate;
  10. use PDO;
  11. use PDOStatement;
  12. use Serializable;
  13. /**
  14. *
  15. * Idiorm
  16. *
  17. * http://github.com/j4mie/idiorm/
  18. *
  19. * A single-class super-simple database abstraction layer for PHP.
  20. * Provides (nearly) zero-configuration object-relational mapping
  21. * and a fluent interface for building basic, commonly-used queries.
  22. *
  23. * BSD Licensed.
  24. *
  25. * Copyright (c) 2010, Jamie Matthews
  26. * All rights reserved.
  27. *
  28. * Redistribution and use in source and binary forms, with or without
  29. * modification, are permitted provided that the following conditions are met:
  30. *
  31. * * Redistributions of source code must retain the above copyright notice, this
  32. * list of conditions and the following disclaimer.
  33. *
  34. * * Redistributions in binary form must reproduce the above copyright notice,
  35. * this list of conditions and the following disclaimer in the documentation
  36. * and/or other materials provided with the distribution.
  37. *
  38. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  39. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  40. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  41. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
  42. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  43. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  44. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  45. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  46. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  47. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  48. *
  49. *
  50. * The methods documented below are magic methods that conform to PSR-1.
  51. * This documentation exposes these methods to doc generators and IDEs.
  52. * @see http://www.php-fig.org/psr/psr-1/
  53. *
  54. * @method static array|string getConfig($key = null, $connection_name = self::DEFAULT_CONNECTION)
  55. * @method static null resetConfig()
  56. * @method static ORM forTable($table_name, $connection_name = self::DEFAULT_CONNECTION)
  57. * @method static null setDb($db, $connection_name = self::DEFAULT_CONNECTION)
  58. * @method static null resetDb()
  59. * @method static null setupLimitClauseStyle($connection_name)
  60. * @method static PDO getDb($connection_name = self::DEFAULT_CONNECTION)
  61. * @method static bool rawExecute($query, $parameters = array())
  62. * @method static PDOStatement getLastStatement()
  63. * @method static string getLastQuery($connection_name = null)
  64. * @method static array getQueryLog($connection_name = self::DEFAULT_CONNECTION)
  65. * @method array getConnectionNames()
  66. * @method $this useIdColumn($id_column)
  67. * @method ORM|bool findOne($id=null)
  68. * @method array|IdiormResultSet findMany()
  69. * @method IdiormResultSet findResultSet()
  70. * @method array findArray()
  71. * @method $this forceAllDirty()
  72. * @method $this rawQuery($query, $parameters = array())
  73. * @method $this tableAlias($alias)
  74. * @method int countNullIdColumns()
  75. * @method $this selectExpr($expr, $alias=null)
  76. * @method ORM selectMany($values)
  77. * @method ORM selectManyExpr($values)
  78. * @method $this rawJoin($table, $constraint, $table_alias, $parameters = array())
  79. * @method $this innerJoin($table, $constraint, $table_alias=null)
  80. * @method $this leftOuterJoin($table, $constraint, $table_alias=null)
  81. * @method $this rightOuterJoin($table, $constraint, $table_alias=null)
  82. * @method $this fullOuterJoin($table, $constraint, $table_alias=null)
  83. * @method $this whereEqual($column_name, $value=null)
  84. * @method $this whereNotEqual($column_name, $value=null)
  85. * @method $this whereIdIs($id)
  86. * @method $this whereAnyIs($values, $operator='=')
  87. * @method array|string whereIdIn($ids)
  88. * @method $this whereLike($column_name, $value=null)
  89. * @method $this whereNotLike($column_name, $value=null)
  90. * @method $this whereGt($column_name, $value=null)
  91. * @method $this whereLt($column_name, $value=null)
  92. * @method $this whereGte($column_name, $value=null)
  93. * @method $this whereLte($column_name, $value=null)
  94. * @method $this whereIn($column_name, $values)
  95. * @method $this whereNotIn($column_name, $values)
  96. * @method $this whereNull($column_name)
  97. * @method $this whereNotNull($column_name)
  98. * @method $this whereRaw($clause, $parameters=array())
  99. * @method $this orderByDesc($column_name)
  100. * @method $this orderByAsc($column_name)
  101. * @method $this orderByExpr($clause)
  102. * @method $this groupBy($column_name)
  103. * @method $this groupByExpr($expr)
  104. * @method $this havingEqual($column_name, $value=null)
  105. * @method $this havingNotEqual($column_name, $value=null)
  106. * @method $this havingIdIs($id)
  107. * @method $this havingLike($column_name, $value=null)
  108. * @method $this havingNotLike($column_name, $value=null)
  109. * @method $this havingGt($column_name, $value=null)
  110. * @method $this havingLt($column_name, $value=null)
  111. * @method $this havingGte($column_name, $value=null)
  112. * @method $this havingLte($column_name, $value=null)
  113. * @method $this havingIn($column_name, $values=null)
  114. * @method $this havingNotIn($column_name, $values=null)
  115. * @method $this havingNull($column_name)
  116. * @method $this havingNotNull($column_name)
  117. * @method $this havingRaw($clause, $parameters=array())
  118. * @method static this clearCache($table_name = null, $connection_name = self::DEFAULT_CONNECTION)
  119. * @method array asArray()
  120. * @method bool setExpr($key, $value = null)
  121. * @method bool isDirty($key)
  122. * @method bool isNew()
  123. */
  124. class ORM implements ArrayAccess {
  125. // ----------------------- //
  126. // --- CLASS CONSTANTS --- //
  127. // ----------------------- //
  128. // WHERE and HAVING condition array keys
  129. const CONDITION_FRAGMENT = 0;
  130. const CONDITION_VALUES = 1;
  131. const DEFAULT_CONNECTION = 'default';
  132. // Limit clause style
  133. const LIMIT_STYLE_TOP_N = "top";
  134. const LIMIT_STYLE_LIMIT = "limit";
  135. // ------------------------ //
  136. // --- CLASS PROPERTIES --- //
  137. // ------------------------ //
  138. // Class configuration
  139. protected static $_default_config = array(
  140. 'connection_string' => 'sqlite::memory:',
  141. 'id_column' => 'id',
  142. 'id_column_overrides' => array(),
  143. 'error_mode' => PDO::ERRMODE_EXCEPTION,
  144. 'username' => null,
  145. 'password' => null,
  146. 'driver_options' => null,
  147. 'identifier_quote_character' => null, // if this is null, will be autodetected
  148. 'limit_clause_style' => null, // if this is null, will be autodetected
  149. 'logging' => false,
  150. 'logger' => null,
  151. 'caching' => false,
  152. 'caching_auto_clear' => false,
  153. 'return_result_sets' => false,
  154. );
  155. // Map of configuration settings
  156. protected static $_config = array();
  157. // Map of database connections, instances of the PDO class
  158. protected static $_db = array();
  159. // Last query run, only populated if logging is enabled
  160. protected static $_last_query;
  161. // Log of all queries run, mapped by connection key, only populated if logging is enabled
  162. protected static $_query_log = array();
  163. // Query cache, only used if query caching is enabled
  164. protected static $_query_cache = array();
  165. // Reference to previously used PDOStatement object to enable low-level access, if needed
  166. protected static $_last_statement = null;
  167. // --------------------------- //
  168. // --- INSTANCE PROPERTIES --- //
  169. // --------------------------- //
  170. // Key name of the connections in self::$_db used by this instance
  171. protected $_connection_name;
  172. // The name of the table the current ORM instance is associated with
  173. protected $_table_name;
  174. // Alias for the table to be used in SELECT queries
  175. protected $_table_alias = null;
  176. // Values to be bound to the query
  177. protected $_values = array();
  178. // Columns to select in the result
  179. protected $_result_columns = array('*');
  180. // Are we using the default result column or have these been manually changed?
  181. protected $_using_default_result_columns = true;
  182. // Join sources
  183. protected $_join_sources = array();
  184. // Should the query include a DISTINCT keyword?
  185. protected $_distinct = false;
  186. // Is this a raw query?
  187. protected $_is_raw_query = false;
  188. // The raw query
  189. protected $_raw_query = '';
  190. // The raw query parameters
  191. protected $_raw_parameters = array();
  192. // Array of WHERE clauses
  193. protected $_where_conditions = array();
  194. // LIMIT
  195. protected $_limit = null;
  196. // OFFSET
  197. protected $_offset = null;
  198. // ORDER BY
  199. protected $_order_by = array();
  200. // GROUP BY
  201. protected $_group_by = array();
  202. // HAVING
  203. protected $_having_conditions = array();
  204. // The data for a hydrated instance of the class
  205. protected $_data = array();
  206. // Fields that have been modified during the
  207. // lifetime of the object
  208. protected $_dirty_fields = array();
  209. // Fields that are to be inserted in the DB raw
  210. protected $_expr_fields = array();
  211. // Is this a new object (has create() been called)?
  212. protected $_is_new = false;
  213. // Name of the column to use as the primary key for
  214. // this instance only. Overrides the config settings.
  215. protected $_instance_id_column = null;
  216. // ---------------------- //
  217. // --- STATIC METHODS --- //
  218. // ---------------------- //
  219. /**
  220. * Pass configuration settings to the class in the form of
  221. * key/value pairs. As a shortcut, if the second argument
  222. * is omitted and the key is a string, the setting is
  223. * assumed to be the DSN string used by PDO to connect
  224. * to the database (often, this will be the only configuration
  225. * required to use Idiorm). If you have more than one setting
  226. * you wish to configure, another shortcut is to pass an array
  227. * of settings (and omit the second argument).
  228. * @param string|array $key
  229. * @param mixed $value
  230. * @param string $connection_name Which connection to use
  231. */
  232. public static function configure($key, $value = null, $connection_name = self::DEFAULT_CONNECTION) {
  233. self::_setup_db_config($connection_name); //ensures at least default config is set
  234. if (is_array($key)) {
  235. // Shortcut: If only one array argument is passed,
  236. // assume it's an array of configuration settings
  237. foreach ($key as $conf_key => $conf_value) {
  238. self::configure($conf_key, $conf_value, $connection_name);
  239. }
  240. } else {
  241. if (is_null($value)) {
  242. // Shortcut: If only one string argument is passed,
  243. // assume it's a connection string
  244. $value = $key;
  245. $key = 'connection_string';
  246. }
  247. self::$_config[$connection_name][$key] = $value;
  248. }
  249. }
  250. /**
  251. * Retrieve configuration options by key, or as whole array.
  252. * @param string $key
  253. * @param string $connection_name Which connection to use
  254. */
  255. public static function get_config($key = null, $connection_name = self::DEFAULT_CONNECTION) {
  256. if ($key) {
  257. return self::$_config[$connection_name][$key];
  258. } else {
  259. return self::$_config[$connection_name];
  260. }
  261. }
  262. /**
  263. * Delete all configs in _config array.
  264. */
  265. public static function reset_config() {
  266. self::$_config = array();
  267. }
  268. /**
  269. * Despite its slightly odd name, this is actually the factory
  270. * method used to acquire instances of the class. It is named
  271. * this way for the sake of a readable interface, ie
  272. * ORM::for_table('table_name')->find_one()-> etc. As such,
  273. * this will normally be the first method called in a chain.
  274. * @param string $table_name
  275. * @param string $connection_name Which connection to use
  276. * @return ORM
  277. */
  278. public static function for_table($table_name, $connection_name = self::DEFAULT_CONNECTION) {
  279. self::_setup_db($connection_name);
  280. return new self($table_name, array(), $connection_name);
  281. }
  282. /**
  283. * Set up the database connection used by the class
  284. * @param string $connection_name Which connection to use
  285. */
  286. protected static function _setup_db($connection_name = self::DEFAULT_CONNECTION) {
  287. if (!array_key_exists($connection_name, self::$_db) ||
  288. !is_object(self::$_db[$connection_name])) {
  289. self::_setup_db_config($connection_name);
  290. $db = new PDO(
  291. self::$_config[$connection_name]['connection_string'],
  292. self::$_config[$connection_name]['username'],
  293. self::$_config[$connection_name]['password'],
  294. self::$_config[$connection_name]['driver_options']
  295. );
  296. $db->setAttribute(PDO::ATTR_ERRMODE, self::$_config[$connection_name]['error_mode']);
  297. self::set_db($db, $connection_name);
  298. }
  299. }
  300. /**
  301. * Ensures configuration (multiple connections) is at least set to default.
  302. * @param string $connection_name Which connection to use
  303. */
  304. protected static function _setup_db_config($connection_name) {
  305. if (!array_key_exists($connection_name, self::$_config)) {
  306. self::$_config[$connection_name] = self::$_default_config;
  307. }
  308. }
  309. /**
  310. * Set the PDO object used by Idiorm to communicate with the database.
  311. * This is public in case the ORM should use a ready-instantiated
  312. * PDO object as its database connection. Accepts an optional string key
  313. * to identify the connection if multiple connections are used.
  314. * @param PDO $db
  315. * @param string $connection_name Which connection to use
  316. */
  317. public static function set_db($db, $connection_name = self::DEFAULT_CONNECTION) {
  318. self::_setup_db_config($connection_name);
  319. self::$_db[$connection_name] = $db;
  320. if(!is_null(self::$_db[$connection_name])) {
  321. self::_setup_identifier_quote_character($connection_name);
  322. self::_setup_limit_clause_style($connection_name);
  323. }
  324. }
  325. /**
  326. * Close and delete all registered PDO objects in _db array.
  327. */
  328. public static function reset_db() {
  329. self::$_db = null;
  330. self::$_db = array();
  331. }
  332. /**
  333. * Detect and initialise the character used to quote identifiers
  334. * (table names, column names etc). If this has been specified
  335. * manually using ORM::configure('identifier_quote_character', 'some-char'),
  336. * this will do nothing.
  337. * @param string $connection_name Which connection to use
  338. */
  339. protected static function _setup_identifier_quote_character($connection_name) {
  340. if (is_null(self::$_config[$connection_name]['identifier_quote_character'])) {
  341. self::$_config[$connection_name]['identifier_quote_character'] =
  342. self::_detect_identifier_quote_character($connection_name);
  343. }
  344. }
  345. /**
  346. * Detect and initialise the limit clause style ("SELECT TOP 5" /
  347. * "... LIMIT 5"). If this has been specified manually using
  348. * ORM::configure('limit_clause_style', 'top'), this will do nothing.
  349. * @param string $connection_name Which connection to use
  350. */
  351. public static function _setup_limit_clause_style($connection_name) {
  352. if (is_null(self::$_config[$connection_name]['limit_clause_style'])) {
  353. self::$_config[$connection_name]['limit_clause_style'] =
  354. self::_detect_limit_clause_style($connection_name);
  355. }
  356. }
  357. /**
  358. * Return the correct character used to quote identifiers (table
  359. * names, column names etc) by looking at the driver being used by PDO.
  360. * @param string $connection_name Which connection to use
  361. * @return string
  362. */
  363. protected static function _detect_identifier_quote_character($connection_name) {
  364. switch(self::get_db($connection_name)->getAttribute(PDO::ATTR_DRIVER_NAME)) {
  365. case 'pgsql':
  366. case 'sqlsrv':
  367. case 'dblib':
  368. case 'mssql':
  369. case 'sybase':
  370. case 'firebird':
  371. return '"';
  372. case 'mysql':
  373. case 'sqlite':
  374. case 'sqlite2':
  375. default:
  376. return '`';
  377. }
  378. }
  379. /**
  380. * Returns a constant after determining the appropriate limit clause
  381. * style
  382. * @param string $connection_name Which connection to use
  383. * @return string Limit clause style keyword/constant
  384. */
  385. protected static function _detect_limit_clause_style($connection_name) {
  386. switch(self::get_db($connection_name)->getAttribute(PDO::ATTR_DRIVER_NAME)) {
  387. case 'sqlsrv':
  388. case 'dblib':
  389. case 'mssql':
  390. return ORM::LIMIT_STYLE_TOP_N;
  391. default:
  392. return ORM::LIMIT_STYLE_LIMIT;
  393. }
  394. }
  395. /**
  396. * Returns the PDO instance used by the the ORM to communicate with
  397. * the database. This can be called if any low-level DB access is
  398. * required outside the class. If multiple connections are used,
  399. * accepts an optional key name for the connection.
  400. * @param string $connection_name Which connection to use
  401. * @return PDO
  402. */
  403. public static function get_db($connection_name = self::DEFAULT_CONNECTION) {
  404. self::_setup_db($connection_name); // required in case this is called before Idiorm is instantiated
  405. return self::$_db[$connection_name];
  406. }
  407. /**
  408. * Executes a raw query as a wrapper for PDOStatement::execute.
  409. * Useful for queries that can't be accomplished through Idiorm,
  410. * particularly those using engine-specific features.
  411. * @example raw_execute('SELECT `name`, AVG(`order`) FROM `customer` GROUP BY `name` HAVING AVG(`order`) > 10')
  412. * @example raw_execute('INSERT OR REPLACE INTO `widget` (`id`, `name`) SELECT `id`, `name` FROM `other_table`')
  413. * @param string $query The raw SQL query
  414. * @param array $parameters Optional bound parameters
  415. * @param string $connection_name Which connection to use
  416. * @return bool Success
  417. */
  418. public static function raw_execute($query, $parameters = array(), $connection_name = self::DEFAULT_CONNECTION) {
  419. self::_setup_db($connection_name);
  420. return self::_execute($query, $parameters, $connection_name);
  421. }
  422. /**
  423. * Returns the PDOStatement instance last used by any connection wrapped by the ORM.
  424. * Useful for access to PDOStatement::rowCount() or error information
  425. * @return PDOStatement
  426. */
  427. public static function get_last_statement() {
  428. return self::$_last_statement;
  429. }
  430. /**
  431. * Internal helper method for executing statments. Logs queries, and
  432. * stores statement object in ::_last_statment, accessible publicly
  433. * through ::get_last_statement()
  434. * @param string $query
  435. * @param array $parameters An array of parameters to be bound in to the query
  436. * @param string $connection_name Which connection to use
  437. * @return bool Response of PDOStatement::execute()
  438. */
  439. protected static function _execute($query, $parameters = array(), $connection_name = self::DEFAULT_CONNECTION) {
  440. $statement = self::get_db($connection_name)->prepare($query);
  441. self::$_last_statement = $statement;
  442. $time = microtime(true);
  443. foreach ($parameters as $key => &$param) {
  444. if (is_null($param)) {
  445. $type = PDO::PARAM_NULL;
  446. } else if (is_bool($param)) {
  447. $type = PDO::PARAM_BOOL;
  448. } else if (is_int($param)) {
  449. $type = PDO::PARAM_INT;
  450. } else {
  451. $type = PDO::PARAM_STR;
  452. }
  453. $statement->bindParam(is_int($key) ? ++$key : $key, $param, $type);
  454. }
  455. $q = $statement->execute();
  456. self::_log_query($query, $parameters, $connection_name, (microtime(true)-$time));
  457. return $q;
  458. }
  459. /**
  460. * Add a query to the internal query log. Only works if the
  461. * 'logging' config option is set to true.
  462. *
  463. * This works by manually binding the parameters to the query - the
  464. * query isn't executed like this (PDO normally passes the query and
  465. * parameters to the database which takes care of the binding) but
  466. * doing it this way makes the logged queries more readable.
  467. * @param string $query
  468. * @param array $parameters An array of parameters to be bound in to the query
  469. * @param string $connection_name Which connection to use
  470. * @param float $query_time Query time
  471. * @return bool
  472. */
  473. protected static function _log_query($query, $parameters, $connection_name, $query_time) {
  474. // If logging is not enabled, do nothing
  475. if (!self::$_config[$connection_name]['logging']) {
  476. return false;
  477. }
  478. if (!isset(self::$_query_log[$connection_name])) {
  479. self::$_query_log[$connection_name] = array();
  480. }
  481. if (empty($parameters)) {
  482. $bound_query = $query;
  483. } else {
  484. // Escape the parameters
  485. $parameters = array_map(array(self::get_db($connection_name), 'quote'), $parameters);
  486. if (array_values($parameters) === $parameters) {
  487. // ? placeholders
  488. // Avoid %format collision for vsprintf
  489. $query = str_replace("%", "%%", $query);
  490. // Replace placeholders in the query for vsprintf
  491. if(false !== strpos($query, "'") || false !== strpos($query, '"')) {
  492. $query = IdiormString::str_replace_outside_quotes("?", "%s", $query);
  493. } else {
  494. $query = str_replace("?", "%s", $query);
  495. }
  496. // Replace the question marks in the query with the parameters
  497. $bound_query = vsprintf($query, $parameters);
  498. } else {
  499. // named placeholders
  500. foreach ($parameters as $key => $val) {
  501. $query = str_replace($key, $val, $query);
  502. }
  503. $bound_query = $query;
  504. }
  505. }
  506. self::$_last_query = $bound_query;
  507. self::$_query_log[$connection_name][] = $bound_query;
  508. if(is_callable(self::$_config[$connection_name]['logger'])){
  509. $logger = self::$_config[$connection_name]['logger'];
  510. $logger($bound_query, $query_time);
  511. }
  512. return true;
  513. }
  514. /**
  515. * Get the last query executed. Only works if the
  516. * 'logging' config option is set to true. Otherwise
  517. * this will return null. Returns last query from all connections if
  518. * no connection_name is specified
  519. * @param null|string $connection_name Which connection to use
  520. * @return string
  521. */
  522. public static function get_last_query($connection_name = null) {
  523. if ($connection_name === null) {
  524. return self::$_last_query;
  525. }
  526. if (!isset(self::$_query_log[$connection_name])) {
  527. return '';
  528. }
  529. return end(self::$_query_log[$connection_name]);
  530. }
  531. /**
  532. * Get an array containing all the queries run on a
  533. * specified connection up to now.
  534. * Only works if the 'logging' config option is
  535. * set to true. Otherwise, returned array will be empty.
  536. * @param string $connection_name Which connection to use
  537. */
  538. public static function get_query_log($connection_name = self::DEFAULT_CONNECTION) {
  539. if (isset(self::$_query_log[$connection_name])) {
  540. return self::$_query_log[$connection_name];
  541. }
  542. return array();
  543. }
  544. /**
  545. * Get a list of the available connection names
  546. * @return array
  547. */
  548. public static function get_connection_names() {
  549. return array_keys(self::$_db);
  550. }
  551. // ------------------------ //
  552. // --- INSTANCE METHODS --- //
  553. // ------------------------ //
  554. /**
  555. * "Private" constructor; shouldn't be called directly.
  556. * Use the ORM::for_table factory method instead.
  557. */
  558. protected function __construct($table_name, $data = array(), $connection_name = self::DEFAULT_CONNECTION) {
  559. $this->_table_name = $table_name;
  560. $this->_data = $data;
  561. $this->_connection_name = $connection_name;
  562. self::_setup_db_config($connection_name);
  563. }
  564. /**
  565. * Create a new, empty instance of the class. Used
  566. * to add a new row to your database. May optionally
  567. * be passed an associative array of data to populate
  568. * the instance. If so, all fields will be flagged as
  569. * dirty so all will be saved to the database when
  570. * save() is called.
  571. */
  572. public function create($data=null) {
  573. $this->_is_new = true;
  574. if (!is_null($data)) {
  575. return $this->hydrate($data)->force_all_dirty();
  576. }
  577. return $this;
  578. }
  579. /**
  580. * Specify the ID column to use for this instance or array of instances only.
  581. * This overrides the id_column and id_column_overrides settings.
  582. *
  583. * This is mostly useful for libraries built on top of Idiorm, and will
  584. * not normally be used in manually built queries. If you don't know why
  585. * you would want to use this, you should probably just ignore it.
  586. */
  587. public function use_id_column($id_column) {
  588. $this->_instance_id_column = $id_column;
  589. return $this;
  590. }
  591. /**
  592. * Create an ORM instance from the given row (an associative
  593. * array of data fetched from the database)
  594. */
  595. protected function _create_instance_from_row($row) {
  596. $instance = self::for_table($this->_table_name, $this->_connection_name);
  597. $instance->use_id_column($this->_instance_id_column);
  598. $instance->hydrate($row);
  599. return $instance;
  600. }
  601. /**
  602. * Tell the ORM that you are expecting a single result
  603. * back from your query, and execute it. Will return
  604. * a single instance of the ORM class, or false if no
  605. * rows were returned.
  606. * As a shortcut, you may supply an ID as a parameter
  607. * to this method. This will perform a primary key
  608. * lookup on the table.
  609. */
  610. public function find_one($id=null) {
  611. if (!is_null($id)) {
  612. $this->where_id_is($id);
  613. }
  614. $this->limit(1);
  615. $rows = $this->_run();
  616. if (empty($rows)) {
  617. return false;
  618. }
  619. return $this->_create_instance_from_row($rows[0]);
  620. }
  621. /**
  622. * Tell the ORM that you are expecting multiple results
  623. * from your query, and execute it. Will return an array
  624. * of instances of the ORM class, or an empty array if
  625. * no rows were returned.
  626. * @return array|\IdiormResultSet
  627. */
  628. public function find_many() {
  629. if(self::$_config[$this->_connection_name]['return_result_sets']) {
  630. return $this->find_result_set();
  631. }
  632. return $this->_find_many();
  633. }
  634. /**
  635. * Tell the ORM that you are expecting multiple results
  636. * from your query, and execute it. Will return an array
  637. * of instances of the ORM class, or an empty array if
  638. * no rows were returned.
  639. * @return array
  640. */
  641. protected function _find_many() {
  642. $rows = $this->_run();
  643. return array_map(array($this, '_create_instance_from_row'), $rows);
  644. }
  645. /**
  646. * Tell the ORM that you are expecting multiple results
  647. * from your query, and execute it. Will return a result set object
  648. * containing instances of the ORM class.
  649. * @return \IdiormResultSet
  650. */
  651. public function find_result_set() {
  652. return new IdiormResultSet($this->_find_many());
  653. }
  654. /**
  655. * Tell the ORM that you are expecting multiple results
  656. * from your query, and execute it. Will return an array,
  657. * or an empty array if no rows were returned.
  658. * @return array
  659. */
  660. public function find_array() {
  661. return $this->_run();
  662. }
  663. /**
  664. * Tell the ORM that you wish to execute a COUNT query.
  665. * Will return an integer representing the number of
  666. * rows returned.
  667. */
  668. public function count($column = '*') {
  669. return $this->_call_aggregate_db_function(__FUNCTION__, $column);
  670. }
  671. /**
  672. * Tell the ORM that you wish to execute a MAX query.
  673. * Will return the max value of the choosen column.
  674. */
  675. public function max($column) {
  676. return $this->_call_aggregate_db_function(__FUNCTION__, $column);
  677. }
  678. /**
  679. * Tell the ORM that you wish to execute a MIN query.
  680. * Will return the min value of the choosen column.
  681. */
  682. public function min($column) {
  683. return $this->_call_aggregate_db_function(__FUNCTION__, $column);
  684. }
  685. /**
  686. * Tell the ORM that you wish to execute a AVG query.
  687. * Will return the average value of the choosen column.
  688. */
  689. public function avg($column) {
  690. return $this->_call_aggregate_db_function(__FUNCTION__, $column);
  691. }
  692. /**
  693. * Tell the ORM that you wish to execute a SUM query.
  694. * Will return the sum of the choosen column.
  695. */
  696. public function sum($column) {
  697. return $this->_call_aggregate_db_function(__FUNCTION__, $column);
  698. }
  699. /**
  700. * Execute an aggregate query on the current connection.
  701. * @param string $sql_function The aggregate function to call eg. MIN, COUNT, etc
  702. * @param string $column The column to execute the aggregate query against
  703. * @return int
  704. */
  705. protected function _call_aggregate_db_function($sql_function, $column) {
  706. $alias = strtolower($sql_function);
  707. $sql_function = strtoupper($sql_function);
  708. if('*' != $column) {
  709. $column = $this->_quote_identifier($column);
  710. }
  711. $result_columns = $this->_result_columns;
  712. $this->_result_columns = array();
  713. $this->select_expr("$sql_function($column)", $alias);
  714. $result = $this->find_one();
  715. $this->_result_columns = $result_columns;
  716. $return_value = 0;
  717. if($result !== false && isset($result->$alias)) {
  718. if (!is_numeric($result->$alias)) {
  719. $return_value = $result->$alias;
  720. }
  721. elseif((int) $result->$alias == (float) $result->$alias) {
  722. $return_value = (int) $result->$alias;
  723. } else {
  724. $return_value = (float) $result->$alias;
  725. }
  726. }
  727. return $return_value;
  728. }
  729. /**
  730. * This method can be called to hydrate (populate) this
  731. * instance of the class from an associative array of data.
  732. * This will usually be called only from inside the class,
  733. * but it's public in case you need to call it directly.
  734. */
  735. public function hydrate($data=array()) {
  736. $this->_data = $data;
  737. return $this;
  738. }
  739. /**
  740. * Force the ORM to flag all the fields in the $data array
  741. * as "dirty" and therefore update them when save() is called.
  742. */
  743. public function force_all_dirty() {
  744. $this->_dirty_fields = $this->_data;
  745. return $this;
  746. }
  747. /**
  748. * Perform a raw query. The query can contain placeholders in
  749. * either named or question mark style. If placeholders are
  750. * used, the parameters should be an array of values which will
  751. * be bound to the placeholders in the query. If this method
  752. * is called, all other query building methods will be ignored.
  753. */
  754. public function raw_query($query, $parameters = array()) {
  755. $this->_is_raw_query = true;
  756. $this->_raw_query = $query;
  757. $this->_raw_parameters = $parameters;
  758. return $this;
  759. }
  760. /**
  761. * Add an alias for the main table to be used in SELECT queries
  762. */
  763. public function table_alias($alias) {
  764. $this->_table_alias = $alias;
  765. return $this;
  766. }
  767. /**
  768. * Internal method to add an unquoted expression to the set
  769. * of columns returned by the SELECT query. The second optional
  770. * argument is the alias to return the expression as.
  771. */
  772. protected function _add_result_column($expr, $alias=null) {
  773. if (!is_null($alias)) {
  774. $expr .= " AS " . $this->_quote_identifier($alias);
  775. }
  776. if ($this->_using_default_result_columns) {
  777. $this->_result_columns = array($expr);
  778. $this->_using_default_result_columns = false;
  779. } else {
  780. $this->_result_columns[] = $expr;
  781. }
  782. return $this;
  783. }
  784. /**
  785. * Counts the number of columns that belong to the primary
  786. * key and their value is null.
  787. */
  788. public function count_null_id_columns() {
  789. if (is_array($this->_get_id_column_name())) {
  790. return count(array_filter($this->id(), 'is_null'));
  791. } else {
  792. return is_null($this->id()) ? 1 : 0;
  793. }
  794. }
  795. /**
  796. * Add a column to the list of columns returned by the SELECT
  797. * query. This defaults to '*'. The second optional argument is
  798. * the alias to return the column as.
  799. */
  800. public function select($column, $alias=null) {
  801. $column = $this->_quote_identifier($column);
  802. return $this->_add_result_column($column, $alias);
  803. }
  804. /**
  805. * Add an unquoted expression to the list of columns returned
  806. * by the SELECT query. The second optional argument is
  807. * the alias to return the column as.
  808. */
  809. public function select_expr($expr, $alias=null) {
  810. return $this->_add_result_column($expr, $alias);
  811. }
  812. /**
  813. * Add columns to the list of columns returned by the SELECT
  814. * query. This defaults to '*'. Many columns can be supplied
  815. * as either an array or as a list of parameters to the method.
  816. *
  817. * Note that the alias must not be numeric - if you want a
  818. * numeric alias then prepend it with some alpha chars. eg. a1
  819. *
  820. * @example select_many(array('alias' => 'column', 'column2', 'alias2' => 'column3'), 'column4', 'column5');
  821. * @example select_many('column', 'column2', 'column3');
  822. * @example select_many(array('column', 'column2', 'column3'), 'column4', 'column5');
  823. *
  824. * @return ORM
  825. */
  826. public function select_many() {
  827. $columns = func_get_args();
  828. if(!empty($columns)) {
  829. $columns = $this->_normalise_select_many_columns($columns);
  830. foreach($columns as $alias => $column) {
  831. if(is_numeric($alias)) {
  832. $alias = null;
  833. }
  834. $this->select($column, $alias);
  835. }
  836. }
  837. return $this;
  838. }
  839. /**
  840. * Add an unquoted expression to the list of columns returned
  841. * by the SELECT query. Many columns can be supplied as either
  842. * an array or as a list of parameters to the method.
  843. *
  844. * Note that the alias must not be numeric - if you want a
  845. * numeric alias then prepend it with some alpha chars. eg. a1
  846. *
  847. * @example select_many_expr(array('alias' => 'column', 'column2', 'alias2' => 'column3'), 'column4', 'column5')
  848. * @example select_many_expr('column', 'column2', 'column3')
  849. * @example select_many_expr(array('column', 'column2', 'column3'), 'column4', 'column5')
  850. *
  851. * @return ORM
  852. */
  853. public function select_many_expr() {
  854. $columns = func_get_args();
  855. if(!empty($columns)) {
  856. $columns = $this->_normalise_select_many_columns($columns);
  857. foreach($columns as $alias => $column) {
  858. if(is_numeric($alias)) {
  859. $alias = null;
  860. }
  861. $this->select_expr($column, $alias);
  862. }
  863. }
  864. return $this;
  865. }
  866. /**
  867. * Take a column specification for the select many methods and convert it
  868. * into a normalised array of columns and aliases.
  869. *
  870. * It is designed to turn the following styles into a normalised array:
  871. *
  872. * array(array('alias' => 'column', 'column2', 'alias2' => 'column3'), 'column4', 'column5'))
  873. *
  874. * @param array $columns
  875. * @return array
  876. */
  877. protected function _normalise_select_many_columns($columns) {
  878. $return = array();
  879. foreach($columns as $column) {
  880. if(is_array($column)) {
  881. foreach($column as $key => $value) {
  882. if(!is_numeric($key)) {
  883. $return[$key] = $value;
  884. } else {
  885. $return[] = $value;
  886. }
  887. }
  888. } else {
  889. $return[] = $column;
  890. }
  891. }
  892. return $return;
  893. }
  894. /**
  895. * Add a DISTINCT keyword before the list of columns in the SELECT query
  896. */
  897. public function distinct() {
  898. $this->_distinct = true;
  899. return $this;
  900. }
  901. /**
  902. * Internal method to add a JOIN source to the query.
  903. *
  904. * The join_operator should be one of INNER, LEFT OUTER, CROSS etc - this
  905. * will be prepended to JOIN.
  906. *
  907. * The table should be the name of the table to join to.
  908. *
  909. * The constraint may be either a string or an array with three elements. If it
  910. * is a string, it will be compiled into the query as-is, with no escaping. The
  911. * recommended way to supply the constraint is as an array with three elements:
  912. *
  913. * first_column, operator, second_column
  914. *
  915. * Example: array('user.id', '=', 'profile.user_id')
  916. *
  917. * will compile to
  918. *
  919. * ON `user`.`id` = `profile`.`user_id`
  920. *
  921. * The final (optional) argument specifies an alias for the joined table.
  922. */
  923. protected function _add_join_source($join_operator, $table, $constraint, $table_alias=null) {
  924. $join_operator = trim("{$join_operator} JOIN");
  925. $table = $this->_quote_identifier($table);
  926. // Add table alias if present
  927. if (!is_null($table_alias)) {
  928. $table_alias = $this->_quote_identifier($table_alias);
  929. $table .= " {$table_alias}";
  930. }
  931. // Build the constraint
  932. if (is_array($constraint)) {
  933. list($first_column, $operator, $second_column) = $constraint;
  934. $first_column = $this->_quote_identifier($first_column);
  935. $second_column = $this->_quote_identifier($second_column);
  936. $constraint = "{$first_column} {$operator} {$second_column}";
  937. }
  938. $this->_join_sources[] = "{$join_operator} {$table} ON {$constraint}";
  939. return $this;
  940. }
  941. /**
  942. * Add a RAW JOIN source to the query
  943. */
  944. public function raw_join($table, $constraint, $table_alias, $parameters = array()) {
  945. // Add table alias if present
  946. if (!is_null($table_alias)) {
  947. $table_alias = $this->_quote_identifier($table_alias);
  948. $table .= " {$table_alias}";
  949. }
  950. $this->_values = array_merge($this->_values, $parameters);
  951. // Build the constraint
  952. if (is_array($constraint)) {
  953. list($first_column, $operator, $second_column) = $constraint;
  954. $first_column = $this->_quote_identifier($first_column);
  955. $second_column = $this->_quote_identifier($second_column);
  956. $constraint = "{$first_column} {$operator} {$second_column}";
  957. }
  958. $this->_join_sources[] = "{$table} ON {$constraint}";
  959. return $this;
  960. }
  961. /**
  962. * Add a simple JOIN source to the query
  963. */
  964. public function join($table, $constraint, $table_alias=null) {
  965. return $this->_add_join_source("", $table, $constraint, $table_alias);
  966. }
  967. /**
  968. * Add an INNER JOIN souce to the query
  969. */
  970. public function inner_join($table, $constraint, $table_alias=null) {
  971. return $this->_add_join_source("INNER", $table, $constraint, $table_alias);
  972. }
  973. /**
  974. * Add a LEFT OUTER JOIN souce to the query
  975. */
  976. public function left_outer_join($table, $constraint, $table_alias=null) {
  977. return $this->_add_join_source("LEFT OUTER", $table, $constraint, $table_alias);
  978. }
  979. /**
  980. * Add an RIGHT OUTER JOIN souce to the query
  981. */
  982. public function right_outer_join($table, $constraint, $table_alias=null) {
  983. return $this->_add_join_source("RIGHT OUTER", $table, $constraint, $table_alias);
  984. }
  985. /**
  986. * Add an FULL OUTER JOIN souce to the query
  987. */
  988. public function full_outer_join($table, $constraint, $table_alias=null) {
  989. return $this->_add_join_source("FULL OUTER", $table, $constraint, $table_alias);
  990. }
  991. /**
  992. * Internal method to add a HAVING condition to the query
  993. */
  994. protected function _add_having($fragment, $values=array()) {
  995. return $this->_add_condition('having', $fragment, $values);
  996. }
  997. /**
  998. * Internal method to add a HAVING condition to the query
  999. */
  1000. protected function _add_simple_having($column_name, $separator, $value) {
  1001. return $this->_add_simple_condition('having', $column_name, $separator, $value);
  1002. }
  1003. /**
  1004. * Internal method to add a HAVING clause with multiple values (like IN and NOT IN)
  1005. */
  1006. public function _add_having_placeholder($column_name, $separator, $values) {
  1007. if (!is_array($column_name)) {
  1008. $data = array($column_name => $values);
  1009. } else {
  1010. $data = $column_name;
  1011. }
  1012. $result = $this;
  1013. foreach ($data as $key => $val) {
  1014. $column = $result->_quote_identifier($key);
  1015. $placeholders = $result->_create_placeholders($val);
  1016. $result = $result->_add_having("{$column} {$separator} ({$placeholders})", $val);
  1017. }
  1018. return $result;
  1019. }
  1020. /**
  1021. * Internal method to add a HAVING clause with no parameters(like IS NULL and IS NOT NULL)
  1022. */
  1023. public function _add_having_no_value($column_name, $operator) {
  1024. $conditions = (is_array($column_name)) ? $column_name : array($column_name);
  1025. $result = $this;
  1026. foreach($conditions as $column) {
  1027. $column = $this->_quote_identifier($column);
  1028. $result = $result->_add_having("{$column} {$operator}");
  1029. }
  1030. return $result;
  1031. }
  1032. /**
  1033. * Internal method to add a WHERE condition to the query
  1034. */
  1035. protected function _add_where($fragment, $values=array()) {
  1036. return $this->_add_condition('where', $fragment, $values);
  1037. }
  1038. /**
  1039. * Internal method to add a WHERE condition to the query
  1040. */
  1041. protected function _add_simple_where($column_name, $separator, $value) {
  1042. return $this->_add_simple_condition('where', $column_name, $separator, $value);
  1043. }
  1044. /**
  1045. * Add a WHERE clause with multiple values (like IN and NOT IN)
  1046. */
  1047. public function _add_where_placeholder($column_name, $separator, $values) {
  1048. if (!is_array($column_name)) {
  1049. $data = array($column_name => $values);
  1050. } else {
  1051. $data = $column_name;
  1052. }
  1053. $result = $this;
  1054. foreach ($data as $key => $val) {
  1055. $column = $result->_quote_identifier($key);
  1056. $placeholders = $result->_create_placeholders($val);
  1057. $result = $result->_add_where("{$column} {$separator} ({$placeholders})", $val);
  1058. }
  1059. return $result;
  1060. }
  1061. /**
  1062. * Add a WHERE clause with no parameters(like IS NULL and IS NOT NULL)
  1063. */
  1064. public function _add_where_no_value($column_name, $operator) {
  1065. $conditions = (is_array($column_name)) ? $column_name : array($column_name);
  1066. $result = $this;
  1067. foreach($conditions as $column) {
  1068. $column = $this->_quote_identifier($column);
  1069. $result = $result->_add_where("{$column} {$operator}");
  1070. }
  1071. return $result;
  1072. }
  1073. /**
  1074. * Internal method to add a HAVING or WHERE condition to the query
  1075. */
  1076. protected function _add_condition($type, $fragment, $values=array()) {
  1077. $conditions_class_property_name = "_{$type}_conditions";
  1078. if (!is_array($values)) {
  1079. $values = array($values);
  1080. }
  1081. array_push($this->$conditions_class_property_name, array(
  1082. self::CONDITION_FRAGMENT => $fragment,
  1083. self::CONDITION_VALUES => $values,
  1084. ));
  1085. return $this;
  1086. }
  1087. /**
  1088. * Helper method to compile a simple COLUMN SEPARATOR VALUE
  1089. * style HAVING or WHERE condition into a string and value ready to
  1090. * be passed to the _add_condition method. Avoids duplication
  1091. * of the call to _quote_identifier
  1092. *
  1093. * If column_name is an associative array, it will add a condition for each column
  1094. */
  1095. protected function _add_simple_condition($type, $column_name, $separator, $value) {
  1096. $multiple = is_array($column_name) ? $column_name : array($column_name => $value);
  1097. $result = $this;
  1098. foreach($multiple as $key => $val) {
  1099. // Add the table name in case of ambiguous columns
  1100. if (count($result->_join_sources) > 0 && strpos($key, '.') === false) {
  1101. $table = $result->_table_name;
  1102. if (!is_null($result->_table_alias)) {
  1103. $table = $result->_table_alias;
  1104. }
  1105. $key = "{$table}.{$key}";
  1106. }
  1107. $key = $result->_quote_identifier($key);
  1108. $result = $result->_add_condition($type, "{$key} {$separator} ?", $val);
  1109. }
  1110. return $result;
  1111. }
  1112. /**
  1113. * Return a string containing the given number of question marks,
  1114. * separated by commas. Eg "?, ?, ?"
  1115. */
  1116. protected function _create_placeholders($fields) {
  1117. if(!empty($fields)) {
  1118. $db_fields = array();
  1119. foreach($fields as $key => $value) {
  1120. // Process expression fields directly into the query
  1121. if(array_key_exists($key, $this->_expr_fields)) {
  1122. $db_fields[] = $value;
  1123. } else {
  1124. $db_fields[] = '?';
  1125. }
  1126. }
  1127. return implode(', ', $db_fields);
  1128. }
  1129. }
  1130. /**
  1131. * Helper method that filters a column/value array returning only those
  1132. * columns that belong to a compound primary key.
  1133. *
  1134. * If the key contains a column that does not exist in the given array,
  1135. * a null value will be returned for it.
  1136. */
  1137. protected function _get_compound_id_column_values($value) {
  1138. $filtered = array();
  1139. foreach($this->_get_id_column_name() as $key) {
  1140. $filtered[$key] = isset($value[$key]) ? $value[$key] : null;
  1141. }
  1142. return $filtered;
  1143. }
  1144. /**
  1145. * Helper method that filters an array containing compound column/value
  1146. * arrays.
  1147. */
  1148. protected function _get_compound_id_column_values_array($values) {
  1149. $filtered = array();
  1150. foreach($values as $value) {
  1151. $filtered[] = $this->_get_compound_id_column_values($value);
  1152. }
  1153. return $filtered;
  1154. }
  1155. /**
  1156. * Add a WHERE column = value clause to your query. Each time
  1157. * this is called in the chain, an additional WHERE will be
  1158. * added, and these will be ANDed together when the final query
  1159. * is built.
  1160. *
  1161. * If you use an array in $column_name, a new clause will be
  1162. * added for each element. In this case, $value is ignored.
  1163. */
  1164. public function where($column_name, $value=null) {
  1165. return $this->where_equal($column_name, $value);
  1166. }
  1167. /**
  1168. * More explicitly named version of for the where() method.
  1169. * Can be used if preferred.
  1170. */
  1171. public function where_equal($column_name, $value=null) {
  1172. return $this->_add_simple_where($column_name, '=', $value);
  1173. }
  1174. /**
  1175. * Add a WHERE column != value clause to your query.
  1176. */
  1177. public function where_not_equal($column_name, $value=null) {
  1178. return $this->_add_simple_where($column_name, '!=', $value);
  1179. }
  1180. /**
  1181. * Special method to query the table by its primary key
  1182. *
  1183. * If primary key is compound, only the columns that
  1184. * belong to they key will be used for the query
  1185. */
  1186. public function where_id_is($id) {
  1187. return (is_array($this->_get_id_column_name())) ?
  1188. $this->where($this->_get_compound_id_column_values($id), null) :
  1189. $this->where($this->_get_id_column_name(), $id);
  1190. }
  1191. /**
  1192. * Allows adding a WHERE clause that matches any of the conditions
  1193. * specified in the array. Each element in the associative array will
  1194. * be a different condition, where the key will be the column name.
  1195. *
  1196. * By default, an equal operator will be used against all columns, but
  1197. * it can be overriden for any or every column using the second parameter.
  1198. *
  1199. * Each condition will be ORed together when added to the final query.
  1200. */
  1201. public function where_any_is($values, $operator='=') {
  1202. $data = array();
  1203. $query = array("((");
  1204. $first = true;
  1205. foreach ($values as $value) {
  1206. if ($first) {
  1207. $first = false;
  1208. } else {
  1209. $query[] = ") OR (";
  1210. }
  1211. $firstsub = true;
  1212. foreach($value as $key => $item) {
  1213. $op = is_string($operator) ? $operator : (isset($operator[$key]) ? $operator[$key] : '=');
  1214. if ($firstsub) {
  1215. $firstsub = false;
  1216. } else {
  1217. $query[] = "AND";
  1218. }
  1219. $query[] = $this->_quote_identifier($key);
  1220. $data[] = $item;
  1221. $query[] = $op . " ?";
  1222. }
  1223. }
  1224. $query[] = "))";
  1225. return $this->where_raw(implode(' ', $query), $data);
  1226. }
  1227. /**
  1228. * Similar to where_id_is() but allowing multiple primary keys.
  1229. *
  1230. * If primary key is compound, only the columns that
  1231. * belong to they key will be used for the query
  1232. */
  1233. public function where_id_in($ids) {
  1234. return (is_array($this->_get_id_column_name())) ?
  1235. $this->where_any_is($this->_get_compound_id_column_values_array($ids)) :
  1236. $this->where_in($this->_get_id_column_name(), $ids);
  1237. }
  1238. /**
  1239. * Add a WHERE ... LIKE clause to your query.
  1240. */
  1241. public function where_like($column_name, $value=null) {
  1242. return $this->_add_simple_where($column_name, 'LIKE', $value);
  1243. }
  1244. /**
  1245. * Add where WHERE ... NOT LIKE clause to your query.
  1246. */
  1247. public function where_not_like($column_name, $value=null) {
  1248. return $this->_add_simple_where($column_name, 'NOT LIKE', $value);
  1249. }
  1250. /**
  1251. * Add a WHERE ... > clause to your query
  1252. */
  1253. public function where_gt($column_name, $value=null) {
  1254. return $this->_add_simple_where($column_name, '>', $value);
  1255. }
  1256. /**
  1257. * Add a WHERE ... < clause to your query
  1258. */
  1259. public function where_lt($column_name, $value=null) {
  1260. return $this->_add_simple_where($column_name, '<', $value);
  1261. }
  1262. /**
  1263. * Add a WHERE ... >= clause to your query
  1264. */
  1265. public function where_gte($column_name, $value=null) {
  1266. return $this->_add_simple_where($column_name, '>=', $value);
  1267. }
  1268. /**
  1269. * Add a WHERE ... <= clause to your query
  1270. */
  1271. public function where_lte($column_name, $value=null) {
  1272. return $this->_add_simple_where($column_name, '<=', $value);
  1273. }
  1274. /**
  1275. * Add a WHERE ... IN clause to your query
  1276. */
  1277. public function where_in($column_name, $values) {
  1278. return $this->_add_where_placeholder($column_name, 'IN', $values);
  1279. }
  1280. /**
  1281. * Add a WHERE ... NOT IN clause to your query
  1282. */
  1283. public function where_not_in($column_name, $values) {
  1284. return $this->_add_where_placeholder($column_name, 'NOT IN', $values);
  1285. }
  1286. /**
  1287. * Add a WHERE column IS NULL clause to your query
  1288. */
  1289. public function where_null($column_name) {
  1290. return $this->_add_where_no_value($column_name, "IS NULL");
  1291. }
  1292. /**
  1293. * Add a WHERE column IS NOT NULL clause to your query
  1294. */
  1295. public function where_not_null($column_name) {
  1296. return $this->_add_where_no_value($column_name, "IS NOT NULL");
  1297. }
  1298. /**
  1299. * Add a raw WHERE clause to the query. The clause should
  1300. * contain question mark placeholders, which will be bound
  1301. * to the parameters supplied in the second argument.
  1302. */
  1303. public function where_raw($clause, $parameters=array()) {
  1304. return $this->_add_where($clause, $parameters);
  1305. }
  1306. /**
  1307. * Add a LIMIT to the query
  1308. */
  1309. public function limit($limit) {
  1310. $this->_limit = $limit;
  1311. return $this;
  1312. }
  1313. /**
  1314. * Add an OFFSET to the query
  1315. */
  1316. public function offset($offset) {
  1317. $this->_offset = $offset;
  1318. return $this;
  1319. }
  1320. /**
  1321. * Add an ORDER BY clause to the query
  1322. */
  1323. protected function _add_order_by($column_name, $ordering) {
  1324. $column_name = $this->_quote_identifier($column_name);
  1325. $this->_order_by[] = "{$column_name} {$ordering}";
  1326. return $this;
  1327. }
  1328. /**
  1329. * Add an ORDER BY column DESC clause
  1330. */
  1331. public function order_by_desc($column_name) {
  1332. return $this->_add_order_by($column_name, 'DESC');
  1333. }
  1334. /**
  1335. * Add an ORDER BY column ASC clause
  1336. */
  1337. public function order_by_asc($column_name) {
  1338. return $this->_add_order_by($column_name, 'ASC');
  1339. }
  1340. /**
  1341. * Add an unquoted expression as an ORDER BY clause
  1342. */
  1343. public function order_by_expr($clause) {
  1344. $this->_order_by[] = $clause;
  1345. return $this;
  1346. }
  1347. /**
  1348. * Add a column to the list of columns to GROUP BY
  1349. */
  1350. public function group_by($column_name) {
  1351. $column_name = $this->_quote_identifier($column_name);
  1352. $this->_group_by[] = $column_name;
  1353. return $this;
  1354. }
  1355. /**
  1356. * Add an unquoted expression to the list of columns to GROUP BY
  1357. */
  1358. public function group_by_expr($expr) {
  1359. $this->_group_by[] = $expr;
  1360. return $this;
  1361. }
  1362. /**
  1363. * Add a HAVING column = value clause to your query. Each time
  1364. * this is called in the chain, an additional HAVING will be
  1365. * added, and these will be ANDed together when the final query
  1366. * is built.
  1367. *
  1368. * If you use an array in $column_name, a new clause will be
  1369. * added for each element. In this case, $value is ignored.
  1370. */
  1371. public function having($column_name, $value=null) {
  1372. return $this->having_equal($column_name, $value);
  1373. }
  1374. /**
  1375. * More explicitly named version of for the having() method.
  1376. * Can be used if preferred.
  1377. */
  1378. public function having_equal($column_name, $value=null) {
  1379. return $this->_add_simple_having($column_name, '=', $value);
  1380. }
  1381. /**
  1382. * Add a HAVING column != value clause to your query.
  1383. */
  1384. public function having_not_equal($column_name, $value=null) {
  1385. return $this->_add_simple_having($column_name, '!=', $value);
  1386. }
  1387. /**
  1388. * Special method to query the table by its primary key.
  1389. *
  1390. * If primary key is compound, only the columns that
  1391. * belong to they key will be used for the query
  1392. */
  1393. public function having_id_is($id) {
  1394. return (is_array($this->_get_id_column_name())) ?
  1395. $this->having($this->_get_compound_id_column_values($id), null) :
  1396. $this->having($this->_get_id_column_name(), $id);
  1397. }
  1398. /**
  1399. * Add a HAVING ... LIKE clause to your query.
  1400. */
  1401. public function having_like($column_name, $value=null) {
  1402. return $this->_add_simple_having($column_name, 'LIKE', $value);
  1403. }
  1404. /**
  1405. * Add where HAVING ... NOT LIKE clause to your query.
  1406. */
  1407. public function having_not_like($column_name, $value=null) {
  1408. return $this->_add_simple_having($column_name, 'NOT LIKE', $value);
  1409. }
  1410. /**
  1411. * Add a HAVING ... > clause to your query
  1412. */
  1413. public function having_gt($column_name, $value=null) {
  1414. return $this->_add_simple_having($column_name, '>', $value);
  1415. }
  1416. /**
  1417. * Add a HAVING ... < clause to your query
  1418. */
  1419. public function having_lt($column_name, $value=null) {
  1420. return $this->_add_simple_having($column_name, '<', $value);
  1421. }
  1422. /**
  1423. * Add a HAVING ... >= clause to your query
  1424. */
  1425. public function having_gte($column_name, $value=null) {
  1426. return $this->_add_simple_having($column_name, '>=', $value);
  1427. }
  1428. /**
  1429. * Add a HAVING ... <= clause to your query
  1430. */
  1431. public function having_lte($column_name, $value=null) {
  1432. return $this->_add_simple_having($column_name, '<=', $value);
  1433. }
  1434. /**
  1435. * Add a HAVING ... IN clause to your query
  1436. */
  1437. public function having_in($column_name, $values=null) {
  1438. return $this->_add_having_placeholder($column_name, 'IN', $values);
  1439. }
  1440. /**
  1441. * Add a HAVING ... NOT IN clause to your query
  1442. */
  1443. public function having_not_in($column_name, $values=null) {
  1444. return $this->_add_having_placeholder($column_name, 'NOT IN', $values);
  1445. }
  1446. /**
  1447. * Add a HAVING column IS NULL clause to your query
  1448. */
  1449. public function having_null($column_name) {
  1450. return $this->_add_having_no_value($column_name, 'IS NULL');
  1451. }
  1452. /**
  1453. * Add a HAVING column IS NOT NULL clause to your query
  1454. */
  1455. public function having_not_null($column_name) {
  1456. return $this->_add_having_no_value($column_name, 'IS NOT NULL');
  1457. }
  1458. /**
  1459. * Add a raw HAVING clause to the query. The clause should
  1460. * contain question mark placeholders, which will be bound
  1461. * to the parameters supplied in the second argument.
  1462. */
  1463. public function having_raw($clause, $parameters=array()) {
  1464. return $this->_add_having($clause, $parameters);
  1465. }
  1466. /**
  1467. * Build a SELECT statement based on the clauses that have
  1468. * been passed to this instance by chaining method calls.
  1469. */
  1470. protected function _build_select() {
  1471. // If the query is raw, just set the $this->_values to be
  1472. // the raw query parameters and return the raw query
  1473. if ($this->_is_raw_query) {
  1474. $this->_values = $this->_raw_parameters;
  1475. return $this->_raw_query;
  1476. }
  1477. // Build and return the full SELECT statement by concatenating
  1478. // the results of calling each separate builder method.
  1479. return $this->_join_if_not_empty(" ", array(
  1480. $this->_build_select_start(),
  1481. $this->_build_join(),
  1482. $this->_build_where(),
  1483. $this->_build_group_by(),
  1484. $this->_build_having(),
  1485. $this->_build_order_by(),
  1486. $this->_build_limit(),
  1487. $this->_build_offset(),
  1488. ));
  1489. }
  1490. /**
  1491. * Build the start of the SELECT statement
  1492. */
  1493. protected function _build_select_start() {
  1494. $fragment = 'SELECT ';
  1495. $result_columns = implode(', ', $this->_result_columns);
  1496. if (!is_null($this->_limit) &&
  1497. self::$_config[$this->_connection_name]['limit_clause_style'] === ORM::LIMIT_STYLE_TOP_N) {
  1498. $fragment .= "TOP {$this->_limit} ";
  1499. }
  1500. if ($this->_distinct) {
  1501. $result_columns = 'DISTINCT ' . $result_columns;
  1502. }
  1503. $fragment .= "{$result_columns} FROM " . $this->_quote_identifier($this->_table_name);
  1504. if (!is_null($this->_table_alias)) {
  1505. $fragment .= " " . $this->_quote_identifier($this->_table_alias);
  1506. }
  1507. return $fragment;
  1508. }
  1509. /**
  1510. * Build the JOIN sources
  1511. */
  1512. protected function _build_join() {
  1513. if (count($this->_join_sources) === 0) {
  1514. return '';
  1515. }
  1516. return implode(' ', $this->_join_sources);
  1517. }
  1518. /**
  1519. * Build the WHERE clause(s)
  1520. */
  1521. protected function _build_where() {
  1522. return $this->_build_conditions('where');
  1523. }
  1524. /**
  1525. * Build the HAVING clause(s)
  1526. */
  1527. protected function _build_having() {
  1528. return $this->_build_conditions('having');
  1529. }
  1530. /**
  1531. * Build GROUP BY
  1532. */
  1533. protected function _build_group_by() {
  1534. if (count($this->_group_by) === 0) {
  1535. return '';
  1536. }
  1537. return "GROUP BY " . implode(', ', $this->_group_by);
  1538. }
  1539. /**
  1540. * Build a WHERE or HAVING clause
  1541. * @param string $type
  1542. * @return string
  1543. */
  1544. protected function _build_conditions($type) {
  1545. $conditions_class_property_name = "_{$type}_conditions";
  1546. // If there are no clauses, return empty string
  1547. if (count($this->$conditions_class_property_name) === 0) {
  1548. return '';
  1549. }
  1550. $conditions = array();
  1551. foreach ($this->$conditions_class_property_name as $condition) {
  1552. $conditions[] = $condition[self::CONDITION_FRAGMENT];
  1553. $this->_values = array_merge($this->_values, $condition[self::CONDITION_VALUES]);
  1554. }
  1555. return strtoupper($type) . " " . implode(' AND ', $conditions);
  1556. }
  1557. /**
  1558. * Build ORDER BY
  1559. */
  1560. protected function _build_order_by() {
  1561. if (count($this->_order_by) === 0) {
  1562. return '';
  1563. }
  1564. return "ORDER BY " . implode(', ', $this->_order_by);
  1565. }
  1566. /**
  1567. * Build LIMIT
  1568. */
  1569. protected function _build_limit() {
  1570. $fragment = '';
  1571. if (!is_null($this->_limit) &&
  1572. self::$_config[$this->_connection_name]['limit_clause_style'] == ORM::LIMIT_STYLE_LIMIT) {
  1573. if (self::get_db($this->_connection_name)->getAttribute(PDO::ATTR_DRIVER_NAME) == 'firebird') {
  1574. $fragment = 'ROWS';
  1575. } else {
  1576. $fragment = 'LIMIT';
  1577. }
  1578. $fragment .= " {$this->_limit}";
  1579. }
  1580. return $fragment;
  1581. }
  1582. /**
  1583. * Build OFFSET
  1584. */
  1585. protected function _build_offset() {
  1586. if (!is_null($this->_offset)) {
  1587. $clause = 'OFFSET';
  1588. if (self::get_db($this->_connection_name)->getAttribute(PDO::ATTR_DRIVER_NAME) == 'firebird') {
  1589. $clause = 'TO';
  1590. }
  1591. return "$clause " . $this->_offset;
  1592. }
  1593. return '';
  1594. }
  1595. /**
  1596. * Wrapper around PHP's join function which
  1597. * only adds the pieces if they are not empty.
  1598. */
  1599. protected function _join_if_not_empty($glue, $pieces) {
  1600. $filtered_pieces = array();
  1601. foreach ($pieces as $piece) {
  1602. if (is_string($piece)) {
  1603. $piece = trim($piece);
  1604. }
  1605. if (!empty($piece)) {
  1606. $filtered_pieces[] = $piece;
  1607. }
  1608. }
  1609. return implode($glue, $filtered_pieces);
  1610. }
  1611. /**
  1612. * Quote a string that is used as an identifier
  1613. * (table names, column names etc). This method can
  1614. * also deal with dot-separated identifiers eg table.column
  1615. */
  1616. protected function _quote_one_identifier($identifier) {
  1617. $parts = explode('.', $identifier);
  1618. $parts = array_map(array($this, '_quote_identifier_part'), $parts);
  1619. return implode('.', $parts);
  1620. }
  1621. /**
  1622. * Quote a string that is used as an identifier
  1623. * (table names, column names etc) or an array containing
  1624. * multiple identifiers. This method can also deal with
  1625. * dot-separated identifiers eg table.column
  1626. */
  1627. protected function _quote_identifier($identifier) {
  1628. if (is_array($identifier)) {
  1629. $result = array_map(array($this, '_quote_one_identifier'), $identifier);
  1630. return implode(', ', $result);
  1631. } else {
  1632. return $this->_quote_one_identifier($identifier);
  1633. }
  1634. }
  1635. /**
  1636. * This method performs the actual quoting of a single
  1637. * part of an identifier, using the identifier quote
  1638. * character specified in the config (or autodetected).
  1639. */
  1640. protected function _quote_identifier_part($part) {
  1641. if ($part === '*') {
  1642. return $part;
  1643. }
  1644. $quote_character = self::$_config[$this->_connection_name]['identifier_quote_character'];
  1645. // double up any identifier quotes to escape them
  1646. return $quote_character .
  1647. str_replace($quote_character,
  1648. $quote_character . $quote_character,
  1649. $part
  1650. ) . $quote_character;
  1651. }
  1652. /**
  1653. * Create a cache key for the given query and parameters.
  1654. */
  1655. protected static function _create_cache_key($query, $parameters, $table_name = null, $connection_name = self::DEFAULT_CONNECTION) {
  1656. if(isset(self::$_config[$connection_name]['create_cache_key']) and is_callable(self::$_config[$connection_name]['create_cache_key'])){
  1657. return call_user_func_array(self::$_config[$connection_name]['create_cache_key'], array($query, $parameters, $table_name, $connection_name));
  1658. }
  1659. $parameter_string = implode(',', $parameters);
  1660. $key = $query . ':' . $parameter_string;
  1661. return sha1($key);
  1662. }
  1663. /**
  1664. * Check the query cache for the given cache key. If a value
  1665. * is cached for the key, return the value. Otherwise, return false.
  1666. */
  1667. protected static function _check_query_cache($cache_key, $table_name = null, $connection_name = self::DEFAULT_CONNECTION) {
  1668. if(isset(self::$_config[$connection_name]['check_query_cache']) and is_callable(self::$_config[$connection_name]['check_query_cache'])){
  1669. return call_user_func_array(self::$_config[$connection_name]['check_query_cache'], array($cache_key, $table_name, $connection_name));
  1670. } elseif (isset(self::$_query_cache[$connection_name][$cache_key])) {
  1671. return self::$_query_cache[$connection_name][$cache_key];
  1672. }
  1673. return false;
  1674. }
  1675. /**
  1676. * Clear the query cache
  1677. */
  1678. public static function clear_cache($table_name = null, $connection_name = self::DEFAULT_CONNECTION) {
  1679. self::$_query_cache = array();
  1680. if(isset(self::$_config[$connection_name]['clear_cache']) and is_callable(self::$_config[$connection_name]['clear_cache'])){
  1681. return call_user_func_array(self::$_config[$connection_name]['clear_cache'], array($table_name, $connection_name));
  1682. }
  1683. }
  1684. /**
  1685. * Add the given value to the query cache.
  1686. */
  1687. protected static function _cache_query_result($cache_key, $value, $table_name = null, $connection_name = self::DEFAULT_CONNECTION) {
  1688. if(isset(self::$_config[$connection_name]['cache_query_result']) and is_callable(self::$_config[$connection_name]['cache_query_result'])){
  1689. return call_user_func_array(self::$_config[$connection_name]['cache_query_result'], array($cache_key, $value, $table_name, $connection_name));
  1690. } elseif (!isset(self::$_query_cache[$connection_name])) {
  1691. self::$_query_cache[$connection_name] = array();
  1692. }
  1693. self::$_query_cache[$connection_name][$cache_key] = $value;
  1694. }
  1695. /**
  1696. * Execute the SELECT query that has been built up by chaining methods
  1697. * on this class. Return an array of rows as associative arrays.
  1698. */
  1699. protected function _run() {
  1700. $query = $this->_build_select();
  1701. $caching_enabled = self::$_config[$this->_connection_name]['caching'];
  1702. if ($caching_enabled) {
  1703. $cache_key = self::_create_cache_key($query, $this->_values, $this->_table_name, $this->_connection_name);
  1704. $cached_result = self::_check_query_cache($cache_key, $this->_table_name, $this->_connection_name);
  1705. if ($cached_result !== false) {
  1706. $this->_reset_idiorm_state();
  1707. return $cached_result;
  1708. }
  1709. }
  1710. self::_execute($query, $this->_values, $this->_connection_name);
  1711. $statement = self::get_last_statement();
  1712. $rows = array();
  1713. while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
  1714. $rows[] = $row;
  1715. }
  1716. if ($caching_enabled) {
  1717. self::_cache_query_result($cache_key, $rows, $this->_table_name, $this->_connection_name);
  1718. }
  1719. $this->_reset_idiorm_state();
  1720. return $rows;
  1721. }
  1722. /**
  1723. * Reset the Idiorm instance state
  1724. */
  1725. private function _reset_idiorm_state() {
  1726. $this->_values = array();
  1727. $this->_result_columns = array('*');
  1728. $this->_using_default_result_columns = true;
  1729. }
  1730. /**
  1731. * Return the raw data wrapped by this ORM
  1732. * instance as an associative array. Column
  1733. * names may optionally be supplied as arguments,
  1734. * if so, only those keys will be returned.
  1735. */
  1736. public function as_array() {
  1737. if (func_num_args() === 0) {
  1738. return $this->_data;
  1739. }
  1740. $args = func_get_args();
  1741. return array_intersect_key($this->_data, array_flip($args));
  1742. }
  1743. /**
  1744. * Return the value of a property of this object (database row)
  1745. * or null if not present.
  1746. *
  1747. * If a column-names array is passed, it will return a associative array
  1748. * with the value of each column or null if it is not present.
  1749. */
  1750. public function get($key) {
  1751. if (is_array($key)) {
  1752. $result = array();
  1753. foreach($key as $column) {
  1754. $result[$column] = isset($this->_data[$column]) ? $this->_data[$column] : null;
  1755. }
  1756. return $result;
  1757. } else {
  1758. return isset($this->_data[$key]) ? $this->_data[$key] : null;
  1759. }
  1760. }
  1761. /**
  1762. * Return the name of the column in the database table which contains
  1763. * the primary key ID of the row.
  1764. */
  1765. protected function _get_id_column_name() {
  1766. if (!is_null($this->_instance_id_column)) {
  1767. return $this->_instance_id_column;
  1768. }
  1769. if (isset(self::$_config[$this->_connection_name]['id_column_overrides'][$this->_table_name])) {
  1770. return self::$_config[$this->_connection_name]['id_column_overrides'][$this->_table_name];
  1771. }
  1772. return self::$_config[$this->_connection_name]['id_column'];
  1773. }
  1774. /**
  1775. * Get the primary key ID of this object.
  1776. */
  1777. public function id($disallow_null = false) {
  1778. $id = $this->get($this->_get_id_column_name());
  1779. if ($disallow_null) {
  1780. if (is_array($id)) {
  1781. foreach ($id as $id_part) {
  1782. if ($id_part === null) {
  1783. throw new Exception('Primary key ID contains null value(s)');
  1784. }
  1785. }
  1786. } else if ($id === null) {
  1787. throw new Exception('Primary key ID missing from row or is null');
  1788. }
  1789. }
  1790. return $id;
  1791. }
  1792. /**
  1793. * Set a property to a particular value on this object.
  1794. * To set multiple properties at once, pass an associative array
  1795. * as the first parameter and leave out the second parameter.
  1796. * Flags the properties as 'dirty' so they will be saved to the
  1797. * database when save() is called.
  1798. */
  1799. public function set($key, $value = null) {
  1800. return $this->_set_orm_property($key, $value);
  1801. }
  1802. /**
  1803. * Set a property to a particular value on this object.
  1804. * To set multiple properties at once, pass an associative array
  1805. * as the first parameter and leave out the second parameter.
  1806. * Flags the properties as 'dirty' so they will be saved to the
  1807. * database when save() is called.
  1808. * @param string|array $key
  1809. * @param string|null $value
  1810. */
  1811. public function set_expr($key, $value = null) {
  1812. return $this->_set_orm_property($key, $value, true);
  1813. }
  1814. /**
  1815. * Set a property on the ORM object.
  1816. * @param string|array $key
  1817. * @param string|null $value
  1818. * @param bool $raw Whether this value should be treated as raw or not
  1819. */
  1820. protected function _set_orm_property($key, $value = null, $expr = false) {
  1821. if (!is_array($key)) {
  1822. $key = array($key => $value);
  1823. }
  1824. foreach ($key as $field => $value) {
  1825. $this->_data[$field] = $value;
  1826. $this->_dirty_fields[$field] = $value;
  1827. if (false === $expr and isset($this->_expr_fields[$field])) {
  1828. unset($this->_expr_fields[$field]);
  1829. } else if (true === $expr) {
  1830. $this->_expr_fields[$field] = true;
  1831. }
  1832. }
  1833. return $this;
  1834. }
  1835. /**
  1836. * Check whether the given field has been changed since this
  1837. * object was saved.
  1838. */
  1839. public function is_dirty($key) {
  1840. return array_key_exists($key, $this->_dirty_fields);
  1841. }
  1842. /**
  1843. * Check whether the model was the result of a call to create() or not
  1844. * @return bool
  1845. */
  1846. public function is_new() {
  1847. return $this->_is_new;
  1848. }
  1849. /**
  1850. * Save any fields which have been modified on this object
  1851. * to the database.
  1852. */
  1853. public function save() {
  1854. $query = array();
  1855. // remove any expression fields as they are already baked into the query
  1856. $values = array_values(array_diff_key($this->_dirty_fields, $this->_expr_fields));
  1857. if (!$this->_is_new) { // UPDATE
  1858. // If there are no dirty values, do nothing
  1859. if (empty($values) && empty($this->_expr_fields)) {
  1860. return true;
  1861. }
  1862. $query = $this->_build_update();
  1863. $id = $this->id(true);
  1864. if (is_array($id)) {
  1865. $values = array_merge($values, array_values($id));
  1866. } else {
  1867. $values[] = $id;
  1868. }
  1869. } else { // INSERT
  1870. $query = $this->_build_insert();
  1871. }
  1872. $success = self::_execute($query, $values, $this->_connection_name);
  1873. $caching_auto_clear_enabled = self::$_config[$this->_connection_name]['caching_auto_clear'];
  1874. if($caching_auto_clear_enabled){
  1875. self::clear_cache($this->_table_name, $this->_connection_name);
  1876. }
  1877. // If we've just inserted a new record, set the ID of this object
  1878. if ($this->_is_new) {
  1879. $this->_is_new = false;
  1880. if ($this->count_null_id_columns() != 0) {
  1881. $db = self::get_db($this->_connection_name);
  1882. if($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'pgsql') {
  1883. // it may return several columns if a compound primary
  1884. // key is used
  1885. $row = self::get_last_statement()->fetch(PDO::FETCH_ASSOC);
  1886. foreach($row as $key => $value) {
  1887. $this->_data[$key] = $value;
  1888. }
  1889. } else {
  1890. $column = $this->_get_id_column_name();
  1891. // if the primary key is compound, assign the last inserted id
  1892. // to the first column
  1893. if (is_array($column)) {
  1894. $column = reset($column);
  1895. }
  1896. $this->_data[$column] = $db->lastInsertId();
  1897. }
  1898. }
  1899. }
  1900. $this->_dirty_fields = $this->_expr_fields = array();
  1901. return $success;
  1902. }
  1903. /**
  1904. * Add a WHERE clause for every column that belongs to the primary key
  1905. */
  1906. public function _add_id_column_conditions(&$query) {
  1907. $query[] = "WHERE";
  1908. $keys = is_array($this->_get_id_column_name()) ? $this->_get_id_column_name() : array( $this->_get_id_column_name() );
  1909. $first = true;
  1910. foreach($keys as $key) {
  1911. if ($first) {
  1912. $first = false;
  1913. }
  1914. else {
  1915. $query[] = "AND";
  1916. }
  1917. $query[] = $this->_quote_identifier($key);
  1918. $query[] = "= ?";
  1919. }
  1920. }
  1921. /**
  1922. * Build an UPDATE query
  1923. */
  1924. protected function _build_update() {
  1925. $query = array();
  1926. $query[] = "UPDATE {$this->_quote_identifier($this->_table_name)} SET";
  1927. $field_list = array();
  1928. foreach ($this->_dirty_fields as $key => $value) {
  1929. if(!array_key_exists($key, $this->_expr_fields)) {
  1930. $value = '?';
  1931. }
  1932. $field_list[] = "{$this->_quote_identifier($key)} = $value";
  1933. }
  1934. $query[] = implode(', ', $field_list);
  1935. $this->_add_id_column_conditions($query);
  1936. return implode(' ', $query);
  1937. }
  1938. /**
  1939. * Build an INSERT query
  1940. */
  1941. protected function _build_insert() {
  1942. $query[] = "INSERT INTO";
  1943. $query[] = $this->_quote_identifier($this->_table_name);
  1944. $field_list = array_map(array($this, '_quote_identifier'), array_keys($this->_dirty_fields));
  1945. $query[] = "(" . implode(', ', $field_list) . ")";
  1946. $query[] = "VALUES";
  1947. $placeholders = $this->_create_placeholders($this->_dirty_fields);
  1948. $query[] = "({$placeholders})";
  1949. if (self::get_db($this->_connection_name)->getAttribute(PDO::ATTR_DRIVER_NAME) == 'pgsql') {
  1950. $query[] = 'RETURNING ' . $this->_quote_identifier($this->_get_id_column_name());
  1951. }
  1952. return implode(' ', $query);
  1953. }
  1954. /**
  1955. * Delete this record from the database
  1956. */
  1957. public function delete() {
  1958. $query = array(
  1959. "DELETE FROM",
  1960. $this->_quote_identifier($this->_table_name)
  1961. );
  1962. $this->_add_id_column_conditions($query);
  1963. return self::_execute(implode(' ', $query), is_array($this->id(true)) ? array_values($this->id(true)) : array($this->id(true)), $this->_connection_name);
  1964. }
  1965. /**
  1966. * Delete many records from the database
  1967. */
  1968. public function delete_many() {
  1969. // Build and return the full DELETE statement by concatenating
  1970. // the results of calling each separate builder method.
  1971. $query = $this->_join_if_not_empty(" ", array(
  1972. "DELETE FROM",
  1973. $this->_quote_identifier($this->_table_name),
  1974. $this->_build_where(),
  1975. ));
  1976. return self::_execute($query, $this->_values, $this->_connection_name);
  1977. }
  1978. // --------------------- //
  1979. // --- ArrayAccess --- //
  1980. // --------------------- //
  1981. public function offsetExists($key) {
  1982. return array_key_exists($key, $this->_data);
  1983. }
  1984. public function offsetGet($key) {
  1985. return $this->get($key);
  1986. }
  1987. public function offsetSet($key, $value) {
  1988. if(is_null($key)) {
  1989. throw new InvalidArgumentException('You must specify a key/array index.');
  1990. }
  1991. $this->set($key, $value);
  1992. }
  1993. public function offsetUnset($key) {
  1994. unset($this->_data[$key]);
  1995. unset($this->_dirty_fields[$key]);
  1996. }
  1997. // --------------------- //
  1998. // --- MAGIC METHODS --- //
  1999. // --------------------- //
  2000. public function __get($key) {
  2001. return $this->offsetGet($key);
  2002. }
  2003. public function __set($key, $value) {
  2004. $this->offsetSet($key, $value);
  2005. }
  2006. public function __unset($key) {
  2007. $this->offsetUnset($key);
  2008. }
  2009. public function __isset($key) {
  2010. return $this->offsetExists($key);
  2011. }
  2012. /**
  2013. * Magic method to capture calls to undefined class methods.
  2014. * In this case we are attempting to convert camel case formatted
  2015. * methods into underscore formatted methods.
  2016. *
  2017. * This allows us to call ORM methods using camel case and remain
  2018. * backwards compatible.
  2019. *
  2020. * @param string $name
  2021. * @param array $arguments
  2022. * @return ORM
  2023. */
  2024. public function __call($name, $arguments)
  2025. {
  2026. $method = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $name));
  2027. if (method_exists($this, $method)) {
  2028. return call_user_func_array(array($this, $method), $arguments);
  2029. } else {
  2030. throw new IdiormMethodMissingException("Method $name() does not exist in class " . get_class($this));
  2031. }
  2032. }
  2033. /**
  2034. * Magic method to capture calls to undefined static class methods.
  2035. * In this case we are attempting to convert camel case formatted
  2036. * methods into underscore formatted methods.
  2037. *
  2038. * This allows us to call ORM methods using camel case and remain
  2039. * backwards compatible.
  2040. *
  2041. * @param string $name
  2042. * @param array $arguments
  2043. * @return ORM
  2044. */
  2045. public static function __callStatic($name, $arguments)
  2046. {
  2047. $method = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $name));
  2048. return call_user_func_array(array('MailPoetVendor\Idiorm\ORM', $method), $arguments);
  2049. }
  2050. }
  2051. /**
  2052. * A class to handle str_replace operations that involve quoted strings
  2053. * @example IdiormString::str_replace_outside_quotes('?', '%s', 'columnA = "Hello?" AND columnB = ?');
  2054. * @example IdiormString::value('columnA = "Hello?" AND columnB = ?')->replace_outside_quotes('?', '%s');
  2055. * @author Jeff Roberson <ridgerunner@fluxbb.org>
  2056. * @author Simon Holywell <treffynnon@php.net>
  2057. * @link http://stackoverflow.com/a/13370709/461813 StackOverflow answer
  2058. */
  2059. class IdiormString {
  2060. protected $subject;
  2061. protected $search;
  2062. protected $replace;
  2063. /**
  2064. * Get an easy to use instance of the class
  2065. * @param string $subject
  2066. * @return \self
  2067. */
  2068. public static function value($subject) {
  2069. return new self($subject);
  2070. }
  2071. /**
  2072. * Shortcut method: Replace all occurrences of the search string with the replacement
  2073. * string where they appear outside quotes.
  2074. * @param string $search
  2075. * @param string $replace
  2076. * @param string $subject
  2077. * @return string
  2078. */
  2079. public static function str_replace_outside_quotes($search, $replace, $subject) {
  2080. return self::value($subject)->replace_outside_quotes($search, $replace);
  2081. }
  2082. /**
  2083. * Set the base string object
  2084. * @param string $subject
  2085. */
  2086. public function __construct($subject) {
  2087. $this->subject = (string) $subject;
  2088. }
  2089. /**
  2090. * Replace all occurrences of the search string with the replacement
  2091. * string where they appear outside quotes
  2092. * @param string $search
  2093. * @param string $replace
  2094. * @return string
  2095. */
  2096. public function replace_outside_quotes($search, $replace) {
  2097. $this->search = $search;
  2098. $this->replace = $replace;
  2099. return $this->_str_replace_outside_quotes();
  2100. }
  2101. /**
  2102. * Validate an input string and perform a replace on all ocurrences
  2103. * of $this->search with $this->replace
  2104. * @author Jeff Roberson <ridgerunner@fluxbb.org>
  2105. * @link http://stackoverflow.com/a/13370709/461813 StackOverflow answer
  2106. * @return string
  2107. */
  2108. protected function _str_replace_outside_quotes(){
  2109. $re_valid = '/
  2110. # Validate string having embedded quoted substrings.
  2111. ^ # Anchor to start of string.
  2112. (?: # Zero or more string chunks.
  2113. "[^"\\\\]*(?:\\\\.[^"\\\\]*)*" # Either a double quoted chunk,
  2114. | \'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\' # or a single quoted chunk,
  2115. | [^\'"\\\\]+ # or an unquoted chunk (no escapes).
  2116. )* # Zero or more string chunks.
  2117. \z # Anchor to end of string.
  2118. /sx';
  2119. if (!preg_match($re_valid, $this->subject)) {
  2120. throw new IdiormStringException("Subject string is not valid in the replace_outside_quotes context.");
  2121. }
  2122. $re_parse = '/
  2123. # Match one chunk of a valid string having embedded quoted substrings.
  2124. ( # Either $1: Quoted chunk.
  2125. "[^"\\\\]*(?:\\\\.[^"\\\\]*)*" # Either a double quoted chunk,
  2126. | \'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\' # or a single quoted chunk.
  2127. ) # End $1: Quoted chunk.
  2128. | ([^\'"\\\\]+) # or $2: an unquoted chunk (no escapes).
  2129. /sx';
  2130. return preg_replace_callback($re_parse, array($this, '_str_replace_outside_quotes_cb'), $this->subject);
  2131. }
  2132. /**
  2133. * Process each matching chunk from preg_replace_callback replacing
  2134. * each occurrence of $this->search with $this->replace
  2135. * @author Jeff Roberson <ridgerunner@fluxbb.org>
  2136. * @link http://stackoverflow.com/a/13370709/461813 StackOverflow answer
  2137. * @param array $matches
  2138. * @return string
  2139. */
  2140. protected function _str_replace_outside_quotes_cb($matches) {
  2141. // Return quoted string chunks (in group $1) unaltered.
  2142. if ($matches[1]) return $matches[1];
  2143. // Process only unquoted chunks (in group $2).
  2144. return preg_replace('/'. preg_quote($this->search, '/') .'/',
  2145. $this->replace, $matches[2]);
  2146. }
  2147. }
  2148. /**
  2149. * A result set class for working with collections of model instances
  2150. * @author Simon Holywell <treffynnon@php.net>
  2151. * @method null setResults(array $results)
  2152. * @method array getResults()
  2153. */
  2154. class IdiormResultSet implements Countable, IteratorAggregate, ArrayAccess, Serializable {
  2155. /**
  2156. * The current result set as an array
  2157. * @var array
  2158. */
  2159. protected $_results = array();
  2160. /**
  2161. * Optionally set the contents of the result set by passing in array
  2162. * @param array $results
  2163. */
  2164. public function __construct(array $results = array()) {
  2165. $this->set_results($results);
  2166. }
  2167. /**
  2168. * Set the contents of the result set by passing in array
  2169. * @param array $results
  2170. */
  2171. public function set_results(array $results) {
  2172. $this->_results = $results;
  2173. }
  2174. /**
  2175. * Get the current result set as an array
  2176. * @return array
  2177. */
  2178. public function get_results() {
  2179. return $this->_results;
  2180. }
  2181. /**
  2182. * Get the current result set as an array
  2183. * @return array
  2184. */
  2185. public function as_array() {
  2186. return $this->get_results();
  2187. }
  2188. /**
  2189. * Get the number of records in the result set
  2190. * @return int
  2191. */
  2192. public function count() {
  2193. return count($this->_results);
  2194. }
  2195. /**
  2196. * Get an iterator for this object. In this case it supports foreaching
  2197. * over the result set.
  2198. * @return \ArrayIterator
  2199. */
  2200. public function getIterator() {
  2201. return new ArrayIterator($this->_results);
  2202. }
  2203. /**
  2204. * ArrayAccess
  2205. * @param int|string $offset
  2206. * @return bool
  2207. */
  2208. public function offsetExists($offset) {
  2209. return isset($this->_results[$offset]);
  2210. }
  2211. /**
  2212. * ArrayAccess
  2213. * @param int|string $offset
  2214. * @return mixed
  2215. */
  2216. public function offsetGet($offset) {
  2217. return $this->_results[$offset];
  2218. }
  2219. /**
  2220. * ArrayAccess
  2221. * @param int|string $offset
  2222. * @param mixed $value
  2223. */
  2224. public function offsetSet($offset, $value) {
  2225. $this->_results[$offset] = $value;
  2226. }
  2227. /**
  2228. * ArrayAccess
  2229. * @param int|string $offset
  2230. */
  2231. public function offsetUnset($offset) {
  2232. unset($this->_results[$offset]);
  2233. }
  2234. /**
  2235. * Serializable
  2236. * @return string
  2237. */
  2238. public function serialize() {
  2239. return serialize($this->_results);
  2240. }
  2241. /**
  2242. * Serializable
  2243. * @param string $serialized
  2244. * @return array
  2245. */
  2246. public function unserialize($serialized) {
  2247. return unserialize($serialized);
  2248. }
  2249. /**
  2250. * Call a method on all models in a result set. This allows for method
  2251. * chaining such as setting a property on all models in a result set or
  2252. * any other batch operation across models.
  2253. * @example ORM::for_table('Widget')->find_many()->set('field', 'value')->save();
  2254. * @param string $method
  2255. * @param array $params
  2256. * @return IdiormResultSet
  2257. */
  2258. public function __call($method, $params = array()) {
  2259. foreach($this->_results as $model) {
  2260. if (method_exists($model, $method)) {
  2261. call_user_func_array(array($model, $method), $params);
  2262. } else {
  2263. throw new IdiormMethodMissingException("Method $method() does not exist in class " . get_class($this));
  2264. }
  2265. }
  2266. return $this;
  2267. }
  2268. }
  2269. /**
  2270. * A placeholder for exceptions eminating from the IdiormString class
  2271. */
  2272. class IdiormStringException extends Exception {}
  2273. class IdiormMethodMissingException extends Exception {}