database_test.test 118 KB
Newer Older
1 2 3 4 5 6
<?php

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

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

  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
    // This ends up being a test for table drop and create, too, which is nice.
    foreach ($schema as $name => $data) {
      if (db_table_exists($name)) {
45
        db_drop_table($name);
46
      }
47
      db_create_table($name, $data);
48
    }
49 50

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

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
  /**
   * 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();
77 78 79 80 81
  }

  /**
   * Setup our sample data.
   *
82
   * These are added using db_query(), since we're not trying to test the
83 84 85
   * INSERT operations here, just populate.
   */
  function addSampleData() {
86 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
    // 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();
165
  }
166 167 168 169 170 171 172
}

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

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

  /**
   * 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.
188 189
    $connection_info = Database::getConnectionInfo('default');
    Database::addConnectionInfo('default', 'slave', $connection_info['default']);
190 191

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

194 195 196
    $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.'));
197 198 199

    // Try to open those targets another time, that should return the same objects.
    $db1b = Database::getConnection('default', 'default');
200
    $db2b = Database::getConnection('slave', 'default');
201 202
    $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.'));
203 204 205

    // Try to open an unknown target.
    $unknown_target = $this->randomName();
206
    $db3 = Database::getConnection($unknown_target, 'default');
207 208
    $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.'));
209 210

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

  /**
   * 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');
228
    $db2 = Database::getConnection('slave', 'default');
229

230
    $this->assertIdentical($db1, $db2, t('Both targets refer to the same connection.'));
231
  }
232 233 234 235 236 237 238 239 240 241 242 243 244

  /**
   * Tests the closing of a database connection.
   */
  function testConnectionClosing() {
    // Open the default target so we have an object to compare.
    $db1 = Database::getConnection('default', 'default');

    // Try to close the the default connection, then open a new one.
    Database::closeConnection('default', 'default');
    $db2 = Database::getConnection('default', 'default');

    // Opening a connection after closing it should yield an object different than the original.
245
    $this->assertNotIdentical($db1, $db2, t('Opening the default connection after it is closed returns a new object.'));
246
  }
247 248 249 250 251 252 253 254 255 256 257 258 259

  /**
   * Tests the connection options of the active database.
   */
  function testConnectionOptions() {
    $connection_info = Database::getConnectionInfo('default');

    // Be sure we're connected to the default database.
    $db = Database::getConnection('default', 'default');
    $connectionOptions = $db->getConnectionOptions();

    // In the MySQL driver, the port can be different, so check individual
    // options.
260 261
    $this->assertEqual($connection_info['default']['driver'], $connectionOptions['driver'], t('The default connection info driver matches the current connection options driver.'));
    $this->assertEqual($connection_info['default']['database'], $connectionOptions['database'], t('The default connection info database matches the current connection options database.'));
262 263 264 265 266 267 268 269

    // Set up identical slave and confirm connection options are identical.
    Database::addConnectionInfo('default', 'slave', $connection_info['default']);
    $db2 = Database::getConnection('slave', 'default');
    $connectionOptions2 = $db2->getConnectionOptions();

    // Get a fresh copy of the default connection options.
    $connectionOptions = $db->getConnectionOptions();
270
    $this->assertIdentical($connectionOptions, $connectionOptions2, t('The default and slave connection options are identical.'));
271 272 273 274 275 276 277 278 279

    // Set up a new connection with different connection info.
    $test = $connection_info['default'];
    $test['database'] .= 'test';
    Database::addConnectionInfo('test', 'default', $test);
    $connection_info = Database::getConnectionInfo('test');

    // Get a fresh copy of the default connection options.
    $connectionOptions = $db->getConnectionOptions();
280
    $this->assertNotEqual($connection_info['default']['database'], $connectionOptions['database'], t('The test connection info database does not match the current connection options database.'));
281
  }
282 283 284 285
}

/**
 * Test fetch actions, part 1.
286
 *
287 288 289
 * We get timeout errors if we try to run too many tests at once.
 */
class DatabaseFetchTestCase extends DatabaseTestCase {
290

291
  public static function getInfo() {
292
    return array(
293 294 295
      'name' => 'Fetch tests',
      'description' => 'Test the Database system\'s various fetch capabilities.',
      'group' => 'Database',
296 297 298 299 300 301 302 303
    );
  }

