database_test.test 92.1 KB
Newer Older
1 2 3 4 5 6 7
<?php
// $Id$

/**
 * Dummy class for fetching into a class.
 *
 * PDO supports using a new instance of an arbitrary class for records
8 9
 * rather than just a stdClass or array. This class is for testing that
 * functionality. (See testQueryFetchClass() below)
10
 */
11 12 13 14
class FakeRecord { }

/**
 * Base test class for databases.
15
 *
16 17 18 19 20 21 22 23
 * Because all database tests share the same test data, we can centralize that
 * here.
 */
class DatabaseTestCase extends DrupalWebTestCase {

  function setUp() {
    parent::setUp('database_test');

24 25 26 27 28 29
    $schema['test'] = drupal_get_schema('test');
    $schema['test_people'] = drupal_get_schema('test_people');
    $schema['test_one_blob'] = drupal_get_schema('test_one_blob');
    $schema['test_two_blobs'] = drupal_get_schema('test_two_blobs');
    $schema['test_task'] = drupal_get_schema('test_task');

30 31 32 33 34 35 36 37 38 39 40 41
    $this->installTables($schema);

    $this->addSampleData();
  }

  /**
   * Set up several tables needed by a certain test.
   *
   * @param $schema
   *   An array of table definitions to install.
   */
  function installTables($schema) {
42 43 44 45 46
    // This ends up being a test for table drop and create, too, which is nice.
    $ret = array();
    foreach ($schema as $name => $data) {
      if (db_table_exists($name)) {
        db_drop_table($ret, $name);
47
      }
48
      db_create_table($ret, $name, $data);
49
    }
50 51 52

    foreach ($schema as $name => $data) {
      $this->assertTrue(db_table_exists($name), t('Table @name created successfully.', array('@name' => $name)));
53
    }
54
  }
55

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
  /**
   * Set up tables for NULL handling.
   */
  function ensureSampleDataNull() {
    $schema['test_null'] = drupal_get_schema('test_null');
    $this->installTables($schema);

    db_insert('test_null')
    ->fields(array('name', 'age'))
    ->values(array(
      'name' => 'Kermit',
      'age' => 25,
    ))
    ->values(array(
      'name' => 'Fozzie',
      'age' => NULL,
    ))
    ->values(array(
      'name' => 'Gonzo',
      'age' => 27,
    ))
    ->execute();
78 79 80 81 82
  }

  /**
   * Setup our sample data.
   *
83
   * These are added using db_query(), since we're not trying to test the
84 85 86
   * INSERT operations here, just populate.
   */
  function addSampleData() {
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    // We need the IDs, so we can't use a multi-insert here.
    $john = db_insert('test')
      ->fields(array(
        'name' => 'John',
        'age' => 25,
        'job' => 'Singer',
      ))
      ->execute();

    $george = db_insert('test')
      ->fields(array(
        'name' => 'George',
        'age' => 27,
        'job' => 'Singer',
      ))
      ->execute();

    $ringo = db_insert('test')
      ->fields(array(
        'name' => 'Ringo',
        'age' => 28,
        'job' => 'Drummer',
      ))
      ->execute();

    $paul = db_insert('test')
      ->fields(array(
        'name' => 'Paul',
        'age' => 26,
        'job' => 'Songwriter',
      ))
      ->execute();

    db_insert('test_people')
      ->fields(array(
        'name' => 'Meredith',
        'age' => 30,
        'job' => 'Speaker',
      ))
      ->execute();

    db_insert('test_task')
      ->fields(array('pid', 'task', 'priority'))
      ->values(array(
        'pid' => $john,
        'task' => 'eat',
        'priority' => 3,
      ))
      ->values(array(
        'pid' => $john,
        'task' => 'sleep',
        'priority' => 4,
      ))
      ->values(array(
        'pid' => $john,
        'task' => 'code',
        'priority' => 1,
      ))
      ->values(array(
        'pid' => $george,
        'task' => 'sing',
        'priority' => 2,
      ))
      ->values(array(
        'pid' => $george,
        'task' => 'sleep',
        'priority' => 2,
      ))
      ->values(array(
        'pid' => $paul,
        'task' => 'found new band',
        'priority' => 1,
      ))
      ->values(array(
        'pid' => $paul,
        'task' => 'perform at superbowl',
        'priority' => 3,
      ))
      ->execute();
166
  }
167 168 169 170 171 172 173
}

