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

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