  /**
   * Confirm that we can fetch a record properly in default object mode.
   */
  function testQueryFetchDefault() {
    $records = array();
304
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25));
305
    $this->assertTrue($result instanceof DatabaseStatementInterface, t('Result set is a Drupal statement object.'));
306 307
    foreach ($result as $record) {
      $records[] = $record;
308 309
      $this->assertTrue(is_object($record), t('Record is an object.'));
      $this->assertIdentical($record->name, 'John', t('25 year old is John.'));
310 311
    }

312
    $this->assertIdentical(count($records), 1, t('There is only one record.'));
313 314 315 316 317 318 319
  }

  /**
   * Confirm that we can fetch a record to an object explicitly.
   */
  function testQueryFetchObject() {
    $records = array();
320
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => PDO::FETCH_OBJ));
321 322
    foreach ($result as $record) {
      $records[] = $record;
323 324
      $this->assertTrue(is_object($record), t('Record is an object.'));
      $this->assertIdentical($record->name, 'John', t('25 year old is John.'));
325 326
    }

327
    $this->assertIdentical(count($records), 1, t('There is only one record.'));
328 329 330 331 332 333 334
  }

  /**
   * Confirm that we can fetch a record to an array associative explicitly.
   */
  function testQueryFetchArray() {
    $records = array();
335
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => PDO::FETCH_ASSOC));
336 337
    foreach ($result as $record) {
      $records[] = $record;
338 339
      if ($this->assertTrue(is_array($record), t('Record is an array.'))) {
        $this->assertIdentical($record['name'], 'John', t('Record can be accessed associatively.'));
340 341 342
      }
    }

343
    $this->assertIdentical(count($records), 1, t('There is only one record.'));
344 345 346 347 348 349 350 351 352
  }

  /**
   * Confirm that we can fetch a record into a new instance of a custom class.
   *
   * @see FakeRecord
   */
  function testQueryFetchClass() {
    $records = array();
353
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => 'FakeRecord'));
354 355
    foreach ($result as $record) {
      $records[] = $record;
356 357
      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.'));
358 359 360
      }
    }

361
    $this->assertIdentical(count($records), 1, t('There is only one record.'));
362 363 364 365 366
  }
}

/**
 * Test fetch actions, part 2.
367
 *
368 369 370 371
 * We get timeout errors if we try to run too many tests at once.
 */
class DatabaseFetch2TestCase extends DatabaseTestCase {

372
  public static function getInfo() {
373
    return array(
374 375 376
      'name' => 'Fetch tests, part 2',
      'description' => 'Test the Database system\'s various fetch capabilities.',
      'group' => 'Database',
377 378 379 380 381 382 383 384 385 386
    );
  }

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

  // Confirm that we can fetch a record into an indexed array explicitly.
  function testQueryFetchNum() {
    $records = array();
387
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => PDO::FETCH_NUM));
388 389
    foreach ($result as $record) {
      $records[] = $record;
390 391
      if ($this->assertTrue(is_array($record), t('Record is an array.'))) {
        $this->assertIdentical($record[0], 'John', t('Record can be accessed numerically.'));
392 393 394 395 396 397 398 399 400 401 402
      }
    }

    $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();
403
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => PDO::FETCH_BOTH));
404 405
    foreach ($result as $record) {
      $records[] = $record;
406 407 408
      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.'));
409 410 411
      }
    }

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

  /**
   * Confirm that we can fetch an entire column of a result set at once.
417
   */
418 419
  function testQueryFetchCol() {
    $records = array();
420
    $result = db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25));
421
    $column = $result->fetchCol();
422
    $this->assertIdentical(count($column), 3, t('fetchCol() returns the right number of records.'));
423

424
    $result = db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25));
425 426
    $i = 0;
    foreach ($result as $record) {
427
      $this->assertIdentical($record->name, $column[$i++], t('Column matches direct accesss.'));
428 429 430 431 432 433 434 435 436
    }
  }
}

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

437
  public static function getInfo() {
438
    return array(
439 440 441
      'name' => 'Insert tests',
      'description' => 'Test the Insert query builder.',
      'group' => 'Database',
442 443 444 445 446 447 448
    );
  }

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

451 452 453 454 455 456
    $query = db_insert('test');
    $query->fields(array(
      'name' => 'Yoko',
      'age' => '29',
    ));
    $query->execute();
