blob: af62dcf3d78f55a29fd64e4749cf9a67d3362562 [file] [log] [blame]
Derek Allard2067d1a2008-11-13 22:59:24 +00001<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2/**
3 * Code Igniter
4 *
5 * An open source application development framework for PHP 4.3.2 or newer
6 *
7 * @package CodeIgniter
8 * @author ExpressionEngine Dev Team
Derek Jones7f3719f2010-01-05 13:35:37 +00009 * @copyright Copyright (c) 2008 - 2010, EllisLab, Inc.
Derek Allard2067d1a2008-11-13 22:59:24 +000010 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
12 * @since Version 1.0
13 * @filesource
14 */
15
16// ------------------------------------------------------------------------
17
18/**
19 * Database Utility Class
20 *
21 * @category Database
22 * @author ExpressionEngine Dev Team
23 * @link http://codeigniter.com/user_guide/database/
24 */
25class CI_DB_utility extends CI_DB_forge {
26
27 var $db;
28 var $data_cache = array();
29
30 /**
31 * Constructor
32 *
33 * Grabs the CI super object instance so we can access it.
34 *
35 */
36 function CI_DB_utility()
37 {
38 // Assign the main database object to $this->db
39 $CI =& get_instance();
40 $this->db =& $CI->db;
41
42 log_message('debug', "Database Utility Class Initialized");
43 }
44
45 // --------------------------------------------------------------------
46
47 /**
48 * List databases
49 *
50 * @access public
51 * @return bool
52 */
53 function list_databases()
54 {
55 // Is there a cached result?
56 if (isset($this->data_cache['db_names']))
57 {
58 return $this->data_cache['db_names'];
59 }
60
61 $query = $this->db->query($this->_list_databases());
62 $dbs = array();
63 if ($query->num_rows() > 0)
64 {
65 foreach ($query->result_array() as $row)
66 {
67 $dbs[] = current($row);
68 }
69 }
70
71 $this->data_cache['db_names'] = $dbs;
72 return $this->data_cache['db_names'];
73 }
74
75 // --------------------------------------------------------------------
76
77 /**
Derek Allarde7f03252010-02-04 16:47:01 +000078 * Determine if a particular database exists
79 *
80 * @access public
81 * @param string
82 * @return boolean
83 */
84 function database_exists($database_name)
85 {
86 return ( ! in_array($database_name, $this->list_databases())) ? FALSE : TRUE;
87 }
88
89 // --------------------------------------------------------------------
90
91 /**
Derek Allard2067d1a2008-11-13 22:59:24 +000092 * Optimize Table
93 *
94 * @access public
95 * @param string the table name
96 * @return bool
97 */
98 function optimize_table($table_name)
99 {
100 $sql = $this->_optimize_table($table_name);
101
102 if (is_bool($sql))
103 {
104 show_error('db_must_use_set');
105 }
106
107 $query = $this->db->query($sql);
108 $res = $query->result_array();
109
110 // Note: Due to a bug in current() that affects some versions
111 // of PHP we can not pass function call directly into it
112 return current($res);
113 }
114
115 // --------------------------------------------------------------------
116
117 /**
118 * Optimize Database
119 *
120 * @access public
121 * @return array
122 */
123 function optimize_database()
124 {
125 $result = array();
126 foreach ($this->db->list_tables() as $table_name)
127 {
128 $sql = $this->_optimize_table($table_name);
129
130 if (is_bool($sql))
131 {
132 return $sql;
133 }
134
135 $query = $this->db->query($sql);
136
137 // Build the result array...
138 // Note: Due to a bug in current() that affects some versions
139 // of PHP we can not pass function call directly into it
140 $res = $query->result_array();
141 $res = current($res);
142 $key = str_replace($this->db->database.'.', '', current($res));
143 $keys = array_keys($res);
144 unset($res[$keys[0]]);
145
146 $result[$key] = $res;
147 }
148
149 return $result;
150 }
151
152 // --------------------------------------------------------------------
153
154 /**
155 * Repair Table
156 *
157 * @access public
158 * @param string the table name
159 * @return bool
160 */
161 function repair_table($table_name)
162 {
163 $sql = $this->_repair_table($table_name);
164
165 if (is_bool($sql))
166 {
167 return $sql;
168 }
169
170 $query = $this->db->query($sql);
171
172 // Note: Due to a bug in current() that affects some versions
173 // of PHP we can not pass function call directly into it
174 $res = $query->result_array();
175 return current($res);
176 }
177
178 // --------------------------------------------------------------------
179
180 /**
181 * Generate CSV from a query result object
182 *
183 * @access public
184 * @param object The query result object
185 * @param string The delimiter - comma by default
186 * @param string The newline character - \n by default
187 * @param string The enclosure - double quote by default
188 * @return string
189 */
190 function csv_from_result($query, $delim = ",", $newline = "\n", $enclosure = '"')
191 {
Derek Jones47874132009-02-10 17:32:15 +0000192 if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
Derek Allard2067d1a2008-11-13 22:59:24 +0000193 {
194 show_error('You must submit a valid result object');
195 }
196
197 $out = '';
198
199 // First generate the headings from the table column names
200 foreach ($query->list_fields() as $name)
201 {
202 $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim;
203 }
204
205 $out = rtrim($out);
206 $out .= $newline;
207
208 // Next blast through the result array and build out the rows
209 foreach ($query->result_array() as $row)
210 {
211 foreach ($row as $item)
212 {
213 $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim;
214 }
215 $out = rtrim($out);
216 $out .= $newline;
217 }
218
219 return $out;
220 }
221
222 // --------------------------------------------------------------------
223
224 /**
225 * Generate XML data from a query result object
226 *
227 * @access public
228 * @param object The query result object
229 * @param array Any preferences
230 * @return string
231 */
232 function xml_from_result($query, $params = array())
233 {
Pascal Kriete69b1fcc2009-08-24 16:42:52 +0000234 if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
Derek Allard2067d1a2008-11-13 22:59:24 +0000235 {
236 show_error('You must submit a valid result object');
237 }
238
239 // Set our default values
240 foreach (array('root' => 'root', 'element' => 'element', 'newline' => "\n", 'tab' => "\t") as $key => $val)
241 {
242 if ( ! isset($params[$key]))
243 {
244 $params[$key] = $val;
245 }
246 }
247
248 // Create variables for convenience
249 extract($params);
250
251 // Load the xml helper
252 $CI =& get_instance();
253 $CI->load->helper('xml');
254
255 // Generate the result
256 $xml = "<{$root}>".$newline;
257 foreach ($query->result_array() as $row)
258 {
259 $xml .= $tab."<{$element}>".$newline;
260
261 foreach ($row as $key => $val)
262 {
263 $xml .= $tab.$tab."<{$key}>".xml_convert($val)."</{$key}>".$newline;
264 }
265 $xml .= $tab."</{$element}>".$newline;
266 }
267 $xml .= "</$root>".$newline;
268
269 return $xml;
270 }
271
272 // --------------------------------------------------------------------
273
274 /**
275 * Database Backup
276 *
277 * @access public
278 * @return void
279 */
280 function backup($params = array())
281 {
282 // If the parameters have not been submitted as an
283 // array then we know that it is simply the table
284 // name, which is a valid short cut.
285 if (is_string($params))
286 {
287 $params = array('tables' => $params);
288 }
289
290 // ------------------------------------------------------
291
292 // Set up our default preferences
293 $prefs = array(
294 'tables' => array(),
295 'ignore' => array(),
296 'filename' => '',
297 'format' => 'gzip', // gzip, zip, txt
298 'add_drop' => TRUE,
299 'add_insert' => TRUE,
300 'newline' => "\n"
301 );
302
303 // Did the user submit any preferences? If so set them....
304 if (count($params) > 0)
305 {
306 foreach ($prefs as $key => $val)
307 {
308 if (isset($params[$key]))
309 {
310 $prefs[$key] = $params[$key];
311 }
312 }
313 }
314
315 // ------------------------------------------------------
316
317 // Are we backing up a complete database or individual tables?
318 // If no table names were submitted we'll fetch the entire table list
319 if (count($prefs['tables']) == 0)
320 {
321 $prefs['tables'] = $this->db->list_tables();
322 }
323
324 // ------------------------------------------------------
325
326 // Validate the format
327 if ( ! in_array($prefs['format'], array('gzip', 'zip', 'txt'), TRUE))
328 {
329 $prefs['format'] = 'txt';
330 }
331
332 // ------------------------------------------------------
333
334 // Is the encoder supported? If not, we'll either issue an
335 // error or use plain text depending on the debug settings
336 if (($prefs['format'] == 'gzip' AND ! @function_exists('gzencode'))
337 OR ($prefs['format'] == 'zip' AND ! @function_exists('gzcompress')))
338 {
339 if ($this->db->db_debug)
340 {
341 return $this->db->display_error('db_unsuported_compression');
342 }
343
344 $prefs['format'] = 'txt';
345 }
346
347 // ------------------------------------------------------
348
349 // Set the filename if not provided - Only needed with Zip files
350 if ($prefs['filename'] == '' AND $prefs['format'] == 'zip')
351 {
352 $prefs['filename'] = (count($prefs['tables']) == 1) ? $prefs['tables'] : $this->db->database;
353 $prefs['filename'] .= '_'.date('Y-m-d_H-i', time());
354 }
355
356 // ------------------------------------------------------
357
358 // Was a Gzip file requested?
359 if ($prefs['format'] == 'gzip')
360 {
361 return gzencode($this->_backup($prefs));
362 }
363
364 // ------------------------------------------------------
365
366 // Was a text file requested?
367 if ($prefs['format'] == 'txt')
368 {
369 return $this->_backup($prefs);
370 }
371
372 // ------------------------------------------------------
373
374 // Was a Zip file requested?
375 if ($prefs['format'] == 'zip')
376 {
377 // If they included the .zip file extension we'll remove it
378 if (preg_match("|.+?\.zip$|", $prefs['filename']))
379 {
380 $prefs['filename'] = str_replace('.zip', '', $prefs['filename']);
381 }
382
383 // Tack on the ".sql" file extension if needed
384 if ( ! preg_match("|.+?\.sql$|", $prefs['filename']))
385 {
386 $prefs['filename'] .= '.sql';
387 }
388
389 // Load the Zip class and output it
390
391 $CI =& get_instance();
392 $CI->load->library('zip');
393 $CI->zip->add_data($prefs['filename'], $this->_backup($prefs));
394 return $CI->zip->get_zip();
395 }
396
397 }
398
399}
400
401
402/* End of file DB_utility.php */
Derek Jonesa3ffbbb2008-05-11 18:18:29 +0000403/* Location: ./system/database/DB_utility.php */