3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2010, StatusNet, Inc.
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.
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.
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/>.
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
23 * Extended DB_DataObject to improve a few things:
24 * - free global resources from destructor
25 * - remove bogus global references from serialized objects
26 * - don't leak memory when loading already-used .ini files
27 * (eg when using the same schema on thousands of databases)
29 class Safe_DataObject extends DB_DataObject
32 * Destructor to free global memory resources associated with
33 * this data object when it's unset or goes out of scope.
34 * DB_DataObject doesn't do this yet by itself.
40 if (method_exists('DB_DataObject', '__destruct')) {
46 * Magic function called at clone() time.
48 * We use this to drop connection with some global resources.
49 * This supports the fairly common pattern where individual
50 * items being read in a loop via a single object are cloned
51 * for individual processing, then fall out of scope when the
52 * loop comes around again.
54 * As that triggers the destructor, we want to make sure that
55 * the original object doesn't have its database result killed.
56 * It will still be freed properly when the original object
61 $this->_DB_resultid = false;
65 * Magic function called at serialize() time.
67 * We use this to drop a couple process-specific references
68 * from DB_DataObject which can cause trouble in future
71 * @return array of variable names to include in serialization.
75 $vars = array_keys(get_object_vars($this));
76 $skip = array('_DB_resultid', '_link_loaded');
77 return array_diff($vars, $skip);
81 * Magic function called at unserialize() time.
83 * Clean out some process-specific variables which might
84 * be floating around from a previous process's cached
87 * Old cached objects may still have them.
91 // Refers to global state info from a previous process.
92 // Clear this out so we don't accidentally break global
93 // state in *this* process.
94 $this->_DB_resultid = null;
95 // We don't have any local DBO refs, so clear these out.
96 $this->_link_loaded = false;
100 * Magic function called when someone attempts to call a method
101 * that doesn't exist. DB_DataObject uses this to implement
102 * setters and getters for fields, but neglects to throw an error
103 * when you just misspell an actual method name. This leads to
104 * silent failures which can cause all kinds of havoc.
106 * @param string $method
107 * @param array $params
111 function __call($method, $params)
114 // Yes, that's _call with one underscore, which does the
115 // actual implementation.
116 if ($this->_call($method, $params, $return)) {
119 // Low level exception. No need for i18n as discussed with Brion.
120 throw new Exception('Call to undefined method ' .
121 get_class($this) . '::' . $method);
126 * Work around memory-leak bugs...
127 * Had to copy-paste the whole function in order to patch a couple lines of it.
128 * Would be nice if this code was better factored.
130 * @param optional string name of database to assign / read
131 * @param optional array structure of database, and keys
132 * @param optional array table links
135 * @return true or PEAR:error on wrong paramenters.. or false if no file exists..
136 * or the array(tablename => array(column_name=>type)) if called with 1 argument.. (databasename)
138 function databaseStructure()
140 global $_DB_DATAOBJECT;
144 if ($args = func_get_args()) {
146 if (count($args) == 1) {
148 // this returns all the tables and their structure..
149 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
150 $this->debug("Loading Generator as databaseStructure called with args",1);
153 $x = new DB_DataObject;
154 $x->_database = $args[0];
156 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
158 $tables = $DB->getListOf('tables');
159 class_exists('DB_DataObject_Generator') ? '' :
160 require_once 'DB/DataObject/Generator.php';
162 foreach($tables as $table) {
163 $y = new DB_DataObject_Generator;
164 $y->fillTableSchema($x->_database,$table);
166 return $_DB_DATAOBJECT['INI'][$x->_database];
169 $_DB_DATAOBJECT['INI'][$args[0]] = isset($_DB_DATAOBJECT['INI'][$args[0]]) ?
170 $_DB_DATAOBJECT['INI'][$args[0]] + $args[1] : $args[1];
172 if (isset($args[1])) {
173 $_DB_DATAOBJECT['LINKS'][$args[0]] = isset($_DB_DATAOBJECT['LINKS'][$args[0]]) ?
174 $_DB_DATAOBJECT['LINKS'][$args[0]] + $args[2] : $args[2];
181 if (!$this->_database) {
186 if (!empty($_DB_DATAOBJECT['INI'][$this->_database])) {
188 // database loaded - but this is table is not available..
190 empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])
191 && !empty($_DB_DATAOBJECT['CONFIG']['proxy'])
193 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
194 $this->debug("Loading Generator to fetch Schema",1);
196 class_exists('DB_DataObject_Generator') ? '' :
197 require_once 'DB/DataObject/Generator.php';
200 $x = new DB_DataObject_Generator;
201 $x->fillTableSchema($this->_database,$this->__table);
206 if (empty($_DB_DATAOBJECT['CONFIG'])) {
207 DB_DataObject::_loadConfig();
210 // if you supply this with arguments, then it will take those
211 // as the database and links array...
213 $schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
214 array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
217 if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
218 $schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
219 $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
220 explode(PATH_SEPARATOR,$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
223 /* BEGIN CHANGED FROM UPSTREAM */
224 $_DB_DATAOBJECT['INI'][$this->_database] = $this->parseIniFiles($schemas);
225 /* END CHANGED FROM UPSTREAM */
227 // now have we loaded the structure..
229 if (!empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
232 // - if not try building it..
233 if (!empty($_DB_DATAOBJECT['CONFIG']['proxy'])) {
234 class_exists('DB_DataObject_Generator') ? '' :
235 require_once 'DB/DataObject/Generator.php';
237 $x = new DB_DataObject_Generator;
238 $x->fillTableSchema($this->_database,$this->__table);
239 // should this fail!!!???
242 $this->debug("Cant find database schema: {$this->_database}/{$this->__table} \n".
243 "in links file data: " . print_r($_DB_DATAOBJECT['INI'],true),"databaseStructure",5);
244 // we have to die here!! - it causes chaos if we don't (including looping forever!)
245 // Low level exception. No need for i18n as discussed with Brion.
246 $this->raiseError( "Unable to load schema for database and table (turn debugging up to 5 for full error message)", DB_DATAOBJECT_ERROR_INVALIDARGS, PEAR_ERROR_DIE);
250 /** For parseIniFiles */
251 protected static $iniCache = array();
254 * When switching site configurations, DB_DataObject was loading its
255 * .ini files over and over, leaking gobs of memory.
256 * This refactored helper function uses a local cache of .ini files
257 * to minimize the leaks.
259 * @param array of .ini file names $schemas
262 protected function parseIniFiles(array $schemas)
264 $key = implode("|", $schemas);
265 if (!isset(Safe_DataObject::$iniCache[$key])) {
267 foreach ($schemas as $ini) {
268 if (file_exists($ini) && is_file($ini)) {
269 $data = array_merge($data, parse_ini_file($ini, true));
271 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
272 if (!is_readable ($ini)) {
273 $this->debug("ini file is not readable: $ini","databaseStructure",1);
275 $this->debug("Loaded ini file: $ini","databaseStructure",1);
279 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
280 $this->debug("Missing ini file: $ini","databaseStructure",1);
284 Safe_DataObject::$iniCache[$key] = $data;
287 return Safe_DataObject::$iniCache[$key];