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

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

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

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

24
25
26
27
28
29
30
31
32
33
34
    $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');

    // This ends up being a test for table drop and create, too, which is nice.
    $ret = array();
    foreach ($schema as $name => $data) {
      if (db_table_exists($name)) {
        db_drop_table($ret, $name);
35
      }
36
      db_create_table($ret, $name, $data);
37
    }
38
39
40

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

    $this->addSampleData();
44
45
46
47
48
  }

  /**
   * Setup our sample data.
   *
49
   * These are added using db_query(), since we're not trying to test the
50
51
52
   * INSERT operations here, just populate.
   */
  function addSampleData() {
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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
    // 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();
132
  }
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
}

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

  function getInfo() {
    return array(
      'name' => t('Connection tests'),
      'description' => t('Tests of the core database system.'),
      'group' => t('Database'),
    );
  }

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

    $db1 = Database::getConnection('default', 'default');
159
    $db2 = Database::getConnection('slave', 'default');
160

161
162
163
    $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.'));
164
165
166

    // Try to open those targets another time, that should return the same objects.
    $db1b = Database::getConnection('default', 'default');
167
    $db2b = Database::getConnection('slave', 'default');
168
169
170
171
172
    $this->assertIdentical($db1, $db1b, t('A second call to getConnection() returns the same object.'));
    $this->assertIdentical($db2, $db2b, t('A second call to getConnection() returns the same object.'));

    // Try to open an unknown target.
    $unknown_target = $this->randomName();
173
    $db3 = Database::getConnection($unknown_target, 'default');
174
175
176
177
    $this->assertNotNull($db3, t('Opening an unknown target returns a real connection object.'));
    $this->assertIdentical($db1, $db3, t('An unknown target opens the default connection.'));

    // Try to open that unknown target another time, that should return the same object.
178
    $db3b = Database::getConnection($unknown_target, 'default');
179
    $this->assertIdentical($db3, $db3b, t('A second call to getConnection() returns the same object.'));
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
  }

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

197
    $this->assertIdentical($db1, $db2, t('Both targets refer to the same connection.'));
198
  }
199
200
201
202
}

/**
 * Test fetch actions, part 1.
203
 *
204
205
206
 * We get timeout errors if we try to run too many tests at once.
 */
class DatabaseFetchTestCase extends DatabaseTestCase {
207

208
209
210
211
212
213
214
215
216
217
218
219
220
221
  function getInfo() {
    return array(
      'name' => t('Fetch tests'),
      'description' => t('Test the Database system\'s various fetch capabilities.'),
      'group' => t('Database'),
    );
  }

  /**
   * Confirm that we can fetch a record properly in default object mode.
   */
  function testQueryFetchDefault() {
    $records = array();
    $result = db_query("SELECT name FROM {test} WHERE age = :age", array(':age' => 25));
222
    $this->assertTrue($result instanceof DatabaseStatementInterface, t('Result set is a Drupal statement object.'));
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
    foreach ($result as $record) {
      $records[] = $record;
      $this->assertTrue(is_object($record), t('Record is an object.'));
      $this->assertIdentical($record->name, 'John', t('25 year old is John.'));
    }

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

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

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

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

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

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

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

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

  function getInfo() {
    return array(
291
      'name' => t('Fetch tests, part 2'),
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
      'description' => t('Test the Database system\'s various fetch capabilities.'),
      'group' => t('Database'),
    );
  }

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

  // Confirm that we can fetch a record into an indexed array explicitly.
  function testQueryFetchNum() {
    $records = array();
    $result = db_query("SELECT name FROM {test} WHERE age = :age", array(':age' => 25), array('fetch' => PDO::FETCH_NUM));
    foreach ($result as $record) {
      $records[] = $record;
      if ($this->assertTrue(is_array($record), t('Record is an array.'))) {
        $this->assertIdentical($record[0], 'John', t('Record can be accessed numerically.'));
      }
    }

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

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

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

  /**
   * Confirm that we can fetch an entire column of a result set at once.
334
   */
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
  function testQueryFetchCol() {
    $records = array();
    $result = db_query("SELECT name FROM {test} WHERE age > :age", array(':age' => 25));
    $column = $result->fetchCol();
    $this->assertIdentical(count($column), 3, t('fetchCol() returns the right number of records.'));

    $result = db_query("SELECT name FROM {test} WHERE age > :age", array(':age' => 25));
    $i = 0;
    foreach ($result as $record) {
      $this->assertIdentical($record->name, $column[$i++], t('Column matches direct accesss.'));
    }
  }
}

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

  function getInfo() {
    return array(
      'name' => t('Insert tests'),
      'description' => t('Test the Insert query builder.'),
      'group' => t('Database'),
    );
  }

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

368
369
370
371
372
373
    $query = db_insert('test');
    $query->fields(array(
      'name' => 'Yoko',
      'age' => '29',
    ));
    $query->execute();
374

375
376
377
378
    $num_records_after = db_query("SELECT COUNT(*) FROM {test}")->fetchField();
    $this->assertIdentical($num_records_before + 1, (int)$num_records_after, t('Record inserts correctly.'));
    $saved_age = db_query("SELECT age FROM {test} WHERE name = :name", array(':name' => 'Yoko'))->fetchField();
    $this->assertIdentical($saved_age, '29', t('Can retrieve after inserting.'));
379
380
381
382
383
384
  }

