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

3
4
5
6
7
8
9
10
use Drupal\Core\Database\Database;
use Drupal\Core\Database\StatementEmpty;
use Drupal\Core\Database\StatementInterface;
use Drupal\Core\Database\TransactionOutOfOrderException;
use Drupal\Core\Database\TransactionNoActiveException;
use Drupal\Core\Database\Query\Merge;
use Drupal\Core\Database\Query\InvalidMergeQueryException;
use Drupal\Core\Database\Query\NoFieldsException;
11

12
13
14
15
/**
 * Dummy class for fetching into a class.
 *
 * PDO supports using a new instance of an arbitrary class for records
16
17
 * rather than just a stdClass or array. This class is for testing that
 * functionality. (See testQueryFetchClass() below)
18
 */
19
20
21
22
class FakeRecord { }

/**
 * Base test class for databases.
23
 *
24
25
26
27
28
 * Because all database tests share the same test data, we can centralize that
 * here.
 */
class DatabaseTestCase extends DrupalWebTestCase {
  function setUp() {
29
30
31
32
33
34
    $modules = func_get_args();
    if (isset($modules[0]) && is_array($modules[0])) {
      $modules = $modules[0];
    }
    $modules[] = 'database_test';
    parent::setUp($modules);
35

36
37
38
39
40
41
    $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');

42
43
44
45
46
47
48
49
50
51
52
53
    $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) {
54
55
56
    // 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)) {
57
        db_drop_table($name);
58
      }
59
      db_create_table($name, $data);
60
    }
61
62

    foreach ($schema as $name => $data) {
63
      $this->assertTrue(db_table_exists($name), t('Table @name created successfully.', array('@name' => $name)));
64
    }
65
  }
66

67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
  /**
   * 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();
89
90
91
92
93
  }

  /**
   * Setup our sample data.
   *
94
   * These are added using db_query(), since we're not trying to test the
95
96
97
   * INSERT operations here, just populate.
   */
  function addSampleData() {
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
167
168
169
170
171
172
173
174
175
176
    // 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();
177
  }
178
179
180
181
182
183
184
}

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

185
  public static function getInfo() {
186
    return array(
187
188
189
      'name' => 'Connection tests',
      'description' => 'Tests of the core database system.',
      'group' => 'Database',
190
191
192
193
194
195
196
197
198
199
    );
  }

  /**
   * 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.
200
201
    $connection_info = Database::getConnectionInfo('default');
    Database::addConnectionInfo('default', 'slave', $connection_info['default']);
202
203

    $db1 = Database::getConnection('default', 'default');
204
    $db2 = Database::getConnection('slave', 'default');
205

206
207
208
    $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.'));
209
210
211

    // Try to open those targets another time, that should return the same objects.
    $db1b = Database::getConnection('default', 'default');
212
    $db2b = Database::getConnection('slave', 'default');
213
214
    $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.'));
215
216
217

    // Try to open an unknown target.
    $unknown_target = $this->randomName();
218
    $db3 = Database::getConnection($unknown_target, 'default');
219
220
    $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.'));
221
222

    // Try to open that unknown target another time, that should return the same object.
223
    $db3b = Database::getConnection($unknown_target, 'default');
224
    $this->assertIdentical($db3, $db3b, t('A second call to getConnection() returns the same object.'));
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
  }

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

242
    $this->assertIdentical($db1, $db2, t('Both targets refer to the same connection.'));
243
  }
244
245
246
247
248
249
250
251
252
253
254
255
256

  /**
   * 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.
257
    $this->assertNotIdentical($db1, $db2, t('Opening the default connection after it is closed returns a new object.'));
258
  }
259
260
261
262
263
264
265
266
267
268
269
270
271

  /**
   * 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.
272
273
    $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.'));
274
275
276
277
278
279
280
281

    // 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();
282
    $this->assertIdentical($connectionOptions, $connectionOptions2, t('The default and slave connection options are identical.'));
283
284
285
286
287
288
289
290
291

    // 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();
292
    $this->assertNotEqual($connection_info['default']['database'], $connectionOptions['database'], t('The test connection info database does not match the current connection options database.'));
293
  }
294
295
296
297
}

/**
 * Test fetch actions, part 1.
298
 *
299
300
301
 * We get timeout errors if we try to run too many tests at once.
 */
class DatabaseFetchTestCase extends DatabaseTestCase {
302

303
  public static function getInfo() {
304
    return array(
305
306
307
      'name' => 'Fetch tests',
      'description' => 'Test the Database system\'s various fetch capabilities.',
      'group' => 'Database',
308
309
310
311
312
313
314
315
    );
  }

  /**
   * Confirm that we can fetch a record properly in default object mode.
   */
  function testQueryFetchDefault() {
    $records = array();
316
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25));
317
    $this->assertTrue($result instanceof StatementInterface, t('Result set is a Drupal statement object.'));
