~tsep-dev/tsep/0.9-beta

« back to all changes in this revision

Viewing changes to branches/symfony/cake/libs/model/datasources/dbo/dbo_mysql.php

  • Committer: geoffreyfishing
  • Date: 2011-01-11 23:46:12 UTC
  • Revision ID: svn-v4:ae0de26e-ed09-4cbe-9a20-e40b4c60ac6c::125
Created a symfony branch for future migration to symfony

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<?php
 
2
/**
 
3
 * MySQL layer for DBO
 
4
 *
 
5
 * PHP versions 4 and 5
 
6
 *
 
7
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 
8
 * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
 
9
 *
 
10
 * Licensed under The MIT License
 
11
 * Redistributions of files must retain the above copyright notice.
 
12
 *
 
13
 * @copyright     Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
 
14
 * @link          http://cakephp.org CakePHP(tm) Project
 
15
 * @package       cake
 
16
 * @subpackage    cake.cake.libs.model.datasources.dbo
 
17
 * @since         CakePHP(tm) v 0.10.5.1790
 
18
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 
19
 */
 
20
 
 
21
/**
 
22
 * Provides common base for MySQL & MySQLi connections
 
23
 *
 
24
 * @package       cake
 
25
 * @subpackage    cake.cake.libs.model.datasources.dbo
 
26
 */
 
27
class DboMysqlBase extends DboSource {
 
28
 
 
29
/**
 
30
 * Description property.
 
31
 *
 
32
 * @var string
 
33
 */
 
34
        var $description = "MySQL DBO Base Driver";
 
35
 
 
36
/**
 
37
 * Start quote
 
38
 *
 
39
 * @var string
 
40
 */
 
41
        var $startQuote = "`";
 
42
 
 
43
/**
 
44
 * End quote
 
45
 *
 
46
 * @var string
 
47
 */
 
48
        var $endQuote = "`";
 
49
 
 
50
/**
 
51
 * use alias for update and delete. Set to true if version >= 4.1
 
52
 *
 
53
 * @var boolean
 
54
 * @access protected
 
55
 */
 
56
        var $_useAlias = true;
 
57
 
 
58
/**
 
59
 * Index of basic SQL commands
 
60
 *
 
61
 * @var array
 
62
 * @access protected
 
63
 */
 
64
        var $_commands = array(
 
65
                'begin'    => 'START TRANSACTION',
 
66
                'commit'   => 'COMMIT',
 
67
                'rollback' => 'ROLLBACK'
 
68
        );
 
69
 
 
70
/**
 
71
 * List of engine specific additional field parameters used on table creating
 
72
 *
 
73
 * @var array
 
74
 * @access public
 
75
 */
 
76
        var $fieldParameters = array(
 
77
                'charset' => array('value' => 'CHARACTER SET', 'quote' => false, 'join' => ' ', 'column' => false, 'position' => 'beforeDefault'),
 
78
                'collate' => array('value' => 'COLLATE', 'quote' => false, 'join' => ' ', 'column' => 'Collation', 'position' => 'beforeDefault'),
 
79
                'comment' => array('value' => 'COMMENT', 'quote' => true, 'join' => ' ', 'column' => 'Comment', 'position' => 'afterDefault')
 
80
        );
 
81
 
 
82
/**
 
83
 * List of table engine specific parameters used on table creating
 
84
 *
 
85
 * @var array
 
86
 * @access public
 
87
 */
 
88
        var $tableParameters = array(
 
89
                'charset' => array('value' => 'DEFAULT CHARSET', 'quote' => false, 'join' => '=', 'column' => 'charset'),
 
90
                'collate' => array('value' => 'COLLATE', 'quote' => false, 'join' => '=', 'column' => 'Collation'),
 
91
                'engine' => array('value' => 'ENGINE', 'quote' => false, 'join' => '=', 'column' => 'Engine')
 
92
        );
 
93
 
 
94
/**
 
95
 * MySQL column definition
 
96
 *
 
97
 * @var array
 
98
 */
 
99
        var $columns = array(
 
100
                'primary_key' => array('name' => 'NOT NULL AUTO_INCREMENT'),
 
101
                'string' => array('name' => 'varchar', 'limit' => '255'),
 
102
                'text' => array('name' => 'text'),
 
103
                'integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'),
 
104
                'float' => array('name' => 'float', 'formatter' => 'floatval'),
 
105
                'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
 
106
                'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
 
107
                'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
 
108
                'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
 
109
                'binary' => array('name' => 'blob'),
 
110
                'boolean' => array('name' => 'tinyint', 'limit' => '1')
 
111
        );
 