/**
 * Test connection management.
 */
class DatabaseConnectionTestCase extends DatabaseTestCase {

174
  public static function getInfo() {
175 176 177 178 179 180 181 182 183 184 185 186 187 188
    return array(
      'name' => t('Connection tests'),
      'description' => t('Tests of the core database system.'),
      'group' => t('Database'),
    );
  }

  /**
   * Test that connections return appropriate connection objects.
   */
  function testConnectionRouting() {
    // Clone the master credentials to a slave connection.
    // Note this will result in two independent connection objects that happen
    // to point to the same place.
189 190
    $connection_info = Database::getConnectionInfo('default');
    Database::addConnectionInfo('default', 'slave', $connection_info['default']);
191 192

    $db1 = Database::getConnection('default', 'default');
193
    $db2 = Database::getConnection('slave', 'default');
194

195 196 197
    $this->assertNotNull($db1, t('default connection is a real connection object.'));
    $this->assertNotNull($db2, t('slave connection is a real connection object.'));
    $this->assertNotIdentical($db1, $db2, t('Each target refers to a different connection.'));
198 199 200

    // Try to open those targets another time, that should return the same objects.
    $db1b = Database::getConnection('default', 'default');
201
    $db2b = Database::getConnection('slave', 'default');
202 203 204 205 206
    $this->assertIdentical($db1, $db1b, t('A second call to getConnection() returns the same object.'));
    $this->assertIdentical($db2, $db2b, t('A second call to getConnection() returns the same object.'));

    // Try to open an unknown target.
    $unknown_target = $this->randomName();
207
    $db3 = Database::getConnection($unknown_target, 'default');
208 209 210 211
    $this->assertNotNull($db3, t('Opening an unknown target returns a real connection object.'));
    $this->assertIdentical($db1, $db3, t('An unknown target opens the default connection.'));

    // Try to open that unknown target another time, that should return the same object.
212
    $db3b = Database::getConnection($unknown_target, 'default');
213
    $this->assertIdentical($db3, $db3b, t('A second call to getConnection() returns the same object.'));
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
  }

  /**
   * Test that connections return appropriate connection objects.
   */
  function testConnectionRoutingOverride() {
    // Clone the master credentials to a slave connection.
    // Note this will result in two independent connection objects that happen
    // to point to the same place.
    $connection_info = Database::getConnectionInfo('default');
    Database::addConnectionInfo('default', 'slave', $connection_info['default']);

    Database::ignoreTarget('default', 'slave');

    $db1 = Database::getConnection('default', 'default');
229
    $db2 = Database::getConnection('slave', 'default');
230

231
    $this->assertIdentical($db1, $db2, t('Both targets refer to the same connection.'));
232
  }
233 234 235 236
}

/**
 * Test fetch actions, part 1.
237
 *
238 239 240
 * We get timeout errors if we try to run too many tests at once.
 */
class DatabaseFetchTestCase extends DatabaseTestCase {
241

242
  public static function getInfo() {
243 244 245 246 247 248 249 250 251 252 253 254
    return array(
      'name' => t('Fetch tests'),
      'description' => t('Test the Database system\'s various fetch capabilities.'),
      'group' => t('Database'),
    );
  }

  /**
   * Confirm that we can fetch a record properly in default object mode.
   */
  function testQueryFetchDefault() {
    $records = array();
255
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25));
256
    $this->assertTrue($result instanceof DatabaseStatementInterface, t('Result set is a Drupal statement object.'));
