2
0

Abstract.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  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-2009 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-2009 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. echo $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 boolean $auto If true, heed the AUTO_QUOTE_IDENTIFIERS config option.
  885. * @param string $as The string to add between the identifier/expression and the alias.
  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. * @return 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_Statement|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. }