summaryrefslogtreecommitdiffstats
path: root/user_guide_src/source/database/utilities.rst
blob: da53cba385e85b85f4d193fca6df9d4a7e9de042 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
######################
Database Utility Class
######################

The Database Utility Class contains methods that help you manage your
database.

.. contents::
    :local:
    :depth: 2


******************************
Initializing the Utility Class
******************************

.. important:: In order to initialize the Utility class, your database
	driver must already be running, since the utilities class relies on it.

Load the Utility Class as follows::

	$this->load->dbutil()

You can also pass another database object to the DB Utility loader, in case
the database you want to manage isn't the default one::

	$this->myutil = $this->load->dbutil($this->other_db, TRUE);

In the above example, we're passing a custom database object as the first
parameter and then tell it to return the dbutil object, instead of
assigning it directly to ``$this->dbutil``.

.. note:: Both of the parameters can be used individually, just pass an empty
	value as the first one if you wish to skip it.

Once initialized you will access the methods using the ``$this->dbutil``
object::

	$this->dbutil->some_method()

****************************
Using the Database Utilities
****************************

Retrieve list of database names
================================

Returns an array of database names::

	$dbs = $this->dbutil->list_databases();

	foreach ($dbs as $db)
	{
 		echo $db;
	}


Determine If a Database Exists
==============================

Sometimes it's helpful to know whether a particular database exists.
Returns a boolean TRUE/FALSE. Usage example::

	if ($this->dbutil->database_exists('database_name'))
	{
		// some code...
	}

.. note:: Replace *database_name* with the name of the table you are
	looking for. This method is case sensitive.

Optimize a Table
================

Permits you to optimize a table using the table name specified in the
first parameter. Returns TRUE/FALSE based on success or failure::

	if ($this->dbutil->optimize_table('table_name'))
	{
		echo 'Success!';
	}

.. note:: Not all database platforms support table optimization. It is
	mostly for use with MySQL.

Repair a Table
==============

Permits you to repair a table using the table name specified in the
first parameter. Returns TRUE/FALSE based on success or failure::

	if ($this->dbutil->repair_table('table_name'))
	{
		echo 'Success!';
	}

.. note:: Not all database platforms support table repairs.

Optimize a Database
===================

Permits you to optimize the database your DB class is currently
connected to. Returns an array containing the DB status messages or
FALSE on failure.

::

	$result = $this->dbutil->optimize_database();

	if ($result !== FALSE)
	{
		print_r($result);
	}

.. note:: Not all database platforms support table optimization. It
	it is mostly for use with MySQL.

Export a Query Result as a CSV File
===================================

Permits you to generate a CSV file from a query result. The first
parameter of the method must contain the result object from your
query. Example::

	$this->load->dbutil();

	$query = $this->db->query("SELECT * FROM mytable");

	echo $this->dbutil->csv_from_result($query);

The second, third, and fourth parameters allow you to set the delimiter
newline, and enclosure characters respectively. By default commas are
used as the delimiter, "\n" is used as a new line, and a double-quote
is used as the enclosure. Example::

	$delimiter = ",";
	$newline = "\r\n";
	$enclosure = '"';

	echo $this->dbutil->csv_from_result($query, $delimiter, $newline, $enclosure);

.. important:: This method will NOT write the CSV file for you. It
	simply creates the CSV layout. If you need to write the file
	use the :doc:`File Helper <../helpers/file_helper>`.

Export a Query Result as an XML Document
========================================

Permits you to generate an XML file from a query result. The first
parameter expects a query result object, the second may contain an
optional array of config parameters. Example::

	$this->load->dbutil();

	$query = $this->db->query("SELECT * FROM mytable");

	$config = array (
		'root'		=> 'root',
		'element'	=> 'element',
		'newline'	=> "\n",
		'tab'		=> "\t"
	);

	echo $this->dbutil->xml_from_result($query, $config);

.. important:: This method will NOT write the XML file for you. It
	simply creates the XML layout. If you need to write the file
	use the :doc:`File Helper <../helpers/file_helper>`.

********************
Backup Your Database
********************

Database Backup Notes
=====================

Permits you to backup your full database or individual tables. The
backup data can be compressed in either Zip or Gzip format.

.. note:: This feature is only available for MySQL and Interbase/Firebird databases.

.. note:: For Interbase/Firebird databases, the backup file name is the only parameter.

		Eg. $this->dbutil->backup('db_backup_filename');