257 258 259 260 261 262 263 264 265 266 267 268 269 270
    foreach ($result as $record) {
      $records[] = $record;
      $this->assertTrue(is_object($record), t('Record is an object.'));
      $this->assertIdentical($record->name, 'John', t('25 year old is John.'));
    }

    $this->assertIdentical(count($records), 1, t('There is only one record.'));
  }

  /**
   * Confirm that we can fetch a record to an object explicitly.
   */
  function testQueryFetchObject() {
    $records = array();
271
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => PDO::FETCH_OBJ));
272 273 274 275 276 277 278 279 280 281 282 283 284 285
    foreach ($result as $record) {
      $records[] = $record;
      $this->assertTrue(is_object($record), t('Record is an object.'));
      $this->assertIdentical($record->name, 'John', t('25 year old is John.'));
    }

    $this->assertIdentical(count($records), 1, t('There is only one record.'));
  }

  /**
   * Confirm that we can fetch a record to an array associative explicitly.
   */
  function testQueryFetchArray() {
    $records = array();
286
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => PDO::FETCH_ASSOC));
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    foreach ($result as $record) {
      $records[] = $record;
      if ($this->assertTrue(is_array($record), t('Record is an array.'))) {
        $this->assertIdentical($record['name'], 'John', t('Record can be accessed associatively.'));
      }
    }

    $this->assertIdentical(count($records), 1, t('There is only one record.'));
  }

  /**
   * Confirm that we can fetch a record into a new instance of a custom class.
   *
   * @see FakeRecord
   */
  function testQueryFetchClass() {
    $records = array();
304
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => 'FakeRecord'));
305 306 307 308 309 310 311 312 313 314 315 316 317
    foreach ($result as $record) {
      $records[] = $record;
      if ($this->assertTrue($record instanceof FakeRecord, t('Record is an object of class FakeRecord.'))) {
        $this->assertIdentical($record->name, 'John', t('25 year old is John.'));
      }
    }

    $this->assertIdentical(count($records), 1, t('There is only one record.'));
  }
}

/**
 * Test fetch actions, part 2.
318
 *
319 320 321 322
 * We get timeout errors if we try to run too many tests at once.
 */
class DatabaseFetch2TestCase extends DatabaseTestCase {

323
  public static function getInfo() {
324
    return array(
325
      'name' => t('Fetch tests, part 2'),
326 327 328 329 330 331 332 333 334 335 336 337
      'description' => t('Test the Database system\'s various fetch capabilities.'),
      'group' => t('Database'),
    );
  }

  function setUp() {
    parent::setUp();
  }

  // Confirm that we can fetch a record into an indexed array explicitly.
  function testQueryFetchNum() {
    $records = array();
338
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => PDO::FETCH_NUM));
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
    foreach ($result as $record) {
      $records[] = $record;
      if ($this->assertTrue(is_array($record), t('Record is an array.'))) {
        $this->assertIdentical($record[0], 'John', t('Record can be accessed numerically.'));
      }
    }

    $this->assertIdentical(count($records), 1, 'There is only one record');
  }

  /**
   * Confirm that we can fetch a record into a doubly-keyed array explicitly.
   */
  function testQueryFetchBoth() {
    $records = array();
354
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => PDO::FETCH_BOTH));
355 356 357 358 359 360 361 362 363 364 365 366 367
    foreach ($result as $record) {
      $records[] = $record;
      if ($this->assertTrue(is_array($record), t('Record is an array.'))) {
        $this->assertIdentical($record[0], 'John', t('Record can be accessed numerically.'));
        $this->assertIdentical($record['name'], 'John', t('Record can be accessed associatively.'));
      }
    }

    $this->assertIdentical(count($records), 1, t('There is only one record.'));
  }

  /**
   * Confirm that we can fetch an entire column of a result set at once.
368
   */
369 370
  function testQueryFetchCol() {
    $records = array();
371
    $result = db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25));
372 373 374
    $column = $result->fetchCol();
    $this->assertIdentical(count($column), 3, t('fetchCol() returns the right number of records.'));

375
    $result = db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25));
376 377 378 379 380 381 382 383 384 385 386 387
    $i = 0;
    foreach ($result as $record) {
      $this->assertIdentical($record->name, $column[$i++], t('Column matches direct accesss.'));
    }
  }
}

/**
 * Test the insert builder.
 */
class DatabaseInsertTestCase extends DatabaseTestCase {

388
  public static function getInfo() {
389 390 391 392 393 394 395 396 397 398 399
    return array(
      'name' => t('Insert tests'),
      'description' => t('Test the Insert query builder.'),
      'group' => t('Database'),
    );
  }

  /**
   * Test the very basic insert functionality.
   */
  function testSimpleInsert() {
400
    $num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
401

402 403 404 405 406 407
    $query = db_insert('test');
    $query->fields(array(
      'name' => 'Yoko',
      'age' => '29',
    ));
    $query->execute();
408

409
    $num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
410
    $this->assertIdentical($num_records_before + 1, (int)$num_records_after, t('Record inserts correctly.'));
411
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Yoko'))->fetchField();
412
    $this->assertIdentical($saved_age, '29', t('Can retrieve after inserting.'));
413 414 415 416 417 418
  }