112
 
 
113
/**
 
114
 * Returns an array of the fields in given table name.
 
115
 *
 
116
 * @param string $tableName Name of database table to inspect
 
117
 * @return array Fields in table. Keys are name and type
 
118
 */
 
119
        function describe(&$model) {
 
120
                $cache = parent::describe($model);
 
121
                if ($cache != null) {
 
122
                        return $cache;
 
123
                }
 
124
                $fields = false;
 
125
                $cols = $this->query('SHOW FULL COLUMNS FROM ' . $this->fullTableName($model));
 
126
 
 
127
                foreach ($cols as $column) {
 
128
                        $colKey = array_keys($column);
 
129
                        if (isset($column[$colKey[0]]) && !isset($column[0])) {
 
130
                                $column[0] = $column[$colKey[0]];
 
131
                        }
 
132
                        if (isset($column[0])) {
 
133
                                $fields[$column[0]['Field']] = array(
 
134
                                        'type' => $this->column($column[0]['Type']),
 
135
                                        'null' => ($column[0]['Null'] == 'YES' ? true : false),
 
136
                                        'default' => $column[0]['Default'],
 
137
                                        'length' => $this->length($column[0]['Type']),
 
138
                                );
 
139
                                if (!empty($column[0]['Key']) && isset($this->index[$column[0]['Key']])) {
 
140
                                        $fields[$column[0]['Field']]['key'] = $this->index[$column[0]['Key']];
 
141
                                }
 
142
                                foreach ($this->fieldParameters as $name => $value) {
 
143
                                        if (!empty($column[0][$value['column']])) {
 
144
                                                $fields[$column[0]['Field']][$name] = $column[0][$value['column']];
 
145
                                        }
 
146
                                }
 
147
                                if (isset($fields[$column[0]['Field']]['collate'])) {
 
148
                                        $charset = $this->getCharsetName($fields[$column[0]['Field']]['collate']);
 
149
                                        if ($charset) {
 
150
                                                $fields[$column[0]['Field']]['charset'] = $charset;
 
151
                                        }
 
152
                                }
 
153
                        }
 
154
                }
 
155
                $this->__cacheDescription($this->fullTableName($model, false), $fields);
 
156
                return $fields;
 
157
        }
 
158
 
 
159
/**
 
160
 * Generates and executes an SQL UPDATE statement for given model, fields, and values.
 
161
 *
 
162
 * @param Model $model
 
163
 * @param array $fields
 
164
 * @param array $values
 
165
 * @param mixed $conditions
 
166
 * @return array
 
167
 */
 
168
        function update(&$model, $fields = array(), $values = null, $conditions = null) {
 
169
                if (!$this->_useAlias) {
 
170
                        return parent::update($model, $fields, $values, $conditions);
 
171
                }
 
172
 
 
173
                if ($values == null) {
 
174
                        $combined = $fields;
 
175
                } else {
 
176
                        $combined = array_combine($fields, $values);
 
177
                }
 
178
 
 
179
                $alias = $joins = false;
 
180
                $fields = $this->_prepareUpdateFields($model, $combined, empty($conditions), !empty($conditions));
 
181
                $fields = implode(', ', $fields);
 
182
                $table = $this->fullTableName($model);
 
183
 
 
184
                if (!empty($conditions)) {
 
185
                        $alias = $this->name($model->alias);
 
186
                        if ($model->name == $model->alias) {
 
187
                                $joins = implode(' ', $this->_getJoins($model));
 
188
                        }
 
189
                }
 
190
                $conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model);
 