318
319
    foreach ($result as $record) {
      $records[] = $record;
320
321
      $this->assertTrue(is_object($record), t('Record is an object.'));
      $this->assertIdentical($record->name, 'John', t('25 year old is John.'));
322
323
    }

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

  /**
   * Confirm that we can fetch a record to an object explicitly.
   */
  function testQueryFetchObject() {
    $records = array();
332
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => PDO::FETCH_OBJ));
333
334
    foreach ($result as $record) {
      $records[] = $record;
335
336
      $this->assertTrue(is_object($record), t('Record is an object.'));
      $this->assertIdentical($record->name, 'John', t('25 year old is John.'));
337
338
    }

339
    $this->assertIdentical(count($records), 1, t('There is only one record.'));
340
341
342
343
344
345
346
  }

  /**
   * Confirm that we can fetch a record to an array associative explicitly.
   */
  function testQueryFetchArray() {
    $records = array();
347
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => PDO::FETCH_ASSOC));
348
349
    foreach ($result as $record) {
      $records[] = $record;
350
351
      if ($this->assertTrue(is_array($record), t('Record is an array.'))) {
        $this->assertIdentical($record['name'], 'John', t('Record can be accessed associatively.'));
352
353
354
      }
    }

355
    $this->assertIdentical(count($records), 1, t('There is only one record.'));
356
357
358
359
360
361
362
363
364
  }

  /**
   * Confirm that we can fetch a record into a new instance of a custom class.
   *
   * @see FakeRecord
   */
  function testQueryFetchClass() {
    $records = array();
365
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => 'FakeRecord'));
366
367
    foreach ($result as $record) {
      $records[] = $record;
368
369
      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.'));
370
371
372
      }
    }

373
    $this->assertIdentical(count($records), 1, t('There is only one record.'));
374
375
376
377
378
  }
}

/**
 * Test fetch actions, part 2.
379
 *
380
381
382
383
 * We get timeout errors if we try to run too many tests at once.
 */
class DatabaseFetch2TestCase extends DatabaseTestCase {

384
  public static function getInfo() {
385
    return array(
386
387
388
      'name' => 'Fetch tests, part 2',
      'description' => 'Test the Database system\'s various fetch capabilities.',
      'group' => 'Database',
389
390
391
392
393
394
    );
  }

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

    $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();
411
    $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => PDO::FETCH_BOTH));
412
413
    foreach ($result as $record) {
      $records[] = $record;
414
415
416
      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.'));
417
418
419
      }
    }

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

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

432
    $result = db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25));
433
434
    $i = 0;
    foreach ($result as $record) {
435
      $this->assertIdentical($record->name, $column[$i++], t('Column matches direct accesss.'));
436
437
438
439
440
441
442
443
444
    }
  }
}

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

445
  public static function getInfo() {
446
    return array(
447
448
449
      'name' => 'Insert tests',
      'description' => 'Test the Insert query builder.',
      'group' => 'Database',
450
451
452
453
454
455
456
    );
  }

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

459
460
461
462
463
464
    $query = db_insert('test');
    $query->fields(array(
      'name' => 'Yoko',
      'age' => '29',
    ));
    $query->execute();
465

466
    $num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
467
    $this->assertIdentical($num_records_before + 1, (int) $num_records_after, t('Record inserts correctly.'));
468
    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Yoko'))->fetchField();
469
    $this->assertIdentical($saved_age, '29', t('Can retrieve after inserting.'));
470
471
472
473
474
475
  }

  /**
   * Test that we can insert multiple records in one query object.
   */
  function testMultiInsert() {
476
    $num_records_before = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494

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

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

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

511
    $query = db_insert('test');
512

513
514
515
516
    $query->fields(array(
      'name' => 'Larry',
      'age' => '30',
    ));
517
    $query->execute();  // This should run the insert, but leave the fields intact.
518
519
520
521
522
523
524
525
526
527
528
529

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

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

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

  /**
   * Test that inserts return the proper auto-increment ID.
   */
  function testInsertLastInsertID() {
564
565
    $id = db_insert('test')
      ->fields(array(
566
567
568
569
570
        'name' => 'Larry',
        'age' => '30',
      ))
      ->execute();

571
    $this->assertIdentical($id, '5', t('Auto-increment ID returned successfully.'));
572
  }
573
574
575
576
577

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

    $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Meredith'))->fetchField();
597
    $this->assertIdentical($saved_age, '30', t('Can retrieve after inserting.'));
598
  }
599
600
601
602
603
604
605
}

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

606
  public static function getInfo() {
607
    return array(
608
609
610
      'name' => 'Insert tests, LOB fields',
      'description' => 'Test the Insert query builder with LOB fields.',
      'group' => 'Database',
611
612
613
614
615
616
617
618
    );
  }

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

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

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