  /**
   * Test that we can insert multiple records in one query object.
   */
  function testMultiInsert() {
419
    $num_records_before = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437

    $query = db_insert('test');
    $query->fields(array(
      'name' => 'Larry',
      'age' => '30',
    ));

    // We should be able to specify values in any order if named.
    $query->values(array(
      'age' => '31',
      'name' => 'Curly',
    ));

    // We should be able to say "use the field order".
    // This is not the recommended mechanism for most cases, but it should work.
    $query->values(array('Moe', '32'));
    $query->execute();

438
    $num_records_after = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
439
    $this->assertIdentical($num_records_before + 3, $num_records_after, t('Record inserts correctly.'));
440
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Larry'))->fetchField();
441
    $this->assertIdentical($saved_age, '30', t('Can retrieve after inserting.'));
442
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Curly'))->fetchField();
443
    $this->assertIdentical($saved_age, '31', t('Can retrieve after inserting.'));
444
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Moe'))->fetchField();
445
    $this->assertIdentical($saved_age, '32', t('Can retrieve after inserting.'));
446 447 448 449 450 451
  }

  /**
   * Test that an insert object can be reused with new data after it executes.
   */
  function testRepeatedInsert() {
452
    $num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
453

454
    $query = db_insert('test');
455

456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
    $query->fields(array(
      'name' => 'Larry',
      'age' => '30',
    ));
    $query->execute();  // This should run the insert, but leave the fields intact.

    // We should be able to specify values in any order if named.
    $query->values(array(
      'age' => '31',
      'name' => 'Curly',
    ));
    $query->execute();

    // We should be able to say "use the field order".
    $query->values(array('Moe', '32'));
    $query->execute();

473
    $num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
474
    $this->assertIdentical((int) $num_records_before + 3, (int) $num_records_after, t('Record inserts correctly.'));
475
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Larry'))->fetchField();
476
    $this->assertIdentical($saved_age, '30', t('Can retrieve after inserting.'));
477
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Curly'))->fetchField();
478
    $this->assertIdentical($saved_age, '31', t('Can retrieve after inserting.'));
479
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Moe'))->fetchField();
480
    $this->assertIdentical($saved_age, '32', t('Can retrieve after inserting.'));
481 482 483 484 485 486 487 488 489 490 491 492 493 494
  }

  /**
   * Test that we can specify fields without values and specify values later.
   */
  function testInsertFieldOnlyDefinintion() {
    // This is useful for importers, when we want to create a query and define
    // its fields once, then loop over a multi-insert execution.
    db_insert('test')
      ->fields(array('name', 'age'))
      ->values(array('Larry', '30'))
      ->values(array('Curly', '31'))
      ->values(array('Moe', '32'))
      ->execute();
495
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Larry'))->fetchField();
496
    $this->assertIdentical($saved_age, '30', t('Can retrieve after inserting.'));
497
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Curly'))->fetchField();
498
    $this->assertIdentical($saved_age, '31', t('Can retrieve after inserting.'));
499
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Moe'))->fetchField();
500
    $this->assertIdentical($saved_age, '32', t('Can retrieve after inserting.'));
501 502 503 504 505 506
  }

  /**
   * Test that inserts return the proper auto-increment ID.
   */
  function testInsertLastInsertID() {
507 508
    $id = db_insert('test')
      ->fields(array(
509 510 511 512 513 514
        'name' => 'Larry',
        'age' => '30',
      ))
      ->execute();

    $this->assertIdentical($id, '5', t('Auto-increment ID returned successfully.'));
515 516 517 518 519 520 521 522
  }
}

/**
 * Insert tests using LOB fields, which are weird on some databases.
 */
class DatabaseInsertLOBTestCase extends DatabaseTestCase {

523
  public static function getInfo() {
524 525 526 527 528 529 530 531 532 533 534 535 536
    return array(
      'name' => t('Insert tests, LOB fields'),
      'description' => t('Test the Insert query builder with LOB fields.'),
      'group' => t('Database'),
    );
  }

