Abstract.php 52 KB

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