Abstract.php 48 KB

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