  /**
   * Test that we can insert a single blob field successfully.
   */
  function testInsertOneBlob() {
    $data = "This is\000a test.";
    $this->assertTrue(strlen($data) === 15, t('Test data contains a NULL.'));
537 538 539 540
    $id = db_insert('test_one_blob')
      ->fields(array('blob1' => $data))
      ->execute();
    $r = db_query('SELECT * FROM {test_one_blob} WHERE id = :id', array(':id' => $id))->fetchAssoc();
541 542 543 544 545 546 547
    $this->assertTrue($r['blob1'] === $data, t('Can insert a blob: id @id, @data.', array('@id' => $id, '@data' => serialize($r))));
  }

  /**
   * Test that we can insert multiple blob fields in the same query.
   */
  function testInsertMultipleBlob() {
548 549 550 551
    $id = db_insert('test_two_blobs')
      ->fields(array(
        'blob1' => 'This is',
        'blob2' => 'a test',
552
      ))
553 554
      ->execute();
    $r = db_query('SELECT * FROM {test_two_blobs} WHERE id = :id', array(':id' => $id))->fetchAssoc();
555 556 557 558 559 560 561 562 563
    $this->assertTrue($r['blob1'] === 'This is' && $r['blob2'] === 'a test', t('Can insert multiple blobs per row.'));
  }
}

/**
 * Insert tests for "database default" values.
 */
class DatabaseInsertDefaultsTestCase extends DatabaseTestCase {

564
  public static function getInfo() {
565
    return array(
566
      'name' => t('Insert tests, default fields'),
567 568 569 570
      'description' => t('Test the Insert query builder with default values.'),
      'group' => t('Database'),
    );
  }
571

572 573 574 575
  /**
   * Test that we can run a query that is "default values for everything".
   */
  function testDefaultInsert() {
576 577
    $query = db_insert('test')->useDefaults(array('job'));
    $id = $query->execute();
578

579
    $schema = drupal_get_schema('test');
580

581
    $job = db_query('SELECT job FROM {test} WHERE id = :id', array(':id' => $id))->fetchField();
582
    $this->assertEqual($job, $schema['fields']['job']['default'], t('Default field value is set.'));
583 584
  }

585 586 587 588
  /**
   * Test that no action will be preformed if no fields are specified.
   */
  function testDefaultEmptyInsert() {
589
    $num_records_before = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
590

591 592
    $result = db_insert('test')->execute();
    $this->assertNull($result, t('Return NULL as no fields are specified.'));
593

594
    $num_records_after = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
595
    $this->assertIdentical($num_records_before, $num_records_after, t('Do nothing as no fields are specified.'));
596 597
  }

598 599 600 601
  /**
   * Test that we can insert fields with values and defaults in the same query.
   */
  function testDefaultInsertWithFields() {
602 603 604
    $query = db_insert('test')
      ->fields(array('name' => 'Bob'))
      ->useDefaults(array('job'));
605
    $id = $query->execute();
606

607
    $schema = drupal_get_schema('test');
608

609
    $job = db_query('SELECT job FROM {test} WHERE id = :id', array(':id' => $id))->fetchField();
610
    $this->assertEqual($job, $schema['fields']['job']['default'], t('Default field value is set.'));
611 612 613 614 615 616 617 618
  }
}

/**
 * Update builder tests.
 */
class DatabaseUpdateTestCase extends DatabaseTestCase {

619
  public static function getInfo() {
620 621 622 623 624 625 626 627 628 629 630
    return array(
      'name' => t('Update tests'),
      'description' => t('Test the Update query builder.'),
      'group' => t('Database'),
    );
  }

  /**
   * Confirm that we can update a single record successfully.
   */
  function testSimpleUpdate() {
631 632 633 634
    $num_updated = db_update('test')
      ->fields(array('name' => 'Tiffany'))
      ->condition('id', 1)
      ->execute();
635 636
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));

637
    $saved_name = db_query('SELECT name FROM {test} WHERE id = :id', array(':id' => 1))->fetchField();
638 639
    $this->assertIdentical($saved_name, 'Tiffany', t('Updated name successfully.'));
  }
640

641 642 643 644
  /**
   * Confirm that we can update a multiple records successfully.
   */
  function testMultiUpdate() {
645 646 647 648
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->condition('job', 'Singer')
      ->execute();
649 650
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));

651
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
652 653 654 655 656 657 658
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
  }

  /**
   * Confirm that we can update a multiple records with a non-equality condition.
   */
  function testMultiGTUpdate() {
659 660 661 662
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->condition('age', 26, '>')
      ->execute();
663 664
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));