.. note:: Due to the limited execution time and memory available to PHP,
	backing up very large databases may not be possible. If your database is
	very large you might need to backup directly from your SQL server via
	the command line, or have your server admin do it for you if you do not
	have root privileges.

Usage Example
=============

::

	// Load the DB utility class
	$this->load->dbutil();

	// Backup your entire database and assign it to a variable
	$backup =& $this->dbutil->backup();

	// Load the file helper and write the file to your server
	$this->load->helper('file');
	write_file('/path/to/mybackup.gz', $backup);

	// Load the download helper and send the file to your desktop
	$this->load->helper('download');
	force_download('mybackup.gz', $backup);

Setting Backup Preferences
==========================

Backup preferences are set by submitting an array of values to the first
parameter of the ``backup()`` method. Example::

	$prefs = array(
		'tables'	=> array('table1', 'table2'),	// Array of tables to backup.
		'ignore'	=> array(),			// List of tables to omit from the backup
		'format'	=> 'txt',			// gzip, zip, txt
		'filename'	=> 'mybackup.sql',		// File name - NEEDED ONLY WITH ZIP FILES
		'add_drop'	=> TRUE,			// Whether to add DROP TABLE statements to backup file
		'add_insert'	=> TRUE,			// Whether to add INSERT data to backup file
		'newline'	=> "\n"				// Newline character used in backup file
	);

	$this->dbutil->backup($prefs);

Description of Backup Preferences
=================================

======================= ======================= ======================= ========================================================================
Preference              Default Value           Options                 Description
======================= ======================= ======================= ========================================================================
**tables**               empty array             None                    An array of tables you want backed up. If left blank all tables will be
                                                                         exported.
**ignore**               empty array             None                    An array of tables you want the backup routine to ignore.
**format**               gzip                    gzip, zip, txt          The file format of the export file.
**filename**             the current date/time   None                    The name of the backed-up file. The name is needed only if you are using
                                                                         zip compression.
**add_drop**             TRUE                    TRUE/FALSE              Whether to include DROP TABLE statements in your SQL export file.
**add_insert**           TRUE                    TRUE/FALSE              Whether to include INSERT statements in your SQL export file.
**newline**              "\\n"                   "\\n", "\\r", "\\r\\n"  Type of newline to use in your SQL export file.
**foreign_key_checks**   TRUE                    TRUE/FALSE              Whether output should keep foreign key checks enabled.
======================= ======================= ======================= ========================================================================

***************
Class Reference
***************

.. class:: DB_utility

	.. method:: backup($params)

		:param	array	$params: associative array of backup preferences
		:returns:	void
                :rtype:         void

		Perform a database backup, per user preferences

        .. method:: csv_from_results($query, $delim = ',', $newline = "\n", $enclosure = '"')

                :param  object  $query:   DB_result with data to backup
                :param  string  $delim:  Delimniter character for the CSV file, default is ','
                :param  string  $newline:    Character to use for newlines, default is "\n"
                :param  string  $enclosure:  Delimiter used for enclosure, default is '"'
                :returns:   The generated CSV file as a string
                :rtype:     string

	.. method:: database_exists($database_name)

		:param	string	$database_name: name of the database to check for
		:returns:	TRUE if the database exists, FALSE otherwise
                :rtype:         boolean

		Perform a database backup, per user preferences

	.. method:: database_exists($database_name)

		:param	string	$database_name: name of the database to check for
		:returns:	TRUE if the database exists, FALSE otherwise
                :rtype:         boolean

		Check for the existence of a database

	.. method:: list_databases()

		:returns:	Array of database names found
                :rtype:         array

		Retrieve all the database names

	.. method:: optimize_database()

		:returns:	Array of optimization messages, FALSE on failure
                :rtype:         array

		Optimizes a database

	.. method:: optimize_table($table_name)

                :param  string  $table_name:    Name of the table to optimize
		:returns:	Array of optimization messages, FALSE on failure
                :rtype:         array

		Optimizes a database table

	.. method:: repair_table($table_name)

                :param  string  $table_name:    Name of the table to repair
		:returns:	Array of repair messages, FALSE on failure
                :rtype:         array

		Repairs a database table

        .. method:: xml_from_results($query, $params)

                :param  object  $query:   DB_result with data to backup
                :param  array  $params:  Associative array of preferences
                :returns:   The generated XML document as a string
                :rtype:         string