457

458
    $num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
459
    $this->assertIdentical($num_records_before + 1, (int) $num_records_after, t('Record inserts correctly.'));
460
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Yoko'))->fetchField();
461
    $this->assertIdentical($saved_age, '29', t('Can retrieve after inserting.'));
462 463 464 465 466 467
  }

  /**
   * Test that we can insert multiple records in one query object.
   */
  function testMultiInsert() {
468
    $num_records_before = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486

    $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();

487
    $num_records_after = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
488
    $this->assertIdentical($num_records_before + 3, $num_records_after, t('Record inserts correctly.'));
489
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Larry'))->fetchField();
490
    $this->assertIdentical($saved_age, '30', t('Can retrieve after inserting.'));
491
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Curly'))->fetchField();
492
    $this->assertIdentical($saved_age, '31', t('Can retrieve after inserting.'));
493
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Moe'))->fetchField();
494
    $this->assertIdentical($saved_age, '32', t('Can retrieve after inserting.'));
495 496 497 498 499 500
  }

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

503
    $query = db_insert('test');
504

505 506 507 508
    $query->fields(array(
      'name' => 'Larry',
      'age' => '30',
    ));
509
    $query->execute();  // This should run the insert, but leave the fields intact.
510 511 512 513 514 515 516 517 518 519 520 521

    // 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();

522
    $num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
523
    $this->assertIdentical((int) $num_records_before + 3, (int) $num_records_after, t('Record inserts correctly.'));
524
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Larry'))->fetchField();
525
    $this->assertIdentical($saved_age, '30', t('Can retrieve after inserting.'));
526
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Curly'))->fetchField();
527
    $this->assertIdentical($saved_age, '31', t('Can retrieve after inserting.'));
528
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Moe'))->fetchField();
529
    $this->assertIdentical($saved_age, '32', t('Can retrieve after inserting.'));
530 531 532 533 534 535 536 537 538 539 540 541 542 543
  }

  /**
   * 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();
544
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Larry'))->fetchField();
545
    $this->assertIdentical($saved_age, '30', t('Can retrieve after inserting.'));
546
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Curly'))->fetchField();
547
    $this->assertIdentical($saved_age, '31', t('Can retrieve after inserting.'));
548
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Moe'))->fetchField();
549
    $this->assertIdentical($saved_age, '32', t('Can retrieve after inserting.'));
550 551 552 553 554 555
  }

  /**
   * Test that inserts return the proper auto-increment ID.
   */
  function testInsertLastInsertID() {
556 557
    $id = db_insert('test')
      ->fields(array(
558 559 560 561 562
        'name' => 'Larry',
        'age' => '30',
      ))
      ->execute();

563
    $this->assertIdentical($id, '5', t('Auto-increment ID returned successfully.'));
564
  }
565 566 567 568 569

  /**
   * Test that the INSERT INTO ... SELECT ... syntax works.
   */
  function testInsertSelect() {
570 571 572 573 574 575
    $query = db_select('test_people', 'tp');
    // The query builder will always append expressions after fields.
    // Add the expression first to test that the insert fields are correctly
    // re-ordered.
    $query->addExpression('tp.age', 'age');
    $query
576
      ->fields('tp', array('name','job'))
577 578 579 580 581 582 583
      ->condition('tp.name', 'Meredith');

    // The resulting query should be equivalent to:
    // INSERT INTO test (age, name, job)
    // SELECT tp.age AS age, tp.name AS name, tp.job AS job
    // FROM test_people tp
    // WHERE tp.name = 'Meredith'
584 585 586 587 588
    db_insert('test')
      ->from($query)
      ->execute();

    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Meredith'))->fetchField();
589
    $this->assertIdentical($saved_age, '30', t('Can retrieve after inserting.'));
590
  }
591 592 593 594 595 596 597
}

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

