Abstract.php 39 KB

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