1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "storage/browser/quota/quota_database.h"
9 #include "base/auto_reset.h"
10 #include "base/bind.h"
11 #include "base/files/file_util.h"
12 #include "sql/connection.h"
13 #include "sql/meta_table.h"
14 #include "sql/statement.h"
15 #include "sql/transaction.h"
16 #include "storage/browser/quota/special_storage_policy.h"
21 // Definitions for database schema.
23 const int kCurrentVersion
= 4;
24 const int kCompatibleVersion
= 2;
26 const char kHostQuotaTable
[] = "HostQuotaTable";
27 const char kOriginInfoTable
[] = "OriginInfoTable";
28 const char kIsOriginTableBootstrapped
[] = "IsOriginTableBootstrapped";
30 bool VerifyValidQuotaConfig(const char* key
) {
31 return (key
!= NULL
&&
32 (!strcmp(key
, QuotaDatabase::kDesiredAvailableSpaceKey
) ||
33 !strcmp(key
, QuotaDatabase::kTemporaryQuotaOverrideKey
)));
36 const int kCommitIntervalMs
= 30000;
38 } // anonymous namespace
41 const char QuotaDatabase::kDesiredAvailableSpaceKey
[] = "DesiredAvailableSpace";
42 const char QuotaDatabase::kTemporaryQuotaOverrideKey
[] =
43 "TemporaryQuotaOverride";
45 const QuotaDatabase::TableSchema
QuotaDatabase::kTables
[] = {
47 "(host TEXT NOT NULL,"
48 " type INTEGER NOT NULL,"
49 " quota INTEGER DEFAULT 0,"
50 " UNIQUE(host, type))" },
52 "(origin TEXT NOT NULL,"
53 " type INTEGER NOT NULL,"
54 " used_count INTEGER DEFAULT 0,"
55 " last_access_time INTEGER DEFAULT 0,"
56 " last_modified_time INTEGER DEFAULT 0,"
57 " UNIQUE(origin, type))" },
61 const QuotaDatabase::IndexSchema
QuotaDatabase::kIndexes
[] = {
70 { "OriginLastAccessTimeIndex",
74 { "OriginLastModifiedTimeIndex",
76 "(last_modified_time)",
80 struct QuotaDatabase::QuotaTableImporter
{
81 bool Append(const QuotaTableEntry
& entry
) {
82 entries
.push_back(entry
);
85 std::vector
<QuotaTableEntry
> entries
;
88 // Clang requires explicit out-of-line constructors for them.
89 QuotaDatabase::QuotaTableEntry::QuotaTableEntry()
90 : type(kStorageTypeUnknown
),
94 QuotaDatabase::QuotaTableEntry::QuotaTableEntry(
95 const std::string
& host
,
103 QuotaDatabase::OriginInfoTableEntry::OriginInfoTableEntry()
104 : type(kStorageTypeUnknown
),
108 QuotaDatabase::OriginInfoTableEntry::OriginInfoTableEntry(
112 const base::Time
& last_access_time
,
113 const base::Time
& last_modified_time
)
116 used_count(used_count
),
117 last_access_time(last_access_time
),
118 last_modified_time(last_modified_time
) {
121 // QuotaDatabase ------------------------------------------------------------
122 QuotaDatabase::QuotaDatabase(const base::FilePath
& path
)
123 : db_file_path_(path
),
124 is_recreating_(false),
125 is_disabled_(false) {
128 QuotaDatabase::~QuotaDatabase() {
130 db_
->CommitTransaction();
134 void QuotaDatabase::CloseConnection() {
139 bool QuotaDatabase::GetHostQuota(
140 const std::string
& host
, StorageType type
, int64
* quota
) {
142 if (!LazyOpen(false))
147 " FROM HostQuotaTable"
148 " WHERE host = ? AND type = ?";
150 sql::Statement
statement(db_
->GetCachedStatement(SQL_FROM_HERE
, kSql
));
151 statement
.BindString(0, host
);
152 statement
.BindInt(1, static_cast<int>(type
));
154 if (!statement
.Step())
157 *quota
= statement
.ColumnInt64(0);
161 bool QuotaDatabase::SetHostQuota(
162 const std::string
& host
, StorageType type
, int64 quota
) {
168 "INSERT OR REPLACE INTO HostQuotaTable"
169 " (quota, host, type)"
171 sql::Statement
statement(db_
->GetCachedStatement(SQL_FROM_HERE
, kSql
));
172 statement
.BindInt64(0, quota
);
173 statement
.BindString(1, host
);
174 statement
.BindInt(2, static_cast<int>(type
));
176 if (!statement
.Run())
183 bool QuotaDatabase::SetOriginLastAccessTime(
184 const GURL
& origin
, StorageType type
, base::Time last_access_time
) {
188 sql::Statement statement
;
191 if (FindOriginUsedCount(origin
, type
, &used_count
)) {
194 "UPDATE OriginInfoTable"
195 " SET used_count = ?, last_access_time = ?"
196 " WHERE origin = ? AND type = ?";
197 statement
.Assign(db_
->GetCachedStatement(SQL_FROM_HERE
, kSql
));
200 "INSERT INTO OriginInfoTable"
201 " (used_count, last_access_time, origin, type)"
202 " VALUES (?, ?, ?, ?)";
203 statement
.Assign(db_
->GetCachedStatement(SQL_FROM_HERE
, kSql
));
205 statement
.BindInt(0, used_count
);
206 statement
.BindInt64(1, last_access_time
.ToInternalValue());
207 statement
.BindString(2, origin
.spec());
208 statement
.BindInt(3, static_cast<int>(type
));
210 if (!statement
.Run())
217 bool QuotaDatabase::SetOriginLastModifiedTime(
218 const GURL
& origin
, StorageType type
, base::Time last_modified_time
) {
222 sql::Statement statement
;
225 if (FindOriginUsedCount(origin
, type
, &dummy
)) {
227 "UPDATE OriginInfoTable"
228 " SET last_modified_time = ?"
229 " WHERE origin = ? AND type = ?";
230 statement
.Assign(db_
->GetCachedStatement(SQL_FROM_HERE
, kSql
));
233 "INSERT INTO OriginInfoTable"
234 " (last_modified_time, origin, type) VALUES (?, ?, ?)";
235 statement
.Assign(db_
->GetCachedStatement(SQL_FROM_HERE
, kSql
));
237 statement
.BindInt64(0, last_modified_time
.ToInternalValue());
238 statement
.BindString(1, origin
.spec());
239 statement
.BindInt(2, static_cast<int>(type
));
241 if (!statement
.Run())
248 bool QuotaDatabase::RegisterInitialOriginInfo(
249 const std::set
<GURL
>& origins
, StorageType type
) {
253 typedef std::set
<GURL
>::const_iterator itr_type
;
254 for (itr_type itr
= origins
.begin(), end
= origins
.end();
257 "INSERT OR IGNORE INTO OriginInfoTable"
258 " (origin, type) VALUES (?, ?)";
259 sql::Statement
statement(db_
->GetCachedStatement(SQL_FROM_HERE
, kSql
));
260 statement
.BindString(0, itr
->spec());
261 statement
.BindInt(1, static_cast<int>(type
));
263 if (!statement
.Run())
271 bool QuotaDatabase::DeleteHostQuota(
272 const std::string
& host
, StorageType type
) {
273 if (!LazyOpen(false))
277 "DELETE FROM HostQuotaTable"
278 " WHERE host = ? AND type = ?";
280 sql::Statement
statement(db_
->GetCachedStatement(SQL_FROM_HERE
, kSql
));
281 statement
.BindString(0, host
);
282 statement
.BindInt(1, static_cast<int>(type
));
284 if (!statement
.Run())
291 bool QuotaDatabase::DeleteOriginInfo(
292 const GURL
& origin
, StorageType type
) {
293 if (!LazyOpen(false))
297 "DELETE FROM OriginInfoTable"
298 " WHERE origin = ? AND type = ?";
300 sql::Statement
statement(db_
->GetCachedStatement(SQL_FROM_HERE
, kSql
));
301 statement
.BindString(0, origin
.spec());
302 statement
.BindInt(1, static_cast<int>(type
));
304 if (!statement
.Run())
311 bool QuotaDatabase::GetQuotaConfigValue(const char* key
, int64
* value
) {
312 if (!LazyOpen(false))
314 DCHECK(VerifyValidQuotaConfig(key
));
315 return meta_table_
->GetValue(key
, value
);
318 bool QuotaDatabase::SetQuotaConfigValue(const char* key
, int64 value
) {
321 DCHECK(VerifyValidQuotaConfig(key
));
322 return meta_table_
->SetValue(key
, value
);
325 bool QuotaDatabase::GetLRUOrigin(
327 const std::set
<GURL
>& exceptions
,
328 SpecialStoragePolicy
* special_storage_policy
,
331 if (!LazyOpen(false))
334 const char* kSql
= "SELECT origin FROM OriginInfoTable"
336 " ORDER BY last_access_time ASC";
338 sql::Statement
statement(db_
->GetCachedStatement(SQL_FROM_HERE
, kSql
));
339 statement
.BindInt(0, static_cast<int>(type
));
341 while (statement
.Step()) {
342 GURL
url(statement
.ColumnString(0));
343 if (exceptions
.find(url
) != exceptions
.end())
345 if (special_storage_policy
&&
346 special_storage_policy
->IsStorageUnlimited(url
))
353 return statement
.Succeeded();
356 bool QuotaDatabase::GetOriginsModifiedSince(
357 StorageType type
, std::set
<GURL
>* origins
, base::Time modified_since
) {
359 if (!LazyOpen(false))
362 const char* kSql
= "SELECT origin FROM OriginInfoTable"
363 " WHERE type = ? AND last_modified_time >= ?";
365 sql::Statement
statement(db_
->GetCachedStatement(SQL_FROM_HERE
, kSql
));
366 statement
.BindInt(0, static_cast<int>(type
));
367 statement
.BindInt64(1, modified_since
.ToInternalValue());
370 while (statement
.Step())
371 origins
->insert(GURL(statement
.ColumnString(0)));
373 return statement
.Succeeded();
376 bool QuotaDatabase::IsOriginDatabaseBootstrapped() {
381 return meta_table_
->GetValue(kIsOriginTableBootstrapped
, &flag
) && flag
;
384 bool QuotaDatabase::SetOriginDatabaseBootstrapped(bool bootstrap_flag
) {
388 return meta_table_
->SetValue(kIsOriginTableBootstrapped
, bootstrap_flag
);
391 void QuotaDatabase::Commit() {
395 if (timer_
.IsRunning())
398 db_
->CommitTransaction();
399 db_
->BeginTransaction();
402 void QuotaDatabase::ScheduleCommit() {
403 if (timer_
.IsRunning())
405 timer_
.Start(FROM_HERE
, base::TimeDelta::FromMilliseconds(kCommitIntervalMs
),
406 this, &QuotaDatabase::Commit
);
409 bool QuotaDatabase::FindOriginUsedCount(
410 const GURL
& origin
, StorageType type
, int* used_count
) {
412 if (!LazyOpen(false))
416 "SELECT used_count FROM OriginInfoTable"
417 " WHERE origin = ? AND type = ?";
419 sql::Statement
statement(db_
->GetCachedStatement(SQL_FROM_HERE
, kSql
));
420 statement
.BindString(0, origin
.spec());
421 statement
.BindInt(1, static_cast<int>(type
));
423 if (!statement
.Step())
426 *used_count
= statement
.ColumnInt(0);
430 bool QuotaDatabase::LazyOpen(bool create_if_needed
) {
434 // If we tried and failed once, don't try again in the same session
435 // to avoid creating an incoherent mess on disk.
439 bool in_memory_only
= db_file_path_
.empty();
440 if (!create_if_needed
&&
441 (in_memory_only
|| !base::PathExists(db_file_path_
))) {
445 db_
.reset(new sql::Connection
);
446 meta_table_
.reset(new sql::MetaTable
);
448 db_
->set_histogram_tag("Quota");
451 if (in_memory_only
) {
452 opened
= db_
->OpenInMemory();
453 } else if (!base::CreateDirectory(db_file_path_
.DirName())) {
454 LOG(ERROR
) << "Failed to create quota database directory.";
456 opened
= db_
->Open(db_file_path_
);
461 if (!opened
|| !EnsureDatabaseVersion()) {
462 LOG(ERROR
) << "Failed to open the quota database.";
469 // Start a long-running transaction.
470 db_
->BeginTransaction();
475 bool QuotaDatabase::EnsureDatabaseVersion() {
476 static const size_t kTableCount
= arraysize(kTables
);
477 static const size_t kIndexCount
= arraysize(kIndexes
);
478 if (!sql::MetaTable::DoesTableExist(db_
.get()))
479 return CreateSchema(db_
.get(), meta_table_
.get(),
480 kCurrentVersion
, kCompatibleVersion
,
481 kTables
, kTableCount
,
482 kIndexes
, kIndexCount
);
484 if (!meta_table_
->Init(db_
.get(), kCurrentVersion
, kCompatibleVersion
))
487 if (meta_table_
->GetCompatibleVersionNumber() > kCurrentVersion
) {
488 LOG(WARNING
) << "Quota database is too new.";
492 if (meta_table_
->GetVersionNumber() < kCurrentVersion
) {
493 if (!UpgradeSchema(meta_table_
->GetVersionNumber()))
494 return ResetSchema();
498 DCHECK(sql::MetaTable::DoesTableExist(db_
.get()));
499 for (size_t i
= 0; i
< kTableCount
; ++i
) {
500 DCHECK(db_
->DoesTableExist(kTables
[i
].table_name
));
508 bool QuotaDatabase::CreateSchema(
509 sql::Connection
* database
,
510 sql::MetaTable
* meta_table
,
511 int schema_version
, int compatible_version
,
512 const TableSchema
* tables
, size_t tables_size
,
513 const IndexSchema
* indexes
, size_t indexes_size
) {
514 // TODO(kinuko): Factor out the common code to create databases.
515 sql::Transaction
transaction(database
);
516 if (!transaction
.Begin())
519 if (!meta_table
->Init(database
, schema_version
, compatible_version
))
522 for (size_t i
= 0; i
< tables_size
; ++i
) {
523 std::string
sql("CREATE TABLE ");
524 sql
+= tables
[i
].table_name
;
525 sql
+= tables
[i
].columns
;
526 if (!database
->Execute(sql
.c_str())) {
527 VLOG(1) << "Failed to execute " << sql
;
532 for (size_t i
= 0; i
< indexes_size
; ++i
) {
534 if (indexes
[i
].unique
)
535 sql
+= "CREATE UNIQUE INDEX ";
537 sql
+= "CREATE INDEX ";
538 sql
+= indexes
[i
].index_name
;
540 sql
+= indexes
[i
].table_name
;
541 sql
+= indexes
[i
].columns
;
542 if (!database
->Execute(sql
.c_str())) {
543 VLOG(1) << "Failed to execute " << sql
;
548 return transaction
.Commit();
551 bool QuotaDatabase::ResetSchema() {
552 DCHECK(!db_file_path_
.empty());
553 DCHECK(base::PathExists(db_file_path_
));
554 VLOG(1) << "Deleting existing quota data and starting over.";
559 if (!sql::Connection::Delete(db_file_path_
))
562 // So we can't go recursive.
566 base::AutoReset
<bool> auto_reset(&is_recreating_
, true);
567 return LazyOpen(true);
570 bool QuotaDatabase::UpgradeSchema(int current_version
) {
571 if (current_version
== 2) {
572 QuotaTableImporter importer
;
573 typedef std::vector
<QuotaTableEntry
> QuotaTableEntries
;
574 if (!DumpQuotaTable(base::Bind(&QuotaTableImporter::Append
,
575 base::Unretained(&importer
)))) {
579 for (QuotaTableEntries::const_iterator iter
= importer
.entries
.begin();
580 iter
!= importer
.entries
.end(); ++iter
) {
581 if (!SetHostQuota(iter
->host
, iter
->type
, iter
->quota
))
590 bool QuotaDatabase::DumpQuotaTable(const QuotaTableCallback
& callback
) {
594 const char* kSql
= "SELECT * FROM HostQuotaTable";
595 sql::Statement
statement(db_
->GetCachedStatement(SQL_FROM_HERE
, kSql
));
597 while (statement
.Step()) {
598 QuotaTableEntry entry
= QuotaTableEntry(
599 statement
.ColumnString(0),
600 static_cast<StorageType
>(statement
.ColumnInt(1)),
601 statement
.ColumnInt64(2));
603 if (!callback
.Run(entry
))
607 return statement
.Succeeded();
610 bool QuotaDatabase::DumpOriginInfoTable(
611 const OriginInfoTableCallback
& callback
) {
616 const char* kSql
= "SELECT * FROM OriginInfoTable";
617 sql::Statement
statement(db_
->GetCachedStatement(SQL_FROM_HERE
, kSql
));
619 while (statement
.Step()) {
620 OriginInfoTableEntry
entry(
621 GURL(statement
.ColumnString(0)),
622 static_cast<StorageType
>(statement
.ColumnInt(1)),
623 statement
.ColumnInt(2),
624 base::Time::FromInternalValue(statement
.ColumnInt64(3)),
625 base::Time::FromInternalValue(statement
.ColumnInt64(4)));
627 if (!callback
.Run(entry
))
631 return statement
.Succeeded();
634 bool operator<(const QuotaDatabase::QuotaTableEntry
& lhs
,
635 const QuotaDatabase::QuotaTableEntry
& rhs
) {
636 if (lhs
.host
< rhs
.host
) return true;
637 if (rhs
.host
< lhs
.host
) return false;
638 if (lhs
.type
< rhs
.type
) return true;
639 if (rhs
.type
< lhs
.type
) return false;
640 return lhs
.quota
< rhs
.quota
;
643 bool operator<(const QuotaDatabase::OriginInfoTableEntry
& lhs
,
644 const QuotaDatabase::OriginInfoTableEntry
& rhs
) {
645 if (lhs
.origin
< rhs
.origin
) return true;
646 if (rhs
.origin
< lhs
.origin
) return false;
647 if (lhs
.type
< rhs
.type
) return true;
648 if (rhs
.type
< lhs
.type
) return false;
649 if (lhs
.used_count
< rhs
.used_count
) return true;
650 if (rhs
.used_count
< lhs
.used_count
) return false;
651 return lhs
.last_access_time
< rhs
.last_access_time
;
654 } // namespace storage