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-2010 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 23657 2011-01-22 16:01:47Z ralph $
21: */
22:
23: /**
24: * @see Zend_Db_Adapter_Abstract
25: */
26: require_once 'Zend/Db/Adapter/Abstract.php';
27:
28: /**
29: * @see Zend_Db_Adapter_Abstract
30: */
31: require_once 'Zend/Db/Select.php';
32:
33: /**
34: * @see Zend_Db
35: */
36: require_once 'Zend/Db.php';
37:
38: /**
39: * Class for SQL table interface.
40: *
41: * @category Zend
42: * @package Zend_Db
43: * @subpackage Table
44: * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
45: * @license http://framework.zend.com/license/new-bsd New BSD License
46: */
47: abstract class Zend_Db_Table_Abstract
48: {
49:
50: const ADAPTER = 'db';
51: const DEFINITION = 'definition';
52: const DEFINITION_CONFIG_NAME = 'definitionConfigName';
53: const SCHEMA = 'schema';
54: const NAME = 'name';
55: const PRIMARY = 'primary';
56: const COLS = 'cols';
57: const METADATA = 'metadata';
58: const METADATA_CACHE = 'metadataCache';
59: const METADATA_CACHE_IN_CLASS = 'metadataCacheInClass';
60: const ROW_CLASS = 'rowClass';
61: const ROWSET_CLASS = 'rowsetClass';
62: const REFERENCE_MAP = 'referenceMap';
63: const DEPENDENT_TABLES = 'dependentTables';
64: const SEQUENCE = 'sequence';
65:
66: const COLUMNS = 'columns';
67: const REF_TABLE_CLASS = 'refTableClass';
68: const REF_COLUMNS = 'refColumns';
69: const ON_DELETE = 'onDelete';
70: const ON_UPDATE = 'onUpdate';
71:
72: const CASCADE = 'cascade';
73: const RESTRICT = 'restrict';
74: const SET_NULL = 'setNull';
75:
76: const DEFAULT_NONE = 'defaultNone';
77: const DEFAULT_CLASS = 'defaultClass';
78: const DEFAULT_DB = 'defaultDb';
79:
80: const SELECT_WITH_FROM_PART = true;
81: const SELECT_WITHOUT_FROM_PART = false;
82:
83: /**
84: * Default Zend_Db_Adapter_Abstract object.
85: *
86: * @var Zend_Db_Adapter_Abstract
87: */
88: protected static $_defaultDb;
89:
90: /**
91: * Optional Zend_Db_Table_Definition object
92: *
93: * @var unknown_type
94: */
95: protected $_definition = null;
96:
97: /**
98: * Optional definition config name used in concrete implementation
99: *
100: * @var string
101: */
102: protected $_definitionConfigName = null;
103:
104: /**
105: * Default cache for information provided by the adapter's describeTable() method.
106: *
107: * @var Zend_Cache_Core
108: */
109: protected static $_defaultMetadataCache = null;
110:
111: /**
112: * Zend_Db_Adapter_Abstract object.
113: *
114: * @var Zend_Db_Adapter_Abstract
115: */
116: protected $_db;
117:
118: /**
119: * The schema name (default null means current schema)
120: *
121: * @var array
122: */
123: protected $_schema = null;
124:
125: /**
126: * The table name.
127: *
128: * @var string
129: */
130: protected $_name = null;
131:
132: /**
133: * The table column names derived from Zend_Db_Adapter_Abstract::describeTable().
134: *
135: * @var array
136: */
137: protected $_cols;
138:
139: /**
140: * The primary key column or columns.
141: * A compound key should be declared as an array.
142: * You may declare a single-column primary key
143: * as a string.
144: *
145: * @var mixed
146: */
147: protected $_primary = null;
148:
149: /**
150: * If your primary key is a compound key, and one of the columns uses
151: * an auto-increment or sequence-generated value, set _identity
152: * to the ordinal index in the $_primary array for that column.
153: * Note this index is the position of the column in the primary key,
154: * not the position of the column in the table. The primary key
155: * array is 1-based.
156: *
157: * @var integer
158: */
159: protected $_identity = 1;
160:
161: /**
162: * Define the logic for new values in the primary key.
163: * May be a string, boolean true, or boolean false.
164: *
165: * @var mixed
166: */
167: protected $_sequence = true;
168:
169: /**
170: * Information provided by the adapter's describeTable() method.
171: *
172: * @var array
173: */
174: protected $_metadata = array();
175:
176: /**
177: * Cache for information provided by the adapter's describeTable() method.
178: *
179: * @var Zend_Cache_Core
180: */
181: protected $_metadataCache = null;
182:
183: /**
184: * Flag: whether or not to cache metadata in the class
185: * @var bool
186: */
187: protected $_metadataCacheInClass = true;
188:
189: /**
190: * Classname for row
191: *
192: * @var string
193: */
194: protected $_rowClass = 'Zend_Db_Table_Row';
195:
196: /**
197: * Classname for rowset
198: *
199: * @var string
200: */
201: protected $_rowsetClass = 'Zend_Db_Table_Rowset';
202:
203: /**
204: * Associative array map of declarative referential integrity rules.
205: * This array has one entry per foreign key in the current table.
206: * Each key is a mnemonic name for one reference rule.
207: *
208: * Each value is also an associative array, with the following keys:
209: * - columns = array of names of column(s) in the child table.
210: * - refTableClass = class name of the parent table.
211: * - refColumns = array of names of column(s) in the parent table,
212: * in the same order as those in the 'columns' entry.
213: * - onDelete = "cascade" means that a delete in the parent table also
214: * causes a delete of referencing rows in the child table.
215: * - onUpdate = "cascade" means that an update of primary key values in
216: * the parent table also causes an update of referencing
217: * rows in the child table.
218: *
219: * @var array
220: */
221: protected $_referenceMap = array();
222:
223: /**
224: * Simple array of class names of tables that are "children" of the current
225: * table, in other words tables that contain a foreign key to this one.
226: * Array elements are not table names; they are class names of classes that
227: * extend Zend_Db_Table_Abstract.
228: *
229: * @var array
230: */
231: protected $_dependentTables = array();
232:
233:
234: protected $_defaultSource = self::DEFAULT_NONE;
235: protected $_defaultValues = array();
236:
237: /**
238: * Constructor.
239: *
240: * Supported params for $config are:
241: * - db = user-supplied instance of database connector,
242: * or key name of registry instance.
243: * - name = table name.
244: * - primary = string or array of primary key(s).
245: * - rowClass = row class name.
246: * - rowsetClass = rowset class name.
247: * - referenceMap = array structure to declare relationship
248: * to parent tables.
249: * - dependentTables = array of child tables.
250: * - metadataCache = cache for information from adapter describeTable().
251: *
252: * @param mixed $config Array of user-specified config options, or just the Db Adapter.
253: * @return void
254: */
255: public function __construct($config = array())
256: {
257: /**
258: * Allow a scalar argument to be the Adapter object or Registry key.
259: */
260: if (!is_array($config)) {
261: $config = array(self::ADAPTER => $config);
262: }
263:
264: if ($config) {
265: $this->setOptions($config);
266: }
267:
268: $this->_setup();
269: $this->init();
270: }
271:
272: /**
273: * setOptions()
274: *
275: * @param array $options
276: * @return Zend_Db_Table_Abstract
277: */
278: public function setOptions(Array $options)
279: {
280: foreach ($options as $key => $value) {
281: switch ($key) {
282: case self::ADAPTER:
283: $this->_setAdapter($value);
284: break;
285: case self::DEFINITION:
286: $this->setDefinition($value);
287: break;
288: case self::DEFINITION_CONFIG_NAME:
289: $this->setDefinitionConfigName($value);
290: break;
291: case self::SCHEMA:
292: $this->_schema = (string) $value;
293: break;
294: case self::NAME:
295: $this->_name = (string) $value;
296: break;
297: case self::PRIMARY:
298: $this->_primary = (array) $value;
299: break;
300: case self::ROW_CLASS:
301: $this->setRowClass($value);
302: break;
303: case self::ROWSET_CLASS:
304: $this->setRowsetClass($value);
305: break;
306: case self::REFERENCE_MAP:
307: $this->setReferences($value);
308: break;
309: case self::DEPENDENT_TABLES:
310: $this->setDependentTables($value);
311: break;
312: case self::METADATA_CACHE:
313: $this->_setMetadataCache($value);
314: break;
315: case self::METADATA_CACHE_IN_CLASS:
316: $this->setMetadataCacheInClass($value);
317: break;
318: case self::SEQUENCE:
319: $this->_setSequence($value);
320: break;
321: default:
322: // ignore unrecognized configuration directive
323: break;
324: }
325: }
326:
327: return $this;
328: }
329:
330: /**
331: * setDefinition()
332: *
333: * @param Zend_Db_Table_Definition $definition
334: * @return Zend_Db_Table_Abstract
335: */
336: public function setDefinition(Zend_Db_Table_Definition $definition)
337: {
338: $this->_definition = $definition;
339: return $this;
340: }
341:
342: /**
343: * getDefinition()
344: *
345: * @return Zend_Db_Table_Definition|null
346: */
347: public function getDefinition()
348: {
349: return $this->_definition;
350: }
351:
352: /**
353: * setDefinitionConfigName()
354: *
355: * @param string $definition
356: * @return Zend_Db_Table_Abstract
357: */
358: public function setDefinitionConfigName($definitionConfigName)
359: {
360: $this->_definitionConfigName = $definitionConfigName;
361: return $this;
362: }
363:
364: /**
365: * getDefinitionConfigName()
366: *
367: * @return string
368: */
369: public function getDefinitionConfigName()
370: {
371: return $this->_definitionConfigName;
372: }
373:
374: /**
375: * @param string $classname
376: * @return Zend_Db_Table_Abstract Provides a fluent interface
377: */
378: public function setRowClass($classname)
379: {
380: $this->_rowClass = (string) $classname;
381:
382: return $this;
383: }
384:
385: /**
386: * @return string
387: */
388: public function getRowClass()
389: {
390: return $this->_rowClass;
391: }
392:
393: /**
394: * @param string $classname
395: * @return Zend_Db_Table_Abstract Provides a fluent interface
396: */
397: public function setRowsetClass($classname)
398: {
399: $this->_rowsetClass = (string) $classname;
400:
401: return $this;
402: }
403:
404: /**
405: * @return string
406: */
407: public function getRowsetClass()
408: {
409: return $this->_rowsetClass;
410: }
411:
412: /**
413: * Add a reference to the reference map
414: *
415: * @param string $ruleKey
416: * @param string|array $columns
417: * @param string $refTableClass
418: * @param string|array $refColumns
419: * @param string $onDelete
420: * @param string $onUpdate
421: * @return Zend_Db_Table_Abstract
422: */
423: public function addReference($ruleKey, $columns, $refTableClass, $refColumns,
424: $onDelete = null, $onUpdate = null)
425: {
426: $reference = array(self::COLUMNS => (array) $columns,
427: self::REF_TABLE_CLASS => $refTableClass,
428: self::REF_COLUMNS => (array) $refColumns);
429:
430: if (!empty($onDelete)) {
431: $reference[self::ON_DELETE] = $onDelete;
432: }
433:
434: if (!empty($onUpdate)) {
435: $reference[self::ON_UPDATE] = $onUpdate;
436: }
437:
438: $this->_referenceMap[$ruleKey] = $reference;
439:
440: return $this;
441: }
442:
443: /**
444: * @param array $referenceMap
445: * @return Zend_Db_Table_Abstract Provides a fluent interface
446: */
447: public function setReferences(array $referenceMap)
448: {
449: $this->_referenceMap = $referenceMap;
450:
451: return $this;
452: }
453:
454: /**
455: * @param string $tableClassname
456: * @param string $ruleKey OPTIONAL
457: * @return array
458: * @throws Zend_Db_Table_Exception
459: */
460: public function getReference($tableClassname, $ruleKey = null)
461: {
462: $thisClass = get_class($this);
463: if ($thisClass === 'Zend_Db_Table') {
464: $thisClass = $this->_definitionConfigName;
465: }
466: $refMap = $this->_getReferenceMapNormalized();
467: if ($ruleKey !== null) {
468: if (!isset($refMap[$ruleKey])) {
469: require_once "Zend/Db/Table/Exception.php";
470: throw new Zend_Db_Table_Exception("No reference rule \"$ruleKey\" from table $thisClass to table $tableClassname");
471: }
472: if ($refMap[$ruleKey][self::REF_TABLE_CLASS] != $tableClassname) {
473: require_once "Zend/Db/Table/Exception.php";
474: throw new Zend_Db_Table_Exception("Reference rule \"$ruleKey\" does not reference table $tableClassname");
475: }
476: return $refMap[$ruleKey];
477: }
478: foreach ($refMap as $reference) {
479: if ($reference[self::REF_TABLE_CLASS] == $tableClassname) {
480: return $reference;
481: }
482: }
483: require_once "Zend/Db/Table/Exception.php";
484: throw new Zend_Db_Table_Exception("No reference from table $thisClass to table $tableClassname");
485: }
486:
487: /**
488: * @param array $dependentTables
489: * @return Zend_Db_Table_Abstract Provides a fluent interface
490: */
491: public function setDependentTables(array $dependentTables)
492: {
493: $this->_dependentTables = $dependentTables;
494:
495: return $this;
496: }
497:
498: /**
499: * @return array
500: */
501: public function getDependentTables()
502: {
503: return $this->_dependentTables;
504: }
505:
506: /**
507: * set the defaultSource property - this tells the table class where to find default values
508: *
509: * @param string $defaultSource
510: * @return Zend_Db_Table_Abstract
511: */
512: public function setDefaultSource($defaultSource = self::DEFAULT_NONE)
513: {
514: if (!in_array($defaultSource, array(self::DEFAULT_CLASS, self::DEFAULT_DB, self::DEFAULT_NONE))) {
515: $defaultSource = self::DEFAULT_NONE;
516: }
517:
518: $this->_defaultSource = $defaultSource;
519: return $this;
520: }
521:
522: /**
523: * returns the default source flag that determines where defaultSources come from
524: *
525: * @return unknown
526: */
527: public function getDefaultSource()
528: {
529: return $this->_defaultSource;
530: }
531:
532: /**
533: * set the default values for the table class
534: *
535: * @param array $defaultValues
536: * @return Zend_Db_Table_Abstract
537: */
538: public function setDefaultValues(Array $defaultValues)
539: {
540: foreach ($defaultValues as $defaultName => $defaultValue) {
541: if (array_key_exists($defaultName, $this->_metadata)) {
542: $this->_defaultValues[$defaultName] = $defaultValue;
543: }
544: }
545: return $this;
546: }
547:
548: public function getDefaultValues()
549: {
550: return $this->_defaultValues;
551: }
552:
553:
554: /**
555: * Sets the default Zend_Db_Adapter_Abstract for all Zend_Db_Table objects.
556: *
557: * @param mixed $db Either an Adapter object, or a string naming a Registry key
558: * @return void
559: */
560: public static function setDefaultAdapter($db = null)
561: {
562: self::$_defaultDb = self::_setupAdapter($db);
563: }
564:
565: /**
566: * Gets the default Zend_Db_Adapter_Abstract for all Zend_Db_Table objects.
567: *
568: * @return Zend_Db_Adapter_Abstract or null
569: */
570: public static function getDefaultAdapter()
571: {
572: return self::$_defaultDb;
573: }
574:
575: /**
576: * @param mixed $db Either an Adapter object, or a string naming a Registry key
577: * @return Zend_Db_Table_Abstract Provides a fluent interface
578: */
579: protected function _setAdapter($db)
580: {
581: $this->_db = self::_setupAdapter($db);
582: return $this;
583: }
584:
585: /**
586: * Gets the Zend_Db_Adapter_Abstract for this particular Zend_Db_Table object.
587: *
588: * @return Zend_Db_Adapter_Abstract
589: */
590: public function getAdapter()
591: {
592: return $this->_db;
593: }
594:
595: /**
596: * @param mixed $db Either an Adapter object, or a string naming a Registry key
597: * @return Zend_Db_Adapter_Abstract
598: * @throws Zend_Db_Table_Exception
599: */
600: protected static function _setupAdapter($db)
601: {
602: if ($db === null) {
603: return null;
604: }
605: if (is_string($db)) {
606: require_once 'Zend/Registry.php';
607: $db = Zend_Registry::get($db);
608: }
609: if (!$db instanceof Zend_Db_Adapter_Abstract) {
610: require_once 'Zend/Db/Table/Exception.php';
611: 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');
612: }
613: return $db;
614: }
615:
616: /**
617: * Sets the default metadata cache for information returned by Zend_Db_Adapter_Abstract::describeTable().
618: *
619: * If $defaultMetadataCache is null, then no metadata cache is used by default.
620: *
621: * @param mixed $metadataCache Either a Cache object, or a string naming a Registry key
622: * @return void
623: */
624: public static function setDefaultMetadataCache($metadataCache = null)
625: {
626: self::$_defaultMetadataCache = self::_setupMetadataCache($metadataCache);
627: }
628:
629: /**
630: * Gets the default metadata cache for information returned by Zend_Db_Adapter_Abstract::describeTable().
631: *
632: * @return Zend_Cache_Core or null
633: */
634: public static function getDefaultMetadataCache()
635: {
636: return self::$_defaultMetadataCache;
637: }
638:
639: /**
640: * Sets the metadata cache for information returned by Zend_Db_Adapter_Abstract::describeTable().
641: *
642: * If $metadataCache is null, then no metadata cache is used. Since there is no opportunity to reload metadata
643: * after instantiation, this method need not be public, particularly because that it would have no effect
644: * results in unnecessary API complexity. To configure the metadata cache, use the metadataCache configuration
645: * option for the class constructor upon instantiation.
646: *
647: * @param mixed $metadataCache Either a Cache object, or a string naming a Registry key
648: * @return Zend_Db_Table_Abstract Provides a fluent interface
649: */
650: protected function _setMetadataCache($metadataCache)
651: {
652: $this->_metadataCache = self::_setupMetadataCache($metadataCache);
653: return $this;
654: }
655:
656: /**
657: * Gets the metadata cache for information returned by Zend_Db_Adapter_Abstract::describeTable().
658: *
659: * @return Zend_Cache_Core or null
660: */
661: public function getMetadataCache()
662: {
663: return $this->_metadataCache;
664: }
665:
666: /**
667: * Indicate whether metadata should be cached in the class for the duration
668: * of the instance
669: *
670: * @param bool $flag
671: * @return Zend_Db_Table_Abstract
672: */
673: public function setMetadataCacheInClass($flag)
674: {
675: $this->_metadataCacheInClass = (bool) $flag;
676: return $this;
677: }
678:
679: /**
680: * Retrieve flag indicating if metadata should be cached for duration of
681: * instance
682: *
683: * @return bool
684: */
685: public function metadataCacheInClass()
686: {
687: return $this->_metadataCacheInClass;
688: }
689:
690: /**
691: * @param mixed $metadataCache Either a Cache object, or a string naming a Registry key
692: * @return Zend_Cache_Core
693: * @throws Zend_Db_Table_Exception
694: */
695: protected static function _setupMetadataCache($metadataCache)
696: {
697: if ($metadataCache === null) {
698: return null;
699: }
700: if (is_string($metadataCache)) {
701: require_once 'Zend/Registry.php';
702: $metadataCache = Zend_Registry::get($metadataCache);
703: }
704: if (!$metadataCache instanceof Zend_Cache_Core) {
705: require_once 'Zend/Db/Table/Exception.php';
706: 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');
707: }
708: return $metadataCache;
709: }
710:
711: /**
712: * Sets the sequence member, which defines the behavior for generating
713: * primary key values in new rows.
714: * - If this is a string, then the string names the sequence object.
715: * - If this is boolean true, then the key uses an auto-incrementing
716: * or identity mechanism.
717: * - If this is boolean false, then the key is user-defined.
718: * Use this for natural keys, for example.
719: *
720: * @param mixed $sequence
721: * @return Zend_Db_Table_Adapter_Abstract Provides a fluent interface
722: */
723: protected function _setSequence($sequence)
724: {
725: $this->_sequence = $sequence;
726:
727: return $this;
728: }
729:
730: /**
731: * Turnkey for initialization of a table object.
732: * Calls other protected methods for individual tasks, to make it easier
733: * for a subclass to override part of the setup logic.
734: *
735: * @return void
736: */
737: protected function _setup()
738: {
739: $this->_setupDatabaseAdapter();
740: $this->_setupTableName();
741: }
742:
743: /**
744: * Initialize database adapter.
745: *
746: * @return void
747: */
748: protected function _setupDatabaseAdapter()
749: {
750: if (! $this->_db) {
751: $this->_db = self::getDefaultAdapter();
752: if (!$this->_db instanceof Zend_Db_Adapter_Abstract) {
753: require_once 'Zend/Db/Table/Exception.php';
754: throw new Zend_Db_Table_Exception('No adapter found for ' . get_class($this));
755: }
756: }
757: }
758:
759: /**
760: * Initialize table and schema names.
761: *
762: * If the table name is not set in the class definition,
763: * use the class name itself as the table name.
764: *
765: * A schema name provided with the table name (e.g., "schema.table") overrides
766: * any existing value for $this->_schema.
767: *
768: * @return void
769: */
770: protected function _setupTableName()
771: {
772: if (! $this->_name) {
773: $this->_name = get_class($this);
774: } else if (strpos($this->_name, '.')) {
775: list($this->_schema, $this->_name) = explode('.', $this->_name);
776: }
777: }
778:
779: /**
780: * Initializes metadata.
781: *
782: * If metadata cannot be loaded from cache, adapter's describeTable() method is called to discover metadata
783: * information. Returns true if and only if the metadata are loaded from cache.
784: *
785: * @return boolean
786: * @throws Zend_Db_Table_Exception
787: */
788: protected function _setupMetadata()
789: {
790: if ($this->metadataCacheInClass() && (count($this->_metadata) > 0)) {
791: return true;
792: }
793:
794: // Assume that metadata will be loaded from cache
795: $isMetadataFromCache = true;
796:
797: // If $this has no metadata cache but the class has a default metadata cache
798: if (null === $this->_metadataCache && null !== self::$_defaultMetadataCache) {
799: // Make $this use the default metadata cache of the class
800: $this->_setMetadataCache(self::$_defaultMetadataCache);
801: }
802:
803: // If $this has a metadata cache
804: if (null !== $this->_metadataCache) {
805: // Define the cache identifier where the metadata are saved
806:
807: //get db configuration
808: $dbConfig = $this->_db->getConfig();
809:
810: $port = isset($dbConfig['options']['port'])
811: ? ':'.$dbConfig['options']['port']
812: : (isset($dbConfig['port'])
813: ? ':'.$dbConfig['port']
814: : null);
815:
816: $host = isset($dbConfig['options']['host'])
817: ? ':'.$dbConfig['options']['host']
818: : (isset($dbConfig['host'])
819: ? ':'.$dbConfig['host']
820: : null);
821:
822: // Define the cache identifier where the metadata are saved
823: $cacheId = md5( // port:host/dbname:schema.table (based on availabilty)
824: $port . $host . '/'. $dbConfig['dbname'] . ':'
825: . $this->_schema. '.' . $this->_name
826: );
827: }
828:
829: // If $this has no metadata cache or metadata cache misses
830: if (null === $this->_metadataCache || !($metadata = $this->_metadataCache->load($cacheId))) {
831: // Metadata are not loaded from cache
832: $isMetadataFromCache = false;
833: // Fetch metadata from the adapter's describeTable() method
834: $metadata = $this->_db->describeTable($this->_name, $this->_schema);
835: // If $this has a metadata cache, then cache the metadata
836: if (null !== $this->_metadataCache && !$this->_metadataCache->save($metadata, $cacheId)) {
837: trigger_error('Failed saving metadata to metadataCache', E_USER_NOTICE);
838: }
839: }
840:
841: // Assign the metadata to $this
842: $this->_metadata = $metadata;
843:
844: // Return whether the metadata were loaded from cache
845: return $isMetadataFromCache;
846: }
847:
848: /**
849: * Retrieve table columns
850: *
851: * @return array
852: */
853: protected function _getCols()
854: {
855: if (null === $this->_cols) {
856: $this->_setupMetadata();
857: $this->_cols = array_keys($this->_metadata);
858: }
859: return $this->_cols;
860: }
861:
862: /**
863: * Initialize primary key from metadata.
864: * If $_primary is not defined, discover primary keys
865: * from the information returned by describeTable().
866: *
867: * @return void
868: * @throws Zend_Db_Table_Exception
869: */
870: protected function _setupPrimaryKey()
871: {
872: if (!$this->_primary) {
873: $this->_setupMetadata();
874: $this->_primary = array();
875: foreach ($this->_metadata as $col) {
876: if ($col['PRIMARY']) {
877: $this->_primary[ $col['PRIMARY_POSITION'] ] = $col['COLUMN_NAME'];
878: if ($col['IDENTITY']) {
879: $this->_identity = $col['PRIMARY_POSITION'];
880: }
881: }
882: }
883: // if no primary key was specified and none was found in the metadata
884: // then throw an exception.
885: if (empty($this->_primary)) {
886: require_once 'Zend/Db/Table/Exception.php';
887: throw new Zend_Db_Table_Exception('A table must have a primary key, but none was found');
888: }
889: } else if (!is_array($this->_primary)) {
890: $this->_primary = array(1 => $this->_primary);
891: } else if (isset($this->_primary[0])) {
892: array_unshift($this->_primary, null);
893: unset($this->_primary[0]);
894: }
895:
896: $cols = $this->_getCols();
897: if (! array_intersect((array) $this->_primary, $cols) == (array) $this->_primary) {
898: require_once 'Zend/Db/Table/Exception.php';
899: throw new Zend_Db_Table_Exception("Primary key column(s) ("
900: . implode(',', (array) $this->_primary)
901: . ") are not columns in this table ("
902: . implode(',', $cols)
903: . ")");
904: }
905:
906: $primary = (array) $this->_primary;
907: $pkIdentity = $primary[(int) $this->_identity];
908:
909: /**
910: * Special case for PostgreSQL: a SERIAL key implicitly uses a sequence
911: * object whose name is "<table>_<column>_seq".
912: */
913: if ($this->_sequence === true && $this->_db instanceof Zend_Db_Adapter_Pdo_Pgsql) {
914: $this->_sequence = $this->_db->quoteIdentifier("{$this->_name}_{$pkIdentity}_seq");
915: if ($this->_schema) {
916: $this->_sequence = $this->_db->quoteIdentifier($this->_schema) . '.' . $this->_sequence;
917: }
918: }
919: }
920:
921: /**
922: * Returns a normalized version of the reference map
923: *
924: * @return array
925: */
926: protected function _getReferenceMapNormalized()
927: {
928: $referenceMapNormalized = array();
929:
930: foreach ($this->_referenceMap as $rule => $map) {
931:
932: $referenceMapNormalized[$rule] = array();
933:
934: foreach ($map as $key => $value) {
935: switch ($key) {
936:
937: // normalize COLUMNS and REF_COLUMNS to arrays
938: case self::COLUMNS:
939: case self::REF_COLUMNS:
940: if (!is_array($value)) {
941: $referenceMapNormalized[$rule][$key] = array($value);
942: } else {
943: $referenceMapNormalized[$rule][$key] = $value;
944: }
945: break;
946:
947: // other values are copied as-is
948: default:
949: $referenceMapNormalized[$rule][$key] = $value;
950: break;
951: }
952: }
953: }
954:
955: return $referenceMapNormalized;
956: }
957:
958: /**
959: * Initialize object
960: *
961: * Called from {@link __construct()} as final step of object instantiation.
962: *
963: * @return void
964: */
965: public function init()
966: {
967: }
968:
969: /**
970: * Returns table information.
971: *
972: * You can elect to return only a part of this information by supplying its key name,
973: * otherwise all information is returned as an array.
974: *
975: * @param string $key The specific info part to return OPTIONAL
976: * @return mixed
977: */
978: public function info($key = null)
979: {
980: $this->_setupPrimaryKey();
981:
982: $info = array(
983: self::SCHEMA => $this->_schema,
984: self::NAME => $this->_name,
985: self::COLS => $this->_getCols(),
986: self::PRIMARY => (array) $this->_primary,
987: self::METADATA => $this->_metadata,
988: self::ROW_CLASS => $this->getRowClass(),
989: self::ROWSET_CLASS => $this->getRowsetClass(),
990: self::REFERENCE_MAP => $this->_referenceMap,
991: self::DEPENDENT_TABLES => $this->_dependentTables,
992: self::SEQUENCE => $this->_sequence
993: );
994:
995: if ($key === null) {
996: return $info;
997: }
998:
999: if (!array_key_exists($key, $info)) {
1000: require_once 'Zend/Db/Table/Exception.php';
1001: throw new Zend_Db_Table_Exception('There is no table information for the key "' . $key . '"');
1002: }
1003:
1004: return $info[$key];
1005: }
1006:
1007: /**
1008: * Returns an instance of a Zend_Db_Table_Select object.
1009: *
1010: * @param bool $withFromPart Whether or not to include the from part of the select based on the table
1011: * @return Zend_Db_Table_Select
1012: */
1013: public function select($withFromPart = self::SELECT_WITHOUT_FROM_PART)
1014: {
1015: require_once 'Zend/Db/Table/Select.php';
1016: $select = new Zend_Db_Table_Select($this);
1017: if ($withFromPart == self::SELECT_WITH_FROM_PART) {
1018: $select->from($this->info(self::NAME), Zend_Db_Table_Select::SQL_WILDCARD, $this->info(self::SCHEMA));
1019: }
1020: return $select;
1021: }
1022:
1023: /**
1024: * Inserts a new row.
1025: *
1026: * @param array $data Column-value pairs.
1027: * @return mixed The primary key of the row inserted.
1028: */
1029: public function insert(array $data)
1030: {
1031: $this->_setupPrimaryKey();
1032:
1033: /**
1034: * Zend_Db_Table assumes that if you have a compound primary key
1035: * and one of the columns in the key uses a sequence,
1036: * it's the _first_ column in the compound key.
1037: */
1038: $primary = (array) $this->_primary;
1039: $pkIdentity = $primary[(int)$this->_identity];
1040:
1041: /**
1042: * If this table uses a database sequence object and the data does not
1043: * specify a value, then get the next ID from the sequence and add it
1044: * to the row. We assume that only the first column in a compound
1045: * primary key takes a value from a sequence.
1046: */
1047: if (is_string($this->_sequence) && !isset($data[$pkIdentity])) {
1048: $data[$pkIdentity] = $this->_db->nextSequenceId($this->_sequence);
1049: $pkSuppliedBySequence = true;
1050: }
1051:
1052: /**
1053: * If the primary key can be generated automatically, and no value was
1054: * specified in the user-supplied data, then omit it from the tuple.
1055: *
1056: * Note: this checks for sensible values in the supplied primary key
1057: * position of the data. The following values are considered empty:
1058: * null, false, true, '', array()
1059: */
1060: if (!isset($pkSuppliedBySequence) && array_key_exists($pkIdentity, $data)) {
1061: if ($data[$pkIdentity] === null // null
1062: || $data[$pkIdentity] === '' // empty string
1063: || is_bool($data[$pkIdentity]) // boolean
1064: || (is_array($data[$pkIdentity]) && empty($data[$pkIdentity]))) { // empty array
1065: unset($data[$pkIdentity]);
1066: }
1067: }
1068:
1069: /**
1070: * INSERT the new row.
1071: */
1072: $tableSpec = ($this->_schema ? $this->_schema . '.' : '') . $this->_name;
1073: $this->_db->insert($tableSpec, $data);
1074:
1075: /**
1076: * Fetch the most recent ID generated by an auto-increment
1077: * or IDENTITY column, unless the user has specified a value,
1078: * overriding the auto-increment mechanism.
1079: */
1080: if ($this->_sequence === true && !isset($data[$pkIdentity])) {
1081: $data[$pkIdentity] = $this->_db->lastInsertId();
1082: }
1083:
1084: /**
1085: * Return the primary key value if the PK is a single column,
1086: * else return an associative array of the PK column/value pairs.
1087: */
1088: $pkData = array_intersect_key($data, array_flip($primary));
1089: if (count($primary) == 1) {
1090: reset($pkData);
1091: return current($pkData);
1092: }
1093:
1094: return $pkData;
1095: }
1096:
1097: /**
1098: * Check if the provided column is an identity of the table
1099: *
1100: * @param string $column
1101: * @throws Zend_Db_Table_Exception
1102: * @return boolean
1103: */
1104: public function isIdentity($column)
1105: {
1106: $this->_setupPrimaryKey();
1107:
1108: if (!isset($this->_metadata[$column])) {
1109: /**
1110: * @see Zend_Db_Table_Exception
1111: */
1112: require_once 'Zend/Db/Table/Exception.php';
1113:
1114: throw new Zend_Db_Table_Exception('Column "' . $column . '" not found in table.');
1115: }
1116:
1117: return (bool) $this->_metadata[$column]['IDENTITY'];
1118: }
1119:
1120: /**
1121: * Updates existing rows.
1122: *
1123: * @param array $data Column-value pairs.
1124: * @param array|string $where An SQL WHERE clause, or an array of SQL WHERE clauses.
1125: * @return int The number of rows updated.
1126: */
1127: public function update(array $data, $where)
1128: {
1129: $tableSpec = ($this->_schema ? $this->_schema . '.' : '') . $this->_name;
1130: return $this->_db->update($tableSpec, $data, $where);
1131: }
1132:
1133: /**
1134: * Called by a row object for the parent table's class during save() method.
1135: *
1136: * @param string $parentTableClassname
1137: * @param array $oldPrimaryKey
1138: * @param array $newPrimaryKey
1139: * @return int
1140: */
1141: public function _cascadeUpdate($parentTableClassname, array $oldPrimaryKey, array $newPrimaryKey)
1142: {
1143: $this->_setupMetadata();
1144: $rowsAffected = 0;
1145: foreach ($this->_getReferenceMapNormalized() as $map) {
1146: if ($map[self::REF_TABLE_CLASS] == $parentTableClassname && isset($map[self::ON_UPDATE])) {
1147: switch ($map[self::ON_UPDATE]) {
1148: case self::CASCADE:
1149: $newRefs = array();
1150: $where = array();
1151: for ($i = 0; $i < count($map[self::COLUMNS]); ++$i) {
1152: $col = $this->_db->foldCase($map[self::COLUMNS][$i]);
1153: $refCol = $this->_db->foldCase($map[self::REF_COLUMNS][$i]);
1154: if (array_key_exists($refCol, $newPrimaryKey)) {
1155: $newRefs[$col] = $newPrimaryKey[$refCol];
1156: }
1157: $type = $this->_metadata[$col]['DATA_TYPE'];
1158: $where[] = $this->_db->quoteInto(
1159: $this->_db->quoteIdentifier($col, true) . ' = ?',
1160: $oldPrimaryKey[$refCol], $type);
1161: }
1162: $rowsAffected += $this->update($newRefs, $where);
1163: break;
1164: default:
1165: // no action
1166: break;
1167: }
1168: }
1169: }
1170: return $rowsAffected;
1171: }
1172:
1173: /**
1174: * Deletes existing rows.
1175: *
1176: * @param array|string $where SQL WHERE clause(s).
1177: * @return int The number of rows deleted.
1178: */
1179: public function delete($where)
1180: {
1181: $tableSpec = ($this->_schema ? $this->_schema . '.' : '') . $this->_name;
1182: return $this->_db->delete($tableSpec, $where);
1183: }
1184:
1185: /**
1186: * Called by parent table's class during delete() method.
1187: *
1188: * @param string $parentTableClassname
1189: * @param array $primaryKey
1190: * @return int Number of affected rows
1191: */
1192: public function _cascadeDelete($parentTableClassname, array $primaryKey)
1193: {
1194: $this->_setupMetadata();
1195: $rowsAffected = 0;
1196: foreach ($this->_getReferenceMapNormalized() as $map) {
1197: if ($map[self::REF_TABLE_CLASS] == $parentTableClassname && isset($map[self::ON_DELETE])) {
1198: switch ($map[self::ON_DELETE]) {
1199: case self::CASCADE:
1200: $where = array();
1201: for ($i = 0; $i < count($map[self::COLUMNS]); ++$i) {
1202: $col = $this->_db->foldCase($map[self::COLUMNS][$i]);
1203: $refCol = $this->_db->foldCase($map[self::REF_COLUMNS][$i]);
1204: $type = $this->_metadata[$col]['DATA_TYPE'];
1205: $where[] = $this->_db->quoteInto(
1206: $this->_db->quoteIdentifier($col, true) . ' = ?',
1207: $primaryKey[$refCol], $type);
1208: }
1209: $rowsAffected += $this->delete($where);
1210: break;
1211: default:
1212: // no action
1213: break;
1214: }
1215: }
1216: }
1217: return $rowsAffected;
1218: }
1219:
1220: /**
1221: * Fetches rows by primary key. The argument specifies one or more primary
1222: * key value(s). To find multiple rows by primary key, the argument must
1223: * be an array.
1224: *
1225: * This method accepts a variable number of arguments. If the table has a
1226: * multi-column primary key, the number of arguments must be the same as
1227: * the number of columns in the primary key. To find multiple rows in a
1228: * table with a multi-column primary key, each argument must be an array
1229: * with the same number of elements.
1230: *
1231: * The find() method always returns a Rowset object, even if only one row
1232: * was found.
1233: *
1234: * @param mixed $key The value(s) of the primary keys.
1235: * @return Zend_Db_Table_Rowset_Abstract Row(s) matching the criteria.
1236: * @throws Zend_Db_Table_Exception
1237: */
1238: public function find()
1239: {
1240: $this->_setupPrimaryKey();
1241: $args = func_get_args();
1242: $keyNames = array_values((array) $this->_primary);
1243:
1244: if (count($args) < count($keyNames)) {
1245: require_once 'Zend/Db/Table/Exception.php';
1246: throw new Zend_Db_Table_Exception("Too few columns for the primary key");
1247: }
1248:
1249: if (count($args) > count($keyNames)) {
1250: require_once 'Zend/Db/Table/Exception.php';
1251: throw new Zend_Db_Table_Exception("Too many columns for the primary key");
1252: }
1253:
1254: $whereList = array();
1255: $numberTerms = 0;
1256: foreach ($args as $keyPosition => $keyValues) {
1257: $keyValuesCount = count($keyValues);
1258: // Coerce the values to an array.
1259: // Don't simply typecast to array, because the values
1260: // might be Zend_Db_Expr objects.
1261: if (!is_array($keyValues)) {
1262: $keyValues = array($keyValues);
1263: }
1264: if ($numberTerms == 0) {
1265: $numberTerms = $keyValuesCount;
1266: } else if ($keyValuesCount != $numberTerms) {
1267: require_once 'Zend/Db/Table/Exception.php';
1268: throw new Zend_Db_Table_Exception("Missing value(s) for the primary key");
1269: }
1270: $keyValues = array_values($keyValues);
1271: for ($i = 0; $i < $keyValuesCount; ++$i) {
1272: if (!isset($whereList[$i])) {
1273: $whereList[$i] = array();
1274: }
1275: $whereList[$i][$keyPosition] = $keyValues[$i];
1276: }
1277: }
1278:
1279: $whereClause = null;
1280: if (count($whereList)) {
1281: $whereOrTerms = array();
1282: $tableName = $this->_db->quoteTableAs($this->_name, null, true);
1283: foreach ($whereList as $keyValueSets) {
1284: $whereAndTerms = array();
1285: foreach ($keyValueSets as $keyPosition => $keyValue) {
1286: $type = $this->_metadata[$keyNames[$keyPosition]]['DATA_TYPE'];
1287: $columnName = $this->_db->quoteIdentifier($keyNames[$keyPosition], true);
1288: $whereAndTerms[] = $this->_db->quoteInto(
1289: $tableName . '.' . $columnName . ' = ?',
1290: $keyValue, $type);
1291: }
1292: $whereOrTerms[] = '(' . implode(' AND ', $whereAndTerms) . ')';
1293: }
1294: $whereClause = '(' . implode(' OR ', $whereOrTerms) . ')';
1295: }
1296:
1297: // issue ZF-5775 (empty where clause should return empty rowset)
1298: if ($whereClause == null) {
1299: $rowsetClass = $this->getRowsetClass();
1300: if (!class_exists($rowsetClass)) {
1301: require_once 'Zend/Loader.php';
1302: Zend_Loader::loadClass($rowsetClass);
1303: }
1304: return new $rowsetClass(array('table' => $this, 'rowClass' => $this->getRowClass(), 'stored' => true));
1305: }
1306:
1307: return $this->fetchAll($whereClause);
1308: }
1309:
1310: /**
1311: * Fetches all rows.
1312: *
1313: * Honors the Zend_Db_Adapter fetch mode.
1314: *
1315: * @param string|array|Zend_Db_Table_Select $where OPTIONAL An SQL WHERE clause or Zend_Db_Table_Select object.
1316: * @param string|array $order OPTIONAL An SQL ORDER clause.
1317: * @param int $count OPTIONAL An SQL LIMIT count.
1318: * @param int $offset OPTIONAL An SQL LIMIT offset.
1319: * @return Zend_Db_Table_Rowset_Abstract The row results per the Zend_Db_Adapter fetch mode.
1320: */
1321: public function fetchAll($where = null, $order = null, $count = null, $offset = null)
1322: {
1323: if (!($where instanceof Zend_Db_Table_Select)) {
1324: $select = $this->select();
1325:
1326: if ($where !== null) {
1327: $this->_where($select, $where);
1328: }
1329:
1330: if ($order !== null) {
1331: $this->_order($select, $order);
1332: }
1333:
1334: if ($count !== null || $offset !== null) {
1335: $select->limit($count, $offset);
1336: }
1337:
1338: } else {
1339: $select = $where;
1340: }
1341:
1342: $rows = $this->_fetch($select);
1343:
1344: $data = array(
1345: 'table' => $this,
1346: 'data' => $rows,
1347: 'readOnly' => $select->isReadOnly(),
1348: 'rowClass' => $this->getRowClass(),
1349: 'stored' => true
1350: );
1351:
1352: $rowsetClass = $this->getRowsetClass();
1353: if (!class_exists($rowsetClass)) {
1354: require_once 'Zend/Loader.php';
1355: Zend_Loader::loadClass($rowsetClass);
1356: }
1357: return new $rowsetClass($data);
1358: }
1359:
1360: /**
1361: * Fetches one row in an object of type Zend_Db_Table_Row_Abstract,
1362: * or returns null if no row matches the specified criteria.
1363: *
1364: * @param string|array|Zend_Db_Table_Select $where OPTIONAL An SQL WHERE clause or Zend_Db_Table_Select object.
1365: * @param string|array $order OPTIONAL An SQL ORDER clause.
1366: * @return Zend_Db_Table_Row_Abstract|null The row results per the
1367: * Zend_Db_Adapter fetch mode, or null if no row found.
1368: */
1369: public function fetchRow($where = null, $order = null)
1370: {
1371: if (!($where instanceof Zend_Db_Table_Select)) {
1372: $select = $this->select();
1373:
1374: if ($where !== null) {
1375: $this->_where($select, $where);
1376: }
1377:
1378: if ($order !== null) {
1379: $this->_order($select, $order);
1380: }
1381:
1382: $select->limit(1);
1383:
1384: } else {
1385: $select = $where->limit(1);
1386: }
1387:
1388: $rows = $this->_fetch($select);
1389:
1390: if (count($rows) == 0) {
1391: return null;
1392: }
1393:
1394: $data = array(
1395: 'table' => $this,
1396: 'data' => $rows[0],
1397: 'readOnly' => $select->isReadOnly(),
1398: 'stored' => true
1399: );
1400:
1401: $rowClass = $this->getRowClass();
1402: if (!class_exists($rowClass)) {
1403: require_once 'Zend/Loader.php';
1404: Zend_Loader::loadClass($rowClass);
1405: }
1406: return new $rowClass($data);
1407: }
1408:
1409: /**
1410: * Fetches a new blank row (not from the database).
1411: *
1412: * @return Zend_Db_Table_Row_Abstract
1413: * @deprecated since 0.9.3 - use createRow() instead.
1414: */
1415: public function fetchNew()
1416: {
1417: return $this->createRow();
1418: }
1419:
1420: /**
1421: * Fetches a new blank row (not from the database).
1422: *
1423: * @param array $data OPTIONAL data to populate in the new row.
1424: * @param string $defaultSource OPTIONAL flag to force default values into new row
1425: * @return Zend_Db_Table_Row_Abstract
1426: */
1427: public function createRow(array $data = array(), $defaultSource = null)
1428: {
1429: $cols = $this->_getCols();
1430: $defaults = array_combine($cols, array_fill(0, count($cols), null));
1431:
1432: // nothing provided at call-time, take the class value
1433: if ($defaultSource == null) {
1434: $defaultSource = $this->_defaultSource;
1435: }
1436:
1437: if (!in_array($defaultSource, array(self::DEFAULT_CLASS, self::DEFAULT_DB, self::DEFAULT_NONE))) {
1438: $defaultSource = self::DEFAULT_NONE;
1439: }
1440:
1441: if ($defaultSource == self::DEFAULT_DB) {
1442: foreach ($this->_metadata as $metadataName => $metadata) {
1443: if (($metadata['DEFAULT'] != null) &&
1444: ($metadata['NULLABLE'] !== true || ($metadata['NULLABLE'] === true && isset($this->_defaultValues[$metadataName]) && $this->_defaultValues[$metadataName] === true)) &&
1445: (!(isset($this->_defaultValues[$metadataName]) && $this->_defaultValues[$metadataName] === false))) {
1446: $defaults[$metadataName] = $metadata['DEFAULT'];
1447: }
1448: }
1449: } elseif ($defaultSource == self::DEFAULT_CLASS && $this->_defaultValues) {
1450: foreach ($this->_defaultValues as $defaultName => $defaultValue) {
1451: if (array_key_exists($defaultName, $defaults)) {
1452: $defaults[$defaultName] = $defaultValue;
1453: }
1454: }
1455: }
1456:
1457: $config = array(
1458: 'table' => $this,
1459: 'data' => $defaults,
1460: 'readOnly' => false,
1461: 'stored' => false
1462: );
1463:
1464: $rowClass = $this->getRowClass();
1465: if (!class_exists($rowClass)) {
1466: require_once 'Zend/Loader.php';
1467: Zend_Loader::loadClass($rowClass);
1468: }
1469: $row = new $rowClass($config);
1470: $row->setFromArray($data);
1471: return $row;
1472: }
1473:
1474: /**
1475: * Generate WHERE clause from user-supplied string or array
1476: *
1477: * @param string|array $where OPTIONAL An SQL WHERE clause.
1478: * @return Zend_Db_Table_Select
1479: */
1480: protected function _where(Zend_Db_Table_Select $select, $where)
1481: {
1482: $where = (array) $where;
1483:
1484: foreach ($where as $key => $val) {
1485: // is $key an int?
1486: if (is_int($key)) {
1487: // $val is the full condition
1488: $select->where($val);
1489: } else {
1490: // $key is the condition with placeholder,
1491: // and $val is quoted into the condition
1492: $select->where($key, $val);
1493: }
1494: }
1495:
1496: return $select;
1497: }
1498:
1499: /**
1500: * Generate ORDER clause from user-supplied string or array
1501: *
1502: * @param string|array $order OPTIONAL An SQL ORDER clause.
1503: * @return Zend_Db_Table_Select
1504: */
1505: protected function _order(Zend_Db_Table_Select $select, $order)
1506: {
1507: if (!is_array($order)) {
1508: $order = array($order);
1509: }
1510:
1511: foreach ($order as $val) {
1512: $select->order($val);
1513: }
1514:
1515: return $select;
1516: }
1517:
1518: /**
1519: * Support method for fetching rows.
1520: *
1521: * @param Zend_Db_Table_Select $select query options.
1522: * @return array An array containing the row results in FETCH_ASSOC mode.
1523: */
1524: protected function _fetch(Zend_Db_Table_Select $select)
1525: {
1526: $stmt = $this->_db->query($select);
1527: $data = $stmt->fetchAll(Zend_Db::FETCH_ASSOC);
1528: return $data;
1529: }
1530:
1531: }
1532: