Abstract.php 40 KB

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