database_test.test 129 KB
Newer Older
1
2
<?php

3
4
use Drupal\Database\Database;

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

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

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

26
27
28
29
30
31
    $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');

32
33
34
35
36
37
38
39
40
41
42
43
    $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) {
44
45
46
    // 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)) {
47
        db_drop_table($name);
48
      }
49
      db_create_table($name, $data);
50
    }
51
52

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

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

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

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

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

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

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

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

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

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

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

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

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

  /**
   * 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.
247
    $this->assertNotIdentical($db1, $db2, t('Opening the default connection after it is closed returns a new object.'));
248
  }
249
250
251
252
253
254
255
256
257
258
259
260
261

  /**
   * 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.
262
263
    $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.'));
264
265
266
267
268
269
270
271

    // 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();
272
    $this->assertIdentical($connectionOptions, $connectionOptions2, t('The default and slave connection options are identical.'));
273
274
275
276
277
278
279
280
281

    // 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();
282
    $this->assertNotEqual($connection_info['default']['database'], $connectionOptions['database'], t('The test connection info database does not match the current connection options database.'));
283
  }
284
285
286
287
}

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

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

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

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

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

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

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

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

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

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

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

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

382
383
384
385
  function setUp() {
    parent::setUp();
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

505
    $query = db_insert('test');
506

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

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

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

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

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

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

  /**
   * Test that the INSERT INTO ... SELECT ... syntax works.
   */
  function testInsertSelect() {
572
573
574
575
576
577
    $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
578
      ->fields('tp', array('name','job'))
579
580
581
582
583
584
585
      ->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'
586
587
588
589
590
    db_insert('test')
      ->from($query)
      ->execute();

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

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

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

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

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

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

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

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

656
    $schema = drupal_get_schema('test');
657

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

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

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

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

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

689
    $schema = drupal_get_schema('test');
690

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

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

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

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

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

723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
  /**
   * Confirm updating to NULL.
   */
  function testSimpleNullUpdate() {
    $this->ensureSampleDataNull();
    $num_updated = db_update('test_null')
      ->fields(array('age' => NULL))
      ->condition('name', 'Kermit')
      ->execute();
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));

    $saved_age = db_query('SELECT age FROM {test_null} WHERE name = :name', array(':name' => 'Kermit'))->fetchField();
    $this->assertNull($saved_age, t('Updated name successfully.'));
  }

738
739
740
741
  /**
   * Confirm that we can update a multiple records successfully.
   */
  function testMultiUpdate() {
742
743
744
745
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->condition('job', 'Singer')
      ->execute();
746
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));
747

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

  /**
   * Confirm that we can update a multiple records with a non-equality condition.
   */
  function testMultiGTUpdate() {
756
757
758
759
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->condition('age', 26, '>')
      ->execute();
760
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));
761

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

  /**
   * Confirm that we can update a multiple records with a where call.
   */
  function testWhereUpdate() {
770
771
772
773
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->where('age > :age', array(':age' => 26))
      ->execute();
774
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));
775

776
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
777
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
778
779
780
781
782
783
  }

  /**
   * Confirm that we can stack condition and where calls.
   */
  function testWhereAndConditionUpdate() {
784
785
786
787
    $update = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->where('age > :age', array(':age' => 26))
      ->condition('name', 'Ringo');
788
    $num_updated = $update->execute();
789
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));
790

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

795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
  /**
   * 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.'));
  }
814
815
816
817
818
819
820
}

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

821
  public static function getInfo() {
822
    return array(
823
824
825
      'name' => 'Update tests, Complex',
      'description' => 'Test the Update query builder, complex queries.',
      'group' => 'Database',
826
827
828
829
830
831
832
833
834
835
836
837
838
839
    );
  }

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

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

  /**
   * Test WHERE IN clauses.
   */
  function testInConditionUpdate() {
850
851
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
852
853
      ->condition('name', array('John', 'Paul'), 'IN')
      ->execute();
854
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));
855

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

  /**
   * Test WHERE NOT IN clauses.
   */
  function testNotInConditionUpdate() {
864
865
    // The o is lowercase in the 'NoT IN' operator, to make sure the operators
    // work in mixed case.
866
867
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
868
      ->condition('name', array('John', 'Paul', 'George'), 'NoT IN')
869
      ->execute();
870
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));
871

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

  /**
   * Test BETWEEN conditional clauses.
   */
  function testBetweenConditionUpdate() {
880
881
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
882
883
      ->condition('age', array(25, 26), 'BETWEEN')
      ->execute();
884
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));
885

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

  /**
   * Test LIKE conditionals.
   */
  function testLikeConditionUpdate() {
894
895
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
896
897
      ->condition('name', '%ge%', 'LIKE')
      ->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
904
905
906
907
  }

  /**
   * Test update with expression values.
   */
  function testUpdateExpression() {
908
    $before_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
909
910
911
912
    $GLOBALS['larry_test'] = 1;
    $num_updated = db_update('test')
      ->condition('name', 'Ringo')
      ->fields(array('job' => 'Musician'))
913
      ->expression('age', 'age + :age', array(':age' => 4))
914
      ->execute();
915
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));
916

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

