Subversion Repositories PHPX

Rev

Rev 61 | Rev 68 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 61 Rev 66
1
<?php
1
<?php
2
2
3
namespace PointedEars\PHPX\Db;
3
namespace PointedEars\PHPX\Db;
4
4
5
require_once __DIR__ . '/../global.inc';
5
require_once __DIR__ . '/../global.inc';
6
6
7
/**
7
/**
8
 * Generic database model class using PDO (PHP Data Objects)
8
 * Generic database model class using PDO (PHP Data Objects)
9
 *
9
 *
10
 * @property-read PDO $connection
10
 * @property-read PDO $connection
11
 *   Database connection.  Established on read access to this
11
 *   Database connection.  Established on read access to this
12
 *   property if not yet established.
12
 *   property if not yet established.
13
 * @property-read array $lastError
13
 * @property-read array $lastError
14
 *   Last error information of the database operation.
14
 *   Last error information of the database operation.
15
 *   See {@link PDOStatement::errorInfo()}.
15
 *   See {@link PDOStatement::errorInfo()}.
16
 * @property-read string $lastInsertId
16
 * @property-read string $lastInsertId
17
 *   ID of the last inserted row, or the last value from a sequence object,
17
 *   ID of the last inserted row, or the last value from a sequence object,
18
 *   depending on the underlying driver. May not be supported by all databases.
18
 *   depending on the underlying driver. May not be supported by all databases.
19
 * @property-read array $lastResult
19
 * @property-read array $lastResult
20
 *   Last result of the database operation
20
 *   Last result of the database operation
21
 * @property-read boolean $lastSuccess
21
 * @property-read boolean $lastSuccess
22
 *   Last success value of the database operation
22
 *   Last success value of the database operation
23
 * @author Thomas Lahn
23
 * @author Thomas Lahn
24
 */
24
 */