  /**
   * Test that we can insert multiple records in one query object.
   */
  function testMultiInsert() {
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
    $num_records_before = (int) db_query("SELECT COUNT(*) FROM {test}")->fetchField();

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

    $num_records_after = (int) db_query("SELECT COUNT(*) FROM {test}")->fetchField();
    $this->assertIdentical($num_records_before + 3, $num_records_after, t('Record inserts correctly.'));
    $saved_age = db_query("SELECT age FROM {test} WHERE name = :name", array(':name' => 'Larry'))->fetchField();
    $this->assertIdentical($saved_age, '30', t('Can retrieve after inserting.'));
    $saved_age = db_query("SELECT age FROM {test} WHERE name = :name", array(':name' => 'Curly'))->fetchField();
    $this->assertIdentical($saved_age, '31', t('Can retrieve after inserting.'));
    $saved_age = db_query("SELECT age FROM {test} WHERE name = :name", array(':name' => 'Moe'))->fetchField();
    $this->assertIdentical($saved_age, '32', t('Can retrieve after inserting.'));
412
413
414
415
416
417
  }

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

420
    $query = db_insert('test');
421

422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
    $query->fields(array(
      'name' => 'Larry',
      'age' => '30',
    ));
    $query->execute();  // This should run the insert, but leave the fields intact.

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

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

    $num_records_after = db_query("SELECT COUNT(*) FROM {test}")->fetchField();
    $this->assertIdentical((int) $num_records_before + 3, (int) $num_records_after, t('Record inserts correctly.'));
    $saved_age = db_query("SELECT age FROM {test} WHERE name = :name", array(':name' => 'Larry'))->fetchField();
    $this->assertIdentical($saved_age, '30', t('Can retrieve after inserting.'));
    $saved_age = db_query("SELECT age FROM {test} WHERE name = :name", array(':name' => 'Curly'))->fetchField();
    $this->assertIdentical($saved_age, '31', t('Can retrieve after inserting.'));
    $saved_age = db_query("SELECT age FROM {test} WHERE name = :name", array(':name' => 'Moe'))->fetchField();
    $this->assertIdentical($saved_age, '32', t('Can retrieve after inserting.'));
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
  }

  /**
   * 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();
    $saved_age = db_query("SELECT age FROM {test} WHERE name = :name", array(':name' => 'Larry'))->fetchField();
    $this->assertIdentical($saved_age, '30', t('Can retrieve after inserting.'));
463
464
465
466
    $saved_age = db_query("SELECT age FROM {test} WHERE name = :name", array(':name' => 'Curly'))->fetchField();
    $this->assertIdentical($saved_age, '31', t('Can retrieve after inserting.'));
    $saved_age = db_query("SELECT age FROM {test} WHERE name = :name", array(':name' => 'Moe'))->fetchField();
    $this->assertIdentical($saved_age, '32', t('Can retrieve after inserting.'));
467
468
469
470
471
472
  }

  /**
   * Test that inserts return the proper auto-increment ID.
   */
  function testInsertLastInsertID() {
473
474
475
476
477
478
479
    $id = db_insert('test')->fields(array(
        'name' => 'Larry',
        'age' => '30',
      ))
      ->execute();

    $this->assertIdentical($id, '5', t('Auto-increment ID returned successfully.'));
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
  }
}

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

  function getInfo() {
    return array(
      'name' => t('Insert tests, LOB fields'),
      'description' => t('Test the Insert query builder with LOB fields.'),
      'group' => t('Database'),
    );
  }

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

  /**
   * Test that we can insert multiple blob fields in the same query.
   */
  function testInsertMultipleBlob() {
    $id = db_insert('test_two_blobs')->fields(array(
513
      'blob1' => 'This is',
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
      'blob2' => 'a test',
      ))
    ->execute();
    $res = db_query('SELECT * FROM {test_two_blobs} WHERE id = %d', $id);
    $r = db_fetch_array($res);
    $this->assertTrue($r['blob1'] === 'This is' && $r['blob2'] === 'a test', t('Can insert multiple blobs per row.'));
  }
}

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

  function getInfo() {
    return array(
530
      'name' => t('Insert tests, default fields'),
531
532
533
534
      'description' => t('Test the Insert query builder with default values.'),
      'group' => t('Database'),
    );
  }
535

536
537
538
539
  /**
   * Test that we can run a query that is "default values for everything".
   */
  function testDefaultInsert() {
540
541
    $query = db_insert('test')->useDefaults(array('job'));
    $id = $query->execute();
542

543
    $schema = drupal_get_schema('test');
544

545
546
    $job = db_query("SELECT job FROM {test} WHERE id = :id", array(':id' => $id))->fetchField();
    $this->assertEqual($job, $schema['fields']['job']['default'], t('Default field value is set.'));
547
548
  }

549
550
551
552
  /**
   * Test that no action will be preformed if no fields are specified.
   */
  function testDefaultEmptyInsert() {
553
    $num_records_before = (int) db_query("SELECT COUNT(*) FROM {test}")->fetchField();
554

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

558
559
    $num_records_after = (int) db_query("SELECT COUNT(*) FROM {test}")->fetchField();
    $this->assertIdentical($num_records_before, $num_records_after, t('Do nothing as no fields are specified.'));
560
561
  }