647
  public static function getInfo() {
648
    return array(
649
650
651
      'name' => 'Insert tests, default fields',
      'description' => 'Test the Insert query builder with default values.',
      'group' => 'Database',
652
653
    );
  }
654

655
656
657
658
  /**
   * Test that we can run a query that is "default values for everything".
   */
  function testDefaultInsert() {
659
660
    $query = db_insert('test')->useDefaults(array('job'));
    $id = $query->execute();
661

662
    $schema = drupal_get_schema('test');
663

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

668
669
670
671
  /**
   * Test that no action will be preformed if no fields are specified.
   */
  function testDefaultEmptyInsert() {
672
    $num_records_before = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
673

674
675
676
    try {
      $result = db_insert('test')->execute();
      // This is only executed if no exception has been thrown.
677
678
679
      $this->fail(t('Expected exception NoFieldsException has not been thrown.'));
    } catch (NoFieldsException $e) {
      $this->pass(t('Expected exception NoFieldsException has been thrown.'));
680
    }
681

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

686
687
688
689
  /**
   * Test that we can insert fields with values and defaults in the same query.
   */
  function testDefaultInsertWithFields() {
690
691
692
    $query = db_insert('test')
      ->fields(array('name' => 'Bob'))
      ->useDefaults(array('job'));
693
    $id = $query->execute();
694

695
    $schema = drupal_get_schema('test');
696

697
    $job = db_query('SELECT job FROM {test} WHERE id = :id', array(':id' => $id))->fetchField();
698
    $this->assertEqual($job, $schema['fields']['job']['default'], t('Default field value is set.'));
699
700
701
702
703
704
705
706
  }
}

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

707
  public static function getInfo() {
708
    return array(
709
710
711
      'name' => 'Update tests',
      'description' => 'Test the Update query builder.',
      'group' => 'Database',
712
713
714
715
716
717
718
    );
  }

  /**
   * Confirm that we can update a single record successfully.
   */
  function testSimpleUpdate() {
719
720
721
722
    $num_updated = db_update('test')
      ->fields(array('name' => 'Tiffany'))
      ->condition('id', 1)
      ->execute();
723
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));
724

725
    $saved_name = db_query('SELECT name FROM {test} WHERE id = :id', array(':id' => 1))->fetchField();
726
    $this->assertIdentical($saved_name, 'Tiffany', t('Updated name successfully.'));
727
  }
728

729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
  /**
   * 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.'));
  }

744
745
746
747
  /**
   * Confirm that we can update a multiple records successfully.
   */
  function testMultiUpdate() {
748
749
750
751
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->condition('job', 'Singer')
      ->execute();
752
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));
753

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

  /**
   * Confirm that we can update a multiple records with a non-equality condition.
   */
  function testMultiGTUpdate() {
762
763
764
765
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->condition('age', 26, '>')
      ->execute();
766
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));
767

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
  }

  /**
   * Confirm that we can update a multiple records with a where call.
   */
  function testWhereUpdate() {
776
777
778
779
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->where('age > :age', array(':age' => 26))
      ->execute();
780
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));
781

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

  /**
   * Confirm that we can stack condition and where calls.
   */
  function testWhereAndConditionUpdate() {
790
791
792
793
    $update = db_update('test')
      ->fields(array('job' => 'Musician'))
      ->where('age > :age', array(':age' => 26))
      ->condition('name', 'Ringo');
794
    $num_updated = $update->execute();
795
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));
796

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

801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
  /**
   * 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.'));
  }
820
821
822
823
824
825
826
}

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

827
  public static function getInfo() {
828
    return array(
829
830
831
      'name' => 'Update tests, Complex',
      'description' => 'Test the Update query builder, complex queries.',
      'group' => 'Database',
832
833
834
835
836
837
838
839
840
841
842
843
844
845
    );
  }

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

848
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
849
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
850
851
852
853
854
855
  }

  /**
   * Test WHERE IN clauses.
   */
  function testInConditionUpdate() {
856
857
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
858
859
      ->condition('name', array('John', 'Paul'), 'IN')
      ->execute();
860
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));
861

862
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
863
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
864
865
866
867
868
869
  }

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

878
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
879
    $this->assertIdentical($num_matches, '1', t('Updated fields successfully.'));
880
881
882
883
884
885
  }

  /**
   * Test BETWEEN conditional clauses.
   */
  function testBetweenConditionUpdate() {
886
887
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
888
889
      ->condition('age', array(25, 26), 'BETWEEN')
      ->execute();
890
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));
891

892
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
893
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
894
895
896
897
898
899
  }

  /**
   * Test LIKE conditionals.
   */
  function testLikeConditionUpdate() {
900
901
    $num_updated = db_update('test')
      ->fields(array('job' => 'Musician'))
902
903
      ->condition('name', '%ge%', 'LIKE')
      ->execute();
904
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));
905