191
 
 
192
                if ($conditions === false) {
 
193
                        return false;
 
194
                }
 
195
 
 
196
                if (!$this->execute($this->renderStatement('update', compact('table', 'alias', 'joins', 'fields', 'conditions')))) {
 
197
                        $model->onError();
 
198
                        return false;
 
199
                }
 
200
                return true;
 
201
        }
 
202
 
 
203
/**
 
204
 * Generates and executes an SQL DELETE statement for given id/conditions on given model.
 
205
 *
 
206
 * @param Model $model
 
207
 * @param mixed $conditions
 
208
 * @return boolean Success
 
209
 */
 
210
        function delete(&$model, $conditions = null) {
 
211
                if (!$this->_useAlias) {
 
212
                        return parent::delete($model, $conditions);
 
213
                }
 
214
                $alias = $this->name($model->alias);
 
215
                $table = $this->fullTableName($model);
 
216
                $joins = implode(' ', $this->_getJoins($model));
 
217
 
 
218
                if (empty($conditions)) {
 
219
                        $alias = $joins = false;
 
220
                }
 
221
                $conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model);
 
222
 
 
223
                if ($conditions === false) {
 
224
                        return false;
 
225
                }
 
226
 
 
227
                if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
 
228
                        $model->onError();
 
229
                        return false;
 
230
                }
 
231
                return true;
 
232
        }
 
233
 
 
234
/**
 
235
 * Sets the database encoding
 
236
 *
 
237
 * @param string $enc Database encoding
 
238
 */
 
239
        function setEncoding($enc) {
 
240
                return $this->_execute('SET NAMES ' . $enc) != false;
 
241
        }
 
242
 
 
243
/**
 
244
 * Returns an array of the indexes in given datasource name.
 
245
 *
 
246
 * @param string $model Name of model to inspect
 
247
 * @return array Fields in table. Keys are column and unique
 
248
 */
 
249
        function index($model) {
 
250
                $index = array();
 
251
                $table = $this->fullTableName($model);
 
252
                if ($table) {
 
253
                        $indexes = $this->query('SHOW INDEX FROM ' . $table);
 
254
                        if (isset($indexes[0]['STATISTICS'])) {
 
255
                                $keys = Set::extract($indexes, '{n}.STATISTICS');
 
256
                        } else {
 
257
                                $keys = Set::extract($indexes, '{n}.0');
 
258
                        }
 
259
                        foreach ($keys as $i => $key) {
 
260
                                if (!isset($index[$key['Key_name']])) {
 
261
                                        $col = array();
 
262
                                        $index[$key['Key_name']]['column'] = $key['Column_name'];
 
263
                                        $index[$key['Key_name']]['unique'] = intval($key['Non_unique'] == 0);
 
264
                                } else {
 
265
                                        if (!is_array($index[$key['Key_name']]['column'])) {
 
266
                                                $col[] = $index[$key['Key_name']]['column'];
 
267
                                        }
 
268
                                        $col[] = $key['Column_name'];
 
269
                                        $index[$key['Key_name']]['column'] = $col;
 
270
                                }
 
271
                        }
 
272
                }
 
273
                return $index;
 
274
        }
 
275
 
 
276
/**
 
277
 * Generate a MySQL Alter Table syntax for the given Schema comparison
 
278
 *
 
279
 * @param array $compare Result of a CakeSchema::compare()
 
280
 * @return array Array of alter statements to make.
 
281
 */
 