562
563
564
565
  /**
   * Test that we can insert fields with values and defaults in the same query.
   */
  function testDefaultInsertWithFields() {
566
567
    $query = db_insert('test')->fields(array('name' => 'Bob'))->useDefaults(array('job'));
    $id = $query->execute();
568

569
    $schema = drupal_get_schema('test');
570

571
572
    $job = db_query("SELECT job FROM {test} WHERE id = :id", array(':id' => $id))->fetchField();
    $this->assertEqual($job, $schema['fields']['job']['default'], t('Default field value is set.'));
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
  }
}

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

  function getInfo() {
    return array(
      'name' => t('Update tests'),
      'description' => t('Test the Update query builder.'),
      'group' => t('Database'),
    );
  }

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

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

600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
  /**
   * Confirm that we can update a multiple records successfully.
   */
  function testMultiUpdate() {
    $num_updated = db_update('test')->fields(array('job' => 'Musician'))->condition('job', 'Singer')->execute();
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));

    $num_matches = db_query("SELECT count(*) FROM {test} WHERE job = :job", array(':job' => 'Musician'))->fetchField();
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
  }

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

    $num_matches = db_query("SELECT count(*) FROM {test} WHERE job = :job", array(':job' => 'Musician'))->fetchField();
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
  }

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

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

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

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

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

  function getInfo() {
    return array(
      'name' => t('Update tests, Complex'),
      'description' => t('Test the Update query builder, complex queries.'),
      'group' => t('Database'),
    );
  }

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

    $num_matches = db_query("SELECT count(*) FROM {test} WHERE job = :job", array(':job' => 'Musician'))->fetchField();
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
  }

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

    $num_matches = db_query("SELECT count(*) FROM {test} WHERE job = :job", array(':job' => 'Musician'))->fetchField();
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
  }

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

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

  /**
   * Test BETWEEN conditional clauses.
   */
  function testBetweenConditionUpdate() {
706
707
708
709
710
711
712
    $num_updated = db_update('test')->fields(array('job' => 'Musician'))
      ->condition('age', array(25, 26), 'BETWEEN')
      ->execute();
    $this->assertIdentical($num_updated, 2, t('Updated 2 records.'));

    $num_matches = db_query("SELECT count(*) FROM {test} WHERE job = :job", array(':job' => 'Musician'))->fetchField();
    $this->assertIdentical($num_matches, '2', t('Updated fields successfully.'));
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
  }

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

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

  /**
   * Test update with expression values.
   */
  function testUpdateExpression() {
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
    $before_age = db_query("SELECT age FROM {test} WHERE name = 'Ringo'")->fetchField();
    $GLOBALS['larry_test'] = 1;
    $num_updated = db_update('test')
      ->condition('name', 'Ringo')
      ->fields(array('job' => 'Musician'))
      ->expression('age', 'age + :age',array(':age' => 4))
      ->execute();
    $this->assertIdentical($num_updated, 1, t('Updated 1 record.'));

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

    $person = db_query("SELECT * FROM {test} WHERE name = :name", array(':name' => 'Ringo'))->fetch();
    $this->assertEqual($person->name, 'Ringo', t('Name set correctly.'));
    $this->assertEqual($person->age, $before_age + 4, t('Age set correctly.'));
    $this->assertEqual($person->job, 'Musician', t('Job set correctly.'));
    $GLOBALS['larry_test'] = 0;
749
  }
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764

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

    $after_age = db_query("SELECT age FROM {test} WHERE name = 'Ringo'")->fetchField();
    $this->assertEqual($before_age + 4, $after_age, t('Age updated correctly'));
  }
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
}

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

  function getInfo() {
    return array(
      'name' => t('Update tests, LOB'),
      'description' => t('Test the Update query builder with LOB fields.'),
      'group' => t('Database'),
    );
  }

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

    $data .= $data;
    db_update('test_one_blob')->condition('id', $id)->fields(array('blob1' => $data))->execute();

    $res = db_query('SELECT * FROM {test_one_blob} WHERE id = %d', $id);
    $r = db_fetch_array($res);
    $this->assertTrue($r['blob1'] === $data, t('Can update a blob: id @id, @data.', array('@id' => $id, '@data' => serialize($r))));
  }
795

796
797
798
799
800
  /**
   * Confirm that we can update two blob columns in the same table.
   */
  function testUpdateMultipleBlob() {
    $id = db_insert('test_two_blobs')->fields(array(
801
        'blob1' => 'This is',
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
        'blob2' => 'a test')
      )
      ->execute();

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

    $res = db_query('SELECT * FROM {test_two_blobs} WHERE id = %d', $id);
    $r = db_fetch_array($res);
    $this->assertTrue($r['blob1'] === 'and so' && $r['blob2'] === 'is this', t('Can update multiple blobs per row.'));
  }
}

/**
 * Delete tests.
 *
 * 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.
 *
 */
class DatabaseDeleteTestCase extends DatabaseTestCase {

  function getInfo() {
    return array(
      'name' => t('Delete tests'),
      'description' => t('Test the Delete query builder.'),
      'group' => t('Database'),
    );
  }

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

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

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

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

  function getInfo() {
    return array(
      'name' => t('Merge tests'),
      'description' => t('Test the Merge query builder.'),
      'group' => t('Database'),
    );
  }