920
    $person = db_query('SELECT * FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetch();
921
922
923
    $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.'));
924
    $GLOBALS['larry_test'] = 0;
925
  }
926
927
928
929
930

  /**
   * Test update with only expression values.
   */
  function testUpdateOnlyExpression() {
931
    $before_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
932
933
    $num_updated = db_update('test')
      ->condition('name', 'Ringo')
934
      ->expression('age', 'age + :age', array(':age' => 4))
935
      ->execute();
936
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));
937

938
    $after_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
939
    $this->assertEqual($before_age + 4, $after_age, t('Age updated correctly'));
940
  }
941
942
943
944
945
946
947
}

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

948
  public static function getInfo() {
949
    return array(
950
951
952
      'name' => 'Update tests, LOB',
      'description' => 'Test the Update query builder with LOB fields.',
      'group' => 'Database',
953
954
955
956
957
958
959
960
    );
  }

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

    $data .= $data;
967
968
969
970
    db_update('test_one_blob')
      ->condition('id', $id)
      ->fields(array('blob1' => $data))
      ->execute();
971

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

976
977
978
979
  /**
   * Confirm that we can update two blob columns in the same table.
   */
  function testUpdateMultipleBlob() {
980
981
    $id = db_insert('test_two_blobs')
      ->fields(array(
982
        'blob1' => 'This is',
983
984
        'blob2' => 'a test',
      ))
985
986
      ->execute();

987
988
989
990
    db_update('test_two_blobs')
      ->condition('id', $id)
      ->fields(array('blob1' => 'and so', 'blob2' => 'is this'))
      ->execute();
991

992
    $r = db_query('SELECT * FROM {test_two_blobs} WHERE id = :id', array(':id' => $id))->fetchAssoc();
993
    $this->assertTrue($r['blob1'] === 'and so' && $r['blob2'] === 'is this', t('Can update multiple blobs per row.'));
994
995
996
997
  }
}

/**
998
 * Delete/Truncate tests.
999
1000
1001
1002
1003
 *
 * 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.
 *
1004
1005
1006
 * 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.
1007
 */
1008
class DatabaseDeleteTruncateTestCase extends DatabaseTestCase {
1009

1010
  public static function getInfo() {
1011
    return array(
1012
1013
1014
      'name' => 'Delete/Truncate tests',
      'description' => 'Test the Delete and Truncate query builders.',
      'group' => 'Database',
1015
1016
1017
    );
  }

1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
  /**
   * Confirm that we can use a subselect in a delete successfully.
   */
  function testSubselectDelete() {
    $num_records_before = db_query('SELECT COUNT(*) FROM {test_task}')->fetchField();
    $pid_to_delete = db_query("SELECT * FROM {test_task} WHERE task = 'sleep'")->fetchField();

    $subquery = db_select('test', 't')
      ->fields('t', array('id'))
      ->condition('t.id', array($pid_to_delete), 'IN');
    $delete = db_delete('test_task')
      ->condition('task', 'sleep')
      ->condition('pid', $subquery, 'IN');

    $num_deleted = $delete->execute();
1033
    $this->assertEqual($num_deleted, 1, t("Deleted 1 record."));
1034
1035

    $num_records_after = db_query('SELECT COUNT(*) FROM {test_task}')->fetchField();
1036
    $this->assertEqual($num_records_before, $num_records_after + $num_deleted, t('Deletion adds up.'));
1037
1038
  }

1039
1040
1041
1042
  /**
   * Confirm that we can delete a single record successfully.
   */
  function testSimpleDelete() {
1043
    $num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
1044

1045
1046
1047
    $num_deleted = db_delete('test')
      ->condition('id', 1)
      ->execute();
1048
    $this->assertIdentical($num_deleted, 1, t('Deleted 1 record.'));
1049

1050
    $num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
1051
    $this->assertEqual($num_records_before, $num_records_after + $num_deleted, t('Deletion adds up.'));
1052
  }
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062

  /**
   * 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();
1063
    $this->assertEqual(0, $num_records_after, t('Truncate really deletes everything.'));
1064
  }
1065
1066
1067
1068
1069
1070
1071
}

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

1072
  public static function getInfo() {
1073
    return array(
1074
1075
1076
      'name' => 'Merge tests',
      'description' => 'Test the Merge query builder.',
      'group' => 'Database',
1077
1078
1079
1080
1081
1082
1083
    );
  }

  /**
   * Confirm that we can merge-insert a record successfully.
   */
  function testMergeInsert() {
1084
    $num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
1085

1086
    $result = db_merge('test_people')
1087
1088
1089
1090
1091
1092
1093
      ->key(array('job' => 'Presenter'))
      ->fields(array(
        'age' => 31,
        'name' => 'Tiffany',
      ))
      ->execute();

1094
    $this->assertEqual($result, MergeQuery::STATUS_INSERT, t('Insert status returned.'));
1095

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

1099
    $person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Presenter'))->fetch();
1100
1101
1102
    $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.'));
1103
1104
1105
1106
1107
1108
  }

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

1111
    $result = db_merge('test_people')
1112
1113
1114
1115
1116
1117
      ->key(array('job' => 'Speaker'))
      ->fields(array(
        'age' => 31,
        'name' => 'Tiffany',
      ))
      ->execute();
1118