PageRenderTime 51ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/concrete/libraries/3rdparty/Zend/Db/Adapter/Abstract.php

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