Abstract.php 41 KB

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