  /**
   * Confirm that we can merge-insert a record successfully.
   */
  function testMergeInsert() {
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
    $num_records_before = db_query("SELECT COUNT(*) FROM {test_people}")->fetchField();

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

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

    $person = db_query("SELECT * FROM {test_people} WHERE job = :job", array(':job' => 'Presenter'))->fetch();
    $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.'));
880
881
882
883
884
885
886
887
888
889
890
891
  }

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

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

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

893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
    $person = db_query("SELECT * FROM {test_people} WHERE job = :job", array(':job' => 'Speaker'))->fetch();
    $this->assertEqual($person->name, 'Tiffany', t('Name set correctly.'));
    $this->assertEqual($person->age, 31, t('Age set correctly.'));
    $this->assertEqual($person->job, 'Speaker', t('Job set correctly.'));
  }

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

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

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

910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
    $person = db_query("SELECT * FROM {test_people} WHERE job = :job", array(':job' => 'Speaker'))->fetch();
    $this->assertEqual($person->name, 'Tiffany', t('Name set correctly.'));
    $this->assertEqual($person->age, 30, t('Age skipped correctly.'));
    $this->assertEqual($person->job, 'Speaker', t('Job set correctly.'));
  }

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

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

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

927
928
929
930
931
932
933
934
935
936
937
938
939
940
    $person = db_query("SELECT * FROM {test_people} WHERE job = :job", array(':job' => 'Speaker'))->fetch();
    $this->assertEqual($person->name, 'Joe', t('Name set correctly.'));
    $this->assertEqual($person->age, 30, t('Age skipped correctly.'));
    $this->assertEqual($person->job, 'Speaker', t('Job set correctly.'));
  }

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

    $age_before = db_query("SELECT age FROM {test_people} WHERE job = 'Speaker'")->fetchField();

941
    // This is a very contrived example, as I have no idea why you'd want to
942
943
    // change age this way, but that's beside the point.
    // Note that we are also double-setting age here, once as a literal and
944
    // once as an expression. This test will only pass if the expression wins,
945
946
947
948
949
950
951
952
953
    // which is what is supposed to happen.
    db_merge('test_people')
      ->key(array('job' => 'Speaker'))
      ->fields(array('age' => 31, 'name' => 'Tiffany'))
      ->expression('age', 'age + :age', array(':age' => 4))
      ->execute();

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

955
956
957
958
959
    $person = db_query("SELECT * FROM {test_people} WHERE job = :job", array(':job' => 'Speaker'))->fetch();
    $this->assertEqual($person->name, 'Tiffany', t('Name set correctly.'));
    $this->assertEqual($person->age, $age_before + 4, t('Age updated correctly.'));
    $this->assertEqual($person->job, 'Speaker', t('Job set correctly.'));
  }
960

961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
  /**
   * Test that we can merge-insert without any update fields.
   */
  function testMergeInsertWithoutUpdate() {
    $num_records_before = db_query("SELECT COUNT(*) FROM {test_people}")->fetchField();

    db_merge('test_people')
      ->key(array('job' => 'Presenter'))
      ->execute();

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

    $person = db_query("SELECT * FROM {test_people} WHERE job = :job", array(':job' => 'Presenter'))->fetch();
    $this->assertEqual($person->name, '', t('Name set correctly.'));
    $this->assertEqual($person->age, 0, t('Age set correctly.'));
    $this->assertEqual($person->job, 'Presenter', t('Job set correctly.'));
  }

  /**
   * Confirm that we can merge-update without any update fields.
   */
  function testMergeUpdateWithoutUpdate() {
    $num_records_before = db_query("SELECT COUNT(*) FROM {test_people}")->fetchField();

    db_merge('test_people')
      ->key(array('job' => 'Speaker'))
      ->execute();

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

    $person = db_query("SELECT * FROM {test_people} WHERE job = :job", array(':job' => 'Speaker'))->fetch();
    $this->assertEqual($person->name, 'Meredith', t('Name skipped correctly.'));
    $this->assertEqual($person->age, 30, t('Age skipped correctly.'));
    $this->assertEqual($person->job, 'Speaker', t('Job skipped correctly.'));

    db_merge('test_people')
      ->key(array('job' => 'Speaker'))
      ->fields(array('age' => 31))
      ->updateExcept(array('age'))
      ->execute();

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

    $person = db_query("SELECT * FROM {test_people} WHERE job = :job", array(':job' => 'Speaker'))->fetch();
    $this->assertEqual($person->name, 'Meredith', t('Name skipped correctly.'));
    $this->assertEqual($person->age, 30, t('Age skipped correctly.'));
    $this->assertEqual($person->job, 'Speaker', t('Job skipped correctly.'));
  }

1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
  /**
   * Test that an invalid merge query throws an exception like it is supposed to.
   */
  function testInvalidMerge() {
    try {
      // This query should die because there is no key field specified.
      db_merge('test_people')
        ->fields(array(
          'age' => 31,
          'name' => 'Tiffany',
        ))
        ->execute();
    }
    catch (InvalidMergeQueryException $e) {
      $this->pass(t('InvalidMergeQueryException thrown for invalid query.'));
      return;
    }
    $this->fail(t('No InvalidMergeQueryException thrown'));
  }
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
}

/**
 * Test the SELECT builder.
 *
 */
class DatabaseSelectTestCase extends DatabaseTestCase {

  function getInfo() {
    return array(
      'name' => t('Select tests'),
      'description' => t('Test the Select query builder.'),
      'group' => t('Database'),
    );
  }

  /**
   * Test rudimentary SELECT statements.
   */
  function testSimpleSelect() {
1052
1053
1054
1055
    $query = db_select('test');
    $name_field = $query->addField('test', 'name');
    $age_field = $query->addField('test', 'age', 'age');
    $result = $query->execute();
1056

1057
1058
1059
    $num_records = 0;
    foreach ($result as $record) {
      $num_records++;
1060
    }
1061
1062

    $this->assertEqual($num_records, 4, t('Returned the correct number of rows.'));
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
  }