282
        function alterSchema($compare, $table = null) {
 
283
                if (!is_array($compare)) {
 
284
                        return false;
 
285
                }
 
286
                $out = '';
 
287
                $colList = array();
 
288
                foreach ($compare as $curTable => $types) {
 
289
                        $indexes = $tableParameters = $colList = array();
 
290
                        if (!$table || $table == $curTable) {
 
291
                                $out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
 
292
                                foreach ($types as $type => $column) {
 
293
                                        if (isset($column['indexes'])) {
 
294
                                                $indexes[$type] = $column['indexes'];
 
295
                                                unset($column['indexes']);
 
296
                                        }
 
297
                                        if (isset($column['tableParameters'])) {
 
298
                                                $tableParameters[$type] = $column['tableParameters'];
 
299
                                                unset($column['tableParameters']);
 
300
                                        }
 
301
                                        switch ($type) {
 
302
                                                case 'add':
 
303
                                                        foreach ($column as $field => $col) {
 
304
                                                                $col['name'] = $field;
 
305
                                                                $alter = 'ADD ' . $this->buildColumn($col);
 
306
                                                                if (isset($col['after'])) {
 
307
                                                                        $alter .= ' AFTER ' . $this->name($col['after']);
 
308
                                                                }
 
309
                                                                $colList[] = $alter;
 
310
                                                        }
 
311
                                                break;
 
312
                                                case 'drop':
 
313
                                                        foreach ($column as $field => $col) {
 
314
                                                                $col['name'] = $field;
 
315
                                                                $colList[] = 'DROP ' . $this->name($field);
 
316
                                                        }
 
317
                                                break;
 
318
                                                case 'change':
 
319
                                                        foreach ($column as $field => $col) {
 
320
                                                                if (!isset($col['name'])) {
 
321
                                                                        $col['name'] = $field;
 
322
                                                                }
 
323
                                                                $colList[] = 'CHANGE ' . $this->name($field) . ' ' . $this->buildColumn($col);
 
324
                                                        }
 
325
                                                break;
 
326
                                        }
 
327
                                }
 
328
                                $colList = array_merge($colList, $this->_alterIndexes($curTable, $indexes));
 
329
                                $colList = array_merge($colList, $this->_alterTableParameters($curTable, $tableParameters));
 
330
                                $out .= "\t" . join(",\n\t", $colList) . ";\n\n";
 
331
                        }
 
332
                }
 
333
                return $out;
 
334
        }
 
335
 
 
336
/**
 
337
 * Generate a MySQL "drop table" statement for the given Schema object
 
338
 *
 
339
 * @param object $schema An instance of a subclass of CakeSchema
 
340
 * @param string $table Optional.  If specified only the table name given will be generated.
 
341
 *                      Otherwise, all tables defined in the schema are generated.
 
342
 * @return string
 
343
 */
 
344
        function dropSchema($schema, $table = null) {
 
345
                if (!is_a($schema, 'CakeSchema')) {
 
346
                        trigger_error(__('Invalid schema object', true), E_USER_WARNING);
 
347
                        return null;
 
348
                }
 
349
                $out = '';
 
350
                foreach ($schema->tables as $curTable => $columns) {
 
351
                        if (!$table || $table == $curTable) {
 
352
                                $out .= 'DROP TABLE IF EXISTS ' . $this->fullTableName($curTable) . ";\n";
 
353
                        }
 
354
                }
 
355
                return $out;
 
356
        }
 
357
 
 
358
/**
 
359
 * Generate MySQL table parameter alteration statementes for a table.
 
360
 *
 
361
 * @param string $table Table to alter parameters for.
 
362
 * @param array $parameters Parameters to add & drop.
 
363
 * @return array Array of table property alteration statementes.
 
364
 * @todo Implement this method.
 
365
 */
 
366
        function _alterTableParameters($table, $parameters) {
 
367
                if (isset($parameters['change'])) {
 
368
                        return $this->buildTableParameters($parameters['change']);
 
369
                }
 
370
                return array();
 
371
        }
 
