2
0

Abstract.php 39 KB

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