Subversion Repositories PHPX

Rev

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

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