Subversion Repositories PHPX

Rev

Rev 51 | Rev 58 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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