  /**
   * Test basic conditionals on SELECT statements.
   */
  function testSimpleSelectConditional() {
    $query = db_select('test');
    $name_field = $query->addField('test', 'name');
    $age_field = $query->addField('test', 'age', 'age');
    $query->condition('age', 27);
    $result = $query->execute();
1074

1075
    // Check that the aliases are being created the way we want.
1076
    $this->assertEqual($name_field, 'name', t('Name field alias is correct.'));
1077
    $this->assertEqual($age_field, 'age', t('Age field alias is correct.'));
1078

1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
    // Ensure that we got the right record.
    $record = $result->fetch();
    $this->assertEqual($record->$name_field, 'George', t('Fetched name is correct.'));
    $this->assertEqual($record->$age_field, 27, t('Fetched age is correct.'));
  }

  /**
   * Test SELECT statements with expressions.
   */
  function testSimpleSelectExpression() {
    $query = db_select('test');
    $name_field = $query->addField('test', 'name');
    $age_field = $query->addExpression("age*2", 'double_age');
    $query->condition('age', 27);
    $result = $query->execute();
1094

1095
    // Check that the aliases are being created the way we want.
1096
    $this->assertEqual($name_field, 'name', t('Name field alias is correct.'));
1097
    $this->assertEqual($age_field, 'double_age', t('Age field alias is correct.'));
1098

1099
1100
1101
1102
1103
    // Ensure that we got the right record.
    $record = $result->fetch();
    $this->assertEqual($record->$name_field, 'George', t('Fetched name is correct.'));
    $this->assertEqual($record->$age_field, 27*2, t('Fetched age expression is correct.'));
  }
1104

1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
  /**
   * Test SELECT statements with multiple expressions.
   */
  function testSimpleSelectExpressionMultiple() {
    $query = db_select('test');
    $name_field = $query->addField('test', 'name');
    $age_double_field = $query->addExpression("age*2");
    $age_triple_field = $query->addExpression("age*3");
    $query->condition('age', 27);
    $result = $query->execute();

    // Check that the aliases are being created the way we want.
    $this->assertEqual($age_double_field, 'expression', t('Double age field alias is correct.'));
    $this->assertEqual($age_triple_field, 'expression_2', t('Triple age field alias is correct.'));

    // Ensure that we got the right record.
    $record = $result->fetch();
    $this->assertEqual($record->$name_field, 'George', t('Fetched name is correct.'));
    $this->assertEqual($record->$age_double_field, 27*2, t('Fetched double age expression is correct.'));
    $this->assertEqual($record->$age_triple_field, 27*3, t('Fetched triple age expression is correct.'));
  }

1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
  /**
   * Test adding multiple fields to a select statement at the same time.
   */
  function testSimpleSelectMultipleFields() {
    $record = db_select('test')
      ->fields('test', array('id', 'name', 'age', 'job'))
      ->condition('age', 27)
      ->execute()->fetchObject();

    // Check that all fields we asked for are present.
    $this->assertNotNull($record->id, t('ID field is present.'));
    $this->assertNotNull($record->name, t('Name field is present.'));
    $this->assertNotNull($record->age, t('Age field is present.'));
    $this->assertNotNull($record->job, t('Job field is present.'));

    // Ensure that we got the right record.
    // Check that all fields we asked for are present.
    $this->assertEqual($record->id, 2, t('ID field has the correct value.'));
    $this->assertEqual($record->name, 'George', t('Name field has the correct value.'));
    $this->assertEqual($record->age, 27, t('Age field has the correct value.'));
    $this->assertEqual($record->job, 'Singer', t('Job field has the correct value.'));
  }

  /**
   * Test adding all fields from a given table to a select statement.
   */
  function testSimpleSelectAllFields() {
    $record = db_select('test')
      ->fields('test')
      ->condition('age', 27)
      ->execute()->fetchObject();

    // Check that all fields we asked for are present.
    $this->assertNotNull($record->id, t('ID field is present.'));
    $this->assertNotNull($record->name, t('Name field is present.'));
    $this->assertNotNull($record->age, t('Age field is present.'));
    $this->assertNotNull($record->job, t('Job field is present.'));

    // Ensure that we got the right record.
    // Check that all fields we asked for are present.
    $this->assertEqual($record->id, 2, t('ID field has the correct value.'));
    $this->assertEqual($record->name, 'George', t('Name field has the correct value.'));
    $this->assertEqual($record->age, 27, t('Age field has the correct value.'));
    $this->assertEqual($record->job, 'Singer', t('Job field has the correct value.'));
  }
1172
1173
}

1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
/**
 * Test case for subselects in a dynamic SELECT query.
 */
class DatabaseSelectSubqueryTestCase extends DatabaseTestCase {

  function getInfo() {
    return array(
      'name' => t('Select tests, subqueries'),
      'description' => t('Test the Select query builder.'),
      'group' => t('Database'),
    );
  }