906
    $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
907
    $this->assertIdentical($num_matches, '1', t('Updated fields successfully.'));
908
909
910
911
912
913
  }

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

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

926
    $person = db_query('SELECT * FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetch();
927
928
929
    $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.'));
930
    $GLOBALS['larry_test'] = 0;
931
  }
932
933
934
935
936

  /**
   * Test update with only expression values.
   */
  function testUpdateOnlyExpression() {
937
    $before_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
938
939
    $num_updated = db_update('test')
      ->condition('name', 'Ringo')
940
      ->expression('age', 'age + :age', array(':age' => 4))
941
      ->execute();
942
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));
943

944
    $after_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
945
    $this->assertEqual($before_age + 4, $after_age, t('Age updated correctly'));
946
  }
947
948
949
950
951
952
953
}

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

954
  public static function getInfo() {
955
    return array(
956
957
958
      'name' => 'Update tests, LOB',
      'description' => 'Test the Update query builder with LOB fields.',
      'group' => 'Database',
959
960
961
962
963
964
965
966
    );
  }

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

    $data .= $data;
973
974
975
976
    db_update('test_one_blob')
      ->condition('id', $id)
      ->fields(array('blob1' => $data))
      ->execute();
977

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

982
983
984
985
  /**
   * Confirm that we can update two blob columns in the same table.
   */
  function testUpdateMultipleBlob() {
986
987
    $id = db_insert('test_two_blobs')
      ->fields(array(
988
        'blob1' => 'This is',
989
990
        'blob2' => 'a test',
      ))
991
992
      ->execute();

993
994
995
996
    db_update('test_two_blobs')
      ->condition('id', $id)
      ->fields(array('blob1' => 'and so', 'blob2' => 'is this'))
      ->execute();
997

998
    $r = db_query('SELECT * FROM {test_two_blobs} WHERE id = :id', array(':id' => $id))->fetchAssoc();
999
    $this->assertTrue($r['blob1'] === 'and so' && $r['blob2'] === 'is this', t('Can update multiple blobs per row.'));
1000
1001
1002
1003
  }
}

/**
1004
 * Delete/Truncate tests.
1005
1006
1007
1008
1009
 *
 * 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.
 *
1010
1011
1012
 * 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.
1013
 */
1014
class DatabaseDeleteTruncateTestCase extends DatabaseTestCase {
1015

1016
  public static function getInfo() {
1017
    return array(
1018
1019
1020
      'name' => 'Delete/Truncate tests',
      'description' => 'Test the Delete and Truncate query builders.',
      'group' => 'Database',
1021
1022
1023
    );
  }

1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
  /**
   * 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();
1039
    $this->assertEqual($num_deleted, 1, t("Deleted 1 record."));
1040
1041

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

1045
1046
1047
1048
  /**
   * Confirm that we can delete a single record successfully.
   */
  function testSimpleDelete() {
1049
    $num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
1050

1051
1052
1053
    $num_deleted = db_delete('test')
      ->condition('id', 1)
      ->execute();
1054
    $this->assertIdentical($num_deleted, 1, t('Deleted 1 record.'));
1055

1056
    $num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
1057
    $this->assertEqual($num_records_before, $num_records_after + $num_deleted, t('Deletion adds up.'));
1058
  }
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068

  /**
   * 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();
1069
    $this->assertEqual(0, $num_records_after, t('Truncate really deletes everything.'));
1070
  }
1071
1072
1073
1074
1075
1076
1077
}

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

1078
  public static function getInfo() {
1079
    return array(
1080
1081
1082
      'name' => 'Merge tests',
      'description' => 'Test the Merge query builder.',
      'group' => 'Database',
1083
1084
1085
1086
1087
1088
1089
    );
  }

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

1092
    $result = db_merge('test_people')
1093
1094
1095
1096
1097
1098
1099
      ->key(array('job' => 'Presenter'))
      ->fields(array(
        'age' => 31,
        'name' => 'Tiffany',
      ))
      ->execute();

Crell's avatar
Crell committed
1100
    $this->assertEqual($result, Merge::STATUS_INSERT, t('Insert status returned.'));
1101

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

1105
    $person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Presenter'))->fetch();
1106
1107
1108
    $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.'));
1109
1110
1111
1112
1113
1114
  }

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

1117
    $result = db_merge('test_people')
1118
1119
1120
1121
1122
1123
      ->key(array('job' => 'Speaker'))
      ->fields(array(
        'age' => 31,
        'name' => 'Tiffany',
      ))
      ->execute();
1124

Crell's avatar
Crell committed
1125
    $this->assertEqual($result, Merge::STATUS_UPDATE, t('Update status returned.'));
1126