Abstract.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  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-2010 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-2010 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. );
  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. $i = 0;
  475. foreach ($bind as $col => $val) {
  476. $cols[] = $this->quoteIdentifier($col, true);
  477. if ($val instanceof Zend_Db_Expr) {
  478. $vals[] = $val->__toString();
  479. unset($bind[$col]);
  480. } else {
  481. if ($this->supportsParameters('positional')) {
  482. $vals[] = '?';
  483. } else {
  484. if ($this->supportsParameters('named')) {
  485. unset($bind[$col]);
  486. $bind[':col'.$i] = $val;
  487. $vals[] = ':col'.$i;
  488. $i++;
  489. } else {
  490. /** @see Zend_Db_Adapter_Exception */
  491. require_once 'Zend/Db/Adapter/Exception.php';
  492. throw new Zend_Db_Adapter_Exception(get_class($this) ." doesn't support positional or named binding");
  493. }
  494. }
  495. }
  496. }
  497. // build the statement
  498. $sql = "INSERT INTO "
  499. . $this->quoteIdentifier($table, true)
  500. . ' (' . implode(', ', $cols) . ') '
  501. . 'VALUES (' . implode(', ', $vals) . ')';
  502. // execute the statement and return the number of affected rows
  503. if ($this->supportsParameters('positional')) {
  504. $bind = array_values($bind);
  505. }
  506. $stmt = $this->query($sql, $bind);
  507. $result = $stmt->rowCount();
  508. return $result;
  509. }
  510. /**
  511. * Updates table rows with specified data based on a WHERE clause.
  512. *
  513. * @param mixed $table The table to update.
  514. * @param array $bind Column-value pairs.
  515. * @param mixed $where UPDATE WHERE clause(s).
  516. * @return int The number of affected rows.
  517. */
  518. public function update($table, array $bind, $where = '')
  519. {
  520. /**
  521. * Build "col = ?" pairs for the statement,
  522. * except for Zend_Db_Expr which is treated literally.
  523. */
  524. $set = array();
  525. $i = 0;
  526. foreach ($bind as $col => $val) {
  527. if ($val instanceof Zend_Db_Expr) {
  528. $val = $val->__toString();
  529. unset($bind[$col]);
  530. } else {
  531. if ($this->supportsParameters('positional')) {
  532. $val = '?';
  533. } else {
  534. if ($this->supportsParameters('named')) {
  535. unset($bind[$col]);
  536. $bind[':col'.$i] = $val;
  537. $val = ':col'.$i;
  538. $i++;
  539. } else {
  540. /** @see Zend_Db_Adapter_Exception */
  541. require_once 'Zend/Db/Adapter/Exception.php';
  542. throw new Zend_Db_Adapter_Exception(get_class($this) ." doesn't support positional or named binding");
  543. }
  544. }
  545. }
  546. $set[] = $this->quoteIdentifier($col, true) . ' = ' . $val;
  547. }
  548. $where = $this->_whereExpr($where);
  549. /**
  550. * Build the UPDATE statement
  551. */
  552. $sql = "UPDATE "
  553. . $this->quoteIdentifier($table, true)
  554. . ' SET ' . implode(', ', $set)
  555. . (($where) ? " WHERE $where" : '');
  556. /**
  557. * Execute the statement and return the number of affected rows
  558. */
  559. if ($this->supportsParameters('positional')) {
  560. $stmt = $this->query($sql, array_values($bind));
  561. } else {
  562. $stmt = $this->query($sql, $bind);
  563. }
  564. $result = $stmt->rowCount();
  565. return $result;
  566. }
  567. /**
  568. * Deletes table rows based on a WHERE clause.
  569. *
  570. * @param mixed $table The table to update.
  571. * @param mixed $where DELETE WHERE clause(s).
  572. * @return int The number of affected rows.
  573. */
  574. public function delete($table, $where = '')
  575. {
  576. $where = $this->_whereExpr($where);
  577. /**
  578. * Build the DELETE statement
  579. */
  580. $sql = "DELETE FROM "
  581. . $this->quoteIdentifier($table, true)
  582. . (($where) ? " WHERE $where" : '');
  583. /**
  584. * Execute the statement and return the number of affected rows
  585. */
  586. $stmt = $this->query($sql);
  587. $result = $stmt->rowCount();
  588. return $result;
  589. }
  590. /**
  591. * Convert an array, string, or Zend_Db_Expr object
  592. * into a string to put in a WHERE clause.
  593. *
  594. * @param mixed $where
  595. * @return string
  596. */
  597. protected function _whereExpr($where)
  598. {
  599. if (empty($where)) {
  600. return $where;
  601. }
  602. if (!is_array($where)) {
  603. $where = array($where);
  604. }
  605. foreach ($where as $cond => &$term) {
  606. // is $cond an int? (i.e. Not a condition)
  607. if (is_int($cond)) {
  608. // $term is the full condition
  609. if ($term instanceof Zend_Db_Expr) {
  610. $term = $term->__toString();
  611. }
  612. } else {
  613. // $cond is the condition with placeholder,
  614. // and $term is quoted into the condition
  615. $term = $this->quoteInto($cond, $term);
  616. }
  617. $term = '(' . $term . ')';
  618. }
  619. $where = implode(' AND ', $where);
  620. return $where;
  621. }
  622. /**
  623. * Creates and returns a new Zend_Db_Select object for this adapter.
  624. *
  625. * @return Zend_Db_Select
  626. */
  627. public function select()
  628. {
  629. return new Zend_Db_Select($this);
  630. }
  631. /**
  632. * Get the fetch mode.
  633. *
  634. * @return int
  635. */
  636. public function getFetchMode()
  637. {
  638. return $this->_fetchMode;
  639. }
  640. /**
  641. * Fetches all SQL result rows as a sequential array.
  642. * Uses the current fetchMode for the adapter.
  643. *
  644. * @param string|Zend_Db_Select $sql An SQL SELECT statement.
  645. * @param mixed $bind Data to bind into SELECT placeholders.
  646. * @param mixed $fetchMode Override current fetch mode.
  647. * @return array
  648. */
  649. public function fetchAll($sql, $bind = array(), $fetchMode = null)
  650. {
  651. if ($fetchMode === null) {
  652. $fetchMode = $this->_fetchMode;
  653. }
  654. $stmt = $this->query($sql, $bind);
  655. $result = $stmt->fetchAll($fetchMode);
  656. return $result;
  657. }
  658. /**
  659. * Fetches the first row of the SQL result.
  660. * Uses the current fetchMode for the adapter.
  661. *
  662. * @param string|Zend_Db_Select $sql An SQL SELECT statement.
  663. * @param mixed $bind Data to bind into SELECT placeholders.
  664. * @param mixed $fetchMode Override current fetch mode.
  665. * @return array
  666. */
  667. public function fetchRow($sql, $bind = array(), $fetchMode = null)
  668. {
  669. if ($fetchMode === null) {
  670. $fetchMode = $this->_fetchMode;
  671. }
  672. $stmt = $this->query($sql, $bind);
  673. $result = $stmt->fetch($fetchMode);
  674. return $result;
  675. }
  676. /**
  677. * Fetches all SQL result rows as an associative array.
  678. *
  679. * The first column is the key, the entire row array is the
  680. * value. You should construct the query to be sure that
  681. * the first column contains unique values, or else
  682. * rows with duplicate values in the first column will
  683. * overwrite previous data.
  684. *
  685. * @param string|Zend_Db_Select $sql An SQL SELECT statement.
  686. * @param mixed $bind Data to bind into SELECT placeholders.
  687. * @return array
  688. */
  689. public function fetchAssoc($sql, $bind = array())
  690. {
  691. $stmt = $this->query($sql, $bind);
  692. $data = array();
  693. while ($row = $stmt->fetch(Zend_Db::FETCH_ASSOC)) {
  694. $tmp = array_values(array_slice($row, 0, 1));
  695. $data[$tmp[0]] = $row;
  696. }
  697. return $data;
  698. }
  699. /**
  700. * Fetches the first column of all SQL result rows as an array.
  701. *
  702. * The first column in each row is used as the array key.
  703. *
  704. * @param string|Zend_Db_Select $sql An SQL SELECT statement.
  705. * @param mixed $bind Data to bind into SELECT placeholders.
  706. * @return array
  707. */
  708. public function fetchCol($sql, $bind = array())
  709. {
  710. $stmt = $this->query($sql, $bind);
  711. $result = $stmt->fetchAll(Zend_Db::FETCH_COLUMN, 0);
  712. return $result;
  713. }
  714. /**
  715. * Fetches all SQL result rows as an array of key-value pairs.
  716. *
  717. * The first column is the key, the second column is the
  718. * value.
  719. *
  720. * @param string|Zend_Db_Select $sql An SQL SELECT statement.
  721. * @param mixed $bind Data to bind into SELECT placeholders.
  722. * @return array
  723. */
  724. public function fetchPairs($sql, $bind = array())
  725. {
  726. $stmt = $this->query($sql, $bind);
  727. $data = array();
  728. while ($row = $stmt->fetch(Zend_Db::FETCH_NUM)) {
  729. $data[$row[0]] = $row[1];
  730. }
  731. return $data;
  732. }
  733. /**
  734. * Fetches the first column of the first row of the SQL result.
  735. *
  736. * @param string|Zend_Db_Select $sql An SQL SELECT statement.
  737. * @param mixed $bind Data to bind into SELECT placeholders.
  738. * @return string
  739. */
  740. public function fetchOne($sql, $bind = array())
  741. {
  742. $stmt = $this->query($sql, $bind);
  743. $result = $stmt->fetchColumn(0);
  744. return $result;
  745. }
  746. /**
  747. * Quote a raw string.
  748. *
  749. * @param string $value Raw string
  750. * @return string Quoted string
  751. */
  752. protected function _quote($value)
  753. {
  754. if (is_int($value)) {
  755. return $value;
  756. } elseif (is_float($value)) {
  757. return sprintf('%F', $value);
  758. }
  759. return "'" . addcslashes($value, "\000\n\r\\'\"\032") . "'";
  760. }
  761. /**
  762. * Safely quotes a value for an SQL statement.
  763. *
  764. * If an array is passed as the value, the array values are quoted
  765. * and then returned as a comma-separated string.
  766. *
  767. * @param mixed $value The value to quote.
  768. * @param mixed $type OPTIONAL the SQL datatype name, or constant, or null.
  769. * @return mixed An SQL-safe quoted value (or string of separated values).
  770. */
  771. public function quote($value, $type = null)
  772. {
  773. $this->_connect();
  774. if ($value instanceof Zend_Db_Select) {
  775. return '(' . $value->assemble() . ')';
  776. }
  777. if ($value instanceof Zend_Db_Expr) {
  778. return $value->__toString();
  779. }
  780. if (is_array($value)) {
  781. foreach ($value as &$val) {
  782. $val = $this->quote($val, $type);
  783. }
  784. return implode(', ', $value);
  785. }
  786. if ($type !== null && array_key_exists($type = strtoupper($type), $this->_numericDataTypes)) {
  787. $quotedValue = '0';
  788. switch ($this->_numericDataTypes[$type]) {
  789. case Zend_Db::INT_TYPE: // 32-bit integer
  790. $quotedValue = (string) intval($value);
  791. break;
  792. case Zend_Db::BIGINT_TYPE: // 64-bit integer
  793. // ANSI SQL-style hex literals (e.g. x'[\dA-F]+')
  794. // are not supported here, because these are string
  795. // literals, not numeric literals.
  796. if (preg_match('/^(
  797. [+-]? # optional sign
  798. (?:
  799. 0[Xx][\da-fA-F]+ # ODBC-style hexadecimal
  800. |\d+ # decimal or octal, or MySQL ZEROFILL decimal
  801. (?:[eE][+-]?\d+)? # optional exponent on decimals or octals
  802. )
  803. )/x',
  804. (string) $value, $matches)) {
  805. $quotedValue = $matches[1];
  806. }
  807. break;
  808. case Zend_Db::FLOAT_TYPE: // float or decimal
  809. $quotedValue = sprintf('%F', $value);
  810. }
  811. return $quotedValue;
  812. }
  813. return $this->_quote($value);
  814. }
  815. /**
  816. * Quotes a value and places into a piece of text at a placeholder.
  817. *
  818. * The placeholder is a question-mark; all placeholders will be replaced
  819. * with the quoted value. For example:
  820. *
  821. * <code>
  822. * $text = "WHERE date < ?";
  823. * $date = "2005-01-02";
  824. * $safe = $sql->quoteInto($text, $date);
  825. * // $safe = "WHERE date < '2005-01-02'"
  826. * </code>
  827. *
  828. * @param string $text The text with a placeholder.
  829. * @param mixed $value The value to quote.
  830. * @param string $type OPTIONAL SQL datatype
  831. * @param integer $count OPTIONAL count of placeholders to replace
  832. * @return string An SQL-safe quoted value placed into the original text.
  833. */
  834. public function quoteInto($text, $value, $type = null, $count = null)
  835. {
  836. if ($count === null) {
  837. return str_replace('?', $this->quote($value, $type), $text);
  838. } else {
  839. while ($count > 0) {
  840. if (strpos($text, '?') !== false) {
  841. $text = substr_replace($text, $this->quote($value, $type), strpos($text, '?'), 1);
  842. }
  843. --$count;
  844. }
  845. return $text;
  846. }
  847. }
  848. /**
  849. * Quotes an identifier.
  850. *
  851. * Accepts a string representing a qualified indentifier. For Example:
  852. * <code>
  853. * $adapter->quoteIdentifier('myschema.mytable')
  854. * </code>
  855. * Returns: "myschema"."mytable"
  856. *
  857. * Or, an array of one or more identifiers that may form a qualified identifier:
  858. * <code>
  859. * $adapter->quoteIdentifier(array('myschema','my.table'))
  860. * </code>
  861. * Returns: "myschema"."my.table"
  862. *
  863. * The actual quote character surrounding the identifiers may vary depending on
  864. * the adapter.
  865. *
  866. * @param string|array|Zend_Db_Expr $ident The identifier.
  867. * @param boolean $auto If true, heed the AUTO_QUOTE_IDENTIFIERS config option.
  868. * @return string The quoted identifier.
  869. */
  870. public function quoteIdentifier($ident, $auto=false)
  871. {
  872. return $this->_quoteIdentifierAs($ident, null, $auto);
  873. }
  874. /**
  875. * Quote a column identifier and alias.
  876. *
  877. * @param string|array|Zend_Db_Expr $ident The identifier or expression.
  878. * @param string $alias An alias for the column.
  879. * @param boolean $auto If true, heed the AUTO_QUOTE_IDENTIFIERS config option.
  880. * @return string The quoted identifier and alias.
  881. */
  882. public function quoteColumnAs($ident, $alias, $auto=false)
  883. {
  884. return $this->_quoteIdentifierAs($ident, $alias, $auto);
  885. }
  886. /**
  887. * Quote a table identifier and alias.
  888. *
  889. * @param string|array|Zend_Db_Expr $ident The identifier or expression.
  890. * @param string $alias An alias for the table.
  891. * @param boolean $auto If true, heed the AUTO_QUOTE_IDENTIFIERS config option.
  892. * @return string The quoted identifier and alias.
  893. */
  894. public function quoteTableAs($ident, $alias = null, $auto = false)
  895. {
  896. return $this->_quoteIdentifierAs($ident, $alias, $auto);
  897. }
  898. /**
  899. * Quote an identifier and an optional alias.
  900. *
  901. * @param string|array|Zend_Db_Expr $ident The identifier or expression.
  902. * @param string $alias An optional alias.
  903. * @param boolean $auto If true, heed the AUTO_QUOTE_IDENTIFIERS config option.
  904. * @param string $as The string to add between the identifier/expression and the alias.
  905. * @return string The quoted identifier and alias.
  906. */
  907. protected function _quoteIdentifierAs($ident, $alias = null, $auto = false, $as = ' AS ')
  908. {
  909. if ($ident instanceof Zend_Db_Expr) {
  910. $quoted = $ident->__toString();
  911. } elseif ($ident instanceof Zend_Db_Select) {
  912. $quoted = '(' . $ident->assemble() . ')';
  913. } else {
  914. if (is_string($ident)) {
  915. $ident = explode('.', $ident);
  916. }
  917. if (is_array($ident)) {
  918. $segments = array();
  919. foreach ($ident as $segment) {
  920. if ($segment instanceof Zend_Db_Expr) {
  921. $segments[] = $segment->__toString();
  922. } else {
  923. $segments[] = $this->_quoteIdentifier($segment, $auto);
  924. }
  925. }
  926. if ($alias !== null && end($ident) == $alias) {
  927. $alias = null;
  928. }
  929. $quoted = implode('.', $segments);
  930. } else {
  931. $quoted = $this->_quoteIdentifier($ident, $auto);
  932. }
  933. }
  934. if ($alias !== null) {
  935. $quoted .= $as . $this->_quoteIdentifier($alias, $auto);
  936. }
  937. return $quoted;
  938. }
  939. /**
  940. * Quote an identifier.
  941. *
  942. * @param string $value The identifier or expression.
  943. * @param boolean $auto If true, heed the AUTO_QUOTE_IDENTIFIERS config option.
  944. * @return string The quoted identifier and alias.
  945. */
  946. protected function _quoteIdentifier($value, $auto=false)
  947. {
  948. if ($auto === false || $this->_autoQuoteIdentifiers === true) {
  949. $q = $this->getQuoteIdentifierSymbol();
  950. return ($q . str_replace("$q", "$q$q", $value) . $q);
  951. }
  952. return $value;
  953. }
  954. /**
  955. * Returns the symbol the adapter uses for delimited identifiers.
  956. *
  957. * @return string
  958. */
  959. public function getQuoteIdentifierSymbol()
  960. {
  961. return '"';
  962. }
  963. /**
  964. * Return the most recent value from the specified sequence in the database.
  965. * This is supported only on RDBMS brands that support sequences
  966. * (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null.
  967. *
  968. * @param string $sequenceName
  969. * @return string
  970. */
  971. public function lastSequenceId($sequenceName)
  972. {
  973. return null;
  974. }
  975. /**
  976. * Generate a new value from the specified sequence in the database, and return it.
  977. * This is supported only on RDBMS brands that support sequences
  978. * (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null.
  979. *
  980. * @param string $sequenceName
  981. * @return string
  982. */
  983. public function nextSequenceId($sequenceName)
  984. {
  985. return null;
  986. }
  987. /**
  988. * Helper method to change the case of the strings used
  989. * when returning result sets in FETCH_ASSOC and FETCH_BOTH
  990. * modes.
  991. *
  992. * This is not intended to be used by application code,
  993. * but the method must be public so the Statement class
  994. * can invoke it.
  995. *
  996. * @param string $key
  997. * @return string
  998. */
  999. public function foldCase($key)
  1000. {
  1001. switch ($this->_caseFolding) {
  1002. case Zend_Db::CASE_LOWER:
  1003. $value = strtolower((string) $key);
  1004. break;
  1005. case Zend_Db::CASE_UPPER:
  1006. $value = strtoupper((string) $key);
  1007. break;
  1008. case Zend_Db::CASE_NATURAL:
  1009. default:
  1010. $value = (string) $key;
  1011. }
  1012. return $value;
  1013. }
  1014. /**
  1015. * called when object is getting serialized
  1016. * This disconnects the DB object that cant be serialized
  1017. *
  1018. * @throws Zend_Db_Adapter_Exception
  1019. * @return array
  1020. */
  1021. public function __sleep()
  1022. {
  1023. if ($this->_allowSerialization == false) {
  1024. /** @see Zend_Db_Adapter_Exception */
  1025. require_once 'Zend/Db/Adapter/Exception.php';
  1026. throw new Zend_Db_Adapter_Exception(get_class($this) ." is not allowed to be serialized");
  1027. }
  1028. $this->_connection = false;
  1029. return array_keys(array_diff_key(get_object_vars($this), array('_connection'=>false)));
  1030. }
  1031. /**
  1032. * called when object is getting unserialized
  1033. *
  1034. * @return void
  1035. */
  1036. public function __wakeup()
  1037. {
  1038. if ($this->_autoReconnectOnUnserialize == true) {
  1039. $this->getConnection();
  1040. }
  1041. }
  1042. /**
  1043. * Abstract Methods
  1044. */
  1045. /**
  1046. * Returns a list of the tables in the database.
  1047. *
  1048. * @return array
  1049. */
  1050. abstract public function listTables();
  1051. /**
  1052. * Returns the column descriptions for a table.
  1053. *
  1054. * The return value is an associative array keyed by the column name,
  1055. * as returned by the RDBMS.
  1056. *
  1057. * The value of each array element is an associative array
  1058. * with the following keys:
  1059. *
  1060. * SCHEMA_NAME => string; name of database or schema
  1061. * TABLE_NAME => string;
  1062. * COLUMN_NAME => string; column name
  1063. * COLUMN_POSITION => number; ordinal position of column in table
  1064. * DATA_TYPE => string; SQL datatype name of column
  1065. * DEFAULT => string; default expression of column, null if none
  1066. * NULLABLE => boolean; true if column can have nulls
  1067. * LENGTH => number; length of CHAR/VARCHAR
  1068. * SCALE => number; scale of NUMERIC/DECIMAL
  1069. * PRECISION => number; precision of NUMERIC/DECIMAL
  1070. * UNSIGNED => boolean; unsigned property of an integer type
  1071. * PRIMARY => boolean; true if column is part of the primary key
  1072. * PRIMARY_POSITION => integer; position of column in primary key
  1073. *
  1074. * @param string $tableName
  1075. * @param string $schemaName OPTIONAL
  1076. * @return array
  1077. */
  1078. abstract public function describeTable($tableName, $schemaName = null);
  1079. /**
  1080. * Creates a connection to the database.
  1081. *
  1082. * @return void
  1083. */
  1084. abstract protected function _connect();
  1085. /**
  1086. * Test if a connection is active
  1087. *
  1088. * @return boolean
  1089. */
  1090. abstract public function isConnected();
  1091. /**
  1092. * Force the connection to close.
  1093. *
  1094. * @return void
  1095. */
  1096. abstract public function closeConnection();
  1097. /**
  1098. * Prepare a statement and return a PDOStatement-like object.
  1099. *
  1100. * @param string|Zend_Db_Select $sql SQL query
  1101. * @return Zend_Db_Statement|PDOStatement
  1102. */
  1103. abstract public function prepare($sql);
  1104. /**
  1105. * Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
  1106. *
  1107. * As a convention, on RDBMS brands that support sequences
  1108. * (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence
  1109. * from the arguments and returns the last id generated by that sequence.
  1110. * On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
  1111. * returns the last value generated for such a column, and the table name
  1112. * argument is disregarded.
  1113. *
  1114. * @param string $tableName OPTIONAL Name of table.
  1115. * @param string $primaryKey OPTIONAL Name of primary key column.
  1116. * @return string
  1117. */
  1118. abstract public function lastInsertId($tableName = null, $primaryKey = null);
  1119. /**
  1120. * Begin a transaction.
  1121. */
  1122. abstract protected function _beginTransaction();
  1123. /**
  1124. * Commit a transaction.
  1125. */
  1126. abstract protected function _commit();
  1127. /**
  1128. * Roll-back a transaction.
  1129. */
  1130. abstract protected function _rollBack();
  1131. /**
  1132. * Set the fetch mode.
  1133. *
  1134. * @param integer $mode
  1135. * @return void
  1136. * @throws Zend_Db_Adapter_Exception
  1137. */
  1138. abstract public function setFetchMode($mode);
  1139. /**
  1140. * Adds an adapter-specific LIMIT clause to the SELECT statement.
  1141. *
  1142. * @param mixed $sql
  1143. * @param integer $count
  1144. * @param integer $offset
  1145. * @return string
  1146. */
  1147. abstract public function limit($sql, $count, $offset = 0);
  1148. /**
  1149. * Check if the adapter supports real SQL parameters.
  1150. *
  1151. * @param string $type 'positional' or 'named'
  1152. * @return bool
  1153. */
  1154. abstract public function supportsParameters($type);
  1155. /**
  1156. * Retrieve server version in PHP style
  1157. *
  1158. * @return string
  1159. */
  1160. abstract public function getServerVersion();
  1161. }