  /**
   * Test that we can use a subquery in a FROM clause.
   */
  function testFromSubquerySelect() {
    // Create a subquery, which is just a normal query object.
    $subquery = db_select('test_task', 'tt');
    $subquery->addField('tt', 'pid', 'pid');
    $subquery->addField('tt', 'task', 'task');
    $subquery->condition('priority', 1);

    // Create another query that joins against the virtual table resulting
    // from the subquery.
    $select = db_select($subquery, 'tt2');
    $select->join('test', 't', 't.id=tt2.pid');
    $select->addField('t', 'name');

    $select->condition('task', 'code');

    // The resulting query should be equivalent to:
    // SELECT t.name
    // FROM (SELECT tt.pid AS pid, tt.task AS task FROM test_task tt WHERE priority=1) tt
    //   INNER JOIN test t ON t.id=tt.pid
    // WHERE tt.task = 'code'
    $people = $select->execute()->fetchCol();

    $this->assertEqual(count($people), 1, t('Returned the correct number of rows.'));
  }

  /**
   * Test that we can use a subquery in a JOIN clause.
   */
  function testJoinSubquerySelect() {
    // Create a subquery, which is just a normal query object.
    $subquery = db_select('test_task', 'tt');
    $subquery->addField('tt', 'pid', 'pid');
    $subquery->condition('priority', 1);

    // Create another query that joins against the virtual table resulting
    // from the subquery.
    $select = db_select('test', 't');
    $select->join($subquery, 'tt', 't.id=tt.pid');
    $select->addField('t', 'name');

    // The resulting query should be equivalent to:
    // SELECT t.name
    // FROM test t
    //   INNER JOIN (SELECT tt.pid AS pid FROM test_task tt WHERE priority=1) tt ON t.id=tt.pid
    $people = $select->execute()->fetchCol();

    $this->assertEqual(count($people), 2, t('Returned the correct number of rows.'));
  }
}

1240
1241
1242
1243
1244
1245
1246
/**
 * Test select with order by clauses.
 */
class DatabaseSelectOrderedTestCase extends DatabaseTestCase {

  function getInfo() {
    return array(
1247
      'name' => t('Select tests, ordered'),
1248
1249
1250
1251
1252
1253
1254
1255
1256
      'description' => t('Test the Select query builder.'),
      'group' => t('Database'),
    );
  }

  /**
   * Test basic order by.
   */
  function testSimpleSelectOrdered() {
1257
1258
1259
1260
1261
    $query = db_select('test');
    $name_field = $query->addField('test', 'name');
    $age_field = $query->addField('test', 'age', 'age');
    $query->orderBy($age_field);
    $result = $query->execute();
1262

1263
1264
1265
1266
1267
1268
    $num_records = 0;
    $last_age = 0;
    foreach ($result as $record) {
      $num_records++;
      $this->assertTrue($record->age >= $last_age, t('Results returned in correct order.'));
      $last_age = $record->age;
1269
    }
1270
1271

    $this->assertEqual($num_records, 4, t('Returned the correct number of rows.'));
1272
1273
  }

1274
1275
1276
1277
  /**
   * Test multiple order by.
   */
  function testSimpleSelectMultiOrdered() {
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
    $query = db_select('test');
    $name_field = $query->addField('test', 'name');
    $age_field = $query->addField('test', 'age', 'age');
    $job_field = $query->addField('test', 'job');
    $query->orderBy($job_field);
    $query->orderBy($age_field);
    $result = $query->execute();

    $num_records = 0;
    $expected = array(
      array('Ringo', 28, 'Drummer'),
      array('John', 25, 'Singer'),
      array('George', 27, 'Singer'),
      array('Paul', 26, 'Songwriter'),
    );
    $results = $result->fetchAll(PDO::FETCH_NUM);
    foreach ($expected as $k => $record) {
      $num_records++;
      foreach ($record as $kk => $col) {
        if ($expected[$k][$kk] != $results[$k][$kk]) {
          $this->assertTrue(FALSE, t('Results returned in correct order.'));
1299
1300
1301
        }
      }
    }
1302
    $this->assertEqual($num_records, 4, t('Returned the correct number of rows.'));
1303
1304
  }

1305
1306
1307
1308
  /**
   * Test order by descending.
   */
  function testSimpleSelectOrderedDesc() {
1309
1310
1311
1312
1313
    $query = db_select('test');
    $name_field = $query->addField('test', 'name');
    $age_field = $query->addField('test', 'age', 'age');
    $query->orderBy($age_field, 'DESC');
    $result = $query->execute();
1314

1315
1316
1317
1318
1319
1320
    $num_records = 0;
    $last_age = 100000000;
    foreach ($result as $record) {
      $num_records++;
      $this->assertTrue($record->age <= $last_age, t('Results returned in correct order.'));
      $last_age = $record->age;
1321
    }
1322
1323

    $this->assertEqual($num_records, 4, t('Returned the correct number of rows.'));
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
  }
}

/**
 * Test more complex select statements.
 */
class DatabaseSelectComplexTestCase extends DatabaseTestCase {

  function getInfo() {
    return array(
1334
      'name' => t('Select tests, complex'),
1335
1336
1337
1338
1339
1340
1341
1342
1343
      'description' => t('Test the Select query builder with more complex queries.'),
      'group' => t('Database'),
    );
  }

