Managed_DataObject.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. <?php
  2. /*
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2010, StatusNet, Inc.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * Wrapper for Memcached_DataObject which knows its own schema definition.
  21. * Builds its own damn settings from a schema definition.
  22. *
  23. * @author Brion Vibber <brion@status.net>
  24. */
  25. abstract class Managed_DataObject extends Memcached_DataObject
  26. {
  27. /**
  28. * The One True Thingy that must be defined and declared.
  29. */
  30. public static function schemaDef()
  31. {
  32. throw new MethodNotImplementedException(__METHOD__);
  33. }
  34. /**
  35. * Get an instance by key
  36. *
  37. * @param string $k Key to use to lookup (usually 'id' for this class)
  38. * @param mixed $v Value to lookup
  39. *
  40. * @return get_called_class() object if found, or null for no hits
  41. *
  42. */
  43. static function getKV($k,$v=NULL)
  44. {
  45. return parent::getClassKV(get_called_class(), $k, $v);
  46. }
  47. /**
  48. * Get an instance by compound key
  49. *
  50. * This is a utility method to get a single instance with a given set of
  51. * key-value pairs. Usually used for the primary key for a compound key; thus
  52. * the name.
  53. *
  54. * @param array $kv array of key-value mappings
  55. *
  56. * @return get_called_class() object if found, or null for no hits
  57. *
  58. */
  59. static function pkeyGet(array $kv)
  60. {
  61. return parent::pkeyGetClass(get_called_class(), $kv);
  62. }
  63. /**
  64. * Get multiple items from the database by key
  65. *
  66. * @param string $keyCol name of column for key
  67. * @param array $keyVals key values to fetch
  68. * @param boolean $skipNulls return only non-null results?
  69. *
  70. * @return array Array of objects, in order
  71. */
  72. static function multiGet($keyCol, array $keyVals, $skipNulls=true)
  73. {
  74. return parent::multiGetClass(get_called_class(), $keyCol, $keyVals, $skipNulls);
  75. }
  76. /**
  77. * Get multiple items from the database by key
  78. *
  79. * @param string $keyCol name of column for key
  80. * @param array $keyVals key values to fetch
  81. * @param array $otherCols Other columns to hold fixed
  82. *
  83. * @return array Array mapping $keyVals to objects, or null if not found
  84. */
  85. static function pivotGet($keyCol, array $keyVals, array $otherCols=array())
  86. {
  87. return parent::pivotGetClass(get_called_class(), $keyCol, $keyVals, $otherCols);
  88. }
  89. /**
  90. * Get a multi-instance object
  91. *
  92. * This is a utility method to get multiple instances with a given set of
  93. * values for a specific column.
  94. *
  95. * @param string $keyCol key column name
  96. * @param array $keyVals array of key values
  97. *
  98. * @return get_called_class() object with multiple instances if found,
  99. * Exception is thrown when no entries are found.
  100. *
  101. */
  102. static function listFind($keyCol, array $keyVals)
  103. {
  104. return parent::listFindClass(get_called_class(), $keyCol, $keyVals);
  105. }
  106. /**
  107. * Get a multi-instance object separated into an array
  108. *
  109. * This is a utility method to get multiple instances with a given set of
  110. * values for a specific key column. Usually used for the primary key when
  111. * multiple values are desired. Result is an array.
  112. *
  113. * @param string $keyCol key column name
  114. * @param array $keyVals array of key values
  115. *
  116. * @return array with an get_called_class() object for each $keyVals entry
  117. *
  118. */
  119. static function listGet($keyCol, array $keyVals)
  120. {
  121. return parent::listGetClass(get_called_class(), $keyCol, $keyVals);
  122. }
  123. /**
  124. * get/set an associative array of table columns
  125. *
  126. * @access public
  127. * @return array (associative)
  128. */
  129. public function table()
  130. {
  131. $table = static::schemaDef();
  132. return array_map(array($this, 'columnBitmap'), $table['fields']);
  133. }
  134. /**
  135. * get/set an array of table primary keys
  136. *
  137. * Key info is pulled from the table definition array.
  138. *
  139. * @access private
  140. * @return array
  141. */
  142. function keys()
  143. {
  144. return array_keys($this->keyTypes());
  145. }
  146. /**
  147. * Get a sequence key
  148. *
  149. * Returns the first serial column defined in the table, if any.
  150. *
  151. * @access private
  152. * @return array (column,use_native,sequence_name)
  153. */
  154. function sequenceKey()
  155. {
  156. $table = static::schemaDef();
  157. foreach ($table['fields'] as $name => $column) {
  158. if ($column['type'] == 'serial') {
  159. // We have a serial/autoincrement column.
  160. // Declare it to be a native sequence!
  161. return array($name, true, false);
  162. }
  163. }
  164. // No sequence key on this table.
  165. return array(false, false, false);
  166. }
  167. /**
  168. * Return key definitions for DB_DataObject and Memcache_DataObject.
  169. *
  170. * DB_DataObject needs to know about keys that the table has; this function
  171. * defines them.
  172. *
  173. * @return array key definitions
  174. */
  175. function keyTypes()
  176. {
  177. $table = static::schemaDef();
  178. $keys = array();
  179. if (!empty($table['unique keys'])) {
  180. foreach ($table['unique keys'] as $idx => $fields) {
  181. foreach ($fields as $name) {
  182. $keys[$name] = 'U';
  183. }
  184. }
  185. }
  186. if (!empty($table['primary key'])) {
  187. foreach ($table['primary key'] as $name) {
  188. $keys[$name] = 'K';
  189. }
  190. }
  191. return $keys;
  192. }
  193. /**
  194. * Build the appropriate DB_DataObject bitfield map for this field.
  195. *
  196. * @param array $column
  197. * @return int
  198. */
  199. function columnBitmap($column)
  200. {
  201. $type = $column['type'];
  202. // For quoting style...
  203. $intTypes = array('int',
  204. 'integer',
  205. 'float',
  206. 'serial',
  207. 'numeric');
  208. if (in_array($type, $intTypes)) {
  209. $style = DB_DATAOBJECT_INT;
  210. } else {
  211. $style = DB_DATAOBJECT_STR;
  212. }
  213. // Data type formatting style...
  214. $formatStyles = array('blob' => DB_DATAOBJECT_BLOB,
  215. 'text' => DB_DATAOBJECT_TXT,
  216. 'date' => DB_DATAOBJECT_DATE,
  217. 'time' => DB_DATAOBJECT_TIME,
  218. 'datetime' => DB_DATAOBJECT_DATE | DB_DATAOBJECT_TIME,
  219. 'timestamp' => DB_DATAOBJECT_MYSQLTIMESTAMP);
  220. if (isset($formatStyles[$type])) {
  221. $style |= $formatStyles[$type];
  222. }
  223. // Nullable?
  224. if (!empty($column['not null'])) {
  225. $style |= DB_DATAOBJECT_NOTNULL;
  226. }
  227. return $style;
  228. }
  229. function links()
  230. {
  231. $links = array();
  232. $table = static::schemaDef();
  233. foreach ($table['foreign keys'] as $keyname => $keydef) {
  234. if (count($keydef) == 2 && is_string($keydef[0]) && is_array($keydef[1]) && count($keydef[1]) == 1) {
  235. if (isset($keydef[1][0])) {
  236. $links[$keydef[1][0]] = $keydef[0].':'.$keydef[1][1];
  237. }
  238. }
  239. }
  240. return $links;
  241. }
  242. /**
  243. * Return a list of all primary/unique keys / vals that will be used for
  244. * caching. This will understand compound unique keys, which
  245. * Memcached_DataObject doesn't have enough info to handle properly.
  246. *
  247. * @return array of strings
  248. */
  249. function _allCacheKeys()
  250. {
  251. $table = static::schemaDef();
  252. $ckeys = array();
  253. if (!empty($table['unique keys'])) {
  254. $keyNames = $table['unique keys'];
  255. foreach ($keyNames as $idx => $fields) {
  256. $val = array();
  257. foreach ($fields as $name) {
  258. $val[$name] = self::valueString($this->$name);
  259. }
  260. $ckeys[] = self::multicacheKey($this->tableName(), $val);
  261. }
  262. }
  263. if (!empty($table['primary key'])) {
  264. $fields = $table['primary key'];
  265. $val = array();
  266. foreach ($fields as $name) {
  267. $val[$name] = self::valueString($this->$name);
  268. }
  269. $ckeys[] = self::multicacheKey($this->tableName(), $val);
  270. }
  271. return $ckeys;
  272. }
  273. /**
  274. * Returns an ID, checked that it is set and reasonably valid
  275. *
  276. * If this dataobject uses a special id field (not 'id'), just
  277. * implement your ID getting method in the child class.
  278. *
  279. * @return int ID of dataobject
  280. * @throws Exception (when ID is not available or not set yet)
  281. */
  282. public function getID()
  283. {
  284. // FIXME: Make these exceptions more specific (their own classes)
  285. if (!isset($this->id)) {
  286. throw new Exception('No ID set.');
  287. } elseif (empty($this->id)) {
  288. throw new Exception('Empty ID for object! (not inserted yet?).');
  289. }
  290. // FIXME: How about forcing to return an int? Or will that overflow eventually?
  291. return $this->id;
  292. }
  293. // 'update' won't write key columns, so we have to do it ourselves.
  294. // This also automatically calls "update" _before_ it sets the keys.
  295. // FIXME: This only works with single-column primary keys so far! Beware!
  296. /**
  297. * @param DB_DataObject &$orig Must be "instanceof" $this
  298. * @param string $pid Primary ID column (no escaping is done on column name!)
  299. */
  300. public function updateWithKeys(&$orig, $pid='id')
  301. {
  302. if (!$orig instanceof $this) {
  303. throw new ServerException('Tried updating a DataObject with a different class than itself.');
  304. }
  305. // do it in a transaction
  306. $this->query('BEGIN');
  307. $parts = array();
  308. foreach ($this->keys() as $k) {
  309. if (strcmp($this->$k, $orig->$k) != 0) {
  310. $parts[] = $k . ' = ' . $this->_quote($this->$k);
  311. }
  312. }
  313. if (count($parts) == 0) {
  314. // No changes to keys, it's safe to run ->update(...)
  315. if ($this->update($orig) === false) {
  316. common_log_db_error($this, 'UPDATE', __FILE__);
  317. // rollback as something bad occurred
  318. $this->query('ROLLBACK');
  319. throw new ServerException("Could not UPDATE non-keys for {$this->__table}");
  320. }
  321. $orig->decache();
  322. $this->encache();
  323. // commit our db transaction since we won't reach the COMMIT below
  324. $this->query('COMMIT');
  325. // @FIXME return true only if something changed (otherwise 0)
  326. return true;
  327. }
  328. $qry = sprintf('UPDATE %1$s SET %2$s WHERE %3$s = %4$s',
  329. common_database_tablename($this->tableName()),
  330. implode(', ', $parts),
  331. $pid,
  332. $this->_quote($this->$pid));
  333. $result = $this->query($qry);
  334. if ($result === false) {
  335. common_log_db_error($this, 'UPDATE', __FILE__);
  336. // rollback as something bad occurred
  337. $this->query('ROLLBACK');
  338. throw new ServerException("Could not UPDATE key fields for {$this->__table}");
  339. }
  340. // Update non-keys too, if the previous endeavour worked.
  341. // The ->update call uses "$this" values for keys, that's why we can't do this until
  342. // the keys are updated (because they might differ from $orig and update the wrong entries).
  343. if ($this->update($orig) === false) {
  344. common_log_db_error($this, 'UPDATE', __FILE__);
  345. // rollback as something bad occurred
  346. $this->query('ROLLBACK');
  347. throw new ServerException("Could not UPDATE non-keys for {$this->__table}");
  348. }
  349. $orig->decache();
  350. $this->encache();
  351. // commit our db transaction
  352. $this->query('COMMIT');
  353. // @FIXME return true only if something changed (otherwise 0)
  354. return $result;
  355. }
  356. }