Abstract.php 40 KB

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