  /**
   * Test simple JOIN statements.
   */
  function testDefaultJoin() {
1344
1345
1346
1347
1348
    $query = db_select('test_task', 't');
    $people_alias = $query->join('test', 'p', 't.pid = p.id');
    $name_field = $query->addField($people_alias, 'name', 'name');
    $task_field = $query->addField('t', 'task', 'task');
    $priority_field = $query->addField('t', 'priority', 'priority');
1349

1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
    $query->orderBy($priority_field);
    $result = $query->execute();

    $num_records = 0;
    $last_priority = 0;
    foreach ($result as $record) {
      $num_records++;
      $this->assertTrue($record->$priority_field >= $last_priority, t('Results returned in correct order.'));
      $this->assertNotEqual($record->$name_field, 'Ringo', t('Taskless person not selected.'));
      $last_priority = $record->$priority_field;
1360
    }
1361
1362

    $this->assertEqual($num_records, 7, t('Returned the correct number of rows.'));
1363
1364
1365
1366
1367
1368
  }

  /**
   * Test LEFT OUTER joins.
   */
  function testLeftOuterJoin() {
1369
1370
1371
1372
1373
    $query = db_select('test', 'p');
    $people_alias = $query->leftJoin('test_task', 't', 't.pid = p.id');
    $name_field = $query->addField('p', 'name', 'name');
    $task_field = $query->addField($people_alias, 'task', 'task');
    $priority_field = $query->addField($people_alias, 'priority', 'priority');
1374

1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
    $query->orderBy($name_field);
    $result = $query->execute();

    $num_records = 0;
    $last_name = 0;

    foreach ($result as $record) {
      $num_records++;
      $this->assertTrue(strcmp($record->$name_field, $last_name) >= 0, t('Results returned in correct order.'));
      $last_priority = $record->$name_field;
1385
    }
1386
1387

    $this->assertEqual($num_records, 8, t('Returned the correct number of rows.'));
1388
1389
1390
1391
1392
1393
  }

  /**
   * Test GROUP BY clauses.
   */
  function testGroupBy() {
1394
1395
1396
1397
1398
1399
    $query = db_select('test_task', 't');
    $count_field = $query->addExpression('COUNT(task)', 'num');
    $task_field = $query->addField('t', 'task');
    $query->orderBy($count_field);
    $query->groupBy($task_field);
    $result = $query->execute();
1400

1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
    $num_records = 0;
    $last_count = 0;
    $records = array();
    foreach ($result as $record) {
      $num_records++;
      $this->assertTrue($record->$count_field >= $last_count, t('Results returned in correct order.'));
      $last_count = $record->$count_field;
      $records[$record->$task_field] = $record->$count_field;
    }

    $correct_results = array(
      'eat' => 1,
      'sleep' => 2,
      'code' => 1,
      'found new band' => 1,
      'perform at superbowl' => 1,
    );
1418

1419
1420
    foreach ($correct_results as $task => $count) {
      $this->assertEqual($records[$task], $count, t("Correct number of '@task' records found.", array('@task' => $task)));
1421
    }
1422
1423

    $this->assertEqual($num_records, 6, t('Returned the correct number of total rows.'));
1424
1425
1426
1427
1428
1429
  }

  /**
   * Test GROUP BY and HAVING clauses together.
   */
  function testGroupByAndHaving() {
1430
1431
1432
1433
1434
1435
1436
    $query = db_select('test_task', 't');
    $count_field = $query->addExpression('COUNT(task)', 'num');
    $task_field = $query->addField('t', 'task');
    $query->orderBy($count_field);
    $query->groupBy($task_field);
    $query->havingCondition('COUNT(task)', 2, '>=');
    $result = $query->execute();
1437

1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
    $num_records = 0;
    $last_count = 0;
    $records = array();
    foreach ($result as $record) {
      $num_records++;
      $this->assertTrue($record->$count_field >= 2, t('Record has the minimum count.'));
      $this->assertTrue($record->$count_field >= $last_count, t('Results returned in correct order.'));
      $last_count = $record->$count_field;
      $records[$record->$task_field] = $record->$count_field;
    }
1448

1449
1450
1451
    $correct_results = array(
      'sleep' => 2,
    );
1452

1453
1454
    foreach ($correct_results as $task => $count) {
      $this->assertEqual($records[$task], $count, t("Correct number of '@task' records found.", array('@task' => $task)));
1455
    }
1456
1457

    $this->assertEqual($num_records, 1, t('Returned the correct number of total rows.'));
1458
1459
1460
1461
1462
1463
  }

  /**
   * Test range queries. The SQL clause varies with the database.
   */
  function testRange() {
1464
1465
1466
1467
1468
    $query = db_select('test');
    $name_field = $query->addField('test', 'name');
    $age_field = $query->addField('test', 'age', 'age');
    $query->range(0, 2);
    $result = $query->execute();
1469

1470
1471
1472
    $num_records = 0;
    foreach ($result as $record) {
      $num_records++;
1473
    }
1474
1475

    $this->assertEqual($num_records, 2, t('Returned the correct number of rows.'));
1476
1477
1478
1479
1480
1481
  }

  /**
   * Test distinct queries.
   */
  function testDistinct() {
1482
1483
1484
1485
    $query = db_select('test_task');
    $task_field = $query->addField('test_task', 'task');
    $query->distinct();
    $result = $query->execute();
1486

1487
1488
1489
    $num_records = 0;
    foreach ($result as $record) {
      $num_records++;
1490
    }
1491
1492

    $this->assertEqual($num_records, 6, t('Returned the correct number of rows.'));
1493
1494
1495
1496
1497
1498
  }