598
  public static function getInfo() {
599
    return array(
600 601 602
      'name' => 'Insert tests, LOB fields',
      'description' => 'Test the Insert query builder with LOB fields.',
      'group' => 'Database',
603 604 605 606 607 608 609 610
    );
  }

  /**
   * Test that we can insert a single blob field successfully.
   */
  function testInsertOneBlob() {
    $data = "This is\000a test.";
611
    $this->assertTrue(strlen($data) === 15, t('Test data contains a NULL.'));
612 613 614 615
    $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();
616
    $this->assertTrue($r['blob1'] === $data, t('Can insert a blob: id @id, @data.', array('@id' => $id, '@data' => serialize($r))));
617 618 619 620 621 622
  }

  /**
   * Test that we can insert multiple blob fields in the same query.
   */
  function testInsertMultipleBlob() {
623 624 625 626
    $id = db_insert('test_two_blobs')
      ->fields(array(
        'blob1' => 'This is',
        'blob2' => 'a test',
627
      ))
628 629
      ->execute();
    $r = db_query('SELECT * FROM {test_two_blobs} WHERE id = :id', array(':id' => $id))->fetchAssoc();
630
    $this->assertTrue($r['blob1'] === 'This is' && $r['blob2'] === 'a test', t('Can insert multiple blobs per row.'));
631 632 633 634 635 636 637 638
  }
}

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

639
  public static function getInfo() {
640
    return array(
641 642 643
      'name' => 'Insert tests, default fields',
      'description' => 'Test the Insert query builder with default values.',
      'group' => 'Database',
644 645
    );
  }
646

647 648 649 650
  /**
   * Test that we can run a query that is "default values for everything".
   */
  function testDefaultInsert() {
651 652
    $query = db_insert('test')->useDefaults(array('job'));
    $id = $query->execute();
653

654
    $schema = drupal_get_schema('test');
655

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

660 661 662 663
  /**
   * Test that no action will be preformed if no fields are specified.
   */
  function testDefaultEmptyInsert() {
664
    $num_records_before = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
665

666 667 668
    try {
      $result = db_insert('test')->execute();
      // This is only executed if no exception has been thrown.
669 670 671
      $this->fail(t('Expected exception NoFieldsException has not been thrown.'));
    } catch (NoFieldsException $e) {
      $this->pass(t('Expected exception NoFieldsException has been thrown.'));
672
    }
673

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

678 679 680 681
  /**
   * Test that we can insert fields with values and defaults in the same query.
   */
  function testDefaultInsertWithFields() {
682 683 684
    $query = db_insert('test')
      ->fields(array('name' => 'Bob'))
      ->useDefaults(array('job'));
685
    $id = $query->execute();
686

687
    $schema = drupal_get_schema('test');
688

689
    $job = db_query('SELECT job FROM {test} WHERE id = :id', array(':id' => $id))->fetchField();
690
    $this->assertEqual($job, $schema['fields']['job']['default'], t('Default field value is set.'));
691 692 693 694 695 696 697 698
  }
}

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

699
  public static function getInfo() {
700
    return array(
701 702 703
      'name' => 'Update tests',
      'description' => 'Test the Update query builder.',
      'group' => 'Database',
704 705 706 707 708 709 710
    );
  }

  /**
   * Confirm that we can update a single record successfully.
   */
  function testSimpleUpdate() {
711 712 713 714
    $num_updated = db_update('test')
      ->fields(array('name' => 'Tiffany'))
      ->condition('id', 1)
      ->execute();
715
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));
716

717
    $saved_name = db_query('SELECT name FROM {test} WHERE id = :id', array(':id' => 1))->fetchField();
718
    $this->assertIdentical($saved_name, 'Tiffany', t('Updated name successfully.'));
719
  }
720

721 722 723 724
  /**
   * Confirm that we can update a multiple records successfully.
   */
  function testMultiUpdate() {
725 726 727 728
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->condition('job', 'Singer')
      ->execute();
729
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));
730

731
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
732
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
733 734 735 736 737 738
  }

  /**
   * Confirm that we can update a multiple records with a non-equality condition.
   */
  function testMultiGTUpdate() {
739 740 741 742
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->condition('age', 26, '>')
      ->execute();
743
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));
744

745
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
746
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
747 748 749 750 751 752
  }

  /**
   * Confirm that we can update a multiple records with a where call.
   */
  function testWhereUpdate() {
753 754 755 756
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->where('age > :age', array(':age' => 26))
      ->execute();
757
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));
758

759
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
760
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
761 762 763 764 765 766
  }

  /**
   * Confirm that we can stack condition and where calls.
   */
  function testWhereAndConditionUpdate() {
767 768 769 770
    $update = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->where('age > :age', array(':age' => 26))
      ->condition('name', 'Ringo');
771
    $num_updated = $update->execute();
772
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));
773

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