665
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
666 667 668 669 670 671 672
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
  }

  /**
   * Confirm that we can update a multiple records with a where call.
   */
  function testWhereUpdate() {
673 674 675 676
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->where('age > :age', array(':age' => 26))
      ->execute();
677 678
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));

679
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
680 681 682 683 684 685 686
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
  }

  /**
   * Confirm that we can stack condition and where calls.
   */
  function testWhereAndConditionUpdate() {
687 688 689 690
    $update = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->where('age > :age', array(':age' => 26))
      ->condition('name', 'Ringo');
691 692 693
    $num_updated = $update->execute();
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));

694
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
695 696
    $this->assertIdentical($num_matches, '1', t('Updated fields successfully.'));
  }
697

698 699 700 701 702 703 704
}

/**
 * Tests for more complex update statements.
 */
class DatabaseUpdateComplexTestCase extends DatabaseTestCase {

705
  public static function getInfo() {
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
    return array(
      'name' => t('Update tests, Complex'),
      'description' => t('Test the Update query builder, complex queries.'),
      'group' => t('Database'),
    );
  }

  /**
   * Test updates with OR conditionals.
   */
  function testOrConditionUpdate() {
    $update = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->condition(db_or()
        ->condition('name', 'John')
        ->condition('name', 'Paul')
      );
    $num_updated = $update->execute();
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));

726
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
727 728 729 730 731 732 733
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
  }

  /**
   * Test WHERE IN clauses.
   */
  function testInConditionUpdate() {
734 735
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
736 737 738 739
      ->condition('name', array('John', 'Paul'), 'IN')
      ->execute();
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));

740
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
741 742 743 744 745 746 747
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
  }

  /**
   * Test WHERE NOT IN clauses.
   */
  function testNotInConditionUpdate() {
748 749
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
750 751 752 753
      ->condition('name', array('John', 'Paul', 'George'), 'NOT IN')
      ->execute();
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));

754
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
755 756 757 758 759 760 761
    $this->assertIdentical($num_matches, '1', t('Updated fields successfully.'));
  }

  /**
   * Test BETWEEN conditional clauses.
   */
  function testBetweenConditionUpdate() {
762 763
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
764 765 766 767
      ->condition('age', array(25, 26), 'BETWEEN')
      ->execute();
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));

768
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
769
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
770 771 772 773 774 775
  }

  /**
   * Test LIKE conditionals.
   */
  function testLikeConditionUpdate() {
776 777
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
778 779 780 781
      ->condition('name', '%ge%', 'LIKE')
      ->execute();
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));

782
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
783 784 785 786 787 788 789
    $this->assertIdentical($num_matches, '1', t('Updated fields successfully.'));
  }

  /**
   * Test update with expression values.
   */
  function testUpdateExpression() {
790
    $before_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
791 792 793 794
    $GLOBALS['larry_test'] = 1;
    $num_updated = db_update('test')
      ->condition('name', 'Ringo')
      ->fields(array('job' => 'Musician'))
795
      ->expression('age', 'age + :age', array(':age' => 4))
796 797 798
      ->execute();
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));

799
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
800 801
    $this->assertIdentical($num_matches, '1', t('Updated fields successfully.'));

802
    $person = db_query('SELECT * FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetch();
803 804 805 806
    $this->assertEqual($person->name, 'Ringo', t('Name set correctly.'));
    $this->assertEqual($person->age, $before_age + 4, t('Age set correctly.'));
    $this->assertEqual($person->job, 'Musician', t('Job set correctly.'));
    $GLOBALS['larry_test'] = 0;
807
  }
808 809 810 811 812

  /**
   * Test update with only expression values.
   */
  function testUpdateOnlyExpression() {
813
    $before_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
814 815
    $num_updated = db_update('test')
      ->condition('name', 'Ringo')
816
      ->expression('age', 'age + :age', array(':age' => 4))
817 818 819
      ->execute();
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));

820
    $after_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
821 822
    $this->assertEqual($before_age + 4, $after_age, t('Age updated correctly'));
  }
823 824 825 826 827 828 829
}

/**
 * Test update queries involving LOB values.
 */
