forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase_unittest.cc
1792 lines (1501 loc) · 64.5 KB
/
database_unittest.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
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
284
285
286
287
288
289
290
291
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
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
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
412
413
414
415
416
417
418
419
420
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
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
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
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
795
796
797
798
799
800
801
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sql/database.h"
#include <stddef.h>
#include <stdint.h>
#include <cstdint>
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/bind.h"
#include "base/test/gtest_util.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/trace_event/process_memory_dump.h"
#include "build/build_config.h"
#include "sql/database_memory_dump_provider.h"
#include "sql/meta_table.h"
#include "sql/sql_features.h"
#include "sql/statement.h"
#include "sql/test/database_test_peer.h"
#include "sql/test/error_callback_support.h"
#include "sql/test/scoped_error_expecter.h"
#include "sql/test/test_helpers.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/sqlite/sqlite3.h"
namespace sql {
namespace {
using sql::test::ExecuteWithResult;
// Helper to return the count of items in sqlite_master. Return -1 in
// case of error.
int SqliteMasterCount(Database* db) {
const char* kMasterCount = "SELECT COUNT(*) FROM sqlite_master";
Statement s(db->GetUniqueStatement(kMasterCount));
return s.Step() ? s.ColumnInt(0) : -1;
}
// Track the number of valid references which share the same pointer.
// This is used to allow testing an implicitly use-after-free case by
// explicitly having the ref count live longer than the object.
class RefCounter {
public:
explicit RefCounter(size_t* counter) : counter_(counter) { (*counter_)++; }
RefCounter(const RefCounter& other) : counter_(other.counter_) {
(*counter_)++;
}
RefCounter& operator=(const RefCounter&) = delete;
~RefCounter() { (*counter_)--; }
private:
size_t* counter_;
};
// Empty callback for implementation of ErrorCallbackSetHelper().
void IgnoreErrorCallback(int error, Statement* stmt) {}
void ErrorCallbackSetHelper(Database* db,
size_t* counter,
const RefCounter& r,
int error,
Statement* stmt) {
// The ref count should not go to zero when changing the callback.
EXPECT_GT(*counter, 0u);
db->set_error_callback(base::BindRepeating(&IgnoreErrorCallback));
EXPECT_GT(*counter, 0u);
}
void ErrorCallbackResetHelper(Database* db,
size_t* counter,
const RefCounter& r,
int error,
Statement* stmt) {
// The ref count should not go to zero when clearing the callback.
EXPECT_GT(*counter, 0u);
db->reset_error_callback();
EXPECT_GT(*counter, 0u);
}
// Handle errors by blowing away the database.
void RazeErrorCallback(Database* db,
int expected_error,
int error,
Statement* stmt) {
// Nothing here needs extended errors at this time.
EXPECT_EQ(expected_error, expected_error & 0xff);
EXPECT_EQ(expected_error, error & 0xff);
db->RazeAndClose();
}
#if defined(OS_POSIX)
// Set a umask and restore the old mask on destruction. Cribbed from
// shared_memory_unittest.cc. Used by POSIX-only UserPermission test.
class ScopedUmaskSetter {
public:
explicit ScopedUmaskSetter(mode_t target_mask) {
old_umask_ = umask(target_mask);
}
~ScopedUmaskSetter() { umask(old_umask_); }
ScopedUmaskSetter(const ScopedUmaskSetter&) = delete;
ScopedUmaskSetter& operator=(const ScopedUmaskSetter&) = delete;
private:
mode_t old_umask_;
};
#endif // defined(OS_POSIX)
} // namespace
// We use the parameter to run all tests with WAL mode on and off.
class SQLDatabaseTest : public testing::Test,
public testing::WithParamInterface<bool> {
public:
enum class OverwriteType {
kTruncate,
kOverwrite,
};
~SQLDatabaseTest() override = default;
void SetUp() override {
db_ = std::make_unique<Database>(GetDBOptions());
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
db_path_ = temp_dir_.GetPath().AppendASCII("database_test.sqlite");
ASSERT_TRUE(db_->Open(db_path_));
}
DatabaseOptions GetDBOptions() {
DatabaseOptions options;
options.wal_mode = IsWALEnabled();
// TODO(crbug.com/1120969): Remove after switching to exclusive mode on by
// default.
options.exclusive_locking = false;
#if defined(OS_FUCHSIA) // Exclusive mode needs to be enabled to enter WAL mode
// on Fuchsia
if (IsWALEnabled()) {
options.exclusive_locking = true;
}
#endif // defined(OS_FUCHSIA)
return options;
}
bool IsWALEnabled() { return GetParam(); }
bool TruncateDatabase() {
base::File file(db_path_,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
return file.SetLength(0);
}
bool OverwriteDatabaseHeader(OverwriteType type) {
base::File file(db_path_,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
if (type == OverwriteType::kTruncate) {
if (!file.SetLength(0))
return false;
}
static constexpr char kText[] = "Now is the winter of our discontent.";
constexpr int kTextBytes = sizeof(kText) - 1;
return file.Write(0, kText, kTextBytes) == kTextBytes;
}
protected:
base::ScopedTempDir temp_dir_;
base::FilePath db_path_;
std::unique_ptr<Database> db_;
};
TEST_P(SQLDatabaseTest, Execute_ValidStatement) {
ASSERT_TRUE(db_->Execute("CREATE TABLE data(contents TEXT)"));
EXPECT_EQ(SQLITE_OK, db_->GetErrorCode());
}
TEST_P(SQLDatabaseTest, Execute_InvalidStatement) {
{
sql::test::ScopedErrorExpecter error_expecter;
error_expecter.ExpectError(SQLITE_ERROR);
EXPECT_FALSE(db_->Execute("CREATE TABLE data("));
EXPECT_TRUE(error_expecter.SawExpectedErrors());
}
EXPECT_EQ(SQLITE_ERROR, db_->GetErrorCode());
}
TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_OneLineValid) {
ASSERT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data(contents TEXT)"));
EXPECT_EQ(SQLITE_OK, db_->GetErrorCode());
}
TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_OneLineInvalid) {
ASSERT_FALSE(db_->ExecuteScriptForTesting("CREATE TABLE data("));
EXPECT_EQ(SQLITE_ERROR, db_->GetErrorCode());
}
TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_ExtraContents) {
EXPECT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data1(id)"))
<< "Minimal statement";
EXPECT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data2(id);"))
<< "Extra semicolon";
EXPECT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data3(id) -- Comment"))
<< "Trailing comment";
EXPECT_TRUE(db_->ExecuteScriptForTesting(
"CREATE TABLE data4(id);CREATE TABLE data5(id)"))
<< "Extra statement without whitespace";
EXPECT_TRUE(db_->ExecuteScriptForTesting(
"CREATE TABLE data6(id); CREATE TABLE data7(id)"))
<< "Extra statement separated by whitespace";
EXPECT_TRUE(db_->ExecuteScriptForTesting("CREATE TABLE data8(id);-- Comment"))
<< "Comment without whitespace";
EXPECT_TRUE(
db_->ExecuteScriptForTesting("CREATE TABLE data9(id); -- Comment"))
<< "Comment sepatated by whitespace";
}
TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_MultipleValidLines) {
EXPECT_TRUE(db_->ExecuteScriptForTesting(R"(
CREATE TABLE data1(contents TEXT);
CREATE TABLE data2(contents TEXT);
CREATE TABLE data3(contents TEXT);
)"));
EXPECT_EQ(SQLITE_OK, db_->GetErrorCode());
// DoesColumnExist() is implemented directly on top of a SQLite call. The
// other schema functions use sql::Statement infrastructure to query the
// schema table.
EXPECT_TRUE(db_->DoesColumnExist("data1", "contents"));
EXPECT_TRUE(db_->DoesColumnExist("data2", "contents"));
EXPECT_TRUE(db_->DoesColumnExist("data3", "contents"));
}
TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_StopsOnCompileError) {
EXPECT_FALSE(db_->ExecuteScriptForTesting(R"(
CREATE TABLE data1(contents TEXT);
CREATE TABLE data1();
CREATE TABLE data3(contents TEXT);
)"));
EXPECT_EQ(SQLITE_ERROR, db_->GetErrorCode());
EXPECT_TRUE(db_->DoesColumnExist("data1", "contents"));
EXPECT_FALSE(db_->DoesColumnExist("data3", "contents"));
}
TEST_P(SQLDatabaseTest, ExecuteScriptForTesting_StopsOnStepError) {
EXPECT_FALSE(db_->ExecuteScriptForTesting(R"(
CREATE TABLE data1(contents TEXT UNIQUE);
INSERT INTO data1(contents) VALUES('value1');
INSERT INTO data1(contents) VALUES('value1');
CREATE TABLE data3(contents TEXT);
)"));
EXPECT_EQ(SQLITE_CONSTRAINT_UNIQUE, db_->GetErrorCode());
EXPECT_TRUE(db_->DoesColumnExist("data1", "contents"));
EXPECT_FALSE(db_->DoesColumnExist("data3", "contents"));
}
TEST_P(SQLDatabaseTest, CachedStatement) {
StatementID id1 = SQL_FROM_HERE;
StatementID id2 = SQL_FROM_HERE;
static const char kId1Sql[] = "SELECT a FROM foo";
static const char kId2Sql[] = "SELECT b FROM foo";
ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
ASSERT_TRUE(db_->Execute("INSERT INTO foo(a, b) VALUES (12, 13)"));
sqlite3_stmt* raw_id1_statement;
sqlite3_stmt* raw_id2_statement;
{
scoped_refptr<Database::StatementRef> ref_from_id1 =
db_->GetCachedStatement(id1, kId1Sql);
raw_id1_statement = ref_from_id1->stmt();
Statement from_id1(std::move(ref_from_id1));
ASSERT_TRUE(from_id1.is_valid());
ASSERT_TRUE(from_id1.Step());
EXPECT_EQ(12, from_id1.ColumnInt(0));
scoped_refptr<Database::StatementRef> ref_from_id2 =
db_->GetCachedStatement(id2, kId2Sql);
raw_id2_statement = ref_from_id2->stmt();
EXPECT_NE(raw_id1_statement, raw_id2_statement);
Statement from_id2(std::move(ref_from_id2));
ASSERT_TRUE(from_id2.is_valid());
ASSERT_TRUE(from_id2.Step());
EXPECT_EQ(13, from_id2.ColumnInt(0));
}
{
scoped_refptr<Database::StatementRef> ref_from_id1 =
db_->GetCachedStatement(id1, kId1Sql);
EXPECT_EQ(raw_id1_statement, ref_from_id1->stmt())
<< "statement was not cached";
Statement from_id1(std::move(ref_from_id1));
ASSERT_TRUE(from_id1.is_valid());
ASSERT_TRUE(from_id1.Step()) << "cached statement was not reset";
EXPECT_EQ(12, from_id1.ColumnInt(0));
scoped_refptr<Database::StatementRef> ref_from_id2 =
db_->GetCachedStatement(id2, kId2Sql);
EXPECT_EQ(raw_id2_statement, ref_from_id2->stmt())
<< "statement was not cached";
Statement from_id2(std::move(ref_from_id2));
ASSERT_TRUE(from_id2.is_valid());
ASSERT_TRUE(from_id2.Step()) << "cached statement was not reset";
EXPECT_EQ(13, from_id2.ColumnInt(0));
}
EXPECT_DCHECK_DEATH(db_->GetCachedStatement(id1, kId2Sql))
<< "Using a different SQL with the same statement ID should DCHECK";
EXPECT_DCHECK_DEATH(db_->GetCachedStatement(id2, kId1Sql))
<< "Using a different SQL with the same statement ID should DCHECK";
}
TEST_P(SQLDatabaseTest, IsSQLValidTest) {
ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
ASSERT_TRUE(db_->IsSQLValid("SELECT a FROM foo"));
ASSERT_FALSE(db_->IsSQLValid("SELECT no_exist FROM foo"));
}
TEST_P(SQLDatabaseTest, DoesTableExist) {
EXPECT_FALSE(db_->DoesTableExist("foo"));
EXPECT_FALSE(db_->DoesTableExist("foo_index"));
ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
ASSERT_TRUE(db_->Execute("CREATE INDEX foo_index ON foo (a)"));
EXPECT_TRUE(db_->DoesTableExist("foo"));
EXPECT_FALSE(db_->DoesTableExist("foo_index"));
// DoesTableExist() is case-sensitive.
EXPECT_FALSE(db_->DoesTableExist("Foo"));
EXPECT_FALSE(db_->DoesTableExist("FOO"));
}
TEST_P(SQLDatabaseTest, DoesIndexExist) {
ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
EXPECT_FALSE(db_->DoesIndexExist("foo"));
EXPECT_FALSE(db_->DoesIndexExist("foo_ubdex"));
ASSERT_TRUE(db_->Execute("CREATE INDEX foo_index ON foo (a)"));
EXPECT_TRUE(db_->DoesIndexExist("foo_index"));
EXPECT_FALSE(db_->DoesIndexExist("foo"));
// DoesIndexExist() is case-sensitive.
EXPECT_FALSE(db_->DoesIndexExist("Foo_index"));
EXPECT_FALSE(db_->DoesIndexExist("Foo_Index"));
EXPECT_FALSE(db_->DoesIndexExist("FOO_INDEX"));
}
TEST_P(SQLDatabaseTest, DoesViewExist) {
EXPECT_FALSE(db_->DoesViewExist("voo"));
ASSERT_TRUE(db_->Execute("CREATE VIEW voo (a) AS SELECT 1"));
EXPECT_FALSE(db_->DoesIndexExist("voo"));
EXPECT_FALSE(db_->DoesTableExist("voo"));
EXPECT_TRUE(db_->DoesViewExist("voo"));
// DoesTableExist() is case-sensitive.
EXPECT_FALSE(db_->DoesViewExist("Voo"));
EXPECT_FALSE(db_->DoesViewExist("VOO"));
}
TEST_P(SQLDatabaseTest, DoesColumnExist) {
ASSERT_TRUE(db_->Execute("CREATE TABLE foo (a, b)"));
EXPECT_FALSE(db_->DoesColumnExist("foo", "bar"));
EXPECT_TRUE(db_->DoesColumnExist("foo", "a"));
ASSERT_FALSE(db_->DoesTableExist("bar"));
EXPECT_FALSE(db_->DoesColumnExist("bar", "b"));
// SQLite resolves table/column names without case sensitivity.
EXPECT_TRUE(db_->DoesColumnExist("FOO", "A"));
EXPECT_TRUE(db_->DoesColumnExist("FOO", "a"));
EXPECT_TRUE(db_->DoesColumnExist("foo", "A"));
}
TEST_P(SQLDatabaseTest, GetLastInsertRowId) {
ASSERT_TRUE(db_->Execute("CREATE TABLE foo (id INTEGER PRIMARY KEY, value)"));
ASSERT_TRUE(db_->Execute("INSERT INTO foo (value) VALUES (12)"));
// Last insert row ID should be valid.
int64_t row = db_->GetLastInsertRowId();
EXPECT_LT(0, row);
// It should be the primary key of the row we just inserted.
Statement s(db_->GetUniqueStatement("SELECT value FROM foo WHERE id=?"));
s.BindInt64(0, row);
ASSERT_TRUE(s.Step());
EXPECT_EQ(12, s.ColumnInt(0));
}
TEST_P(SQLDatabaseTest, Rollback) {
ASSERT_TRUE(db_->BeginTransaction());
ASSERT_TRUE(db_->BeginTransaction());
EXPECT_EQ(2, db_->transaction_nesting());
db_->RollbackTransaction();
EXPECT_FALSE(db_->CommitTransaction());
EXPECT_TRUE(db_->BeginTransaction());
}
// Test the scoped error expecter by attempting to insert a duplicate
// value into an index.
TEST_P(SQLDatabaseTest, ScopedErrorExpecter) {
const char* kCreateSql = "CREATE TABLE foo (id INTEGER UNIQUE)";
ASSERT_TRUE(db_->Execute(kCreateSql));
ASSERT_TRUE(db_->Execute("INSERT INTO foo (id) VALUES (12)"));
{
sql::test::ScopedErrorExpecter expecter;
expecter.ExpectError(SQLITE_CONSTRAINT);
ASSERT_FALSE(db_->Execute("INSERT INTO foo (id) VALUES (12)"));
ASSERT_TRUE(expecter.SawExpectedErrors());
}
}
TEST_P(SQLDatabaseTest, SchemaIntrospectionUsesErrorExpecter) {
const char* kCreateSql = "CREATE TABLE foo (id INTEGER UNIQUE)";
ASSERT_TRUE(db_->Execute(kCreateSql));
ASSERT_FALSE(db_->DoesTableExist("bar"));
ASSERT_TRUE(db_->DoesTableExist("foo"));
ASSERT_TRUE(db_->DoesColumnExist("foo", "id"));
db_->Close();
// Corrupt the database so that nothing works, including PRAGMAs.
ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
{
sql::test::ScopedErrorExpecter expecter;
expecter.ExpectError(SQLITE_CORRUPT);
ASSERT_TRUE(db_->Open(db_path_));
ASSERT_FALSE(db_->DoesTableExist("bar"));
ASSERT_FALSE(db_->DoesTableExist("foo"));
ASSERT_FALSE(db_->DoesColumnExist("foo", "id"));
ASSERT_TRUE(expecter.SawExpectedErrors());
}
}
TEST_P(SQLDatabaseTest, ErrorCallback) {
const char* kCreateSql = "CREATE TABLE foo (id INTEGER UNIQUE)";
ASSERT_TRUE(db_->Execute(kCreateSql));
ASSERT_TRUE(db_->Execute("INSERT INTO foo (id) VALUES (12)"));
int error = SQLITE_OK;
{
ScopedErrorCallback sec(db_.get(),
base::BindRepeating(&CaptureErrorCallback, &error));
EXPECT_FALSE(db_->Execute("INSERT INTO foo (id) VALUES (12)"));
// Later versions of SQLite throw SQLITE_CONSTRAINT_UNIQUE. The specific
// sub-error isn't really important.
EXPECT_EQ(SQLITE_CONSTRAINT, (error & 0xff));
}
// Callback is no longer in force due to reset.
{
error = SQLITE_OK;
sql::test::ScopedErrorExpecter expecter;
expecter.ExpectError(SQLITE_CONSTRAINT);
ASSERT_FALSE(db_->Execute("INSERT INTO foo (id) VALUES (12)"));
ASSERT_TRUE(expecter.SawExpectedErrors());
EXPECT_EQ(SQLITE_OK, error);
}
// base::BindRepeating() can curry arguments to be passed by const reference
// to the callback function. If the callback function calls
// re/set_error_callback(), the storage for those arguments can be
// deleted while the callback function is still executing.
//
// RefCounter() counts how many objects are live using an external
// count. The same counter is passed to the callback, so that it
// can check directly even if the RefCounter object is no longer
// live.
{
size_t count = 0;
ScopedErrorCallback sec(
db_.get(), base::BindRepeating(&ErrorCallbackSetHelper, db_.get(),
&count, RefCounter(&count)));
EXPECT_FALSE(db_->Execute("INSERT INTO foo (id) VALUES (12)"));
}
// Same test, but reset_error_callback() case.
{
size_t count = 0;
ScopedErrorCallback sec(
db_.get(), base::BindRepeating(&ErrorCallbackResetHelper, db_.get(),
&count, RefCounter(&count)));
EXPECT_FALSE(db_->Execute("INSERT INTO foo (id) VALUES (12)"));
}
}
TEST_P(SQLDatabaseTest, Execute_CompilationError) {
bool error_callback_called = false;
db_->set_error_callback(base::BindLambdaForTesting([&](int error,
sql::Statement*
statement) {
EXPECT_EQ(SQLITE_ERROR, error);
EXPECT_EQ(nullptr, statement);
EXPECT_FALSE(error_callback_called)
<< "SQL compilation errors should call the error callback exactly once";
error_callback_called = true;
}));
{
sql::test::ScopedErrorExpecter expecter;
expecter.ExpectError(SQLITE_ERROR);
EXPECT_FALSE(db_->Execute("SELECT missing_column FROM missing_table"));
EXPECT_TRUE(expecter.SawExpectedErrors());
}
EXPECT_TRUE(error_callback_called)
<< "SQL compilation errors should call the error callback";
}
TEST_P(SQLDatabaseTest, GetUniqueStatement_CompilationError) {
bool error_callback_called = false;
db_->set_error_callback(base::BindLambdaForTesting([&](int error,
sql::Statement*
statement) {
EXPECT_EQ(SQLITE_ERROR, error);
EXPECT_EQ(nullptr, statement);
EXPECT_FALSE(error_callback_called)
<< "SQL compilation errors should call the error callback exactly once";
error_callback_called = true;
}));
{
sql::test::ScopedErrorExpecter expecter;
expecter.ExpectError(SQLITE_ERROR);
sql::Statement statement(
db_->GetUniqueStatement("SELECT missing_column FROM missing_table"));
EXPECT_FALSE(statement.is_valid());
EXPECT_TRUE(expecter.SawExpectedErrors());
}
EXPECT_TRUE(error_callback_called)
<< "SQL compilation errors should call the error callback";
}
TEST_P(SQLDatabaseTest, GetCachedStatement_CompilationError) {
bool error_callback_called = false;
db_->set_error_callback(base::BindLambdaForTesting([&](int error,
sql::Statement*
statement) {
EXPECT_EQ(SQLITE_ERROR, error);
EXPECT_EQ(nullptr, statement);
EXPECT_FALSE(error_callback_called)
<< "SQL compilation errors should call the error callback exactly once";
error_callback_called = true;
}));
{
sql::test::ScopedErrorExpecter expecter;
expecter.ExpectError(SQLITE_ERROR);
sql::Statement statement(db_->GetCachedStatement(
SQL_FROM_HERE, "SELECT missing_column FROM missing_table"));
EXPECT_FALSE(statement.is_valid());
EXPECT_TRUE(expecter.SawExpectedErrors());
}
EXPECT_TRUE(error_callback_called)
<< "SQL compilation errors should call the error callback";
}
TEST_P(SQLDatabaseTest, GetUniqueStatement_ExtraContents) {
sql::Statement minimal(db_->GetUniqueStatement("SELECT 1"));
sql::Statement extra_semicolon(db_->GetUniqueStatement("SELECT 1;"));
// It would be nice to flag trailing comments too, as they cost binary size.
// However, there's no easy way of doing that.
sql::Statement trailing_comment(
db_->GetUniqueStatement("SELECT 1 -- Comment"));
EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("SELECT 1;SELECT 2"))
<< "Extra statement without whitespace";
EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("SELECT 1; SELECT 2"))
<< "Extra statement separated by whitespace";
EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("SELECT 1;-- Comment"))
<< "Comment without whitespace";
EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("SELECT 1; -- Comment"))
<< "Comment separated by whitespace";
}
TEST_P(SQLDatabaseTest, GetCachedStatement_ExtraContents) {
sql::Statement minimal(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1"));
sql::Statement extra_semicolon(
db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1;"));
// It would be nice to flag trailing comments too, as they cost binary size.
// However, there's no easy way of doing that.
sql::Statement trailing_comment(
db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1 -- Comment"));
EXPECT_DCHECK_DEATH(
db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1;SELECT 2"))
<< "Extra statement without whitespace";
EXPECT_DCHECK_DEATH(
db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1; SELECT 2"))
<< "Extra statement separated by whitespace";
EXPECT_DCHECK_DEATH(
db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1;-- Comment"))
<< "Comment without whitespace";
EXPECT_DCHECK_DEATH(
db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1; -- Comment"))
<< "Comment separated by whitespace";
}
TEST_P(SQLDatabaseTest, IsSQLValid_ExtraContents) {
EXPECT_TRUE(db_->IsSQLValid("SELECT 1"));
EXPECT_TRUE(db_->IsSQLValid("SELECT 1;"))
<< "Trailing semicolons are currently tolerated";
// It would be nice to flag trailing comments too, as they cost binary size.
// However, there's no easy way of doing that.
EXPECT_TRUE(db_->IsSQLValid("SELECT 1 -- Comment"))
<< "Trailing comments are currently tolerated";
EXPECT_DCHECK_DEATH(db_->IsSQLValid("SELECT 1;SELECT 2"))
<< "Extra statement without whitespace";
EXPECT_DCHECK_DEATH(db_->IsSQLValid("SELECT 1; SELECT 2"))
<< "Extra statement separated by whitespace";
EXPECT_DCHECK_DEATH(db_->IsSQLValid("SELECT 1;-- Comment"))
<< "Comment without whitespace";
EXPECT_DCHECK_DEATH(db_->IsSQLValid("SELECT 1; -- Comment"))
<< "Comment separated by whitespace";
}
TEST_P(SQLDatabaseTest, GetUniqueStatement_NoContents) {
EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("")) << "Empty string";
EXPECT_DCHECK_DEATH(db_->GetUniqueStatement(" ")) << "Space";
EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("\n")) << "Newline";
EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("-- Comment")) << "Comment";
}
TEST_P(SQLDatabaseTest, GetCachedStatement_NoContents) {
EXPECT_DCHECK_DEATH(db_->GetCachedStatement(SQL_FROM_HERE, ""))
<< "Empty string";
EXPECT_DCHECK_DEATH(db_->GetCachedStatement(SQL_FROM_HERE, " ")) << "Space";
EXPECT_DCHECK_DEATH(db_->GetCachedStatement(SQL_FROM_HERE, "\n"))
<< "Newline";
EXPECT_DCHECK_DEATH(db_->GetCachedStatement(SQL_FROM_HERE, "-- Comment"))
<< "Comment";
}
TEST_P(SQLDatabaseTest, IsSQLValid_NoContents) {
EXPECT_DCHECK_DEATH(db_->IsSQLValid("")) << "Empty string";
EXPECT_DCHECK_DEATH(db_->IsSQLValid(" ")) << "Space";
EXPECT_DCHECK_DEATH(db_->IsSQLValid("\n")) << "Newline";
EXPECT_DCHECK_DEATH(db_->IsSQLValid("-- Comment")) << "Comment";
}
// Test that Database::Raze() results in a database without the
// tables from the original database.
TEST_P(SQLDatabaseTest, Raze) {
const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
ASSERT_TRUE(db_->Execute(kCreateSql));
ASSERT_TRUE(db_->Execute("INSERT INTO foo (value) VALUES (12)"));
int pragma_auto_vacuum = 0;
{
Statement s(db_->GetUniqueStatement("PRAGMA auto_vacuum"));
ASSERT_TRUE(s.Step());
pragma_auto_vacuum = s.ColumnInt(0);
ASSERT_TRUE(pragma_auto_vacuum == 0 || pragma_auto_vacuum == 1);
}
// If auto_vacuum is set, there's an extra page to maintain a freelist.
const int kExpectedPageCount = 2 + pragma_auto_vacuum;
{
Statement s(db_->GetUniqueStatement("PRAGMA page_count"));
ASSERT_TRUE(s.Step());
EXPECT_EQ(kExpectedPageCount, s.ColumnInt(0));
}
{
Statement s(db_->GetUniqueStatement("SELECT * FROM sqlite_master"));
ASSERT_TRUE(s.Step());
EXPECT_EQ("table", s.ColumnString(0));
EXPECT_EQ("foo", s.ColumnString(1));
EXPECT_EQ("foo", s.ColumnString(2));
// Table "foo" is stored in the last page of the file.
EXPECT_EQ(kExpectedPageCount, s.ColumnInt(3));
EXPECT_EQ(kCreateSql, s.ColumnString(4));
}
ASSERT_TRUE(db_->Raze());
{
Statement s(db_->GetUniqueStatement("PRAGMA page_count"));
ASSERT_TRUE(s.Step());
EXPECT_EQ(1, s.ColumnInt(0));
}
ASSERT_EQ(0, SqliteMasterCount(db_.get()));
{
Statement s(db_->GetUniqueStatement("PRAGMA auto_vacuum"));
ASSERT_TRUE(s.Step());
// The new database has the same auto_vacuum as a fresh database.
EXPECT_EQ(pragma_auto_vacuum, s.ColumnInt(0));
}
}
// Helper for SQLDatabaseTest.RazePageSize. Creates a fresh db based on
// db_prefix, with the given initial page size, and verifies it against the
// expected size. Then changes to the final page size and razes, verifying that
// the fresh database ends up with the expected final page size.
void TestPageSize(const base::FilePath& db_prefix,
int initial_page_size,
const std::string& expected_initial_page_size,
int final_page_size,
const std::string& expected_final_page_size) {
static const char kCreateSql[] = "CREATE TABLE x (t TEXT)";
static const char kInsertSql1[] = "INSERT INTO x VALUES ('This is a test')";
static const char kInsertSql2[] = "INSERT INTO x VALUES ('That was a test')";
const base::FilePath db_path = db_prefix.InsertBeforeExtensionASCII(
base::NumberToString(initial_page_size));
Database::Delete(db_path);
Database db({.page_size = initial_page_size});
ASSERT_TRUE(db.Open(db_path));
ASSERT_TRUE(db.Execute(kCreateSql));
ASSERT_TRUE(db.Execute(kInsertSql1));
ASSERT_TRUE(db.Execute(kInsertSql2));
ASSERT_EQ(expected_initial_page_size,
ExecuteWithResult(&db, "PRAGMA page_size"));
db.Close();
// Re-open the database while setting a new |options.page_size| in the object.
Database razed_db({.page_size = final_page_size});
ASSERT_TRUE(razed_db.Open(db_path));
// Raze will use the page size set in the connection object, which may not
// match the file's page size.
ASSERT_TRUE(razed_db.Raze());
// SQLite 3.10.2 (at least) has a quirk with the sqlite3_backup() API (used by
// Raze()) which causes the destination database to remember the previous
// page_size, even if the overwriting database changed the page_size. Access
// the actual database to cause the cached value to be updated.
EXPECT_EQ("0",
ExecuteWithResult(&razed_db, "SELECT COUNT(*) FROM sqlite_master"));
EXPECT_EQ(expected_final_page_size,
ExecuteWithResult(&razed_db, "PRAGMA page_size"));
EXPECT_EQ("1", ExecuteWithResult(&razed_db, "PRAGMA page_count"));
}
// Verify that Recovery maintains the page size, and the virtual table
// works with page sizes other than SQLite's default. Also verify the case
// where the default page size has changed.
TEST_P(SQLDatabaseTest, RazePageSize) {
const std::string default_page_size =
ExecuteWithResult(db_.get(), "PRAGMA page_size");
// Sync uses 32k pages.
EXPECT_NO_FATAL_FAILURE(
TestPageSize(db_path_, 32768, "32768", 32768, "32768"));
// Many clients use 4k pages. This is the SQLite default after 3.12.0.
EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 4096, "4096", 4096, "4096"));
// 1k is the default page size before 3.12.0.
EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 1024, "1024", 1024, "1024"));
EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 2048, "2048", 4096, "4096"));
// Databases with no page size specified should result in the default
// page size. 2k has never been the default page size.
ASSERT_NE("2048", default_page_size);
EXPECT_NO_FATAL_FAILURE(TestPageSize(db_path_, 2048, "2048",
DatabaseOptions::kDefaultPageSize,
default_page_size));
}
// Test that Raze() results are seen in other connections.
TEST_P(SQLDatabaseTest, RazeMultiple) {
const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
ASSERT_TRUE(db_->Execute(kCreateSql));
Database other_db(GetDBOptions());
ASSERT_TRUE(other_db.Open(db_path_));
// Check that the second connection sees the table.
ASSERT_EQ(1, SqliteMasterCount(&other_db));
ASSERT_TRUE(db_->Raze());
// The second connection sees the updated database.
ASSERT_EQ(0, SqliteMasterCount(&other_db));
}
TEST_P(SQLDatabaseTest, RazeLocked) {
const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
ASSERT_TRUE(db_->Execute(kCreateSql));
// Open a transaction and write some data in a second connection.
// This will acquire a PENDING or EXCLUSIVE transaction, which will
// cause the raze to fail.
Database other_db(GetDBOptions());
ASSERT_TRUE(other_db.Open(db_path_));
ASSERT_TRUE(other_db.BeginTransaction());
const char* kInsertSql = "INSERT INTO foo VALUES (1, 'data')";
ASSERT_TRUE(other_db.Execute(kInsertSql));
ASSERT_FALSE(db_->Raze());
// Works after COMMIT.
ASSERT_TRUE(other_db.CommitTransaction());
ASSERT_TRUE(db_->Raze());
// Re-create the database.
ASSERT_TRUE(db_->Execute(kCreateSql));
ASSERT_TRUE(db_->Execute(kInsertSql));
// An unfinished read transaction in the other connection also
// blocks raze.
// This doesn't happen in WAL mode because reads are no longer blocked by
// write operations when using a WAL.
if (!IsWALEnabled()) {
const char* kQuery = "SELECT COUNT(*) FROM foo";
Statement s(other_db.GetUniqueStatement(kQuery));
ASSERT_TRUE(s.Step());
ASSERT_FALSE(db_->Raze());
// Completing the statement unlocks the database.
ASSERT_FALSE(s.Step());
ASSERT_TRUE(db_->Raze());
}
}
// Verify that Raze() can handle an empty file. SQLite should treat
// this as an empty database.
TEST_P(SQLDatabaseTest, RazeEmptyDB) {
const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
ASSERT_TRUE(db_->Execute(kCreateSql));
db_->Close();
ASSERT_TRUE(TruncateDatabase());
ASSERT_TRUE(db_->Open(db_path_));
ASSERT_TRUE(db_->Raze());
EXPECT_EQ(0, SqliteMasterCount(db_.get()));
}
// Verify that Raze() can handle a file of junk.
// Need exclusive mode off here as there are some subtleties (by design) around
// how the cache is used with it on which causes the test to fail.
TEST_P(SQLDatabaseTest, RazeNOTADB) {
db_->Close();
Database::Delete(db_path_);
ASSERT_FALSE(base::PathExists(db_path_));
ASSERT_TRUE(OverwriteDatabaseHeader(OverwriteType::kTruncate));
ASSERT_TRUE(base::PathExists(db_path_));
// SQLite will successfully open the handle, but fail when running PRAGMA
// statements that access the database.
{
sql::test::ScopedErrorExpecter expecter;
expecter.ExpectError(SQLITE_NOTADB);
EXPECT_TRUE(db_->Open(db_path_));
ASSERT_TRUE(expecter.SawExpectedErrors());
}
EXPECT_TRUE(db_->Raze());
db_->Close();
// Now empty, the open should open an empty database.
EXPECT_TRUE(db_->Open(db_path_));
EXPECT_EQ(0, SqliteMasterCount(db_.get()));
}
// Verify that Raze() can handle a database overwritten with garbage.
TEST_P(SQLDatabaseTest, RazeNOTADB2) {
const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
ASSERT_TRUE(db_->Execute(kCreateSql));
ASSERT_EQ(1, SqliteMasterCount(db_.get()));
db_->Close();
ASSERT_TRUE(OverwriteDatabaseHeader(OverwriteType::kOverwrite));
// SQLite will successfully open the handle, but will fail with
// SQLITE_NOTADB on pragma statemenets which attempt to read the
// corrupted header.
{
sql::test::ScopedErrorExpecter expecter;
expecter.ExpectError(SQLITE_NOTADB);
EXPECT_TRUE(db_->Open(db_path_));
ASSERT_TRUE(expecter.SawExpectedErrors());
}
EXPECT_TRUE(db_->Raze());
db_->Close();
// Now empty, the open should succeed with an empty database.
EXPECT_TRUE(db_->Open(db_path_));
EXPECT_EQ(0, SqliteMasterCount(db_.get()));
}
// Test that a callback from Open() can raze the database. This is
// essential for cases where the Open() can fail entirely, so the
// Raze() cannot happen later. Additionally test that when the
// callback does this during Open(), the open is retried and succeeds.
TEST_P(SQLDatabaseTest, RazeCallbackReopen) {
const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
ASSERT_TRUE(db_->Execute(kCreateSql));
ASSERT_EQ(1, SqliteMasterCount(db_.get()));
db_->Close();
// Corrupt the database so that nothing works, including PRAGMAs.
ASSERT_TRUE(sql::test::CorruptSizeInHeader(db_path_));
// Open() will succeed, even though the PRAGMA calls within will
// fail with SQLITE_CORRUPT, as will this PRAGMA.
{
sql::test::ScopedErrorExpecter expecter;
expecter.ExpectError(SQLITE_CORRUPT);
ASSERT_TRUE(db_->Open(db_path_));
ASSERT_FALSE(db_->Execute("PRAGMA auto_vacuum"));
db_->Close();
ASSERT_TRUE(expecter.SawExpectedErrors());
}
db_->set_error_callback(
base::BindRepeating(&RazeErrorCallback, db_.get(), SQLITE_CORRUPT));
// When the PRAGMA calls in Open() raise SQLITE_CORRUPT, the error
// callback will call RazeAndClose(). Open() will then fail and be
// retried. The second Open() on the empty database will succeed
// cleanly.
ASSERT_TRUE(db_->Open(db_path_));
ASSERT_TRUE(db_->Execute("PRAGMA auto_vacuum"));
EXPECT_EQ(0, SqliteMasterCount(db_.get()));
}
// Basic test of RazeAndClose() operation.
TEST_P(SQLDatabaseTest, RazeAndClose) {
const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
const char* kPopulateSql = "INSERT INTO foo (value) VALUES (12)";
// Test that RazeAndClose() closes the database, and that the
// database is empty when re-opened.
ASSERT_TRUE(db_->Execute(kCreateSql));
ASSERT_TRUE(db_->Execute(kPopulateSql));
ASSERT_TRUE(db_->RazeAndClose());
ASSERT_FALSE(db_->is_open());
db_->Close();
ASSERT_TRUE(db_->Open(db_path_));
ASSERT_EQ(0, SqliteMasterCount(db_.get()));
// Test that RazeAndClose() can break transactions.
ASSERT_TRUE(db_->Execute(kCreateSql));
ASSERT_TRUE(db_->Execute(kPopulateSql));
ASSERT_TRUE(db_->BeginTransaction());
ASSERT_TRUE(db_->RazeAndClose());
ASSERT_FALSE(db_->is_open());
ASSERT_FALSE(db_->CommitTransaction());
db_->Close();
ASSERT_TRUE(db_->Open(db_path_));
ASSERT_EQ(0, SqliteMasterCount(db_.get()));
}
// Test that various operations fail without crashing after
// RazeAndClose().
TEST_P(SQLDatabaseTest, RazeAndCloseDiagnostics) {
const char* kCreateSql = "CREATE TABLE foo (id INTEGER PRIMARY KEY, value)";
const char* kPopulateSql = "INSERT INTO foo (value) VALUES (12)";
const char* kSimpleSql = "SELECT 1";
ASSERT_TRUE(db_->Execute(kCreateSql));
ASSERT_TRUE(db_->Execute(kPopulateSql));
// Test baseline expectations.
db_->Preload();
ASSERT_TRUE(db_->DoesTableExist("foo"));
ASSERT_TRUE(db_->IsSQLValid(kSimpleSql));
ASSERT_TRUE(db_->Execute(kSimpleSql));
ASSERT_TRUE(db_->is_open());
{
Statement s(db_->GetUniqueStatement(kSimpleSql));
ASSERT_TRUE(s.Step());
}
{
Statement s(db_->GetCachedStatement(SQL_FROM_HERE, kSimpleSql));
ASSERT_TRUE(s.Step());
}
ASSERT_TRUE(db_->BeginTransaction());