778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
  /**
   * Test updating with expressions.
   */
  function testExpressionUpdate() {
    // Set age = 1 for a single row for this test to work.
    db_update('test')
      ->condition('id', 1)
      ->fields(array('age' => 1))
      ->execute();

    // Ensure that expressions are handled properly.  This should set every
    // record's age to a square of itself, which will change only three of the
    // four records in the table since 1*1 = 1. That means only three records
    // are modified, so we should get back 3, not 4, from execute().
    $num_rows = db_update('test')
      ->expression('age', 'age * age')
      ->execute();
    $this->assertIdentical($num_rows, 3, t('Number of affected rows are returned.'));
  }
797 798 799 800 801 802 803
}

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

804
  public static function getInfo() {
805
    return array(
806 807 808
      'name' => 'Update tests, Complex',
      'description' => 'Test the Update query builder, complex queries.',
      'group' => 'Database',
809 810 811 812 813 814 815 816 817 818 819 820 821 822
    );
  }

  /**
   * 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();
823
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));
824

825
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
826
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
827 828 829 830 831 832
  }

  /**
   * Test WHERE IN clauses.
   */
  function testInConditionUpdate() {
833 834
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
835 836
      ->condition('name', array('John', 'Paul'), 'IN')
      ->execute();
837
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));
838

839
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
840
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
841 842 843 844 845 846
  }

  /**
   * Test WHERE NOT IN clauses.
   */
  function testNotInConditionUpdate() {
847 848
    // The o is lowercase in the 'NoT IN' operator, to make sure the operators
    // work in mixed case.
849 850
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
851
      ->condition('name', array('John', 'Paul', 'George'), 'NoT IN')
852
      ->execute();
853
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));
854

855
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
856
    $this->assertIdentical($num_matches, '1', t('Updated fields successfully.'));
857 858 859 860 861 862
  }

  /**
   * Test BETWEEN conditional clauses.
   */
  function testBetweenConditionUpdate() {
863 864
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
865 866
      ->condition('age', array(25, 26), 'BETWEEN')
      ->execute();
867
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));
868

869
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
870
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
871 872 873 874 875 876
  }

  /**
   * Test LIKE conditionals.
   */
  function testLikeConditionUpdate() {
877 878
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
879 880
      ->condition('name', '%ge%', 'LIKE')
      ->execute();
881
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));
882

883
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
884
    $this->assertIdentical($num_matches, '1', t('Updated fields successfully.'));
885 886 887 888 889 890
  }

  /**
   * Test update with expression values.
   */
  function testUpdateExpression() {
891
    $before_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
892 893 894 895
    $GLOBALS['larry_test'] = 1;
    $num_updated = db_update('test')
      ->condition('name', 'Ringo')
      ->fields(array('job' => 'Musician'))
896
      ->expression('age', 'age + :age', array(':age' => 4))
897
      ->execute();
898
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));
899

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

903
    $person = db_query('SELECT * FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetch();
904 905 906
    $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.'));
907
    $GLOBALS['larry_test'] = 0;
908
  }
909 910 911 912 913

  /**
   * Test update with only expression values.
   */
  function testUpdateOnlyExpression() {
914
    $before_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
915 916
    $num_updated = db_update('test')
      ->condition('name', 'Ringo')
917
      ->expression('age', 'age + :age', array(':age' => 4))
918
      ->execute();
919
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));
920

921
    $after_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
922
    $this->assertEqual($before_age + 4, $after_age, t('Age updated correctly'));
923
  }
924 925 926 927 928 929 930
}

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

931
  public static function getInfo() {
932
    return array(
933 934 935
      'name' => 'Update tests, LOB',
      'description' => 'Test the Update query builder with LOB fields.',
      'group' => 'Database',
936 937 938 939 940 941 942 943
    );
  }

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

    $data .= $data;
950 951 952 953
    db_update('test_one_blob')
      ->condition('id', $id)
      ->fields(array('blob1' => $data))
      ->execute();
954

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

959 960 961 962
  /**
   * Confirm that we can update two blob columns in the same table.
   */
  function testUpdateMultipleBlob() {
963 964
    $id = db_insert('test_two_blobs')
      ->fields(array(
965
        'blob1' => 'This is',
966 967
        'blob2' => 'a test',
      ))
968 969
      ->execute();

Dries's avatar