class DatabaseUpdateLOBTestCase extends DatabaseTestCase {

830
  public static function getInfo() {
831 832 833 834 835 836 837 838 839 840 841 842 843
    return array(
      'name' => t('Update tests, LOB'),
      'description' => t('Test the Update query builder with LOB fields.'),
      'group' => t('Database'),
    );
  }

  /**
   * Confirm that we can update a blob column.
   */
  function testUpdateOneBlob() {
    $data = "This is\000a test.";
    $this->assertTrue(strlen($data) === 15, t('Test data contains a NULL.'));
844 845 846
    $id = db_insert('test_one_blob')
      ->fields(array('blob1' => $data))
      ->execute();
847 848

    $data .= $data;
849 850 851 852
    db_update('test_one_blob')
      ->condition('id', $id)
      ->fields(array('blob1' => $data))
      ->execute();
853

854
    $r = db_query('SELECT * FROM {test_one_blob} WHERE id = :id', array(':id' => $id))->fetchAssoc();
855 856
    $this->assertTrue($r['blob1'] === $data, t('Can update a blob: id @id, @data.', array('@id' => $id, '@data' => serialize($r))));
  }
857

858 859 860 861
  /**
   * Confirm that we can update two blob columns in the same table.
   */
  function testUpdateMultipleBlob() {
862 863
    $id = db_insert('test_two_blobs')
      ->fields(array(
864
        'blob1' => 'This is',
865 866
        'blob2' => 'a test',
      ))
867 868
      ->execute();

869 870 871 872
    db_update('test_two_blobs')
      ->condition('id', $id)
      ->fields(array('blob1' => 'and so', 'blob2' => 'is this'))
      ->execute();
873

874
    $r = db_query('SELECT * FROM {test_two_blobs} WHERE id = :id', array(':id' => $id))->fetchAssoc();
875 876 877 878 879
    $this->assertTrue($r['blob1'] === 'and so' && $r['blob2'] === 'is this', t('Can update multiple blobs per row.'));
  }
}

/**
880
 * Delete/Truncate tests.
881 882 883 884 885
 *
 * The DELETE tests are not as extensive, as all of the interesting code for
 * DELETE queries is in the conditional which is identical to the UPDATE and
 * SELECT conditional handling.
 *
886 887 888
 * The TRUNCATE tests are not extensive either, because the behavior of
 * TRUNCATE queries is not consistent across database engines. We only test
 * that a TRUNCATE query actually deletes all rows from the target table.
889
 */
890
class DatabaseDeleteTruncateTestCase extends DatabaseTestCase {
891

892
  public static function getInfo() {
893
    return array(
894 895
      'name' => t('Delete/Truncate tests'),
      'description' => t('Test the Delete and Truncate query builders.'),
896 897 898 899 900 901 902 903
      'group' => t('Database'),
    );
  }

  /**
   * Confirm that we can delete a single record successfully.
   */
  function testSimpleDelete() {
904
    $num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
905

906 907 908
    $num_deleted = db_delete('test')
      ->condition('id', 1)
      ->execute();
909 910
    $this->assertIdentical($num_deleted, 1, t('Deleted 1 record.'));

911
    $num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
912 913
    $this->assertEqual($num_records_before, $num_records_after + $num_deleted, t('Deletion adds up.'));
  }
914 915 916 917 918 919 920 921 922 923 924 925 926


  /**
   * Confirm that we can truncate a whole table successfully.
   */
  function testTruncate() {
    $num_records_before = db_query("SELECT COUNT(*) FROM {test}")->fetchField();

    db_truncate('test')->execute();

    $num_records_after = db_query("SELECT COUNT(*) FROM {test}")->fetchField();
    $this->assertEqual(0, $num_records_after, t('Truncate really deletes everything.'));
  }
927 928 929 930 931 932 933
}

/**
 * Test the MERGE query builder.
 */
class DatabaseMergeTestCase extends DatabaseTestCase {

934
  public static function getInfo() {
935 936 937 938 939 940 941 942 943 944 945
    return array(
      'name' => t('Merge tests'),
      'description' => t('Test the Merge query builder.'),
      'group' => t('Database'),
    );
  }