372
 
 
373
/**
 
374
 * Generate MySQL index alteration statements for a table.
 
375
 *
 
376
 * @param string $table Table to alter indexes for
 
377
 * @param array $new Indexes to add and drop
 
378
 * @return array Index alteration statements
 
379
 */
 
380
        function _alterIndexes($table, $indexes) {
 
381
                $alter = array();
 
382
                if (isset($indexes['drop'])) {
 
383
                        foreach($indexes['drop'] as $name => $value) {
 
384
                                $out = 'DROP ';
 
385
                                if ($name == 'PRIMARY') {
 
386
                                        $out .= 'PRIMARY KEY';
 
387
                                } else {
 
388
                                        $out .= 'KEY ' . $name;
 
389
                                }
 
390
                                $alter[] = $out;
 
391
                        }
 
392
                }
 
393
                if (isset($indexes['add'])) {
 
394
                        foreach ($indexes['add'] as $name => $value) {
 
395
                                $out = 'ADD ';
 
396
                                if ($name == 'PRIMARY') {
 
397
                                        $out .= 'PRIMARY ';
 
398
                                        $name = null;
 
399
                                } else {
 
400
                                        if (!empty($value['unique'])) {
 
401
                                                $out .= 'UNIQUE ';
 
402
                                        }
 
403
                                }
 
404
                                if (is_array($value['column'])) {
 
405
                                        $out .= 'KEY '. $name .' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
 
406
                                } else {
 
407
                                        $out .= 'KEY '. $name .' (' . $this->name($value['column']) . ')';
 
408
                                }
 
409
                                $alter[] = $out;
 
410
                        }
 
411
                }
 
412
                return $alter;
 
413
        }
 
414
 
 
415
/**
 
416
 * Inserts multiple values into a table
 
417
 *
 
418
 * @param string $table
 
419
 * @param string $fields
 
420
 * @param array $values
 
421
 */
 
422
        function insertMulti($table, $fields, $values) {
 
423
                $table = $this->fullTableName($table);
 
424
                if (is_array($fields)) {
 
425
                        $fields = implode(', ', array_map(array(&$this, 'name'), $fields));
 
426
                }
 
427
                $values = implode(', ', $values);
 
428
                $this->query("INSERT INTO {$table} ({$fields}) VALUES {$values}");
 
429
        }
 
430
/**
 
431
 * Returns an detailed array of sources (tables) in the database.
 
432
 *
 
433
 * @param string $name Table name to get parameters 
 
434
 * @return array Array of tablenames in the database
 
435
 */
 
436
        function listDetailedSources($name = null) {
 
437
                $condition = '';
 
438
                if (is_string($name)) {
 
439
                        $condition = ' LIKE ' . $this->value($name);
 
440
                }
 
441
                $result = $this->query('SHOW TABLE STATUS FROM ' . $this->name($this->config['database']) . $condition . ';');
 
442
                if (!$result) {
 
443
                        return array();
 
444
                } else {
 
445
                        $tables = array();
 
446
                        foreach ($result as $row) {
 
447
                                $tables[$row['TABLES']['Name']] = $row['TABLES'];
 
448
                                if (!empty($row['TABLES']['Collation'])) {
 
449
                                        $charset = $this->getCharsetName($row['TABLES']['Collation']);
 
450
                                        if ($charset) {
 
451
                                                $tables[$row['TABLES']['Name']]['charset'] = $charset;
 
452
                                        }
 
453
                                }
 
454
                        }
 
455
                        if (is_string($name)) {
 
456
                                return $tables[$name];
 
457
                        }
 
458
                        return $tables;
 
459
                }
 
460
        }
 
461
 
 
462
/**
 
463
 * Converts database-layer column types to basic types
 
464
 *
 
465
 * @param string $real Real database-layer column type (i.e. "varchar(255)")
 
466
 * @return string Abstract column type (i.e. "string")
 
467
 */
 