25
class Database extends \PointedEars\PHPX\AbstractModel
25
class Database extends \PointedEars\PHPX\AbstractModel
26
{
26
{
27
  /* Access properties */
27
  /* Access properties */
28
28
29
  /**
29
  /**
30
   * DSN of the database
30
   * DSN of the database
31
   * @var string
31
   * @var string
32
   */
32
   */
33
  protected $_dsn = '';
33
  protected $_dsn = '';
34
34
35
  /**
35
  /**
36
   * Username to access the database
36
   * Username to access the database
37
   * @var string
37
   * @var string
38
   */
38
   */
39
  protected $_username;
39
  protected $_username;
40
40
41
  /**
41
  /**
42
   * Password to access the database
42
   * Password to access the database
43
   * @var string
43
   * @var string
44
   */
44
   */
45
  protected $_password;
45
  protected $_password;
46
46
47
  /**
47
  /**
48
   * PDO driver-specific options
48
   * PDO driver-specific options
49
   * @var array
49
   * @var array
50
   */
50
   */
51
  protected $_options = array();
51
  protected $_options = array();
52
52
53
  /**
53
  /**
54
   * Database-specific string to use for quoting a name or value
54
   * Database-specific string to use for quoting a name or value
55
   * left-hand side (for security reasons and to prevent a name
55
   * left-hand side (for security reasons and to prevent a name
56
   * from being parsed as a keyword).
56
   * from being parsed as a keyword).
57
   * @var string
57
   * @var string
58
   */
58
   */
59
  protected $_leftQuote = '';
59
  protected $_leftQuote = '';
60
60
61
  /**
61
  /**
62
   * Database-specific string to use for quoting a name or value
62
   * Database-specific string to use for quoting a name or value
63
   * left-hand side (for security reasons and to prevent a name
63
   * left-hand side (for security reasons and to prevent a name
64
   * from being parsed as a keyword).
64
   * from being parsed as a keyword).
65
   * @var string
65
   * @var string
66
   */
66
   */
67
  protected $_rightQuote = '';
67
  protected $_rightQuote = '';
68
68
69
  /* Status properties */
69
  /* Status properties */
70
70
71
  /**
71
  /**
72
   * Database connection
72
   * Database connection
73
   * @var PDO
73
   * @var PDO
74
   */
74
   */
75
  protected $_connection;
75
  protected $_connection;
76
76
77
  /**
77
  /**
78
   * Last success value of the database operation
78
   * Last success value of the database operation
79
   * @var boolean
79
   * @var boolean
80
   */
80
   */
81
  protected $_lastSuccess;
81
  protected $_lastSuccess;
82
82
83
  /**
83
  /**
84
   * Last error information of the database operation
84
   * Last error information of the database operation
85
   * @var array
85
   * @var array
86
   */
86
   */
87
  protected $_lastError;
87
  protected $_lastError;
88
88
89
  /**
89
  /**
90
   * Last result of the database operation
90
   * Last result of the database operation
91
   * @var array
91
   * @var array
92
   */
92
   */
93
  protected $_lastResult;
93
  protected $_lastResult;
94
94
95
  /**
95
  /**
96
  * ID of the last inserted row, or the last value from a sequence object,
96
  * ID of the last inserted row, or the last value from a sequence object,
97
  * depending on the underlying driver. May not be supported by all databases.
97
  * depending on the underlying driver. May not be supported by all databases.
98
  * @var string
98
  * @var string
99
  */
99
  */
100
  protected $_lastInsertId = '';
100
  protected $_lastInsertId = '';
101
101
102
  /**
102
  /**
103
   * Creates a new <code>Database</code> instance.
103
   * Creates a new <code>Database</code> instance.
104
   *
104
   *
105
   * Each of the parameters is optional and can also be given
105
   * Each of the parameters is optional and can also be given
106
   * by a protected property where the parameter name is preceded
106
   * by a protected property where the parameter name is preceded
107
   * by <code>_</code>.  Parameter values overwrite the default
107
   * by <code>_</code>.  Parameter values overwrite the default
108
   * property values.  It is recommended to use default property
108
   * property values.  It is recommended to use default property
109
   * values of inheriting classes except for small applications
109
   * values of inheriting classes except for small applications
110
   * and testing purposes.
110
   * and testing purposes.
111
   *
111
   *
112
   * @param string $dsn
112
   * @param string $dsn
113
   * @param string $username
113
   * @param string $username
114
   * @param string $password
114
   * @param string $password
115
   * @param array $options
115
   * @param array $options
116
   * @see PDO::__construct()
116
   * @see PDO::__construct()
117
   */
117
   */
118
  public function __construct ($dsn = '', $username = null,
118
  public function __construct ($dsn = '', $username = null,
119
    $password = null, array $options = array())
119
    $password = null, array $options = array())
120
  {
120
  {
121
    if ($dsn !== '')
121
    if ($dsn !== '')
122
    {
122
    {
123
      $this->_dsn = $dsn;
123
      $this->_dsn = $dsn;
124
    }
124
    }
125
125
126
    if ($username !== null)
126
    if ($username !== null)
127
    {
127
    {
128
      $this->_username = $username;
128
      $this->_username = $username;
129
    }
129
    }
130
130
131
    if ($password !== null)
131
    if ($password !== null)
132
    {
132
    {
133
      $this->_password = $password;
133
      $this->_password = $password;
134
    }
134
    }
135
135
136
    if ($options)
136
    if ($options)
137
    {
137
    {
138
      $this->_options = $options;
138
      $this->_options = $options;
139
    }
139
    }
140
  }
140
  }
141
141
142
  /**
142
  /**
143
   * Reads the connection configuration for this database
143
   * Reads the connection configuration for this database
144
   * from the configuration file, application/.config
144
   * from the configuration file, application/.config
145
   *
145
   *
146
   * There must be an INI section named "database:" followed
146
   * There must be an INI section named "database:" followed
147
   * by the value of the <code>$_dbname</code> property
147
   * by the value of the <code>$_dbname</code> property
148
   * containing keys and values for the properties of the
148
   * containing keys and values for the properties of the
149
   * <code>Database</code> instance.  Except for the key
149
   * <code>Database</code> instance.  Except for the key
150
   * <code>dbname</code>, which allows for aliases, all
150
   * <code>dbname</code>, which allows for aliases, all
151
   * keys are ignored if the corresponding properties
151
   * keys are ignored if the corresponding properties
152
   * were set.  That is, definitions in the class file
152
   * were set.  That is, definitions in the class file
153
   * override those in the configuration file.
153
   * override those in the configuration file.
154
   *
154
   *
155
   * @return boolean|array
155
   * @return boolean|array
156
   *   <code>true</code> if the configuration
156
   *   <code>true</code> if the configuration
157
   *   file could be read, the configuration array otherwise.
157
   *   file could be read, the configuration array otherwise.
158
   */
158
   */
159
  public function readConfig ()
159
  public function readConfig ()
160
  {
160
  {
161
        $config = parse_ini_file('application/.config', true);
161
        $config = parse_ini_file('application/.config', true);
162
        if ($config !== false)
162
        if ($config !== false)
163
        {
163
        {
164
                $section = 'database:' . $this->_dbname;
164
                $section = 'database:' . $this->_dbname;
165
                if (isset($config[$section]))
165
                if (isset($config[$section]))
166
                {
166
                {
167
                        $dbconfig = $config[$section];
167
                        $dbconfig = $config[$section];
168
                        foreach (array('host', 'dbname', 'username', 'password', 'charset') as $key)
168
                        foreach (array('host', 'dbname', 'username', 'password', 'charset') as $key)
169
                        {
169
                        {
170
                                $property = "_$key";
170
                                $property = "_$key";
171
                                if (isset($dbconfig[$key])
171
                                if (isset($dbconfig[$key])
172
                                     && $key == 'dbname'
172
                                     && $key == 'dbname'
173
                                                 || (property_exists($this, $property)
173
                                                 || (property_exists($this, $property)
174
                                                                  && $this->$property === null))
174
                                                                  && $this->$property === null))
175
                                {
175
                                {
176
                                        $this->$property = $dbconfig[$key];
176
                                        $this->$property = $dbconfig[$key];
177
                                }
177
                                }
178
                        }
178
                        }
179
                }
179
                }
180
        }
180
        }
181
181
182
        return $config;
182
        return $config;
183
  }
183
  }
184
184
185
  /**
185
  /**
186
   * @return PDO
186
   * @return PDO
187
   */
187
   */
188
  public function getConnection ()
188
  public function getConnection ()
189
  {
189
  {
190
    if ($this->_connection === null)
190
    if ($this->_connection === null)
191
    {
191
    {
192
      $this->_connection =
192
      $this->_connection =
193
        new \PDO($this->_dsn, $this->_username, $this->_password, $this->_options);
193
        new \PDO($this->_dsn, $this->_username, $this->_password, $this->_options);
194
    }
194
    }
195
195
196
    return $this->_connection;
196
    return $this->_connection;
197
  }
197
  }
198
198
199
  /**
199
  /**
200
   * Creates a database according to the specified parameters
200
   * Creates a database according to the specified parameters
201
   *
201
   *
202
   * Should be overwritten and called by inheriting classes.
202
   * Should be overwritten and called by inheriting classes.
203
   *
203
   *
204
   * @param string $dsn
204
   * @param string $dsn
205
   *   Connection DSN (required; must not include the database
205
   *   Connection DSN (required; must not include the database
206
   *   name).
206
   *   name).
207
   * @param string $username = null
207
   * @param string $username = null
208
   *   Connection username.  The default is specified by the
208
   *   Connection username.  The default is specified by the
209
   *   <code>$_username</code> property.  Note that creating
209
   *   <code>$_username</code> property.  Note that creating
210
   *   the database usually requires a user with more privileges
210
   *   the database usually requires a user with more privileges
211
   *   than the one accessing the database or its tables.
211
   *   than the one accessing the database or its tables.
212
   * @param string $password = null
212
   * @param string $password = null
213
   *   Connection password.  The default is specified by the
213
   *   Connection password.  The default is specified by the
214
   *   <code>$_password</code> property.
214
   *   <code>$_password</code> property.
215
   * @param array? $options = null
215
   * @param array? $options = null
216
   *   Connection options.  The default is specified by the
216
   *   Connection options.  The default is specified by the
217
   *   <code>$_options</code> property.
217
   *   <code>$_options</code> property.
218
   * @param string $spec = null
218
   * @param string $spec = null
219
   *   Additional database specifications, like character encoding
219
   *   Additional database specifications, like character encoding
220
   *   and collation.
220
   *   and collation.
221
   * @param boolean $force = false
221
   * @param boolean $force = false
222
   *   If a true-value, the database will be attempted to be
222
   *   If a true-value, the database will be attempted to be
223
   *   created even if there is a database of the name specified
223
   *   created even if there is a database of the name specified
224
   *   by the <code>$_dbname</code> property.
224
   *   by the <code>$_dbname</code> property.
225
   * @return int
225
   * @return int
226
   *   The number of rows affected by the CREATE DATABASE statement.
226
   *   The number of rows affected by the CREATE DATABASE statement.
227
   * @see PDO::__construct()
227
   * @see PDO::__construct()
228
   * @see PDO::exec()
228
   * @see PDO::exec()
229
   */
229
   */
230
  public function create ($dsn, $username = null, $password = null,
230
  public function create ($dsn, $username = null, $password = null,
231
    array $options = null, $dbspec = null, $force = false)
231
    array $options = null, $dbspec = null, $force = false)
232
  {
232
  {
233
    $connection = new \PDO($dsn,
233
    $connection = new \PDO($dsn,
234
      $username !== null ? $username : $this->_username,
234
      $username !== null ? $username : $this->_username,
235
      $password !== null ? $password : $this->_password,
235
      $password !== null ? $password : $this->_password,
236
      $options !== null ? $options : $this->_options);
236
      $options !== null ? $options : $this->_options);
237
237
238
    $query = 'CREATE DATABASE'
238
    $query = 'CREATE DATABASE'
239
           . (!$force ? ' IF NOT EXISTS' : '')
239
           . (!$force ? ' IF NOT EXISTS' : '')
240
           . ' ' . $this->escapeName($this->_dbname)
240
           . ' ' . $this->escapeName($this->_dbname)
241
           . ($dbspec ? ' ' . $dbspec : '');
241
           . ($dbspec ? ' ' . $dbspec : '');
242
242
243
    return $connection->exec($query);
243
    return $connection->exec($query);
244
  }
244
  }
245
245
246
  /**
246
  /**
247
   * Maps column meta-information to a column definition.
247
   * Maps column meta-information to a column definition.
248
   *
248
   *
249
   * Should be overwritten and called by inheriting classes.
249
   * Should be overwritten and called by inheriting classes.
250
   *
250
   *
251
   * @todo
251
   * @todo
252
   * @param array $value
252
   * @param array $value
253
   * @param string $column_name
253
   * @param string $column_name
254
   * @return string
254
   * @return string
255
   */
255
   */
256
  protected function _columnDef (array $data, $column_name)
256
  protected function _columnDef (array $data, $column_name)
257
  {
257
  {
258
        $def = (isset($data['unsigned']) && $data['unsigned'] ? 'UNSIGNED ' : '')
258
        $def = (isset($data['unsigned']) && $data['unsigned'] ? 'UNSIGNED ' : '')
259
                         . $data['type']
259
                         . $data['type']
260
                         . (isset($data['not_null']) && $data['not_null'] ? ' NOT NULL'                     : ' NULL')
260
                         . (isset($data['not_null']) && $data['not_null'] ? ' NOT NULL'                     : ' NULL')
261
                         . (isset($data['default'])  && $data['default']  ? " DEFAULT {$data['default']}"   : '')
261
                         . (isset($data['default'])  && $data['default']  ? " DEFAULT {$data['default']}"   : '')
262
                         . (isset($data['auto_inc']) && $data['auto_inc'] ? ' AUTO_INCREMENT'               : '')
262
                         . (isset($data['auto_inc']) && $data['auto_inc'] ? ' AUTO_INCREMENT'               : '')
263
                         . (isset($data['unique'])   && $data['unique']   ? ' UNIQUE KEY'                   : '')
263
                         . (isset($data['unique'])   && $data['unique']   ? ' UNIQUE KEY'                   : '')
264
                         . (isset($data['primary'])  && $data['primary']  ? ' PRIMARY KEY'                  : '')
264
                         . (isset($data['primary'])  && $data['primary']  ? ' PRIMARY KEY'                  : '')
265
                         . (isset($data['comment'])  && $data['comment']  ? " COMMENT '{$data['comment']}'" : '');
265
                         . (isset($data['comment'])  && $data['comment']  ? " COMMENT '{$data['comment']}'" : '');
266
266
267
        return $this->escapeName($column_name) . ' ' . $def;
267
        return $this->escapeName($column_name) . ' ' . $def;
268
  }
268
  }
269
269
270
  /**
270
  /**
271
   * Creates a database table according to the specified parameters
271
   * Creates a database table according to the specified parameters
272
   *
272
   *
273
   * @todo
273
   * @todo
274
   * @param string $name
274
   * @param string $name
275
   * @param array $columns
275
   * @param array $columns
276
   * @param array $options = null
276
   * @param array $options = null
277
   * @return bool
277
   * @return bool
278
   * @see PDOStatement::execute()
278
   * @see PDOStatement::execute()
279
   */
279
   */
280
  public function createTable ($name, array $columns, array $options = null)
280
  public function createTable ($name, array $columns, array $options = null)
281
  {
281
  {
282
        $class = \get_class($this);
282
        $class = \get_class($this);
283
        $query = 'CREATE TABLE '
283
        $query = 'CREATE TABLE '
284
          . $this->escapeName($name)
284
          . $this->escapeName($name)
285
          . '('
285
          . '('
286
          . array_map(array($this, '_columnDef'), $columns, array_keys($columns)) . ')';
286
          . array_map(array($this, '_columnDef'), $columns, array_keys($columns)) . ')';
287
287
288
        $stmt = $this->prepare($query);
288
        $stmt = $this->prepare($query);
289
289
290
        /* DEBUG */
290
        /* DEBUG */
291
    if (defined('DEBUG') && DEBUG > 1)
291
    if (defined('DEBUG') && DEBUG > 1)
292
    {
292
    {
293
      debug(array(
293
      debug(array(
294
        'query'  => $query,
294
        'query'  => $query,
295
      ));
295
      ));
296
    }
296
    }
297
297
298
    $success =& $this->_lastSuccess;
298
    $success =& $this->_lastSuccess;
299
    $success =  $stmt->execute();
299
    $success =  $stmt->execute();
300
300
301
    $errorInfo =& $this->_lastError;
301
    $errorInfo =& $this->_lastError;
302
    $errorInfo =  $stmt->errorInfo();
302
    $errorInfo =  $stmt->errorInfo();
303
303
304
    $this->_resetLastInsertId();
304
    $this->_resetLastInsertId();
305
305
306
    $result =& $this->_lastResult;
306
    $result =& $this->_lastResult;
307
    $result =  $stmt->fetchAll();
307
    $result =  $stmt->fetchAll();
308
308
309
    if (defined('DEBUG') && DEBUG > 1)
309
    if (defined('DEBUG') && DEBUG > 1)
310
    {
310
    {
311
      debug(array(
311
      debug(array(
312
        '_lastSuccess' => $success,
312
        '_lastSuccess' => $success,
313
        '_lastError'    => $errorInfo,
313
        '_lastError'    => $errorInfo,
314
        '_lastResult'  => $result
314
        '_lastResult'  => $result
315
      ));
315
      ));
316
    }
316
    }
317
317
318
    return $success;
318
    return $success;
319
  }
319
  }
320
320
321
  /**
321
  /**
322
   * Initiates a transaction
322
   * Initiates a transaction
323
   *
323
   *
324
   * @return bool
324
   * @return bool
325
   * @see PDO::beginTransaction()
325
   * @see PDO::beginTransaction()
326
   */
326
   */
327
  public function beginTransaction()
327
  public function beginTransaction()
328
  {
328
  {
329
    return $this->connection->beginTransaction();
329
    return $this->connection->beginTransaction();
330
  }
330
  }
331
331
332
  /**
332
  /**
333
   * Rolls back a transaction
333
   * Rolls back a transaction
334
   *
334
   *
335
   * @return bool
335
   * @return bool
336
   * @see PDO::rollBack()
336
   * @see PDO::rollBack()
337
   */
337
   */
338
  public function rollBack()
338
  public function rollBack()
339
  {
339
  {
340
    return $this->connection->rollBack();
340
    return $this->connection->rollBack();
341
  }
341
  }
342
342
343
  /**
343
  /**
344
   * Commits a transaction
344
   * Commits a transaction
345
   *
345
   *
346
   * @return bool
346
   * @return bool
347
   * @see PDO::commit()
347
   * @see PDO::commit()
348
   */
348
   */
349
  public function commit()
349
  public function commit()
350
  {
350
  {
351
    return $this->connection->commit();
351
    return $this->connection->commit();
352
  }
352
  }
353
353
354
  /**
354
  /**
355
   * Prepares a statement for execution with the database
355
   * Prepares a statement for execution with the database
356
   * @param string $query
356
   * @param string $query
357
   */
357
   */
358
  public function prepare($query, array $driver_options = array())
358
  public function prepare($query, array $driver_options = array())
359
  {
359
  {
360
    return $this->connection->prepare($query, $driver_options);
360
    return $this->connection->prepare($query, $driver_options);
361
  }
361
  }
362
362
363
  /**
363
  /**
364
   * Returns the ID of the last inserted row, or the last value from
364
   * Returns the ID of the last inserted row, or the last value from
365
   * a sequence object, depending on the underlying driver.
365
   * a sequence object, depending on the underlying driver.
366
   *
366
   *
367
   * @return int
367
   * @return int
368
   */
368
   */
369
  public function getLastInsertId()
369
  public function getLastInsertId()
370
  {
370
  {
371
    return $this->_lastInsertId;
371
    return $this->_lastInsertId;
372
  }
372
  }
373
373
374
  /**
374
  /**
375
   * Escapes a database name so that it can be used in a query.
375
   * Escapes a database name so that it can be used in a query.
376
   *
376
   *
377
   * @param string $name
377
   * @param string $name
378
   *   The name to be escaped
378
   *   The name to be escaped
379
   * @return string
379
   * @return string
380
   *   The escaped name
380
   *   The escaped name
381
   */
381
   */
382
  public function escapeName($name)
382
  public function escapeName($name)
383
  {
383
  {
384
    return $this->_leftQuote . $name . $this->_rightQuote;
384
    return $this->_leftQuote . $name . $this->_rightQuote;
385
  }
385
  }
386
386
387
  /**
387
  /**
388
   * Determines if an array is associative (has not all integer keys).
388
   * Determines if an array is associative (has not all integer keys).
389
   *
389
   *
390
   * @author
390
   * @author
391
   *   Algorithm courtesy of squirrel, <http://stackoverflow.com/a/5969617/855543>.
391
   *   Algorithm courtesy of squirrel, <http://stackoverflow.com/a/5969617/855543>.
392
   * @param array $a
392
   * @param array $a
393
   * @return boolean
393
   * @return boolean
394
   *   <code>true</code> if <var>$a</var> is associative,
394
   *   <code>true</code> if <var>$a</var> is associative,
395
   *   <code>false</code> otherwise
395
   *   <code>false</code> otherwise
396
   */
396
   */
397
  protected function _isAssociativeArray(array $a)
397
  protected function _isAssociativeArray(array $a)
398
  {
398
  {
399
    for (reset($a); is_int(key($a)); next($a));
399
    for (reset($a); is_int(key($a)); next($a));
400
    return !is_null(key($a));
400
    return !is_null(key($a));
401
  }
401
  }
402
402
403
  /**
403
  /**
404
   * Escapes an associative array so that its string representation can be used
404
   * Escapes an associative array so that its string representation can be used
405
   * as list with table or column aliases in a query.
405
   * as list with table or column aliases in a query.
406
   *
406
   *
407
   * This method does not actually escape anything; it only inserts the
407
   * This method does not actually escape anything; it only inserts the
408
   * 'AS' keyword.  It should be overridden by inheriting methods.
408
   * 'AS' keyword.  It should be overridden by inheriting methods.
409
   *
409
   *
410
   * NOTE: This method intentionally does not check whether the array actually
410
   * NOTE: This method intentionally does not check whether the array actually
411
   * is associative.
411
   * is associative.
412
   *
412
   *
413
   * @param array &$array
413
   * @param array &$array
414
   *   The array to be escaped
414
   *   The array to be escaped
415
   * @return array
415
   * @return array
416
   *   The escaped array
416
   *   The escaped array
417
   */
417
   */
418
  protected function _escapeAliasArray(array &$array)
418
  protected function _escapeAliasArray(array &$array)
419
  {
419
  {
420
    foreach ($array as $column => &$value)
420
    foreach ($array as $column => &$value)
421
    {
421
    {
422
      $quotedColumn = $column;
422
      $quotedColumn = $column;
423
      if (strpos($column, $this->_leftQuote) === false
423
      if (strpos($column, $this->_leftQuote) === false
424
         && strpos($column, $this->_rightQuote) === false)
424
         && strpos($column, $this->_rightQuote) === false)
425
      {
425
      {
426
        $quotedColumn = $this->_leftQuote . $column . $this->_rightQuote;
426
        $quotedColumn = $this->_leftQuote . $column . $this->_rightQuote;
427
      }
427
      }
428
428
429
      $value = $value . ' AS ' . $quotedColumn;
429
      $value = $value . ' AS ' . $quotedColumn;
430
    }
430
    }
431
431
432
    return $array;
432
    return $array;
433
  }
433
  }
434
434
435
  /**
435
  /**
436
   * @param array $a
436
   * @param array $a
437
   * @param string $prefix
437
   * @param string $prefix
438
   */
438
   */
439
  private static function _expand(array $a, $prefix)
439
  private static function _expand(array $a, $prefix)
440
  {
440
  {
441
    $a2 = array();
441
    $a2 = array();
442
442
443
    foreach ($a as $key => $value)
443
    foreach ($a as $key => $value)
444
    {
444
    {
445
      $a2[] = ':' . $prefix . ($key + 1);
445
      $a2[] = ':' . $prefix . ($key + 1);
446
    }
446
    }
447
447
448
    return $a2;
448
    return $a2;
449
  }
449
  }
450
450
451
  /**
451
  /**
452
   * Escapes an associative array so that its string representation can be used
452
   * Escapes an associative array so that its string representation can be used
453
   * as value list in a query.
453
   * as value list in a query.
454
   *
454
   *
455
   * This method should be overridden by inheriting classes to escape
455
   * This method should be overridden by inheriting classes to escape
456
   * column names as fitting for the database schema they support.  It is
456
   * column names as fitting for the database schema they support.  It is
457
   * strongly recommended that the overriding methods call this method with
457
   * strongly recommended that the overriding methods call this method with
458
   * an appropriate <var>$escape</var> parameter, pass all other parameters
458
   * an appropriate <var>$escape</var> parameter, pass all other parameters
459
   * on unchanged, and return its return value.
459
   * on unchanged, and return its return value.
460
   *
460
   *
461
   * NOTE: Intentionally does not check whether the array actually is associative!
461
   * NOTE: Intentionally does not check whether the array actually is associative!
462
   *
462
   *
463
   * @param array &$array
463
   * @param array &$array
464
   *   The array to be escaped
464
   *   The array to be escaped
465
   * @param string $suffix
465
   * @param string $suffix
466
   *   The string to be appended to the column name for the value placeholder.
466
   *   The string to be appended to the column name for the value placeholder.
467
   *   The default is the empty string.
467
   *   The default is the empty string.
468
   * @param array $escape
468
   * @param array $escape
469
   *   The strings to use left-hand side (index 0) and right-hand side (index 1)
469
   *   The strings to use left-hand side (index 0) and right-hand side (index 1)
470
   *   of the column name.  The default is the empty string, respectively.
470
   *   of the column name.  The default is the empty string, respectively.
471
   * @return array
471
   * @return array
472
   *   The escaped array
472
   *   The escaped array
473
   */
473
   */
474
  protected function _escapeValueArray(array &$array, $suffix = '')
474
  protected function _escapeValueArray(array &$array, $suffix = '')
475
  {
475
  {
476
    $result = array();
476
    $result = array();
477
477
478
    foreach ($array as $column => $value)
478
    foreach ($array as $column => $value)
479
    {
479
    {
480
      $op = '=';
480
      $op = '=';
481
      $placeholder = ":{$column}";
481
      $placeholder = ":{$column}";
482
482
483
      if (is_array($value) && $this->_isAssociativeArray($value))
483
      if (is_array($value) && $this->_isAssociativeArray($value))
484
      {
484
      {
485
        reset($value);
485
        reset($value);
486
        $op = ' ' . key($value) . ' ';
486
        $op = ' ' . key($value) . ' ';
487
487
488
        $value = $value[key($value)];
488
        $value = $value[key($value)];
489
      }
489
      }
490
490
491
      if (is_array($value))
491
      if (is_array($value))
492
      {
492
      {
493
        $placeholder = '(' . implode(', ', self::_expand($value, $column)) . ')';
493
        $placeholder = '(' . implode(', ', self::_expand($value, $column)) . ')';
494
      }
494
      }
495
495
496
      $result[] = $this->_leftQuote . $column . $this->_rightQuote . "{$op}{$placeholder}{$suffix}";
496
      $result[] = $this->_leftQuote . $column . $this->_rightQuote . "{$op}{$placeholder}{$suffix}";
497
    }
497
    }
498
498
499
    return $result;
499
    return $result;
500
  }
500
  }
501
501
502
  /**
502
  /**
503
   * Constructs the WHERE part of a query
503
   * Constructs the WHERE part of a query
504
   *
504
   *
505
   * @param string|array $where
505
   * @param string|array $where
506
   *   Condition
506
   *   Condition
507
   * @param string $suffix
507
   * @param string $suffix
508
   *   The string to be appended to the column name for the value placeholder,
508
   *   The string to be appended to the column name for the value placeholder,
509
   *   passed on to {@link Database::_escapeValueArray()}.  The default is
509
   *   passed on to {@link Database::_escapeValueArray()}.  The default is
510
   *   the empty string.
510
   *   the empty string.
511
   * @return string
511
   * @return string
512
   * @see Database::_escapeValueArray()
512
   * @see Database::_escapeValueArray()
513
   */
513
   */
514
  protected function _where($where, $suffix = '')
514
  protected function _where($where, $suffix = '')
515
  {
515
  {
516
    if (!is_null($where))
516
    if (!is_null($where))
517
    {
517
    {
518
      if (is_array($where))
518
      if (is_array($where))
519
      {
519
      {
520
        if (count($where) < 1)
520
        if (count($where) < 1)
521
        {
521
        {
522
          return '';
522
          return '';
523
        }
523
        }
524
524
525
        if ($this->_isAssociativeArray($where))
525
        if ($this->_isAssociativeArray($where))
526
        {
526
        {
527
          $where = $this->_escapeValueArray($where, $suffix);
527
          $where = $this->_escapeValueArray($where, $suffix);
528
        }
528
        }
529
529
530
        $where = '(' . implode(') AND (', $where) . ')';
530
        $where = '(' . implode(') AND (', $where) . ')';
531
      }
531
      }
532
532
533
      return ' WHERE ' . $where;
533
      return ' WHERE ' . $where;
534
    }
534
    }
535
535
536
    return '';
536
    return '';
537
  }
537
  }
538
538
539
  /**
539
  /**
540
   * Selects data from one or more tables; the resulting records are stored
540
   * Selects data from one or more tables; the resulting records are stored
541
   * in the <code>result</code> property and returned as an associative array,
541
   * in the <code>result</code> property and returned as an associative array,
542
   * where the keys are the column (alias) names.
542
   * where the keys are the column (alias) names.
543
   *
543
   *
544
   * @param string|array[string] $tables Table(s) to select from
544
   * @param string|array[string] $tables Table(s) to select from
545
   * @param string|array[string] $columns Column(s) to select from (optional)
545
   * @param string|array[string] $columns Column(s) to select from (optional)
546
   * @param string|array $where Condition (optional)
546
   * @param string|array $where Condition (optional)
547
   * @param string $order Sort order (optional)
547
   * @param string $order Sort order (optional)
548
   *   If provided, MUST start with ORDER BY or GROUP BY
548
   *   If provided, MUST start with ORDER BY or GROUP BY
549
   * @param string $limit Limit (optional)
549
   * @param string $limit Limit (optional)
550
   * @param int $fetch_style
550
   * @param int $fetch_style
551
   *   The mode that should be used for {@link PDOStatement::fetchAll()}.
551
   *   The mode that should be used for {@link PDOStatement::fetchAll()}.
552
   *   The default is {@link PDO::FETCH_ASSOC}.
552
   *   The default is {@link PDO::FETCH_ASSOC}.
553
   * @return array
553
   * @return array
554
   * @see Database::prepare()
554
   * @see Database::prepare()
555
   * @see PDOStatement::fetchAll()
555
   * @see PDOStatement::fetchAll()
556
   */
556
   */
557
  public function select($tables, $columns = null, $where = null,
557
  public function select($tables, $columns = null, $where = null,
558
    $order = null, $limit = null, $fetch_style = \PDO::FETCH_ASSOC)
558
    $order = null, $limit = null, $fetch_style = \PDO::FETCH_ASSOC)
559
  {
559
  {
560
    if (is_null($columns))
560
    if (is_null($columns))
561
    {
561
    {
562
      $columns = array('*');
562
      $columns = array('*');
563
    }
563
    }
564
564
565
    if (is_array($columns))
565
    if (is_array($columns))
566
    {
566
    {
567
      if ($this->_isAssociativeArray($columns))
567
      if ($this->_isAssociativeArray($columns))
568
      {
568
      {
569
        $columns = $this->_escapeAliasArray($columns);
569
        $columns = $this->_escapeAliasArray($columns);
570
      }
570
      }
571
571
572
      $columns = implode(', ', $columns);
572
      $columns = implode(', ', $columns);
573
    }
573
    }
574
574
575
    if (is_array($tables))
575
    if (is_array($tables))
576
    {
576
    {
577
      if ($this->_isAssociativeArray($columns))
577
      if ($this->_isAssociativeArray($columns))
578
      {
578
      {
579
        $columns = $this->_escapeAliasArray($columns);
579
        $columns = $this->_escapeAliasArray($columns);
580
      }
580
      }
581
581
582
      $tables = implode(', ', $tables);
582
      $tables = implode(', ', $tables);
583
    }
583
    }
584
584
585
    $query = "SELECT {$columns} FROM {$tables}" . $this->_where($where);
585
    $query = "SELECT {$columns} FROM {$tables}" . $this->_where($where);
586
586
587
    if (!is_null($order))
587
    if (!is_null($order))
588
    {
588
    {
589
      if (is_array($order))
589
      if (is_array($order))
590
      {
590
      {
591
        $order = 'ORDER BY ' . implode(', ', $order);
591
        $order = 'ORDER BY ' . implode(', ', $order);
592
      }
592
      }
593
593
594
      $query .= " $order";
594
      $query .= " $order";
595
    }
595
    }
596
596
597
    if (!is_null($limit))
597
    if (!is_null($limit))
598
    {
598
    {
599
      $query .= " LIMIT $limit";
599
      $query .= " LIMIT $limit";
600
    }
600
    }
601
601
602
    $stmt = $this->prepare($query);
602
    $stmt = $this->prepare($query);
603
603
604
    $params = array();
604
    $params = array();
605
605
606
    if (is_array($where) && $this->_isAssociativeArray($where))
606
    if (is_array($where) && $this->_isAssociativeArray($where))
607
    {
607
    {
608
      /* FIXME: Export and reuse this */
608
      /* FIXME: Export and reuse this */
609
      foreach ($where as $column => $condition)
609
      foreach ($where as $column => $condition)
610
      {
610
      {
611
        /* TODO: Also handle function calls as keys */
611
        /* TODO: Also handle function calls as keys */
612
        if (is_array($condition) && $this->_isAssociativeArray($condition))
612
        if (is_array($condition) && $this->_isAssociativeArray($condition))
613
        {
613
        {
614
          reset($condition);
614
          reset($condition);
615
          $condition = $condition[key($condition)];
615
          $condition = $condition[key($condition)];
616
616
617
          if (is_array($condition))
617
          if (is_array($condition))
618
          {
618
          {
619
            foreach (self::_expand($condition, $column) as $param_index => $param_name)
619
            foreach (self::_expand($condition, $column) as $param_index => $param_name)
620
            {
620
            {
621
              $params[$param_name] = $condition[$param_index];
621
              $params[$param_name] = $condition[$param_index];
622
            }
622
            }
623
          }
623
          }
624
        }
624
        }
625
        else
625
        else
626
        {
626
        {
627
          $params[":{$column}"] = $condition;
627
          $params[":{$column}"] = $condition;
628
        }
628
        }
629
      }
629
      }
630
    }
630
    }
631
631
632
    /* DEBUG */
632
    /* DEBUG */
633
    if (defined('DEBUG') && DEBUG > 1)
633
    if (defined('DEBUG') && DEBUG > 1)
634
    {
634
    {
635
      debug(array(
635
      debug(array(
636
        'query'  => $query,
636
        'query'  => $query,
637
        'params' => $params
637
        'params' => $params
638
      ));
638
      ));
639
    }
639
    }
640
640
641
    $success =& $this->_lastSuccess;
641
    $success =& $this->_lastSuccess;
642
    $success =  $stmt->execute($params);
642
    $success =  $stmt->execute($params);
643
643
644
    $errorInfo =& $this->_lastError;
644
    $errorInfo =& $this->_lastError;
645
    $errorInfo =  $stmt->errorInfo();
645
    $errorInfo =  $stmt->errorInfo();
646
646
647
    $result =& $this->_lastResult;
647
    $result =& $this->_lastResult;
648
    $result =  $stmt->fetchAll($fetch_style);
648
    $result =  $stmt->fetchAll($fetch_style);
649
649
650
    if (defined('DEBUG') && DEBUG > 1)
650
    if (defined('DEBUG') && DEBUG > 1)
651
    {
651
    {
652
      debug(array(
652
      debug(array(
653
        '_lastSuccess' => $success,
653
        '_lastSuccess' => $success,
654
        '_lastError'   => $errorInfo,
654
        '_lastError'   => $errorInfo,
655
        '_lastResult'  => $result
655
        '_lastResult'  => $result
656
      ));
656
      ));
657
    }
657
    }
658
658
659
    return $result;
659
    return $result;
660
  }
660
  }
661
661
662
  /**
662
  /**
663
   * Sets and returns the ID of the last inserted row, or the last value from
663
   * Sets and returns the ID of the last inserted row, or the last value from
664
   * a sequence object, depending on the underlying driver.
664
   * a sequence object, depending on the underlying driver.
665
   *
665
   *
666
   * @param string $name
666
   * @param string $name
667
   *   Name of the sequence object from which the ID should be returned.
667
   *   Name of the sequence object from which the ID should be returned.
668
   * @return string
668
   * @return string
669
   */
669
   */
670
  protected function _setLastInsertId($name = null)
670
  protected function _setLastInsertId($name = null)
671
  {
671
  {
672
    return ($this->_lastInsertId = $this->connection->lastInsertId($name));
672
    return ($this->_lastInsertId = $this->connection->lastInsertId($name));
673
  }
673
  }
674
674
675
  /**
675
  /**
676
   * Resets the the ID of the last inserted row, or the last value from
676
   * Resets the the ID of the last inserted row, or the last value from
677
   * a sequence object, depending on the underlying driver.
677
   * a sequence object, depending on the underlying driver.
678
   *
678
   *
679
   * @return string
679
   * @return string
680
   *   The default value
680
   *   The default value
681
   */
681
   */
682
  protected function _resetLastInsertId()
682
  protected function _resetLastInsertId()
683
  {
683
  {
684
    return ($this->_lastInsertId = '');
684
    return ($this->_lastInsertId = '');
685
  }
685
  }
686
686
687
  /**
687
  /**
688
   * Updates one or more records
688
   * Updates one or more records
689
   *
689
   *
690
   * @param string|array $tables
690
   * @param string|array $tables
691
   *   Table name
691
   *   Table name
692
   * @param array $updates
692
   * @param array $updates
693
   *   Associative array of column-value pairs
693
   *   Associative array of column-value pairs
694
   * @param array|string $where
694
   * @param array|string $where
695
   *   Only the records matching this condition are updated
695
   *   Only the records matching this condition are updated
696
   * @return bool
696
   * @return bool
697
   * @see PDOStatement::execute()
697
   * @see PDOStatement::execute()
698
   */
698
   */
699
  public function update ($tables, array $updates, $where = null)
699
  public function update ($tables, array $updates, $where = null)
700
  {
700
  {
701
    if (!$tables)
701
    if (!$tables)
702
    {
702
    {
703
      throw new InvalidArgumentException('No table specified');
703
      throw new InvalidArgumentException('No table specified');
704
    }
704
    }
705
705
706
    if (is_array($tables))
706
    if (is_array($tables))
707
    {
707
    {
708
      $tables = implode(', ', $tables);
708
      $tables = implode(', ', $tables);
709
    }
709
    }
710
710
711
    if (!$updates)
711
    if (!$updates)
712
    {
712
    {
713
      throw new InvalidArgumentException('No values specified');
713
      throw new InvalidArgumentException('No values specified');
714
    }
714
    }
715
715
716
    $params = array();
716
    $params = array();
717
717
718
    if ($this->_isAssociativeArray($updates))
718
    if ($this->_isAssociativeArray($updates))
719
    {
719
    {
720
      foreach ($updates as $key => $condition)
720
      foreach ($updates as $key => $condition)
721
      {
721
      {
722
        $params[":{$key}"] = $condition;
722
        $params[":{$key}"] = $condition;
723
      }
723
      }
724
    }
724
    }
725
725
726
    $updates = implode(', ', $this->_escapeValueArray($updates));
726
    $updates = implode(', ', $this->_escapeValueArray($updates));
727
727
728
    /* TODO: Should escape table names with escapeName(), but what about aliases? */
728
    /* TODO: Should escape table names with escapeName(), but what about aliases? */
729
    $query = "UPDATE {$tables} SET {$updates}" . $this->_where($where, '2');
729
    $query = "UPDATE {$tables} SET {$updates}" . $this->_where($where, '2');
730
730
731
    $stmt = $this->prepare($query);
731
    $stmt = $this->prepare($query);
732
732
733
    if (is_array($where) && $this->_isAssociativeArray($where))
733
    if (is_array($where) && $this->_isAssociativeArray($where))
734
    {
734
    {
735
      foreach ($where as $column => $condition)
735
      foreach ($where as $column => $condition)
736
      {
736
      {
737
        if (is_array($condition) && $this->_isAssociativeArray($condition))
737
        if (is_array($condition) && $this->_isAssociativeArray($condition))
738
        {
738
        {
739
          reset($condition);
739
          reset($condition);
740
          $condition = $condition[key($condition)];
740
          $condition = $condition[key($condition)];
741
741
742
          if (is_array($condition))
742
          if (is_array($condition))
743
          {
743
          {
744
            foreach (self::_expand($condition, $column) as $param_index => $param_name)
744
            foreach (self::_expand($condition, $column) as $param_index => $param_name)
745
            {
745
            {
746
              $params[$param_name] = $condition[$param_index];
746
              $params[$param_name] = $condition[$param_index];
747
            }
747
            }
748
          }
748
          }
749
        }
749
        }
750
        else
750
        else
751
        {
751
        {
752
          $params[":{$column}2"] = $condition;
752
          $params[":{$column}2"] = $condition;
753
        }
753
        }
754
      }
754
      }
755
    }
755
    }
756
756
757
    /* DEBUG */
757
    /* DEBUG */
758
    if (defined('DEBUG') && DEBUG > 1)
758
    if (defined('DEBUG') && DEBUG > 1)
759
    {
759
    {
760
      debug(array(
760
      debug(array(
761
        'query'  => $query,
761
        'query'  => $query,
762
        'params' => $params
762
        'params' => $params
763
      ));
763
      ));
764
    }
764
    }
765
765
766
    $success =& $this->_lastSuccess;
766
    $success =& $this->_lastSuccess;
767
    $success =  $stmt->execute($params);
767
    $success =  $stmt->execute($params);
768
768
769
    $errorInfo =& $this->_lastError;
769
    $errorInfo =& $this->_lastError;
770
    $errorInfo =  $stmt->errorInfo();
770
    $errorInfo =  $stmt->errorInfo();
771
771
772
    $this->_resetLastInsertId();
772
    $this->_resetLastInsertId();
773
773
774
    $result =& $this->_lastResult;
774
    $result =& $this->_lastResult;
775
    $result =  $stmt->fetchAll();
775
    $result =  $stmt->fetchAll();
776
776
777
    if (defined('DEBUG') && DEBUG > 1)
777
    if (defined('DEBUG') && DEBUG > 1)
778
    {
778
    {
779
      debug(array(
779
      debug(array(
780
        '_lastSuccess' => $success,
780
        '_lastSuccess' => $success,
781
        '_lastError'    => $errorInfo,
781
        '_lastError'    => $errorInfo,
782
        '_lastResult'  => $result
782
        '_lastResult'  => $result
783
      ));
783
      ));
784
    }
784
    }
785
785
786
    return $success;
786
    return $success;
787
  }
787
  }
788
788
789
  /**
789
  /**
790
   * Inserts a record into a table.<p>The AUTO_INCREMENT value of the inserted
790
   * Inserts a record into a table.<p>The AUTO_INCREMENT value of the inserted
791
   * row, if any (> 0), is stored in the {@link $lastInsertId} property of
791
   * row, if any (> 0), is stored in the {@link $lastInsertId} property of
792
   * the <code>Database</code> instance.</p>
792
   * the <code>Database</code> instance.</p>
793
   *
793
   *
794
   * @param string $table
794
   * @param string $table
795
   *   Table name
795
   *   Table name
796
   * @param array|string $values
796
   * @param array|string $values
797
   *   Associative array of column-value pairs, indexed array,
797
   *   Associative array of column-value pairs, indexed array,
798
   *   or comma-separated list of values.  If <var>$values</var> is not
798
   *   or comma-separated list of values.  If <var>$values</var> is not
799
   *   an associative array, <var>$cols</var> must be passed if the
799
   *   an associative array, <var>$cols</var> must be passed if the
800
   *   values are not in column order (see below).
800
   *   values are not in column order (see below).
801
   * @param array|string $cols
801
   * @param array|string $cols
802
   *   Indexed array, or comma-separated list of column names.
802
   *   Indexed array, or comma-separated list of column names.
803
   *   Needs only be passed if <var>$values</var> is not an associative array
803
   *   Needs only be passed if <var>$values</var> is not an associative array
804
   *   and the values are not in column order (default: <code>null</code>);
804
   *   and the values are not in column order (default: <code>null</code>);
805
   *   is ignored otherwise.  <strong>You SHOULD NOT rely on column order.</strong>
805
   *   is ignored otherwise.  <strong>You SHOULD NOT rely on column order.</strong>
806
   * @return bool
806
   * @return bool
807
   * @see PDOStatement::execute()
807
   * @see PDOStatement::execute()
808
   */
808
   */
809
  public function insert ($table, $values, $cols = null)
809
  public function insert ($table, $values, $cols = null)
810
  {
810
  {
811
    if ($cols != null)
811
    if ($cols != null)
812
    {
812
    {
813
      $cols = ' ('
813
      $cols = ' ('
814
            . (is_array($cols)
814
            . (is_array($cols)
815
                ? implode(', ', array_map(array($this, 'escapeName'), $cols))
815
                ? implode(', ', array_map(array($this, 'escapeName'), $cols))
816
                : $cols) . ')';
816
                : $cols) . ')';
817
    }
817
    }
818
    else
818
    else
819
    {
819
    {
820
      $cols = '';
820
      $cols = '';
821
    }
821
    }
822
822
823
    /* DEBUG */
823
    /* DEBUG */
824
    if (defined('DEBUG') && DEBUG > 2)
824
    if (defined('DEBUG') && DEBUG > 2)
825
    {
825
    {
826
      debug(array('values' => $values));
826
      debug(array('values' => $values));
827
    }
827
    }
828
828
829
    $params = array();
829
    $params = array();
830
830
831
    if (is_array($values))
831
    if (is_array($values))
832
    {
832
    {
833
      if ($this->_isAssociativeArray($values))
833
      if ($this->_isAssociativeArray($values))
834
      {
834
      {
835
        foreach ($values as $key => $condition)
835
        foreach ($values as $key => $condition)
836
        {
836
        {
837
          $params[":{$key}"] = $condition;
837
          $params[":{$key}"] = $condition;
838
        }
838
        }
839
839
840
        $values = $this->_escapeValueArray($values);
840
        $values = $this->_escapeValueArray($values);
841
841
842
        $cols = '';
842
        $cols = '';
843
        $values = 'SET ' . implode(', ', $values);
843
        $values = 'SET ' . implode(', ', $values);
844
      }
844
      }
845
      else
845
      else
846
      {
846
      {
847
        foreach ($values as &$value)
847
        foreach ($values as &$value)
848
        {
848
        {
849
          if (is_string($value))
849
          if (is_string($value))
850
          {
850
          {
851
            $value = "'" . $value . "'";
851
            $value = "'" . $value . "'";
852
          }
852
          }
853
        }
853
        }
854
854
855
        $values = ' VALUES (' . implode(', ', $values) . ')';
855
        $values = 'VALUES (' . implode(', ', $values) . ')';
856
      }
856
      }
857
    }
857
    }
858
858
859
    /* TODO: Should escape table names with escapeName(), but what about aliases? */
859
    /* TODO: Should escape table names with escapeName(), but what about aliases? */
860
    $query = "INSERT INTO {$table} {$cols} {$values}";
860
    $query = "INSERT INTO {$table} {$cols} {$values}";
861
861
862
    $stmt = $this->prepare($query);
862
    $stmt = $this->prepare($query);
863
863
864
      /* DEBUG */
864
      /* DEBUG */
865
    if (defined('DEBUG') && DEBUG > 1)
865
    if (defined('DEBUG') && DEBUG > 1)
866
    {
866
    {
867
       debug(array(
867
       debug(array(
868
         'query'  => $query,
868
         'query'  => $query,
869
         'params' => $params
869
         'params' => $params
870
       ));
870
       ));
871
    }
871
    }
872
872
873
    $success =& $this->_lastSuccess;
873
    $success =& $this->_lastSuccess;
874
    $success = $stmt->execute($params);
874
    $success = $stmt->execute($params);
875
875
876
    $errorInfo =& $this->_lastError;
876
    $errorInfo =& $this->_lastError;
877
    $errorInfo =  $stmt->errorInfo();
877
    $errorInfo =  $stmt->errorInfo();
878
878
879
    $this->_setLastInsertId();
879
    $this->_setLastInsertId();
880
880
881
    $result =& $this->_lastResult;
881
    $result =& $this->_lastResult;
882
    $result =  $stmt->fetchAll();
882
    $result =  $stmt->fetchAll();
883
883
884
    if (defined('DEBUG') && DEBUG > 1)
884
    if (defined('DEBUG') && DEBUG > 1)
885
    {
885
    {
886
      debug(array(
886
      debug(array(
887
        '_lastSuccess'  => $success,
887
        '_lastSuccess'  => $success,
888
        '_lastError'    => $errorInfo,
888
        '_lastError'    => $errorInfo,
889
        '_lastInsertId' => $this->_lastInsertId,
889
        '_lastInsertId' => $this->_lastInsertId,
890
        '_lastResult'   => $result
890
        '_lastResult'   => $result
891
      ));
891
      ));
892
    }
892
    }
893
893
894
    return $success;
894
    return $success;
895
  }
895
  }
896
896
897
  /**
897
  /**
898
   * Retrieves all rows from a table
898
   * Retrieves all rows from a table
899
   *
899
   *
900
   * @param int[optional] $fetch_style
900
   * @param int[optional] $fetch_style
901
   * @param int[optional] $column_index
901
   * @param int[optional] $column_index
902
   * @param array[optional] $ctor_args
902
   * @param array[optional] $ctor_args
903
   * @return array
903
   * @return array
904
   * @see PDOStatement::fetchAll()
904
   * @see PDOStatement::fetchAll()
905
   */
905
   */
906
  public function fetchAll($table, $fetch_style = null, $column_index = null, array $ctor_args = null)
906
  public function fetchAll($table, $fetch_style = null, $column_index = null, array $ctor_args = null)
907
  {
907
  {
908
    /* NOTE: Cannot use table name as statement parameter */
908
    /* NOTE: Cannot use table name as statement parameter */
909
    $stmt = $this->prepare("SELECT * FROM $table");
909
    $stmt = $this->prepare("SELECT * FROM $table");
910
    $this->_lastSuccess = $stmt->execute();
910
    $this->_lastSuccess = $stmt->execute();
911
911
912
    $this->_lastError = $stmt->errorInfo();
912
    $this->_lastError = $stmt->errorInfo();
913
913
914
    $result =& $this->_lastResult;
914
    $result =& $this->_lastResult;
915
915
916
    if (is_null($fetch_style))
916
    if (is_null($fetch_style))
917
    {
917
    {
918
      $fetch_style = \PDO::FETCH_ASSOC;
918
      $fetch_style = \PDO::FETCH_ASSOC;
919
    }
919
    }
920
920
921
    if (!is_null($ctor_args))
921
    if (!is_null($ctor_args))
922
    {
922
    {
923
      $result = $stmt->fetchAll($fetch_style, $column_index, $ctor_args);
923
      $result = $stmt->fetchAll($fetch_style, $column_index, $ctor_args);
924
    }
924
    }
925
    else if (!is_null($column_index))
925
    else if (!is_null($column_index))
926
    {
926
    {
927
      $result = $stmt->fetchAll($fetch_style, $column_index);
927
      $result = $stmt->fetchAll($fetch_style, $column_index);
928
    }
928
    }
929
    else if (!is_null($fetch_style))
929
    else if (!is_null($fetch_style))
930
    {
930
    {
931
      $result = $stmt->fetchAll($fetch_style);
931
      $result = $stmt->fetchAll($fetch_style);
932
    }
932
    }
933
    else
933
    else
934
    {
934
    {
935
      $result = $stmt->fetchAll();
935
      $result = $stmt->fetchAll();
936
    }
936
    }
937
937
938
    return $result;
938
    return $result;
939
  }
939
  }
940
940
941
  /**
941
  /**
942
   * Deletes one or more records
942
   * Deletes one or more records
943
   *
943
   *
944
   * @param string|array $tables
944
   * @param string|array $tables
945
   *   Table name(s)
945
   *   Table name(s)
946
   * @param array|string $where
946
   * @param array|string $where
947
   *   Only the records matching this condition are deleted
947
   *   Only the records matching this condition are deleted
948
   * @return bool
948
   * @return bool
949
   * @see PDOStatement::execute()
949
   * @see PDOStatement::execute()
950
   */
950
   */
951
  public function delete($tables, $where = null)
951
  public function delete($tables, $where = null)
952
  {
952
  {
953
    if (!$tables)
953
    if (!$tables)
954
    {
954
    {
955
      throw new InvalidArgumentException('No table specified');
955
      throw new InvalidArgumentException('No table specified');
956
    }
956
    }
957
957
958
    if (is_array($tables))
958
    if (is_array($tables))
959
    {
959
    {
960
      $tables = implode(', ', $tables);
960
      $tables = implode(', ', $tables);
961
    }
961
    }
962
962
963
    $params = array();
963
    $params = array();
964
964
965
    $query = "DELETE FROM {$tables}" . $this->_where($where);
965
    $query = "DELETE FROM {$tables}" . $this->_where($where);
966
966
967
    $stmt = $this->prepare($query);
967
    $stmt = $this->prepare($query);
968
968
969
    if ($this->_isAssociativeArray($where))
969
    if ($this->_isAssociativeArray($where))
970
    {
970
    {
971
      foreach ($where as $column => $condition)
971
      foreach ($where as $column => $condition)
972
      {
972
      {
973
        if (is_array($condition) && $this->_isAssociativeArray($condition))
973
        if (is_array($condition) && $this->_isAssociativeArray($condition))
974
        {
974
        {
975
          reset($condition);
975
          reset($condition);
976
          $condition = $condition[key($condition)];
976
          $condition = $condition[key($condition)];
977
977
978
          if (is_array($condition))
978
          if (is_array($condition))
979
          {
979
          {
980
            foreach (self::_expand($condition, $column) as $param_index => $param_name)
980
            foreach (self::_expand($condition, $column) as $param_index => $param_name)
981
            {
981
            {
982
              $params[$param_name] = $condition[$param_index];
982
              $params[$param_name] = $condition[$param_index];
983
            }
983
            }
984
          }
984
          }
985
        }
985
        }
986
        else
986
        else
987
        {
987
        {
988
          $params[":{$column}"] = $condition;
988
          $params[":{$column}"] = $condition;
989
        }
989
        }
990
      }
990
      }
991
    }
991
    }
992
992
993
    /* DEBUG */
993
    /* DEBUG */
994
    if (defined('DEBUG') && DEBUG > 1)
994
    if (defined('DEBUG') && DEBUG > 1)
995
    {
995
    {
996
      debug(array(
996
      debug(array(
997
        'query'  => $query,
997
        'query'  => $query,
998
        'params' => $params
998
        'params' => $params
999
      ));
999
      ));
1000
    }
1000
    }
1001
1001
1002
    $success =& $this->_lastSuccess;
1002
    $success =& $this->_lastSuccess;
1003
    $success =  $stmt->execute($params);
1003
    $success =  $stmt->execute($params);
1004
1004
1005
    $result =& $this->_lastResult;
1005
    $result =& $this->_lastResult;
1006
    $result =  $stmt->fetchAll();
1006
    $result =  $stmt->fetchAll();
1007
1007
1008
    $errorInfo =& $this->_lastError;
1008
    $errorInfo =& $this->_lastError;
1009
    $errorInfo =  $stmt->errorInfo();
1009
    $errorInfo =  $stmt->errorInfo();
1010
1010
1011
    if (defined('DEBUG') && DEBUG > 1)
1011
    if (defined('DEBUG') && DEBUG > 1)
1012
    {
1012
    {
1013
      debug(array(
1013
      debug(array(
1014
        '_lastSuccess' => $success,
1014
        '_lastSuccess' => $success,
1015
        '_lastError'   => $errorInfo,
1015
        '_lastError'   => $errorInfo,
1016
        '_lastResult'  => $result
1016
        '_lastResult'  => $result
1017
      ));
1017
      ));
1018
    }
1018
    }
1019
1019
1020
    return $success;
1020
    return $success;
1021
  }
1021
  }
1022
}
1022
}