Abstract.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Db
  17. * @subpackage Adapter
  18. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. /**
  23. * @see Zend_Db
  24. */
  25. require_once 'Zend/Db.php';
  26. /**
  27. * @see Zend_Db_Select
  28. */
  29. require_once 'Zend/Db/Select.php';
  30. /**
  31. * Class for connecting to SQL databases and performing common operations.
  32. *
  33. * @category Zend
  34. * @package Zend_Db
  35. * @subpackage Adapter
  36. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  37. * @license http://framework.zend.com/license/new-bsd New BSD License
  38. */
  39. abstract class Zend_Db_Adapter_Abstract
  40. {
  41. /**
  42. * User-provided configuration
  43. *
  44. * @var array
  45. */
  46. protected $_config = array();
  47. /**
  48. * Fetch mode
  49. *
  50. * @var integer
  51. */
  52. protected $_fetchMode = Zend_Db::FETCH_ASSOC;
  53. /**
  54. * Query profiler object, of type Zend_Db_Profiler
  55. * or a subclass of that.
  56. *
  57. * @var Zend_Db_Profiler
  58. */
  59. protected $_profiler;
  60. /**
  61. * Default class name for a DB statement.
  62. *
  63. * @var string
  64. */
  65. protected $_defaultStmtClass = 'Zend_Db_Statement';
  66. /**
  67. * Default class name for the profiler object.
  68. *
  69. * @var string
  70. */
  71. protected $_defaultProfilerClass = 'Zend_Db_Profiler';
  72. /**
  73. * Database connection
  74. *
  75. * @var object|resource|null
  76. */
  77. protected $_connection = null;
  78. /**
  79. * Specifies the case of column names retrieved in queries
  80. * Options
  81. * Zend_Db::CASE_NATURAL (default)
  82. * Zend_Db::CASE_LOWER
  83. * Zend_Db::CASE_UPPER
  84. *
  85. * @var integer
  86. */
  87. protected $_caseFolding = Zend_Db::CASE_NATURAL;
  88. /**
  89. * Specifies whether the adapter automatically quotes identifiers.
  90. * If true, most SQL generated by Zend_Db classes applies
  91. * identifier quoting automatically.
  92. * If false, developer must quote identifiers themselves
  93. * by calling quoteIdentifier().
  94. *
  95. * @var bool
  96. */
  97. protected $_autoQuoteIdentifiers = true;
  98. /**
  99. * Keys are UPPERCASE SQL datatypes or the constants
  100. * Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
  101. *
  102. * Values are:
  103. * 0 = 32-bit integer
  104. * 1 = 64-bit integer
  105. * 2 = float or decimal
  106. *
  107. * @var array Associative array of datatypes to values 0, 1, or 2.
  108. */
  109. protected $_numericDataTypes = array(
  110. Zend_Db::INT_TYPE => Zend_Db::INT_TYPE,
  111. Zend_Db::BIGINT_TYPE => Zend_Db::BIGINT_TYPE,
  112. Zend_Db::FLOAT_TYPE => Zend_Db::FLOAT_TYPE
  113. );
  114. /** Weither or not that object can get serialized
  115. *
  116. * @var bool
  117. */
  118. protected $_allowSerialization = true;
  119. /**
  120. * Weither or not the database should be reconnected
  121. * to that adapter when waking up
  122. *
  123. * @var bool
  124. */
  125. protected $_autoReconnectOnUnserialize = false;
  126. /**
  127. * Constructor.
  128. *
  129. * $config is an array of key/value pairs or an instance of Zend_Config
  130. * containing configuration options. These options are common to most adapters:
  131. *
  132. * dbname => (string) The name of the database to user
  133. * username => (string) Connect to the database as this username.
  134. * password => (string) Password associated with the username.
  135. * host => (string) What host to connect to, defaults to localhost
  136. *
  137. * Some options are used on a case-by-case basis by adapters:
  138. *
  139. * port => (string) The port of the database
  140. * persistent => (boolean) Whether to use a persistent connection or not, defaults to false
  141. * protocol => (string) The network protocol, defaults to TCPIP
  142. * caseFolding => (int) style of case-alteration used for identifiers
  143. *
  144. * @param array|Zend_Config $config An array or instance of Zend_Config having configuration data
  145. * @throws Zend_Db_Adapter_Exception
  146. */
  147. public function __construct($config)
  148. {
  149. /*
  150. * Verify that adapter parameters are in an array.
  151. */
  152. if (!is_array($config)) {
  153. /*
  154. * Convert Zend_Config argument to a plain array.
  155. */
  156. if ($config instanceof Zend_Config) {
  157. $config = $config->toArray();
  158. } else {
  159. /**
  160. * @see Zend_Db_Exception
  161. */
  162. require_once 'Zend/Db/Exception.php';
  163. throw new Zend_Db_Exception('Adapter parameters must be in an array or a Zend_Config object');
  164. }
  165. }
  166. $this->_checkRequiredOptions($config);
  167. $options = array(
  168. Zend_Db::CASE_FOLDING => $this->_caseFolding,
  169. Zend_Db::AUTO_QUOTE_IDENTIFIERS => $this->_autoQuoteIdentifiers
  170. );
  171. $driverOptions = array();
  172. /*
  173. * normalize the config and merge it with the defaults
  174. */
  175. if (array_key_exists('options', $config)) {
  176. // can't use array_merge() because keys might be integers
  177. foreach ((array) $config['options'] as $key => $value) {
  178. $options[$key] = $value;
  179. }
  180. }
  181. if (array_key_exists('driver_options', $config)) {
  182. if (!empty($config['driver_options'])) {
  183. // can't use array_merge() because keys might be integers
  184. foreach ((array) $config['driver_options'] as $key => $value) {
  185. $driverOptions[$key] = $value;
  186. }
  187. }
  188. }
  189. if (!isset($config['charset'])) {
  190. $config['charset'] = null;
  191. }
  192. if (!isset($config['persistent'])) {
  193. $config['persistent'] = false;
  194. }
  195. $this->_config = array_merge($this->_config, $config);
  196. $this->_config['options'] = $options;
  197. $this->_config['driver_options'] = $driverOptions;
  198. // obtain the case setting, if there is one
  199. if (array_key_exists(Zend_Db::CASE_FOLDING, $options)) {
  200. $case = (int) $options[Zend_Db::CASE_FOLDING];
  201. switch ($case) {
  202. case Zend_Db::CASE_LOWER:
  203. case Zend_Db::CASE_UPPER:
  204. case Zend_Db::CASE_NATURAL:
  205. $this->_caseFolding = $case;
  206. break;
  207. default:
  208. /** @see Zend_Db_Adapter_Exception */
  209. require_once 'Zend/Db/Adapter/Exception.php';
  210. throw new Zend_Db_Adapter_Exception('Case must be one of the following constants: '
  211. . 'Zend_Db::CASE_NATURAL, Zend_Db::CASE_LOWER, Zend_Db::CASE_UPPER');
  212. }
  213. }
  214. // obtain quoting property if there is one
  215. if (array_key_exists(Zend_Db::AUTO_QUOTE_IDENTIFIERS, $options)) {
  216. $this->_autoQuoteIdentifiers = (bool) $options[Zend_Db::AUTO_QUOTE_IDENTIFIERS];
  217. }
  218. // obtain allow serialization property if there is one
  219. if (array_key_exists(Zend_Db::ALLOW_SERIALIZATION, $options)) {
  220. $this->_allowSerialization = (bool) $options[Zend_Db::ALLOW_SERIALIZATION];
  221. }
  222. // obtain auto reconnect on unserialize property if there is one
  223. if (array_key_exists(Zend_Db::AUTO_RECONNECT_ON_UNSERIALIZE, $options)) {
  224. $this->_autoReconnectOnUnserialize = (bool) $options[Zend_Db::AUTO_RECONNECT_ON_UNSERIALIZE];
  225. }
  226. // create a profiler object
  227. $profiler = false;
  228. if (array_key_exists(Zend_Db::PROFILER, $this->_config)) {
  229. $profiler = $this->_config[Zend_Db::PROFILER];
  230. unset($this->_config[Zend_Db::PROFILER]);
  231. }
  232. $this->setProfiler($profiler);
  233. }
  234. /**
  235. * Check for config options that are mandatory.
  236. * Throw exceptions if any are missing.
  237. *
  238. * @param array $config
  239. * @throws Zend_Db_Adapter_Exception
  240. */
  241. protected function _checkRequiredOptions(array $config)
  242. {
  243. // we need at least a dbname
  244. if (! array_key_exists('dbname', $config)) {
  245. /** @see Zend_Db_Adapter_Exception */
  246. require_once 'Zend/Db/Adapter/Exception.php';
  247. throw new Zend_Db_Adapter_Exception("Configuration array must have a key for 'dbname' that names the database instance");
  248. }
  249. if (! array_key_exists('password', $config)) {
  250. /**
  251. * @see Zend_Db_Adapter_Exception
  252. */
  253. require_once 'Zend/Db/Adapter/Exception.php';
  254. throw new Zend_Db_Adapter_Exception("Configuration array must have a key for 'password' for login credentials");
  255. }
  256. if (! array_key_exists('username', $config)) {
  257. /**
  258. * @see Zend_Db_Adapter_Exception
  259. */
  260. require_once 'Zend/Db/Adapter/Exception.php';
  261. throw new Zend_Db_Adapter_Exception("Configuration array must have a key for 'username' for login credentials");
  262. }
  263. }
  264. /**
  265. * Returns the underlying database connection object or resource.
  266. * If not presently connected, this initiates the connection.
  267. *
  268. * @return object|resource|null
  269. */
  270. public function getConnection()
  271. {
  272. $this->_connect();
  273. return $this->_connection;
  274. }
  275. /**
  276. * Returns the configuration variables in this adapter.
  277. *
  278. * @return array
  279. */
  280. public function getConfig()
  281. {
  282. return $this->_config;
  283. }
  284. /**
  285. * Set the adapter's profiler object.
  286. *
  287. * The argument may be a boolean, an associative array, an instance of
  288. * Zend_Db_Profiler, or an instance of Zend_Config.
  289. *
  290. * A boolean argument sets the profiler to enabled if true, or disabled if
  291. * false. The profiler class is the adapter's default profiler class,
  292. * Zend_Db_Profiler.
  293. *
  294. * An instance of Zend_Db_Profiler sets the adapter's instance to that
  295. * object. The profiler is enabled and disabled separately.
  296. *
  297. * An associative array argument may contain any of the keys 'enabled',
  298. * 'class', and 'instance'. The 'enabled' and 'instance' keys correspond to the
  299. * boolean and object types documented above. The 'class' key is used to name a
  300. * class to use for a custom profiler. The class must be Zend_Db_Profiler or a
  301. * subclass. The class is instantiated with no constructor arguments. The 'class'
  302. * option is ignored when the 'instance' option is supplied.
  303. *
  304. * An object of type Zend_Config may contain the properties 'enabled', 'class', and
  305. * 'instance', just as if an associative array had been passed instead.
  306. *
  307. * @param Zend_Db_Profiler|Zend_Config|array|boolean $profiler
  308. * @return Zend_Db_Adapter_Abstract Provides a fluent interface
  309. * @throws Zend_Db_Profiler_Exception if the object instance or class specified
  310. * is not Zend_Db_Profiler or an extension of that class.
  311. */
  312. public function setProfiler($profiler)
  313. {
  314. $enabled = null;
  315. $profilerClass = $this->_defaultProfilerClass;
  316. $profilerInstance = null;
  317. if ($profilerIsObject = is_object($profiler)) {
  318. if ($profiler instanceof Zend_Db_Profiler) {
  319. $profilerInstance = $profiler;
  320. } else if ($profiler instanceof Zend_Config) {
  321. $profiler = $profiler->toArray();
  322. } else {
  323. /**
  324. * @see Zend_Db_Profiler_Exception
  325. */
  326. require_once 'Zend/Db/Profiler/Exception.php';
  327. throw new Zend_Db_Profiler_Exception('Profiler argument must be an instance of either Zend_Db_Profiler'
  328. . ' or Zend_Config when provided as an object');
  329. }
  330. }
  331. if (is_array($profiler)) {
  332. if (isset($profiler['enabled'])) {
  333. $enabled = (bool) $profiler['enabled'];
  334. }
  335. if (isset($profiler['class'])) {
  336. $profilerClass = $profiler['class'];
  337. }
  338. if (isset($profiler['instance'])) {
  339. $profilerInstance = $profiler['instance'];
  340. }
  341. } else if (!$profilerIsObject) {
  342. $enabled = (bool) $profiler;
  343. }
  344. if ($profilerInstance === null) {
  345. if (!class_exists($profilerClass)) {
  346. require_once 'Zend/Loader.php';
  347. Zend_Loader::loadClass($profilerClass);
  348. }
  349. $profilerInstance = new $profilerClass();
  350. }
  351. if (!$profilerInstance instanceof Zend_Db_Profiler) {
  352. /** @see Zend_Db_Profiler_Exception */
  353. require_once 'Zend/Db/Profiler/Exception.php';
  354. throw new Zend_Db_Profiler_Exception('Class ' . get_class($profilerInstance) . ' does not extend '
  355. . 'Zend_Db_Profiler');
  356. }
  357. if (null !== $enabled) {
  358. $profilerInstance->setEnabled($enabled);
  359. }
  360. $this->_profiler = $profilerInstance;
  361. return $this;
  362. }
  363. /**
  364. * Returns the profiler for this adapter.
  365. *
  366. * @return Zend_Db_Profiler
  367. */
  368. public function getProfiler()
  369. {
  370. return $this->_profiler;
  371. }
  372. /**
  373. * Get the default statement class.
  374. *
  375. * @return string
  376. */
  377. public function getStatementClass()
  378. {
  379. return $this->_defaultStmtClass;
  380. }
  381. /**
  382. * Set the default statement class.
  383. *
  384. * @return Zend_Db_Adapter_Abstract Fluent interface
  385. */
  386. public function setStatementClass($class)
  387. {
  388. $this->_defaultStmtClass = $class;
  389. return $this;
  390. }
  391. /**
  392. * Prepares and executes an SQL statement with bound data.
  393. *
  394. * @param mixed $sql The SQL statement with placeholders.
  395. * May be a string or Zend_Db_Select.
  396. * @param mixed $bind An array of data to bind to the placeholders.
  397. * @return Zend_Db_Statement_Interface
  398. */
  399. public function query($sql, $bind = array())
  400. {
  401. // connect to the database if needed
  402. $this->_connect();
  403. // is the $sql a Zend_Db_Select object?
  404. if ($sql instanceof Zend_Db_Select) {
  405. if (empty($bind)) {
  406. $bind = $sql->getBind();
  407. }
  408. $sql = $sql->assemble();
  409. }
  410. // make sure $bind to an array;
  411. // don't use (array) typecasting because
  412. // because $bind may be a Zend_Db_Expr object
  413. if (!is_array($bind)) {
  414. $bind = array($bind);
  415. }
  416. // prepare and execute the statement with profiling
  417. $stmt = $this->prepare($sql);
  418. $stmt->execute($bind);
  419. // return the results embedded in the prepared statement object
  420. $stmt->setFetchMode($this->_fetchMode);
  421. return $stmt;
  422. }
  423. /**
  424. * Leave autocommit mode and begin a transaction.
  425. *
  426. * @return Zend_Db_Adapter_Abstract
  427. */
  428. public function beginTransaction()
  429. {
  430. $this->_connect();
  431. $q = $this->_profiler->queryStart('begin', Zend_Db_Profiler::TRANSACTION);
  432. $this->_beginTransaction();
  433. $this->_profiler->queryEnd($q);
  434. return $this;
  435. }
  436. /**
  437. * Commit a transaction and return to autocommit mode.
  438. *
  439. * @return Zend_Db_Adapter_Abstract
  440. */
  441. public function commit()
  442. {
  443. $this->_connect();
  444. $q = $this->_profiler->queryStart('commit', Zend_Db_Profiler::TRANSACTION);
  445. $this->_commit();
  446. $this->_profiler->queryEnd($q);
  447. return $this;
  448. }
  449. /**
  450. * Roll back a transaction and return to autocommit mode.
  451. *
  452. * @return Zend_Db_Adapter_Abstract
  453. */
  454. public function rollBack()
  455. {
  456. $this->_connect();
  457. $q = $this->_profiler->queryStart('rollback', Zend_Db_Profiler::TRANSACTION);
  458. $this->_rollBack();
  459. $this->_profiler->queryEnd($q);
  460. return $this;
  461. }
  462. /**
  463. * Inserts a table row with specified data.
  464. *
  465. * @param mixed $table The table to insert data into.
  466. * @param array $bind Column-value pairs.
  467. * @return int The number of affected rows.
  468. */
  469. public function insert($table, array $bind)
  470. {
  471. // extract and quote col names from the array keys
  472. $cols = array();
  473. $vals = array();
  474. foreach ($bind as $col => $val) {
  475. $cols[] = $this->quoteIdentifier($col, true);
  476. if ($val instanceof Zend_Db_Expr) {
  477. $vals[] = $val->__toString();
  478. unset($bind[$col]);
  479. } else {
  480. $vals[] = '?';
  481. }
  482. }
  483. // build the statement
  484. $sql = "INSERT INTO "
  485. . $this->quoteIdentifier($table, true)
  486. . ' (' . implode(', ', $cols) . ') '
  487. . 'VALUES (' . implode(', ', $vals) . ')';
  488. // execute the statement and return the number of affected rows
  489. $stmt = $this->query($sql, array_values($bind));
  490. $result = $stmt->rowCount();
  491. return $result;
  492. }
  493. /**
  494. * Updates table rows with specified data based on a WHERE clause.
  495. *
  496. * @param mixed $table The table to update.
  497. * @param array $bind Column-value pairs.
  498. * @param mixed $where UPDATE WHERE clause(s).
  499. * @return int The number of affected rows.
  500. */
  501. public function update($table, array $bind, $where = '')
  502. {
  503. /**
  504. * Build "col = ?" pairs for the statement,
  505. * except for Zend_Db_Expr which is treated literally.
  506. */
  507. $set = array();
  508. $i = 0;
  509. foreach ($bind as $col => $val) {
  510. if ($val instanceof Zend_Db_Expr) {
  511. $val = $val->__toString();
  512. unset($bind[$col]);
  513. } else {
  514. if ($this->supportsParameters('positional')) {
  515. $val = '?';
  516. } else {
  517. if ($this->supportsParameters('named')) {
  518. unset($bind[$col]);
  519. $bind[':'.$col.$i] = $val;
  520. $val = ':'.$col.$i;
  521. $i++;
  522. } else {
  523. /** @see Zend_Db_Adapter_Exception */
  524. require_once 'Zend/Db/Adapter/Exception.php';
  525. throw new Zend_Db_Adapter_Exception(get_class($this) ." doesn't support positional or named binding");
  526. }
  527. }
  528. }
  529. $set[] = $this->quoteIdentifier($col, true) . ' = ' . $val;
  530. }
  531. $where = $this->_whereExpr($where);
  532. /**
  533. * Build the UPDATE statement
  534. */
  535. $sql = "UPDATE "
  536. . $this->quoteIdentifier($table, true)
  537. . ' SET ' . implode(', ', $set)
  538. . (($where) ? " WHERE $where" : '');
  539. /**
  540. * Execute the statement and return the number of affected rows
  541. */
  542. if ($this->supportsParameters('positional')) {
  543. $stmt = $this->query($sql, array_values($bind));
  544. } else {
  545. $stmt = $this->query($sql, $bind);
  546. }
  547. $result = $stmt->rowCount();
  548. return $result;
  549. }
  550. /**
  551. * Deletes table rows based on a WHERE clause.
  552. *
  553. * @param mixed $table The table to update.
  554. * @param mixed $where DELETE WHERE clause(s).
  555. * @return int The number of affected rows.
  556. */
  557. public function delete($table, $where = '')
  558. {
  559. $where = $this->_whereExpr($where);
  560. /**
  561. * Build the DELETE statement
  562. */
  563. $sql = "DELETE FROM "
  564. . $this->quoteIdentifier($table, true)
  565. . (($where) ? " WHERE $where" : '');
  566. /**
  567. * Execute the statement and return the number of affected rows
  568. */
  569. $stmt = $this->query($sql);
  570. $result = $stmt->rowCount();
  571. return $result;
  572. }
  573. /**
  574. * Convert an array, string, or Zend_Db_Expr object
  575. * into a string to put in a WHERE clause.
  576. *
  577. * @param mixed $where
  578. * @return string
  579. */
  580. protected function _whereExpr($where)
  581. {
  582. if (empty($where)) {
  583. return $where;
  584. }
  585. if (!is_array($where)) {
  586. $where = array($where);
  587. }
  588. foreach ($where as $cond => &$term) {
  589. // is $cond an int? (i.e. Not a condition)
  590. if (is_int($cond)) {
  591. // $term is the full condition
  592. if ($term instanceof Zend_Db_Expr) {
  593. $term = $term->__toString();
  594. }
  595. } else {
  596. // $cond is the condition with placeholder,
  597. // and $term is quoted into the condition
  598. $term = $this->quoteInto($cond, $term);
  599. }
  600. $term = '(' . $term . ')';
  601. }
  602. $where = implode(' AND ', $where);
  603. return $where;
  604. }
  605. /**
  606. * Creates and returns a new Zend_Db_Select object for this adapter.
  607. *
  608. * @return Zend_Db_Select
  609. */
  610. public function select()
  611. {
  612. return new Zend_Db_Select($this);
  613. }
  614. /**
  615. * Get the fetch mode.
  616. *
  617. * @return int
  618. */
  619. public function getFetchMode()
  620. {
  621. return $this->_fetchMode;
  622. }
  623. /**
  624. * Fetches all SQL result rows as a sequential array.
  625. * Uses the current fetchMode for the adapter.
  626. *
  627. * @param string|Zend_Db_Select $sql An SQL SELECT statement.
  628. * @param mixed $bind Data to bind into SELECT placeholders.
  629. * @param mixed $fetchMode Override current fetch mode.
  630. * @return array
  631. */
  632. public function fetchAll($sql, $bind = array(), $fetchMode = null)
  633. {
  634. if ($fetchMode === null) {
  635. $fetchMode = $this->_fetchMode;
  636. }
  637. $stmt = $this->query($sql, $bind);
  638. $result = $stmt->fetchAll($fetchMode);
  639. return $result;
  640. }
  641. /**
  642. * Fetches the first row of the SQL result.
  643. * Uses the current fetchMode for the adapter.
  644. *
  645. * @param string|Zend_Db_Select $sql An SQL SELECT statement.
  646. * @param mixed $bind Data to bind into SELECT placeholders.
  647. * @param mixed $fetchMode Override current fetch mode.
  648. * @return array
  649. */
  650. public function fetchRow($sql, $bind = array(), $fetchMode = null)
  651. {
  652. if ($fetchMode === null) {
  653. $fetchMode = $this->_fetchMode;
  654. }
  655. $stmt = $this->query($sql, $bind);
  656. $result = $stmt->fetch($fetchMode);
  657. return $result;
  658. }
  659. /**
  660. * Fetches all SQL result rows as an associative array.
  661. *
  662. * The first column is the key, the entire row array is the
  663. * value. You should construct the query to be sure that
  664. * the first column contains unique values, or else
  665. * rows with duplicate values in the first column will
  666. * overwrite previous data.
  667. *
  668. * @param string|Zend_Db_Select $sql An SQL SELECT statement.
  669. * @param mixed $bind Data to bind into SELECT placeholders.
  670. * @return string
  671. */
  672. public function fetchAssoc($sql, $bind = array())
  673. {
  674. $stmt = $this->query($sql, $bind);
  675. $data = array();
  676. while ($row = $stmt->fetch(Zend_Db::FETCH_ASSOC)) {
  677. $tmp = array_values(array_slice($row, 0, 1));
  678. $data[$tmp[0]] = $row;
  679. }
  680. return $data;
  681. }
  682. /**
  683. * Fetches the first column of all SQL result rows as an array.
  684. *
  685. * The first column in each row is used as the array key.
  686. *
  687. * @param string|Zend_Db_Select $sql An SQL SELECT statement.
  688. * @param mixed $bind Data to bind into SELECT placeholders.
  689. * @return array
  690. */
  691. public function fetchCol($sql, $bind = array())
  692. {
  693. $stmt = $this->query($sql, $bind);
  694. $result = $stmt->fetchAll(Zend_Db::FETCH_COLUMN, 0);
  695. return $result;
  696. }
  697. /**
  698. * Fetches all SQL result rows as an array of key-value pairs.
  699. *
  700. * The first column is the key, the second column is the
  701. * value.
  702. *
  703. * @param string|Zend_Db_Select $sql An SQL SELECT statement.
  704. * @param mixed $bind Data to bind into SELECT placeholders.
  705. * @return string
  706. */
  707. public function fetchPairs($sql, $bind = array())
  708. {
  709. $stmt = $this->query($sql, $bind);
  710. $data = array();
  711. while ($row = $stmt->fetch(Zend_Db::FETCH_NUM)) {
  712. $data[$row[0]] = $row[1];
  713. }
  714. return $data;
  715. }
  716. /**
  717. * Fetches the first column of the first row of the SQL result.
  718. *
  719. * @param string|Zend_Db_Select $sql An SQL SELECT statement.
  720. * @param mixed $bind Data to bind into SELECT placeholders.
  721. * @return string
  722. */
  723. public function fetchOne($sql, $bind = array())
  724. {
  725. $stmt = $this->query($sql, $bind);
  726. $result = $stmt->fetchColumn(0);
  727. return $result;
  728. }
  729. /**
  730. * Quote a raw string.
  731. *
  732. * @param string $value Raw string
  733. * @return string Quoted string
  734. */
  735. protected function _quote($value)
  736. {
  737. if (is_int($value)) {
  738. return $value;
  739. } elseif (is_float($value)) {
  740. return sprintf('%F', $value);
  741. }
  742. return "'" . addcslashes($value, "\000\n\r\\'\"\032") . "'";
  743. }
  744. /**
  745. * Safely quotes a value for an SQL statement.
  746. *
  747. * If an array is passed as the value, the array values are quoted
  748. * and then returned as a comma-separated string.
  749. *
  750. * @param mixed $value The value to quote.
  751. * @param mixed $type OPTIONAL the SQL datatype name, or constant, or null.
  752. * @return mixed An SQL-safe quoted value (or string of separated values).
  753. */
  754. public function quote($value, $type = null)
  755. {
  756. $this->_connect();
  757. if ($value instanceof Zend_Db_Select) {
  758. return '(' . $value->assemble() . ')';
  759. }
  760. if ($value instanceof Zend_Db_Expr) {
  761. return $value->__toString();
  762. }
  763. if (is_array($value)) {
  764. foreach ($value as &$val) {
  765. $val = $this->quote($val, $type);
  766. }
  767. return implode(', ', $value);
  768. }
  769. if ($type !== null && array_key_exists($type = strtoupper($type), $this->_numericDataTypes)) {
  770. $quotedValue = '0';
  771. switch ($this->_numericDataTypes[$type]) {
  772. case Zend_Db::INT_TYPE: // 32-bit integer
  773. $quotedValue = (string) intval($value);
  774. break;
  775. case Zend_Db::BIGINT_TYPE: // 64-bit integer
  776. // ANSI SQL-style hex literals (e.g. x'[\dA-F]+')
  777. // are not supported here, because these are string
  778. // literals, not numeric literals.
  779. if (preg_match('/^(
  780. [+-]? # optional sign
  781. (?:
  782. 0[Xx][\da-fA-F]+ # ODBC-style hexadecimal
  783. |\d+ # decimal or octal, or MySQL ZEROFILL decimal
  784. (?:[eE][+-]?\d+)? # optional exponent on decimals or octals
  785. )
  786. )/x',
  787. (string) $value, $matches)) {
  788. $quotedValue = $matches[1];
  789. }
  790. break;
  791. case Zend_Db::FLOAT_TYPE: // float or decimal
  792. $quotedValue = sprintf('%F', $value);
  793. }
  794. return $quotedValue;
  795. }
  796. return $this->_quote($value);
  797. }
  798. /**
  799. * Quotes a value and places into a piece of text at a placeholder.
  800. *
  801. * The placeholder is a question-mark; all placeholders will be replaced
  802. * with the quoted value. For example:
  803. *
  804. * <code>
  805. * $text = "WHERE date < ?";
  806. * $date = "2005-01-02";
  807. * $safe = $sql->quoteInto($text, $date);
  808. * // $safe = "WHERE date < '2005-01-02'"
  809. * </code>
  810. *
  811. * @param string $text The text with a placeholder.
  812. * @param mixed $value The value to quote.
  813. * @param string $type OPTIONAL SQL datatype
  814. * @param integer $count OPTIONAL count of placeholders to replace
  815. * @return string An SQL-safe quoted value placed into the original text.
  816. */
  817. public function quoteInto($text, $value, $type = null, $count = null)
  818. {
  819. if ($count === null) {
  820. return str_replace('?', $this->quote($value, $type), $text);
  821. } else {
  822. while ($count > 0) {
  823. if (strpos($text, '?') != false) {
  824. $text = substr_replace($text, $this->quote($value, $type), strpos($text, '?'), 1);
  825. }
  826. --$count;
  827. }
  828. return $text;
  829. }
  830. }
  831. /**
  832. * Quotes an identifier.
  833. *
  834. * Accepts a string representing a qualified indentifier. For Example:
  835. * <code>
  836. * $adapter->quoteIdentifier('myschema.mytable')
  837. * </code>
  838. * Returns: "myschema"."mytable"
  839. *
  840. * Or, an array of one or more identifiers that may form a qualified identifier:
  841. * <code>
  842. * $adapter->quoteIdentifier(array('myschema','my.table'))
  843. * </code>
  844. * Returns: "myschema"."my.table"
  845. *
  846. * The actual quote character surrounding the identifiers may vary depending on
  847. * the adapter.
  848. *
  849. * @param string|array|Zend_Db_Expr $ident The identifier.
  850. * @param boolean $auto If true, heed the AUTO_QUOTE_IDENTIFIERS config option.
  851. * @return string The quoted identifier.
  852. */
  853. public function quoteIdentifier($ident, $auto=false)
  854. {
  855. return $this->_quoteIdentifierAs($ident, null, $auto);
  856. }
  857. /**
  858. * Quote a column identifier and alias.
  859. *
  860. * @param string|array|Zend_Db_Expr $ident The identifier or expression.
  861. * @param string $alias An alias for the column.
  862. * @param boolean $auto If true, heed the AUTO_QUOTE_IDENTIFIERS config option.
  863. * @return string The quoted identifier and alias.
  864. */
  865. public function quoteColumnAs($ident, $alias, $auto=false)
  866. {
  867. return $this->_quoteIdentifierAs($ident, $alias, $auto);
  868. }
  869. /**
  870. * Quote a table identifier and alias.
  871. *
  872. * @param string|array|Zend_Db_Expr $ident The identifier or expression.
  873. * @param string $alias An alias for the table.
  874. * @param boolean $auto If true, heed the AUTO_QUOTE_IDENTIFIERS config option.
  875. * @return string The quoted identifier and alias.
  876. */
  877. public function quoteTableAs($ident, $alias = null, $auto = false)
  878. {
  879. return $this->_quoteIdentifierAs($ident, $alias, $auto);
  880. }
  881. /**
  882. * Quote an identifier and an optional alias.
  883. *
  884. * @param string|array|Zend_Db_Expr $ident The identifier or expression.
  885. * @param string $alias An optional alias.
  886. * @param boolean $auto If true, heed the AUTO_QUOTE_IDENTIFIERS config option.
  887. * @param string $as The string to add between the identifier/expression and the alias.
  888. * @return string The quoted identifier and alias.
  889. */
  890. protected function _quoteIdentifierAs($ident, $alias = null, $auto = false, $as = ' AS ')
  891. {
  892. if ($ident instanceof Zend_Db_Expr) {
  893. $quoted = $ident->__toString();
  894. } elseif ($ident instanceof Zend_Db_Select) {
  895. $quoted = '(' . $ident->assemble() . ')';
  896. } else {
  897. if (is_string($ident)) {
  898. $ident = explode('.', $ident);
  899. }
  900. if (is_array($ident)) {
  901. $segments = array();
  902. foreach ($ident as $segment) {
  903. if ($segment instanceof Zend_Db_Expr) {
  904. $segments[] = $segment->__toString();
  905. } else {
  906. $segments[] = $this->_quoteIdentifier($segment, $auto);
  907. }
  908. }
  909. if ($alias !== null && end($ident) == $alias) {
  910. $alias = null;
  911. }
  912. $quoted = implode('.', $segments);
  913. } else {
  914. $quoted = $this->_quoteIdentifier($ident, $auto);
  915. }
  916. }
  917. if ($alias !== null) {
  918. $quoted .= $as . $this->_quoteIdentifier($alias, $auto);
  919. }
  920. return $quoted;
  921. }
  922. /**
  923. * Quote an identifier.
  924. *
  925. * @param string $value The identifier or expression.
  926. * @param boolean $auto If true, heed the AUTO_QUOTE_IDENTIFIERS config option.
  927. * @return string The quoted identifier and alias.
  928. */
  929. protected function _quoteIdentifier($value, $auto=false)
  930. {
  931. if ($auto === false || $this->_autoQuoteIdentifiers === true) {
  932. $q = $this->getQuoteIdentifierSymbol();
  933. return ($q . str_replace("$q", "$q$q", $value) . $q);
  934. }
  935. return $value;
  936. }
  937. /**
  938. * Returns the symbol the adapter uses for delimited identifiers.
  939. *
  940. * @return string
  941. */
  942. public function getQuoteIdentifierSymbol()
  943. {
  944. return '"';
  945. }
  946. /**
  947. * Return the most recent value from the specified sequence in the database.
  948. * This is supported only on RDBMS brands that support sequences
  949. * (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null.
  950. *
  951. * @param string $sequenceName
  952. * @return string
  953. */
  954. public function lastSequenceId($sequenceName)
  955. {
  956. return null;
  957. }
  958. /**
  959. * Generate a new value from the specified sequence in the database, and return it.
  960. * This is supported only on RDBMS brands that support sequences
  961. * (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null.
  962. *
  963. * @param string $sequenceName
  964. * @return string
  965. */
  966. public function nextSequenceId($sequenceName)
  967. {
  968. return null;
  969. }
  970. /**
  971. * Helper method to change the case of the strings used
  972. * when returning result sets in FETCH_ASSOC and FETCH_BOTH
  973. * modes.
  974. *
  975. * This is not intended to be used by application code,
  976. * but the method must be public so the Statement class
  977. * can invoke it.
  978. *
  979. * @param string $key
  980. * @return string
  981. */
  982. public function foldCase($key)
  983. {
  984. switch ($this->_caseFolding) {
  985. case Zend_Db::CASE_LOWER:
  986. $value = strtolower((string) $key);
  987. break;
  988. case Zend_Db::CASE_UPPER:
  989. $value = strtoupper((string) $key);
  990. break;
  991. case Zend_Db::CASE_NATURAL:
  992. default:
  993. $value = (string) $key;
  994. }
  995. return $value;
  996. }
  997. /**
  998. * called when object is getting serialized
  999. * This disconnects the DB object that cant be serialized
  1000. *
  1001. * @throws Zend_Db_Adapter_Exception
  1002. * @return array
  1003. */
  1004. public function __sleep()
  1005. {
  1006. if ($this->_allowSerialization == false) {
  1007. /** @see Zend_Db_Adapter_Exception */
  1008. require_once 'Zend/Db/Adapter/Exception.php';
  1009. throw new Zend_Db_Adapter_Exception(get_class($this) ." is not allowed to be serialized");
  1010. }
  1011. $this->_connection = false;
  1012. return array_keys(array_diff_key(get_object_vars($this), array('_connection'=>false)));
  1013. }
  1014. /**
  1015. * called when object is getting unserialized
  1016. *
  1017. * @return void
  1018. */
  1019. public function __wakeup()
  1020. {
  1021. if ($this->_autoReconnectOnUnserialize == true) {
  1022. $this->getConnection();
  1023. }
  1024. }
  1025. /**
  1026. * Abstract Methods
  1027. */
  1028. /**
  1029. * Returns a list of the tables in the database.
  1030. *
  1031. * @return array
  1032. */
  1033. abstract public function listTables();
  1034. /**
  1035. * Returns the column descriptions for a table.
  1036. *
  1037. * The return value is an associative array keyed by the column name,
  1038. * as returned by the RDBMS.
  1039. *
  1040. * The value of each array element is an associative array
  1041. * with the following keys:
  1042. *
  1043. * SCHEMA_NAME => string; name of database or schema
  1044. * TABLE_NAME => string;
  1045. * COLUMN_NAME => string; column name
  1046. * COLUMN_POSITION => number; ordinal position of column in table
  1047. * DATA_TYPE => string; SQL datatype name of column
  1048. * DEFAULT => string; default expression of column, null if none
  1049. * NULLABLE => boolean; true if column can have nulls
  1050. * LENGTH => number; length of CHAR/VARCHAR
  1051. * SCALE => number; scale of NUMERIC/DECIMAL
  1052. * PRECISION => number; precision of NUMERIC/DECIMAL
  1053. * UNSIGNED => boolean; unsigned property of an integer type
  1054. * PRIMARY => boolean; true if column is part of the primary key
  1055. * PRIMARY_POSITION => integer; position of column in primary key
  1056. *
  1057. * @param string $tableName
  1058. * @param string $schemaName OPTIONAL
  1059. * @return array
  1060. */
  1061. abstract public function describeTable($tableName, $schemaName = null);
  1062. /**
  1063. * Creates a connection to the database.
  1064. *
  1065. * @return void
  1066. */
  1067. abstract protected function _connect();
  1068. /**
  1069. * Test if a connection is active
  1070. *
  1071. * @return boolean
  1072. */
  1073. abstract public function isConnected();
  1074. /**
  1075. * Force the connection to close.
  1076. *
  1077. * @return void
  1078. */
  1079. abstract public function closeConnection();
  1080. /**
  1081. * Prepare a statement and return a PDOStatement-like object.
  1082. *
  1083. * @param string|Zend_Db_Select $sql SQL query
  1084. * @return Zend_Db_Statement|PDOStatement
  1085. */
  1086. abstract public function prepare($sql);
  1087. /**
  1088. * Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
  1089. *
  1090. * As a convention, on RDBMS brands that support sequences
  1091. * (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence
  1092. * from the arguments and returns the last id generated by that sequence.
  1093. * On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
  1094. * returns the last value generated for such a column, and the table name
  1095. * argument is disregarded.
  1096. *
  1097. * @param string $tableName OPTIONAL Name of table.
  1098. * @param string $primaryKey OPTIONAL Name of primary key column.
  1099. * @return string
  1100. */
  1101. abstract public function lastInsertId($tableName = null, $primaryKey = null);
  1102. /**
  1103. * Begin a transaction.
  1104. */
  1105. abstract protected function _beginTransaction();
  1106. /**
  1107. * Commit a transaction.
  1108. */
  1109. abstract protected function _commit();
  1110. /**
  1111. * Roll-back a transaction.
  1112. */
  1113. abstract protected function _rollBack();
  1114. /**
  1115. * Set the fetch mode.
  1116. *
  1117. * @param integer $mode
  1118. * @return void
  1119. * @throws Zend_Db_Adapter_Exception
  1120. */
  1121. abstract public function setFetchMode($mode);
  1122. /**
  1123. * Adds an adapter-specific LIMIT clause to the SELECT statement.
  1124. *
  1125. * @param mixed $sql
  1126. * @param integer $count
  1127. * @param integer $offset
  1128. * @return string
  1129. */
  1130. abstract public function limit($sql, $count, $offset = 0);
  1131. /**
  1132. * Check if the adapter supports real SQL parameters.
  1133. *
  1134. * @param string $type 'positional' or 'named'
  1135. * @return bool
  1136. */
  1137. abstract public function supportsParameters($type);
  1138. /**
  1139. * Retrieve server version in PHP style
  1140. *
  1141. * @return string
  1142. */
  1143. abstract public function getServerVersion();
  1144. }