468
        function column($real) {
 
469
                if (is_array($real)) {
 
470
                        $col = $real['name'];
 
471
                        if (isset($real['limit'])) {
 
472
                                $col .= '('.$real['limit'].')';
 
473
                        }
 
474
                        return $col;
 
475
                }
 
476
 
 
477
                $col = str_replace(')', '', $real);
 
478
                $limit = $this->length($real);
 
479
                if (strpos($col, '(') !== false) {
 
480
                        list($col, $vals) = explode('(', $col);
 
481
                }
 
482
 
 
483
                if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
 
484
                        return $col;
 
485
                }
 
486
                if (($col == 'tinyint' && $limit == 1) || $col == 'boolean') {
 
487
                        return 'boolean';
 
488
                }
 
489
                if (strpos($col, 'int') !== false) {
 
490
                        return 'integer';
 
491
                }
 
492
                if (strpos($col, 'char') !== false || $col == 'tinytext') {
 
493
                        return 'string';
 
494
                }
 
495
                if (strpos($col, 'text') !== false) {
 
496
                        return 'text';
 
497
                }
 
498
                if (strpos($col, 'blob') !== false || $col == 'binary') {
 
499
                        return 'binary';
 
500
                }
 
501
                if (strpos($col, 'float') !== false || strpos($col, 'double') !== false || strpos($col, 'decimal') !== false) {
 
502
                        return 'float';
 
503
                }
 
504
                if (strpos($col, 'enum') !== false) {
 
505
                        return "enum($vals)";
 
506
                }
 
507
                return 'text';
 
508
        }
 
509
}
 
510
 
 
511
/**
 
512
 * MySQL DBO driver object
 
513
 *
 
514
 * Provides connection and SQL generation for MySQL RDMS
 
515
 *
 
516
 * @package       cake
 
517
 * @subpackage    cake.cake.libs.model.datasources.dbo
 
518
 */
 