  /**
   * Test that we can generate a count query from a built query.
   */
  function testCountQuery() {
1499
1500
1501
1502
    $query = db_select('test');
    $name_field = $query->addField('test', 'name');
    $age_field = $query->addField('test', 'age', 'age');
    $query->orderBy('name');
1503

1504
    $count = $query->countQuery()->execute()->fetchField();
1505

1506
    $this->assertEqual($count, 4, t('Counted the correct number of records.'));
1507

1508
1509
1510
1511
1512
    // Now make sure we didn't break the original query!  We should still have
    // all of the fields we asked for.
    $record = $query->execute()->fetch();
    $this->assertEqual($record->$name_field, 'George', t('Correct data retrieved.'));
    $this->assertEqual($record->$age_field, 27, t('Correct data retrieved.'));
1513
  }
1514
1515
1516
1517
1518
1519
1520

  /**
   * Confirm that we can properly nest conditional clauses.
   */
  function testNestedConditions() {
    // This query should translate to:
    // "SELECT job FROM {test} WHERE name = 'Paul' AND (age = 26 OR age = 27)"
1521
    // That should find only one record. Yes it's a non-optimal way of writing
1522
1523
1524
1525
1526
1527
1528
1529
1530
    // that query but that's not the point!
    $query = db_select('test');
    $query->addField('test', 'job');
    $query->condition('name', 'Paul');
    $query->condition(db_or()->condition('age', 26)->condition('age', 27));

    $job = $query->execute()->fetchField();
    $this->assertEqual($job, 'Songwriter', t('Correct data retrieved.'));
  }
1531
1532
1533
1534
}

/**
 * Select tagging tests.
1535
 *
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
 * Tags are a way to flag queries for alter hooks so they know
 * what type of query it is, such as "node_access".
 */
class DatabaseTaggingTestCase extends DatabaseTestCase {

  function getInfo() {
    return array(
      'name' => t('Query tagging tests'),
      'description' => t('Test the tagging capabilities of the Select builder.'),
      'group' => t('Database'),
    );
  }

  /**
   * Confirm that a query has a "tag" added to it.
   */
  function testHasTag() {
1553
1554
1555
    $query = db_select('test');
    $query->addField('test', 'name');
    $query->addField('test', 'age', 'age');
1556

1557
    $query->addTag('test');
1558

1559
1560
    $this->assertTrue($query->hasTag('test'), t('hasTag() returned true.'));
    $this->assertFalse($query->hasTag('other'), t('hasTag() returned false.'));
1561
1562
1563
1564
1565
1566
  }

  /**
   * Test query tagging "has all of these tags" functionality.
   */
  function testHasAllTags() {
1567
1568
1569
    $query = db_select('test');
    $query->addField('test', 'name');
    $query->addField('test', 'age', 'age');
1570

1571
1572
    $query->addTag('test');
    $query->addTag('other');
1573

1574
1575
    $this->assertTrue($query->hasAllTags('test', 'other'), t('hasAllTags() returned true.'));
    $this->assertFalse($query->hasAllTags('test', 'stuff'), t('hasAllTags() returned false.'));
1576
1577
1578
1579
1580
1581
  }

  /**
   * Test query tagging "has at least one of these tags" functionality.
   */
  function testHasAnyTag() {
1582
1583
1584
    $query = db_select('test');
    $query->addField('test', 'name');
    $query->addField('test', 'age', 'age');
1585

1586
    $query->addTag('test');
1587

1588
1589
    $this->assertTrue($query->hasAnyTag('test', 'other'), t('hasAnyTag() returned true.'));
    $this->assertFalse($query->hasAnyTag('other', 'stuff'), t('hasAnyTag() returned false.'));
1590
1591
1592
1593
  }

  /**
   * Test that we can attach meta data to a query object.
1594
   *
1595
1596
1597
   * This is how we pass additional context to alter hooks.
   */
  function testMetaData() {
1598
1599
1600
1601
1602
1603
1604
1605
    $query = db_select('test');
    $query->addField('test', 'name');
    $query->addField('test', 'age', 'age');

    $data = array(
      'a' => 'A',
      'b' => 'B',
    );
1606

1607
    $query->addMetaData('test', $data);
1608

1609
1610
    $return = $query->getMetaData('test');
    $this->assertEqual($data, $return, t('Corect metadata returned.'));
1611

1612
    $return = $query->getMetaData('nothere');
1613
    $this->assertNull($return, t('Non-existent key returned NULL.'));
1614
1615
1616
1617
1618
  }
}

/**
 * Select alter tests.
1619
 *
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
 * @see database_test_query_alter().
 */
class DatabaseAlterTestCase extends DatabaseTestCase {

  function getInfo() {
    return array(
      'name' => t('Query altering tests'),
      'description' => t('Test the hook_query_alter capabilities of the Select builder.'),
      'group' => t('Database'),
    );
  }

  /**
   * Test that we can do basic alters.
   */
  function testSimpleAlter() {
1636
1637
1638
1639
    $query = db_select('test');
    $query->addField('test', 'name');
    $query->addField('test', 'age', 'age');
    $query->addTag('database_test_alter_add_range');
1640

1641
    $result = $query->execute();
1642

1643
1644
1645
    $num_records = 0;
    foreach ($result as $record) {
      $num_records++;
1646
    }
1647
1648

    $this->assertEqual($num_records, 2, t('Returned the correct number of rows.'));
1649
1650
1651
1652
1653
1654
  }

  /**
   * Test that we can alter the joins on a query.
   */
  function testAlterWithJoin() {
1655
1656
1657
1658
1659
    $query = db_select('test_task');
    $tid_field =