  /**
   * Confirm that we can merge-insert a record successfully.
   */
  function testMergeInsert() {
946
    $num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
947 948 949 950 951 952 953 954 955

    db_merge('test_people')
      ->key(array('job' => 'Presenter'))
      ->fields(array(
        'age' => 31,
        'name' => 'Tiffany',
      ))
      ->execute();

956
    $num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
957 958
    $this->assertEqual($num_records_before + 1, $num_records_after, t('Merge inserted properly.'));

959
    $person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Presenter'))->fetch();
960 961 962
    $this->assertEqual($person->name, 'Tiffany', t('Name set correctly.'));
    $this->assertEqual($person->age, 31, t('Age set correctly.'));
    $this->assertEqual($person->job, 'Presenter', t('Job set correctly.'));
963 964 965 966 967 968
  }

  /**
   * Confirm that we can merge-update a record successfully.
   */
  function testMergeUpdate() {
969
    $num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
970

971 972 973 974 975 976 977
    db_merge('test_people')
      ->key(array('job' => 'Speaker'))
      ->fields(array(
        'age' => 31,
        'name' => 'Tiffany',
      ))
      ->execute();
978

979
    $num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
980
    $this->assertEqual($num_records_before, $num_records_after, t('Merge updated properly.'));
981

982
    $person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
983 984 985 986 987 988 989 990 991
    $this->assertEqual($person->name, 'Tiffany', t('Name set correctly.'));
    $this->assertEqual($person->age, 31, t('Age set correctly.'));
    $this->assertEqual($person->job, 'Speaker', t('Job set correctly.'));
  }

  /**
   * Confirm that we can merge-update a record successfully, with exclusion.
   */
  function testMergeUpdateExcept() {
992
    $num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
993

994 995 996 997 998 999 1000 1001
    db_merge('test_people')
      ->key(array('job' => 'Speaker'))
      ->fields(array(
        'age' => 31,
        'name' => 'Tiffany',
      ))
      ->updateExcept('age')
      ->execute();
1002

1003
    $num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
1004
    $this->assertEqual($num_records_before, $num_records_after, t('Merge updated properly.'));
1005

1006
    $person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
1007 1008 1009 1010 1011 1012 1013 1014 1015
    $this->assertEqual($person->name, 'Tiffany', t('Name set correctly.'));
    $this->assertEqual($person->age, 30, t('Age skipped correctly.'));
    $this->assertEqual($person->job, 'Speaker', t('Job set correctly.'));
  }

  /**
   * Confirm that we can merge-update a record successfully, with alternate replacement.
   */
  function testMergeUpdateExplicit() {
1016
    $num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
1017

1018 1019 1020 1021 1022 1023 1024 1025
    db_merge('test_people')
      ->key(array('job' => 'Speaker'))
      ->fields(array(
        'age' => 31,
        'name' => 'Tiffany',
      ))
      ->update(array('name' => 'Joe'))
      ->execute();
1026

1027
    $num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
1028
    $this->assertEqual($num_records_before, $num_records_after, t('Merge updated properly.'));
1029

1030
    $person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
1031 1032 1033 1034 1035 1036 1037 1038 1039
    $this->assertEqual($person->name, 'Joe', t('Name set correctly.'));
    $this->assertEqual($person->age, 30, t('Age skipped correctly.'));
    $this->assertEqual($person->job, 'Speaker', t('Job set correctly.'));
  }

  /**
   * Confirm that we can merge-update a record successfully, with expressions.
   */
  function testMergeUpdateExpression() {
1040
    $num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
1041

1042
    $age_before = db_query('SELECT age FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetchField();
1043

1044
    // This is a very contrived example, as I have no idea why you'd want to
1045 1046
    // change age this way, but that's beside the point.
    // Note that we are also double-setting age here, once as a literal and
1047
    // once as an expression. This test will only pass if the expression wins,
1048 1049 1050
    // which is what is supposed to happen.
    db_merge('test_people')
      ->key(array('job' => 'Speaker'))
1051 1052 1053 1054
      ->fields(array(
        'age' => 31,
        'name' => 'Tiffany',
      ))
1055 1056 1057
      ->expression('age', 'age + :age', array(':age' => 4))
      ->execute();

1058
    $num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
1059
    $this->assertEqual($num_records_before, $num_records_after, t('Merge updated properly.'));
1060

1061
    $person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
1062 1063 1064 1065
    $this->assertEqual($person->name, 'Tiffany', t('Name set correctly.'));
    $this->assertEqual($person->age, $age_before + 4, t('Age updated correctly.'));
    $this->assertEqual($person->job, 'Speaker', t('Job set correctly.'));
  }
1066

Dries's avatar