519
class DboMysql extends DboMysqlBase {
 
520
 
 
521
/**
 
522
 * Datasource description
 
523
 *
 
524
 * @var string
 
525
 */
 
526
        var $description = "MySQL DBO Driver";
 
527
 
 
528
/**
 
529
 * Base configuration settings for MySQL driver
 
530
 *
 
531
 * @var array
 
532
 */
 
533
        var $_baseConfig = array(
 
534
                'persistent' => true,
 
535
                'host' => 'localhost',
 
536
                'login' => 'root',
 
537
                'password' => '',
 
538
                'database' => 'cake',
 
539
                'port' => '3306'
 
540
        );
 
541
 
 
542
/**
 
543
 * Connects to the database using options in the given configuration array.
 
544
 *
 
545
 * @return boolean True if the database could be connected, else false
 
546
 */
 
547
        function connect() {
 
548
                $config = $this->config;
 
549
                $this->connected = false;
 
550
 
 
551
                if (!$config['persistent']) {
 
552
                        $this->connection = mysql_connect($config['host'] . ':' . $config['port'], $config['login'], $config['password'], true);
 
553
                        $config['connect'] = 'mysql_connect';
 
554
                } else {
 
555
                        $this->connection = mysql_pconnect($config['host'] . ':' . $config['port'], $config['login'], $config['password']);
 
556
                }
 
557
 
 
558
                if (mysql_select_db($config['database'], $this->connection)) {
 
559
                        $this->connected = true;
 
560
                }
 
561
 
 
562
                if (!empty($config['encoding'])) {
 
563
                        $this->setEncoding($config['encoding']);
 
564
                }
 
565
 
 
566
                $this->_useAlias = (bool)version_compare(mysql_get_server_info($this->connection), "4.1", ">=");
 
567
 
 
568
                return $this->connected;
 
569
        }
 
570
 
 
571
/**
 
572
 * Check whether the MySQL extension is installed/loaded
 
573
 *
 
574
 * @return boolean
 
575
 */
 
576
        function enabled() {
 
577
                return extension_loaded('mysql');
 
578
        }
 
579
/**
 
580
 * Disconnects from database.
 
581
 *
 
582
 * @return boolean True if the database could be disconnected, else false
 
583
 */
 
584
        function disconnect() {
 
585
                if (isset($this->results) && is_resource($this->results)) {
 
586
                        mysql_free_result($this->results);
 
587
                }
 
588
                $this->connected = !@mysql_close($this->connection);
 
589
                return !$this->connected;
 
590
        }
 
591
 
 
592
/**
 
593
 * Executes given SQL statement.
 
594
 *
 
595
 * @param string $sql SQL statement
 
596
 * @return resource Result resource identifier
 
597
 * @access protected
 
598
 */
 
599
        function _execute($sql) {
 
600
                return mysql_query($sql, $this->connection);
 
601
        }
 
602
 
 
603
/**
 
604
 * Returns an array of sources (tables) in the database.
 
605
 *
 
606
 * @return array Array of tablenames in the database
 
607
 */
 
608
        function listSources() {
 
609
                $cache = parent::listSources();
 
610
                if ($cache != null) {
 
611
                        return $cache;
 
612
                }
 
613
                $result = $this->_execute('SHOW TABLES FROM ' . $this->name($this->config['database']) . ';');
 
614
 
 
615
                if (!$result) {
 
616
                        return array();
 
617
                } else {
 
618
                        $tables = array();
 
619
 
 
620
                        while ($line = mysql_fetch_row($result)) {
 
621
                                $tables[] = $line[0];
 
622
                        }
 
623
                        parent::listSources($tables);
 
624
                        return $tables;
 
625
                }
 
626
        }
 
627
 
 
628
/**
 
629
 * Returns a quoted and escaped string of $data for use in an SQL statement.
 
630
 *
 
631
 * @param string $data String to be prepared for use in an SQL statement
 
632
 * @param string $column The column into which this data will be inserted
 
633
 * @param boolean $safe Whether or not numeric data should be handled automagically if no column data is provided
 
634
 * @return string Quoted and escaped data
 
635
 */
 
636
        function value($data, $column = null, $safe = false) {
 
637
                $parent = parent::value($data, $column, $safe);
 
638
 
 
639
                if ($parent != null) {
 
640
                        return $parent;
 
641
                }
 
642
                if ($data === null || (is_array($data) && empty($data))) {
 
643
                        return 'NULL';
 
644
                }
 
645
                if ($data === '' && $column !== 'integer' && $column !== 'float' && $column !== 'boolean') {
 
646
                        return  "''";
 
647
                }
 
648
                if (empty($column)) {
 
649
                        $column = $this->introspectType($data);
 
650
                }
 
651
 
 
652
                switch ($column) {
 
653
                        case 'boolean':
 
654
                                return $this->boolean((bool)$data);
 
655
                        break;
 
656
                        case 'integer':
 
657
                        case 'float':
 
658
                                if ($data === '') {
 
659
                                        return 'NULL';
 
660
                                }
 
661
                                if (is_float($data)) {
 
662
                                        return sprintf('%F', $data);
 
663
                                }
 
664
                                if ((is_int($data) || $data === '0') || (
 
665
                                        is_numeric($data) && strpos($data, ',') === false &&
 
666
                                        $data[0] != '0' && strpos($data, 'e') === false)
 
667
                                ) {
 
668
                                        return $data;
 
669
                                }
 
670
                        default:
 
671
                                return "'" . mysql_real_escape_string($data, $this->connection) . "'";
 
672
                        break;
 
673
                }
 
674
        }
 
675
 
 
676
/**
 
677
 * Returns a formatted error message from previous database operation.
 
678
 *
 
679
 * @return string Error message with error number
 
680
 */
 
681
        function lastError() {
 
682
                if (mysql_errno($this->connection)) {
 
683
                        return mysql_errno($this->connection).': '.mysql_error($this->connection);
 
684
                }
 
685
                return null;
 
686
        }
 
687
 
 
688
/**
 
689
 * Returns number of affected rows in previous database operation. If no previous operation exists,
 
690
 * this returns false.
 
691
 *
 
692
 * @return integer Number of affected rows
 
693
 */
 
694
        function lastAffected() {
 
695
                if ($this->_result) {
 
696
                        return mysql_affected_rows($this->connection);
 
697
                }
 
698
                return null;
 
699
        }
 
700
 
 
701
/**
 
702
 * Returns number of rows in previous resultset. If no previous resultset exists,
 
703
 * this returns false.
 
704
 *
 
705
 * @return integer Number of rows in resultset
 
706
 */
 
707
        function lastNumRows() {
 
708
                if ($this->hasResult()) {
 
709
                        return mysql_num_rows($this->_result);
 
710
                }
 
711
                return null;
 
712
        }
 
713
 
 
714
/**
 
715
 * Returns the ID generated from the previous INSERT operation.
 
716
 *
 
717
 * @param unknown_type $source
 
718
 * @return in
 
719
 */
 
720
        function lastInsertId($source = null) {
 
721
                $id = $this->fetchRow('SELECT LAST_INSERT_ID() AS insertID', false);
 
722
                if ($id !== false && !empty($id) && !empty($id[0]) && isset($id[0]['insertID'])) {
 
723
                        return $id[0]['insertID'];
 
724
                }
 
725
 
 
726
                return null;
 
727
        }
 
728
 
 
729
/**
 
730
 * Enter description here...
 
731
 *
 
732
 * @param unknown_type $results
 
733
 */
 
734
        function resultSet(&$results) {
 
735
                if (isset($this->results) && is_resource($this->results) && $this->results != $results) {
 
736
                        mysql_free_result($this->results);
 
737
                }
 
738
                $this->results =& $results;
 
739
                $this->map = array();
 
740
                $numFields = mysql_num_fields($results);
 
741
                $index = 0;
 
742
                $j = 0;
 
743
 
 
744
                while ($j < $numFields) {
 
745
                        $column = mysql_fetch_field($results, $j);
 
746
                        if (!empty($column->table) && strpos($column->name, $this->virtualFieldSeparator) === false) {
 
747
                                $this->map[$index++] = array($column->table, $column->name);
 
748
                        } else {
 
749
                                $this->map[$index++] = array(0, $column->name);
 
750
                        }
 
751
                        $j++;
 
752
                }
 
753
        }
 
754
 
 
755
/**
 
756
 * Fetches the next row from the current result set
 
757
 *
 
758
 * @return unknown
 
759
 */
 
760
        function fetchResult() {
 
761
                if ($row = mysql_fetch_row($this->results)) {
 
762
                        $resultRow = array();
 
763
                        $i = 0;
 
764
                        foreach ($row as $index => $field) {
 
765
                                list($table, $column) = $this->map[$index];
 
766
                                $resultRow[$table][$column] = $row[$index];
 
767
                                $i++;
 
768
                        }
 
769
                        return $resultRow;
 
770
                } else {
 
771
                        return false;
 
772
                }
 
773
        }
 
774
 
 
775
/**
 
776
 * Gets the database encoding
 
777
 *
 
778
 * @return string The database encoding
 
779
 */
 
780
        function getEncoding() {
 
781
                return mysql_client_encoding($this->connection);
 
782
        }
 
783
 
 
784
/**
 
785
 * Query charset by collation
 
786
 *
 
787
 * @param string $name Collation name
 
788
 * @return string Character set name
 
789
 */
 
790
        function getCharsetName($name) {
 
791
                if ((bool)version_compare(mysql_get_server_info($this->connection), "5", ">=")) {
 
792
                        $cols = $this->query('SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME= ' . $this->value($name) . ';');
 
793
                        if (isset($cols[0]['COLLATIONS']['CHARACTER_SET_NAME'])) {
 
794
                                return $cols[0]['COLLATIONS']['CHARACTER_SET_NAME'];
 
795
                        }
 
796
                }
 
797
                return false;
 
798
        }
 
799
}