PageRenderTime 56ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/library/Zend/Db/Table/Abstract.php

https://bitbucket.org/baruffaldi/cms-php-bfcms
PHP | 1194 lines | 584 code | 121 blank | 489 comment | 92 complexity | 15fdf71384bb4e090403a266736c5d17 MD5 | raw file
  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 Table
  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: Abstract.php 6320 2007-09-12 00:27:22Z bkarwin $
  21. */
  22. /**
  23. * @see Zend_Db_Adapter_Abstract
  24. */
  25. require_once 'Zend/Db/Adapter/Abstract.php';
  26. /**
  27. * @see Zend_Db_Adapter_Abstract
  28. */
  29. require_once 'Zend/Db/Select.php';
  30. /**
  31. * @see Zend_Db
  32. */
  33. require_once 'Zend/Db.php';
  34. /**
  35. * Class for SQL table interface.
  36. *
  37. * @category Zend
  38. * @package Zend_Db
  39. * @subpackage Table
  40. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  41. * @license http://framework.zend.com/license/new-bsd New BSD License
  42. */
  43. abstract class Zend_Db_Table_Abstract
  44. {
  45. const ADAPTER = 'db';
  46. const SCHEMA = 'schema';
  47. const NAME = 'name';
  48. const PRIMARY = 'primary';
  49. const COLS = 'cols';
  50. const METADATA = 'metadata';
  51. const METADATA_CACHE = 'metadataCache';
  52. const ROW_CLASS = 'rowClass';
  53. const ROWSET_CLASS = 'rowsetClass';
  54. const REFERENCE_MAP = 'referenceMap';
  55. const DEPENDENT_TABLES = 'dependentTables';
  56. const SEQUENCE = 'sequence';
  57. const COLUMNS = 'columns';
  58. const REF_TABLE_CLASS = 'refTableClass';
  59. const REF_COLUMNS = 'refColumns';
  60. const ON_DELETE = 'onDelete';
  61. const ON_UPDATE = 'onUpdate';
  62. const CASCADE = 'cascade';
  63. const RESTRICT = 'restrict';
  64. const SET_NULL = 'setNull';
  65. /**
  66. * Default Zend_Db_Adapter_Abstract object.
  67. *
  68. * @var Zend_Db_Adapter_Abstract
  69. */
  70. protected static $_defaultDb;
  71. /**
  72. * Default cache for information provided by the adapter's describeTable() method.
  73. *
  74. * @var Zend_Cache_Core
  75. */
  76. protected static $_defaultMetadataCache = null;
  77. /**
  78. * Zend_Db_Adapter_Abstract object.
  79. *
  80. * @var Zend_Db_Adapter_Abstract
  81. */
  82. protected $_db;
  83. /**
  84. * The schema name (default null means current schema)
  85. *
  86. * @var array
  87. */
  88. protected $_schema = null;
  89. /**
  90. * The table name.
  91. *
  92. * @var array
  93. */
  94. protected $_name = null;
  95. /**
  96. * The table column names derived from Zend_Db_Adapter_Abstract::describeTable().
  97. *
  98. * @var array
  99. */
  100. protected $_cols;
  101. /**
  102. * The primary key column or columns.
  103. * A compound key should be declared as an array.
  104. * You may declare a single-column primary key
  105. * as a string.
  106. *
  107. * @var mixed
  108. */
  109. protected $_primary = null;
  110. /**
  111. * If your primary key is a compound key, and one of the columns uses
  112. * an auto-increment or sequence-generated value, set _identity
  113. * to the ordinal index in the $_primary array for that column.
  114. * Note this index is the position of the column in the primary key,
  115. * not the position of the column in the table. The primary key
  116. * array is 1-based.
  117. *
  118. * @var integer
  119. */
  120. protected $_identity = 1;
  121. /**
  122. * Define the logic for new values in the primary key.
  123. * May be a string, boolean true, or boolean false.
  124. *
  125. * @var mixed
  126. */
  127. protected $_sequence = true;
  128. /**
  129. * Information provided by the adapter's describeTable() method.
  130. *
  131. * @var array
  132. */
  133. protected $_metadata = array();
  134. /**
  135. * Cache for information provided by the adapter's describeTable() method.
  136. *
  137. * @var Zend_Cache_Core
  138. */
  139. protected $_metadataCache = null;
  140. /**
  141. * Classname for row
  142. *
  143. * @var string
  144. */
  145. protected $_rowClass = 'Zend_Db_Table_Row';
  146. /**
  147. * Classname for rowset
  148. *
  149. * @var string
  150. */
  151. protected $_rowsetClass = 'Zend_Db_Table_Rowset';
  152. /**
  153. * Associative array map of declarative referential integrity rules.
  154. * This array has one entry per foreign key in the current table.
  155. * Each key is a mnemonic name for one reference rule.
  156. *
  157. * Each value is also an associative array, with the following keys:
  158. * - columns = array of names of column(s) in the child table.
  159. * - refTableClass = class name of the parent table.
  160. * - refColumns = array of names of column(s) in the parent table,
  161. * in the same order as those in the 'columns' entry.
  162. * - onDelete = "cascade" means that a delete in the parent table also
  163. * causes a delete of referencing rows in the child table.
  164. * - onUpdate = "cascade" means that an update of primary key values in
  165. * the parent table also causes an update of referencing
  166. * rows in the child table.
  167. *
  168. * @var array
  169. */
  170. protected $_referenceMap = array();
  171. /**
  172. * Simple array of class names of tables that are "children" of the current
  173. * table, in other words tables that contain a foreign key to this one.
  174. * Array elements are not table names; they are class names of classes that
  175. * extend Zend_Db_Table_Abstract.
  176. *
  177. * @var array
  178. */
  179. protected $_dependentTables = array();
  180. /**
  181. * Constructor.
  182. *
  183. * Supported params for $config are:
  184. * - db = user-supplied instance of database connector,
  185. * or key name of registry instance.
  186. * - name = table name.
  187. * - primary = string or array of primary key(s).
  188. * - rowClass = row class name.
  189. * - rowsetClass = rowset class name.
  190. * - referenceMap = array structure to declare relationship
  191. * to parent tables.
  192. * - dependentTables = array of child tables.
  193. * - metadataCache = cache for information from adapter describeTable().
  194. *
  195. * @param mixed $config Array of user-specified config options, or just the Db Adapter.
  196. * @return void
  197. */
  198. public function __construct($config = array())
  199. {
  200. /**
  201. * Allow a scalar argument to be the Adapter object or Registry key.
  202. */
  203. if (!is_array($config)) {
  204. $config = array(self::ADAPTER => $config);
  205. }
  206. foreach ($config as $key => $value) {
  207. switch ($key) {
  208. case self::ADAPTER:
  209. $this->_setAdapter($value);
  210. break;
  211. case self::SCHEMA:
  212. $this->_schema = (string) $value;
  213. break;
  214. case self::NAME:
  215. $this->_name = (string) $value;
  216. break;
  217. case self::PRIMARY:
  218. $this->_primary = (array) $value;
  219. break;
  220. case self::ROW_CLASS:
  221. $this->setRowClass($value);
  222. break;
  223. case self::ROWSET_CLASS:
  224. $this->setRowsetClass($value);
  225. break;
  226. case self::REFERENCE_MAP:
  227. $this->setReferences($value);
  228. break;
  229. case self::DEPENDENT_TABLES:
  230. $this->setDependentTables($value);
  231. break;
  232. case self::METADATA_CACHE:
  233. $this->_setMetadataCache($value);
  234. break;
  235. case self::SEQUENCE:
  236. $this->_setSequence($value);
  237. break;
  238. default:
  239. // ignore unrecognized configuration directive
  240. break;
  241. }
  242. }
  243. $this->_setup();
  244. $this->init();
  245. }
  246. /**
  247. * @param string $classname
  248. * @return Zend_Db_Table_Abstract Provides a fluent interface
  249. */
  250. public function setRowClass($classname)
  251. {
  252. $this->_rowClass = (string) $classname;
  253. return $this;
  254. }
  255. /**
  256. * @return string
  257. */
  258. public function getRowClass()
  259. {
  260. return $this->_rowClass;
  261. }
  262. /**
  263. * @param string $classname
  264. * @return Zend_Db_Table_Abstract Provides a fluent interface
  265. */
  266. public function setRowsetClass($classname)
  267. {
  268. $this->_rowsetClass = (string) $classname;
  269. return $this;
  270. }
  271. /**
  272. * @return string
  273. */
  274. public function getRowsetClass()
  275. {
  276. return $this->_rowsetClass;
  277. }
  278. /**
  279. * @param array $referenceMap
  280. * @return Zend_Db_Table_Abstract Provides a fluent interface
  281. */
  282. public function setReferences(array $referenceMap)
  283. {
  284. $this->_referenceMap = $referenceMap;
  285. return $this;
  286. }
  287. /**
  288. * @param string $tableClassname
  289. * @param string $ruleKey OPTIONAL
  290. * @return array
  291. * @throws Zend_Db_Table_Exception
  292. */
  293. public function getReference($tableClassname, $ruleKey = null)
  294. {
  295. $thisClass = get_class($this);
  296. $refMap = $this->_getReferenceMapNormalized();
  297. if ($ruleKey !== null) {
  298. if (!isset($refMap[$ruleKey])) {
  299. require_once "Zend/Db/Table/Exception.php";
  300. throw new Zend_Db_Table_Exception("No reference rule \"$ruleKey\" from table $thisClass to table $tableClassname");
  301. }
  302. if ($refMap[$ruleKey][self::REF_TABLE_CLASS] != $tableClassname) {
  303. require_once "Zend/Db/Table/Exception.php";
  304. throw new Zend_Db_Table_Exception("Reference rule \"$ruleKey\" does not reference table $tableClassname");
  305. }
  306. return $refMap[$ruleKey];
  307. }
  308. foreach ($refMap as $reference) {
  309. if ($reference[self::REF_TABLE_CLASS] == $tableClassname) {
  310. return $reference;
  311. }
  312. }
  313. require_once "Zend/Db/Table/Exception.php";
  314. throw new Zend_Db_Table_Exception("No reference from table $thisClass to table $tableClassname");
  315. }
  316. /**
  317. * @param array $dependentTables
  318. * @return Zend_Db_Table_Abstract Provides a fluent interface
  319. */
  320. public function setDependentTables(array $dependentTables)
  321. {
  322. $this->_dependentTables = $dependentTables;
  323. return $this;
  324. }
  325. /**
  326. * @return array
  327. */
  328. public function getDependentTables()
  329. {
  330. return $this->_dependentTables;
  331. }
  332. /**
  333. * Sets the default Zend_Db_Adapter_Abstract for all Zend_Db_Table objects.
  334. *
  335. * @param mixed $db Either an Adapter object, or a string naming a Registry key
  336. * @return void
  337. */
  338. public static final function setDefaultAdapter($db = null)
  339. {
  340. self::$_defaultDb = self::_setupAdapter($db);
  341. }
  342. /**
  343. * Gets the default Zend_Db_Adapter_Abstract for all Zend_Db_Table objects.
  344. *
  345. * @return Zend_Db_Adapter_Abstract or null
  346. */
  347. public static final function getDefaultAdapter()
  348. {
  349. return self::$_defaultDb;
  350. }
  351. /**
  352. * @param mixed $db Either an Adapter object, or a string naming a Registry key
  353. * @return Zend_Db_Table_Abstract Provides a fluent interface
  354. */
  355. protected final function _setAdapter($db)
  356. {
  357. $this->_db = self::_setupAdapter($db);
  358. return $this;
  359. }
  360. /**
  361. * Gets the Zend_Db_Adapter_Abstract for this particular Zend_Db_Table object.
  362. *
  363. * @return Zend_Db_Adapter_Abstract
  364. */
  365. public final function getAdapter()
  366. {
  367. return $this->_db;
  368. }
  369. /**
  370. * @param mixed $db Either an Adapter object, or a string naming a Registry key
  371. * @return Zend_Db_Adapter_Abstract
  372. * @throws Zend_Db_Table_Exception
  373. */
  374. protected static final function _setupAdapter($db)
  375. {
  376. if ($db === null) {
  377. return null;
  378. }
  379. if (is_string($db)) {
  380. require_once 'Zend/Registry.php';
  381. $db = Zend_Registry::get($db);
  382. }
  383. if (!$db instanceof Zend_Db_Adapter_Abstract) {
  384. require_once 'Zend/Db/Table/Exception.php';
  385. throw new Zend_Db_Table_Exception('Argument must be of type Zend_Db_Adapter_Abstract, or a Registry key where a Zend_Db_Adapter_Abstract object is stored');
  386. }
  387. return $db;
  388. }
  389. /**
  390. * Sets the default metadata cache for information returned by Zend_Db_Adapter_Abstract::describeTable().
  391. *
  392. * If $defaultMetadataCache is null, then no metadata cache is used by default.
  393. *
  394. * @param mixed $metadataCache Either a Cache object, or a string naming a Registry key
  395. * @return void
  396. */
  397. public static function setDefaultMetadataCache($metadataCache = null)
  398. {
  399. self::$_defaultMetadataCache = self::_setupMetadataCache($metadataCache);
  400. }
  401. /**
  402. * Gets the default metadata cache for information returned by Zend_Db_Adapter_Abstract::describeTable().
  403. *
  404. * @return Zend_Cache_Core or null
  405. */
  406. public static function getDefaultMetadataCache()
  407. {
  408. return self::$_defaultMetadataCache;
  409. }
  410. /**
  411. * Sets the metadata cache for information returned by Zend_Db_Adapter_Abstract::describeTable().
  412. *
  413. * If $metadataCache is null, then no metadata cache is used. Since there is no opportunity to reload metadata
  414. * after instantiation, this method need not be public, particularly because that it would have no effect
  415. * results in unnecessary API complexity. To configure the metadata cache, use the metadataCache configuration
  416. * option for the class constructor upon instantiation.
  417. *
  418. * @param mixed $metadataCache Either a Cache object, or a string naming a Registry key
  419. * @return Zend_Db_Table_Abstract Provides a fluent interface
  420. */
  421. protected function _setMetadataCache($metadataCache)
  422. {
  423. $this->_metadataCache = self::_setupMetadataCache($metadataCache);
  424. return $this;
  425. }
  426. /**
  427. * Gets the metadata cache for information returned by Zend_Db_Adapter_Abstract::describeTable().
  428. *
  429. * @return Zend_Cache_Core or null
  430. */
  431. public function getMetadataCache()
  432. {
  433. return $this->_metadataCache;
  434. }
  435. /**
  436. * @param mixed $metadataCache Either a Cache object, or a string naming a Registry key
  437. * @return Zend_Cache_Core
  438. * @throws Zend_Db_Table_Exception
  439. */
  440. protected static final function _setupMetadataCache($metadataCache)
  441. {
  442. if ($metadataCache === null) {
  443. return null;
  444. }
  445. if (is_string($metadataCache)) {
  446. require_once 'Zend/Registry.php';
  447. $metadataCache = Zend_Registry::get($metadataCache);
  448. }
  449. if (!$metadataCache instanceof Zend_Cache_Core) {
  450. require_once 'Zend/Db/Table/Exception.php';
  451. throw new Zend_Db_Table_Exception('Argument must be of type Zend_Cache_Core, or a Registry key where a Zend_Cache_Core object is stored');
  452. }
  453. return $metadataCache;
  454. }
  455. /**
  456. * Sets the sequence member, which defines the behavior for generating
  457. * primary key values in new rows.
  458. * - If this is a string, then the string names the sequence object.
  459. * - If this is boolean true, then the key uses an auto-incrementing
  460. * or identity mechanism.
  461. * - If this is boolean false, then the key is user-defined.
  462. * Use this for natural keys, for example.
  463. *
  464. * @param mixed $sequence
  465. * @return Zend_Db_Table_Adapter_Abstract Provides a fluent interface
  466. */
  467. protected function _setSequence($sequence)
  468. {
  469. $this->_sequence = $sequence;
  470. return $this;
  471. }
  472. /**
  473. * Turnkey for initialization of a table object.
  474. * Calls other protected methods for individual tasks, to make it easier
  475. * for a subclass to override part of the setup logic.
  476. *
  477. * @return void
  478. */
  479. protected function _setup()
  480. {
  481. $this->_setupDatabaseAdapter();
  482. $this->_setupTableName();
  483. $this->_setupMetadata();
  484. $this->_setupPrimaryKey();
  485. }
  486. /**
  487. * Initialize database adapter.
  488. *
  489. * @return void
  490. */
  491. protected function _setupDatabaseAdapter()
  492. {
  493. if (! $this->_db) {
  494. $this->_db = self::getDefaultAdapter();
  495. if (!$this->_db instanceof Zend_Db_Adapter_Abstract) {
  496. require_once 'Zend/Db/Table/Exception.php';
  497. throw new Zend_Db_Table_Exception('No adapter found for ' . get_class($this));
  498. }
  499. }
  500. }
  501. /**
  502. * Initialize table and schema names.
  503. *
  504. * If the table name is not set in the class definition,
  505. * use the class name itself as the table name.
  506. *
  507. * A schema name provided with the table name (e.g., "schema.table") overrides
  508. * any existing value for $this->_schema.
  509. *
  510. * @return void
  511. */
  512. protected function _setupTableName()
  513. {
  514. if (! $this->_name) {
  515. $this->_name = get_class($this);
  516. } else if (strpos($this->_name, '.')) {
  517. list($this->_schema, $this->_name) = explode('.', $this->_name);
  518. }
  519. }
  520. /**
  521. * Initializes metadata.
  522. *
  523. * If metadata cannot be loaded from cache, adapter's describeTable() method is called to discover metadata
  524. * information. Returns true if and only if the metadata are loaded from cache.
  525. *
  526. * @return boolean
  527. * @throws Zend_Db_Table_Exception
  528. */
  529. protected function _setupMetadata()
  530. {
  531. // Assume that metadata will be loaded from cache
  532. $isMetadataFromCache = true;
  533. // If $this has no metadata cache but the class has a default metadata cache
  534. if (null === $this->_metadataCache && null !== self::$_defaultMetadataCache) {
  535. // Make $this use the default metadata cache of the class
  536. $this->_setMetadataCache(self::$_defaultMetadataCache);
  537. }
  538. // If $this has a metadata cache
  539. if (null !== $this->_metadataCache) {
  540. // Define the cache identifier where the metadata are saved
  541. $cacheId = md5("$this->_schema.$this->_name");
  542. }
  543. // If $this has no metadata cache or metadata cache misses
  544. if (null === $this->_metadataCache || !($metadata = $this->_metadataCache->load($cacheId))) {
  545. // Metadata are not loaded from cache
  546. $isMetadataFromCache = false;
  547. // Fetch metadata from the adapter's describeTable() method
  548. $metadata = $this->_db->describeTable($this->_name, $this->_schema);
  549. // If $this has a metadata cache, then cache the metadata
  550. if (null !== $this->_metadataCache && !$this->_metadataCache->save($metadata, $cacheId)) {
  551. /**
  552. * @see Zend_Db_Table_Exception
  553. */
  554. require_once 'Zend/Db/Table/Exception.php';
  555. throw new Zend_Db_Table_Exception('Failed saving metadata to metadataCache');
  556. }
  557. }
  558. // Assign the metadata to $this
  559. $this->_metadata = $metadata;
  560. // Update the columns
  561. $this->_cols = array_keys($this->_metadata);
  562. // Return whether the metadata were loaded from cache
  563. return $isMetadataFromCache;
  564. }
  565. /**
  566. * Initialize primary key from metadata.
  567. * If $_primary is not defined, discover primary keys
  568. * from the information returned by describeTable().
  569. *
  570. * @return void
  571. * @throws Zend_Db_Table_Exception
  572. */
  573. protected function _setupPrimaryKey()
  574. {
  575. if (!$this->_primary) {
  576. $this->_primary = array();
  577. foreach ($this->_metadata as $col) {
  578. if ($col['PRIMARY']) {
  579. $this->_primary[ $col['PRIMARY_POSITION'] ] = $col['COLUMN_NAME'];
  580. if ($col['IDENTITY']) {
  581. $this->_identity = $col['PRIMARY_POSITION'];
  582. }
  583. }
  584. }
  585. // if no primary key was specified and none was found in the metadata
  586. // then throw an exception.
  587. if (empty($this->_primary)) {
  588. require_once 'Zend/Db/Table/Exception.php';
  589. throw new Zend_Db_Table_Exception('A table must have a primary key, but none was found');
  590. }
  591. } else if (!is_array($this->_primary)) {
  592. $this->_primary = array(1 => $this->_primary);
  593. } else if (isset($this->_primary[0])) {
  594. array_unshift($this->_primary, null);
  595. unset($this->_primary[0]);
  596. }
  597. if (! array_intersect((array) $this->_primary, $this->_cols) == (array) $this->_primary) {
  598. require_once 'Zend/Db/Table/Exception.php';
  599. throw new Zend_Db_Table_Exception("Primary key column(s) ("
  600. . implode(',', (array) $this->_primary)
  601. . ") are not columns in this table ("
  602. . implode(',', $this->_cols)
  603. . ")");
  604. }
  605. $primary = (array) $this->_primary;
  606. $pkIdentity = $primary[(int) $this->_identity];
  607. /**
  608. * Special case for PostgreSQL: a SERIAL key implicitly uses a sequence
  609. * object whose name is "<table>_<column>_seq".
  610. */
  611. if ($this->_sequence === true && $this->_db instanceof Zend_Db_Adapter_Pdo_Pgsql) {
  612. $this->_sequence = "{$this->_name}_{$pkIdentity}_seq";
  613. if ($this->_schema) {
  614. $this->_sequence = $this->_schema . '.' . $this->_sequence;
  615. }
  616. }
  617. }
  618. /**
  619. * Returns a normalized version of the reference map
  620. *
  621. * @return array
  622. */
  623. protected function _getReferenceMapNormalized()
  624. {
  625. $referenceMapNormalized = array();
  626. foreach ($this->_referenceMap as $rule => $map) {
  627. $referenceMapNormalized[$rule] = array();
  628. foreach ($map as $key => $value) {
  629. switch ($key) {
  630. // normalize COLUMNS and REF_COLUMNS to arrays
  631. case self::COLUMNS:
  632. case self::REF_COLUMNS:
  633. if (!is_array($value)) {
  634. $referenceMapNormalized[$rule][$key] = array($value);
  635. } else {
  636. $referenceMapNormalized[$rule][$key] = $value;
  637. }
  638. break;
  639. // other values are copied as-is
  640. default:
  641. $referenceMapNormalized[$rule][$key] = $value;
  642. break;
  643. }
  644. }
  645. }
  646. return $referenceMapNormalized;
  647. }
  648. /**
  649. * Initialize object
  650. *
  651. * Called from {@link __construct()} as final step of object instantiation.
  652. *
  653. * @return void
  654. */
  655. public function init()
  656. {
  657. }
  658. /**
  659. * Returns table information.
  660. *
  661. * You can elect to return only a part of this information by supplying its key name,
  662. * otherwise all information is returned as an array.
  663. *
  664. * @param $key The specific info part to return OPTIONAL
  665. * @return mixed
  666. */
  667. public function info($key = null)
  668. {
  669. $info = array(
  670. self::SCHEMA => $this->_schema,
  671. self::NAME => $this->_name,
  672. self::COLS => (array) $this->_cols,
  673. self::PRIMARY => (array) $this->_primary,
  674. self::METADATA => $this->_metadata,
  675. self::ROW_CLASS => $this->_rowClass,
  676. self::ROWSET_CLASS => $this->_rowsetClass,
  677. self::REFERENCE_MAP => $this->_referenceMap,
  678. self::DEPENDENT_TABLES => $this->_dependentTables,
  679. self::SEQUENCE => $this->_sequence
  680. );
  681. if ($key === null) {
  682. return $info;
  683. }
  684. if (!array_key_exists($key, $info)) {
  685. require_once 'Zend/Db/Table/Exception.php';
  686. throw new Zend_Db_Table_Exception('There is no table information for the key "' . $key . '"');
  687. }
  688. return $info[$key];
  689. }
  690. /**
  691. * Returns an instance of a Zend_Db_Table_Select object.
  692. *
  693. * @return Zend_Db_Table_Select
  694. */
  695. public function select()
  696. {
  697. require_once 'Zend/Db/Table/Select.php';
  698. return new Zend_Db_Table_Select($this);
  699. }
  700. /**
  701. * Inserts a new row.
  702. *
  703. * @param array $data Column-value pairs.
  704. * @return mixed The primary key of the row inserted.
  705. */
  706. public function insert(array $data)
  707. {
  708. /**
  709. * Zend_Db_Table assumes that if you have a compound primary key
  710. * and one of the columns in the key uses a sequence,
  711. * it's the _first_ column in the compound key.
  712. */
  713. $primary = (array) $this->_primary;
  714. $pkIdentity = $primary[(int)$this->_identity];
  715. /**
  716. * If this table uses a database sequence object and the data does not
  717. * specify a value, then get the next ID from the sequence and add it
  718. * to the row. We assume that only the first column in a compound
  719. * primary key takes a value from a sequence.
  720. */
  721. if (is_string($this->_sequence) && !isset($data[$pkIdentity])) {
  722. $data[$pkIdentity] = $this->_db->nextSequenceId($this->_sequence);
  723. }
  724. /**
  725. * If the primary key can be generated automatically, and no value was
  726. * specified in the user-supplied data, then omit it from the tuple.
  727. */
  728. if (array_key_exists($pkIdentity, $data) && $data[$pkIdentity] === null) {
  729. unset($data[$pkIdentity]);
  730. }
  731. /**
  732. * INSERT the new row.
  733. */
  734. $tableSpec = ($this->_schema ? $this->_schema . '.' : '') . $this->_name;
  735. $this->_db->insert($tableSpec, $data);
  736. /**
  737. * Fetch the most recent ID generated by an auto-increment
  738. * or IDENTITY column, unless the user has specified a value,
  739. * overriding the auto-increment mechanism.
  740. */
  741. if ($this->_sequence === true && !isset($data[$pkIdentity])) {
  742. $data[$pkIdentity] = $this->_db->lastInsertId();
  743. }
  744. /**
  745. * Return the primary key value if the PK is a single column,
  746. * else return an associative array of the PK column/value pairs.
  747. */
  748. $pkData = array_intersect_key($data, array_flip($primary));
  749. if (count($primary) == 1) {
  750. reset($pkData);
  751. return current($pkData);
  752. }
  753. return $pkData;
  754. }
  755. /**
  756. * Updates existing rows.
  757. *
  758. * @param array $data Column-value pairs.
  759. * @param array|string $where An SQL WHERE clause, or an array of SQL WHERE clauses.
  760. * @return int The number of rows updated.
  761. */
  762. public function update(array $data, $where)
  763. {
  764. $tableSpec = ($this->_schema ? $this->_schema . '.' : '') . $this->_name;
  765. return $this->_db->update($tableSpec, $data, $where);
  766. }
  767. /**
  768. * Called by a row object for the parent table's class during save() method.
  769. *
  770. * @param string $parentTableClassname
  771. * @param array $oldPrimaryKey
  772. * @param array $newPrimaryKey
  773. * @return int
  774. */
  775. public function _cascadeUpdate($parentTableClassname, array $oldPrimaryKey, array $newPrimaryKey)
  776. {
  777. $rowsAffected = 0;
  778. foreach ($this->_getReferenceMapNormalized() as $map) {
  779. if ($map[self::REF_TABLE_CLASS] == $parentTableClassname && isset($map[self::ON_UPDATE])) {
  780. switch ($map[self::ON_UPDATE]) {
  781. case self::CASCADE:
  782. $newRefs = array();
  783. for ($i = 0; $i < count($map[self::COLUMNS]); ++$i) {
  784. $col = $this->_db->foldCase($map[self::COLUMNS][$i]);
  785. $refCol = $this->_db->foldCase($map[self::REF_COLUMNS][$i]);
  786. if (array_key_exists($refCol, $newPrimaryKey)) {
  787. $newRefs[$col] = $newPrimaryKey[$refCol];
  788. }
  789. $type = $this->_metadata[$col]['DATA_TYPE'];
  790. $where[] = $this->_db->quoteInto(
  791. $this->_db->quoteIdentifier($col, true) . ' = ?',
  792. $oldPrimaryKey[$refCol], $type);
  793. }
  794. $rowsAffected += $this->update($newRefs, $where);
  795. break;
  796. default:
  797. // no action
  798. break;
  799. }
  800. }
  801. }
  802. return $rowsAffected;
  803. }
  804. /**
  805. * Deletes existing rows.
  806. *
  807. * @param array|string $where SQL WHERE clause(s).
  808. * @return int The number of rows deleted.
  809. */
  810. public function delete($where)
  811. {
  812. $tableSpec = ($this->_schema ? $this->_schema . '.' : '') . $this->_name;
  813. return $this->_db->delete($tableSpec, $where);
  814. }
  815. /**
  816. * Called by parent table's class during delete() method.
  817. *
  818. * @param string $parentTableClassname
  819. * @param array $primaryKey
  820. * @return int Number of affected rows
  821. */
  822. public function _cascadeDelete($parentTableClassname, array $primaryKey)
  823. {
  824. $rowsAffected = 0;
  825. foreach ($this->_getReferenceMapNormalized() as $map) {
  826. if ($map[self::REF_TABLE_CLASS] == $parentTableClassname && isset($map[self::ON_DELETE])) {
  827. switch ($map[self::ON_DELETE]) {
  828. case self::CASCADE:
  829. for ($i = 0; $i < count($map[self::COLUMNS]); ++$i) {
  830. $col = $this->_db->foldCase($map[self::COLUMNS][$i]);
  831. $refCol = $this->_db->foldCase($map[self::REF_COLUMNS][$i]);
  832. $type = $this->_metadata[$col]['DATA_TYPE'];
  833. $where[] = $this->_db->quoteInto(
  834. $this->_db->quoteIdentifier($col, true) . ' = ?',
  835. $primaryKey[$refCol], $type);
  836. }
  837. $rowsAffected += $this->delete($where);
  838. break;
  839. default:
  840. // no action
  841. break;
  842. }
  843. }
  844. }
  845. return $rowsAffected;
  846. }
  847. /**
  848. * Fetches rows by primary key. The argument specifies one or more primary
  849. * key value(s). To find multiple rows by primary key, the argument must
  850. * be an array.
  851. *
  852. * This method accepts a variable number of arguments. If the table has a
  853. * multi-column primary key, the number of arguments must be the same as
  854. * the number of columns in the primary key. To find multiple rows in a
  855. * table with a multi-column primary key, each argument must be an array
  856. * with the same number of elements.
  857. *
  858. * The find() method always returns a Rowset object, even if only one row
  859. * was found.
  860. *
  861. * @param mixed $key The value(s) of the primary keys.
  862. * @return Zend_Db_Table_Rowset_Abstract Row(s) matching the criteria.
  863. * @throws Zend_Db_Table_Exception
  864. */
  865. public function find()
  866. {
  867. $args = func_get_args();
  868. $keyNames = array_values((array) $this->_primary);
  869. if (count($args) < count($keyNames)) {
  870. require_once 'Zend/Db/Table/Exception.php';
  871. throw new Zend_Db_Table_Exception("Too few columns for the primary key");
  872. }
  873. if (count($args) > count($keyNames)) {
  874. require_once 'Zend/Db/Table/Exception.php';
  875. throw new Zend_Db_Table_Exception("Too many columns for the primary key");
  876. }
  877. $whereList = array();
  878. $numberTerms = 0;
  879. foreach ($args as $keyPosition => $keyValues) {
  880. // Coerce the values to an array.
  881. // Don't simply typecast to array, because the values
  882. // might be Zend_Db_Expr objects.
  883. if (!is_array($keyValues)) {
  884. $keyValues = array($keyValues);
  885. }
  886. if ($numberTerms == 0) {
  887. $numberTerms = count($keyValues);
  888. } else if (count($keyValues) != $numberTerms) {
  889. require_once 'Zend/Db/Table/Exception.php';
  890. throw new Zend_Db_Table_Exception("Missing value(s) for the primary key");
  891. }
  892. for ($i = 0; $i < count($keyValues); ++$i) {
  893. if (!isset($whereList[$i])) {
  894. $whereList[$i] = array();
  895. }
  896. $whereList[$i][$keyPosition] = $keyValues[$i];
  897. }
  898. }
  899. $whereClause = null;
  900. if (count($whereList)) {
  901. $whereOrTerms = array();
  902. foreach ($whereList as $keyValueSets) {
  903. $whereAndTerms = array();
  904. foreach ($keyValueSets as $keyPosition => $keyValue) {
  905. $type = $this->_metadata[$keyNames[$keyPosition]]['DATA_TYPE'];
  906. $tableName = $this->_db->quoteTableAs($this->_name);
  907. $columnName = $this->_db->quoteIdentifier($keyNames[$keyPosition], true);
  908. $whereAndTerms[] = $this->_db->quoteInto(
  909. $tableName . '.' . $columnName . ' = ?',
  910. $keyValue, $type);
  911. }
  912. $whereOrTerms[] = '(' . implode(' AND ', $whereAndTerms) . ')';
  913. }
  914. $whereClause = '(' . implode(' OR ', $whereOrTerms) . ')';
  915. }
  916. return $this->fetchAll($whereClause);
  917. }
  918. /**
  919. * Fetches all rows.
  920. *
  921. * Honors the Zend_Db_Adapter fetch mode.
  922. *
  923. * @param string|array|Zend_Db_Table_Select $where OPTIONAL An SQL WHERE clause or Zend_Db_Table_Select object.
  924. * @param string|array $order OPTIONAL An SQL ORDER clause.
  925. * @param int $count OPTIONAL An SQL LIMIT count.
  926. * @param int $offset OPTIONAL An SQL LIMIT offset.
  927. * @return Zend_Db_Table_Rowset_Abstract The row results per the Zend_Db_Adapter fetch mode.
  928. */
  929. public function fetchAll($where = null, $order = null, $count = null, $offset = null)
  930. {
  931. if (!($where instanceof Zend_Db_Table_Select)) {
  932. $select = $this->select();
  933. if ($where !== null) {
  934. $this->_where($select, $where);
  935. }
  936. if ($order !== null) {
  937. $this->_order($select, $order);
  938. }
  939. if ($count !== null || $offset !== null) {
  940. $select->limit($count, $offset);
  941. }
  942. } else {
  943. $select = $where;
  944. }
  945. $rows = $this->_fetch($select);
  946. $data = array(
  947. 'table' => $this,
  948. 'data' => $rows,
  949. 'readOnly' => $select->isReadOnly(),
  950. 'rowClass' => $this->_rowClass,
  951. 'stored' => true
  952. );
  953. @Zend_Loader::loadClass($this->_rowsetClass);
  954. return new $this->_rowsetClass($data);
  955. }
  956. /**
  957. * Fetches one row in an object of type Zend_Db_Table_Row_Abstract,
  958. * or returns Boolean false if no row matches the specified criteria.
  959. *
  960. * @param string|array|Zend_Db_Table_Select $where OPTIONAL An SQL WHERE clause or Zend_Db_Table_Select object.
  961. * @param string|array $order OPTIONAL An SQL ORDER clause.
  962. * @return Zend_Db_Table_Row_Abstract The row results per the
  963. * Zend_Db_Adapter fetch mode, or null if no row found.
  964. */
  965. public function fetchRow($where = null, $order = null)
  966. {
  967. if (!($where instanceof Zend_Db_Table_Select)) {
  968. $select = $this->select();
  969. if ($where !== null) {
  970. $this->_where($select, $where);
  971. }
  972. if ($order !== null) {
  973. $this->_order($select, $order);
  974. }
  975. $select->limit(1);
  976. } else {
  977. $select = $where->limit(1);
  978. }
  979. $rows = $this->_fetch($select);
  980. if (count($rows) == 0) {
  981. return null;
  982. }
  983. $data = array(
  984. 'table' => $this,
  985. 'data' => $rows[0],
  986. 'readOnly' => $select->isReadOnly(),
  987. 'stored' => true
  988. );
  989. @Zend_Loader::loadClass($this->_rowClass);
  990. return new $this->_rowClass($data);
  991. }
  992. /**
  993. * Fetches a new blank row (not from the database).
  994. *
  995. * @return Zend_Db_Table_Row_Abstract
  996. * @deprecated since 0.9.3 - use createRow() instead.
  997. */
  998. public function fetchNew()
  999. {
  1000. return $this->createRow();
  1001. }
  1002. /**
  1003. * Fetches a new blank row (not from the database).
  1004. *
  1005. * @param array $data OPTIONAL data to populate in the new row.
  1006. * @return Zend_Db_Table_Row_Abstract
  1007. */
  1008. public function createRow(array $data = array())
  1009. {
  1010. $defaults = array_combine($this->_cols, array_fill(0, count($this->_cols), null));
  1011. $data = array_intersect_key($data, $defaults);
  1012. $config = array(
  1013. 'table' => $this,
  1014. 'data' => $defaults,
  1015. 'readOnly' => false,
  1016. 'stored' => false
  1017. );
  1018. @Zend_Loader::loadClass($this->_rowClass);
  1019. $row = new $this->_rowClass($config);
  1020. $row->setFromArray($data);
  1021. return $row;
  1022. }
  1023. /**
  1024. * Generate WHERE clause from user-supplied string or array
  1025. *
  1026. * @param string|array $where OPTIONAL An SQL WHERE clause.
  1027. * @return Zend_Db_Table_Select
  1028. */
  1029. protected function _where(Zend_Db_Table_Select $select, $where)
  1030. {
  1031. $where = (array) $where;
  1032. foreach ($where as $key => $val) {
  1033. // is $key an int?
  1034. if (is_int($key)) {
  1035. // $val is the full condition
  1036. $select->where($val);
  1037. } else {
  1038. // $key is the condition with placeholder,
  1039. // and $val is quoted into the condition
  1040. $select->where($key, $val);
  1041. }
  1042. }
  1043. return $select;
  1044. }
  1045. /**
  1046. * Generate ORDER clause from user-supplied string or array
  1047. *
  1048. * @param string|array $order OPTIONAL An SQL ORDER clause.
  1049. * @return Zend_Db_Table_Select
  1050. */
  1051. protected function _order(Zend_Db_Table_Select $select, $order)
  1052. {
  1053. if (!is_array($order)) {
  1054. $order = array($order);
  1055. }
  1056. foreach ($order as $val) {
  1057. $select->order($val);
  1058. }
  1059. return $select;
  1060. }
  1061. /**
  1062. * Support method for fetching rows.
  1063. *
  1064. * @param Zend_Db_Table_Select $select query options.
  1065. * @return array An array containing the row results in FETCH_ASSOC mode.
  1066. */
  1067. protected function _fetch(Zend_Db_Table_Select $select)
  1068. {
  1069. $stmt = $this->_db->query($select);
  1070. $data = $stmt->fetchAll(Zend_Db::FETCH_ASSOC);
  1071. return $data;
  1072. }
  1073. }