SQLite is arelational database management system (RDBMS) thatsupports most of SQL.
SQLite is architected as a library that can be embedded in another application, such as Chrome. SQLite runs in the application's process, and shares its memory and other resources. This is similar to embedded databases likeLevelDB andBerkeleyDB. By contrast, most popular RDMBSes, likePostgreSQL andMySQL, are structured as standalone server processes that accept queries from client processes.
TODO: Explain the process model and locking
TODO: Explain Chrome decisions -- exclusive locking, full per-feature isolation (separate databases and page caches)
The section summarizes aspects of SQLite that are relevant to schema and query design, and may be surprising to readers with prior experience in other popular SQL database systems, such asPostgreSQL andMySQL.
The main bottleneck in SQLite database performance is usually disk I/O. So, designing schemas that perform well requires understanding how SQLite stores data on disk.
At a very high level, a SQLite database is a forest ofB-trees, some of which areB+-trees. The database file is an array of fixed-size pages, where each page stores a B-tree node. The page size can only be set when a database file is created, and impacts both SQL statement execution speed, and memory consumption.
The data in each table (usually calledrows,records, ortuples) is stored in a separate B-tree. The data in each index (calledentries,records ortuples) is also stored in a separate B-tree. So, each B-tree is associated with exactly one table. TheIndexing section goes into further details.
Each B-tree node stores multiple tuples of values. The values and their encodings are described in theValue types section.
Tying everything together: The performance of a SQL statement is roughly the number of database pages touched (read / written) by the statement. These pages are nodes belonging to the B-trees associated with the tables mentioned in the statement. The number of pages touched when accessing a B-tree depends on the B-tree‘s depth. Each B-tree’s depth depends on its record count (number of records stored in it), and on its node width (how many records fit in a node).
SQLite stores values using5 major types, which are summarized below.
NULL is a special type for theNULL
value.
INTEGER represents big-endian twos-complement integers. Boolean values (TRUE
andFALSE
) are represented as the integer values 1 and 0.
REAL represents IEEE 754-2008 64-bit floating point numbers.
TEXT represents strings (sequences of characters) encoded using asupported SQLite encoding. These values aresorted according toa collating sequence ora collating function.
BLOB represents sequences of bytes that are opaque to SQLite. These values are sorted using the bitwise binary comparison offered bymemcmp.
SQLite stores index keys and row values (records / tuples) usinga tightly packed format that makes heavy use ofvarints and variable-length fields. The column types have almost no influence on the encoding of values. This has the following consequences.
TINYINT
andBIGINT
, are treated as aliases forINTEGER
.DECIMAL
,FLOAT
, andDOUBLE PRECISION
are treated as aliases forREAL
.DECIMAL(5,2)
are ignored.CHAR
,CHARACTER VARYING
,VARCHAR
, andCLOB
, are treated as aliases forTEXT
.CHAR(255)
are ignored.SQLite uses clever heuristics, calledtype affinity, to map SQL column types such asVARCHAR
to the major types above.
Chrome database schemas should avoid type affinity, and should not include any information ignored by SQLite.
SQLiteuses B-trees to store both table and index data.
The exclusive use of B-trees reduces the amount of schema design decisions. Notable examples:
There is no equivalent toPostgreSQL's index types. In particular, since there are no hashed indexes, the design does not need to consider whether the index only needs to support equality queries, as opposed to greater/smaller than comparisons.
There is no equivalent toPostgreSQL's table access methods. Each table is clustered by a primary key index, which is implicitly stored in the table's B-tree.
By default, table rows (records / tuples) are stored in a B-tree keyed byrowid, an automatically assigned 64-bit integer key. Effectively, these tables are clustered by rowid, which acts as an implicit primary key. Opting out of this SQLite-specific default requires appendingWITHOUT ROWID
to theCREATE TABLE
instruction.
SQLite'sB-tree page format has optimized special cases for tables clustered by rowid. This makes rowid the most efficientsurrogate key implementation in SQLite. To make this optimization easier to use, any column that is a primary key and has anINTEGER
type is considered an alias for rowid.
Each SQLite indexis stored in a B-tree. Each index entry is stored as a B-tree node whose key is made up of the record‘s index key column values, followed by the record’s primary key column values.
WITHOUT ROWID
table indexes can include primary key columns without additional storage costs. This is because indexes forWITHOUT ROWID
tables enjoya space optimization where columns in both the primary key and the index key are not stored twice in B-tree nodes. Note that data in such tables cannot be recovered bysql::Recovery
.
Ata very high level, SQLite compiles SQL statements (often calledqueries) into bytecode executed by a virtual machine called the VDBE, orthe bytecode engine. A compiled statement can be executed multiple times, amortizing the costs of query parsing and planning. Chrome's SQLite abstraction layer makes it easy to use compiled queries.
Assuming effective use of cached statements, the performance of a SQL statement comes down to thequery plan that SQLite generates for the statement. The query plan is the sequence of B-tree accesses used to execute the statement, which determines the number of B-tree pages touched.
The rest of this section summarizes the following SQLite documentation pages.
At a high level, a SQLite query plan is a sequence ofnested loops, where each loop iterates over the data in a B-tree. Each loop can use the current record of the outer loops.
TODO: Complete this section. Cover joins, sorting, etc.
Ideally, the SQL schemas and statements used by Chrome features would be simple enough that the query plans would be obvious to the reader.
When this isn't the case, the fastest way to get the query plan is to load the schema inthe SQLite shell, and useEXPLAIN QUERY PLAN
.
The following command builds a SQLite shell that uses Chrome's build of SQLite, and supports theEXPLAIN QUERY PLAN
command.
autoninja-C out/Default sqlite_dev_shell
Inside the SQLite shell, the.eqp on
directive automatically shows the results ofEXPLAIN QUERY PLAN
for every SQL statement executed in the shell.
Query steps are the building blocks of SQLite query plans. Each query step is essentially a loop that iterates over the records in a B-tree. These loops differ in terms of how many B-tree pages they touch, and how many records they produce. This sub-section lists the types of steps implemented by SQLite.
Scans visit an entire (table or index) B-tree. For this reason, scans are almost never acceptable in Chrome. Most of our features don't have limits on the amount of stored data, so scans can result in an unbounded amount of I/O.
Atable scan visits the entire table's B-tree.
Acovering index scan visits an entire index B-tree, but doesn't access the associated table B-tree.
SQLite doesn't have any special optimization forCOUNT(*)
queries. In other words, SQLite does not track subtree sizes in its B-tree nodes.
Reviewers sometimes emphasize performance issues by calling the scansfull table scans andfull index scans, where “full” references the fact that the number of B-tree pages accessed is proportional to the entire data set stored on disk.
TODO: Complete this section. Add examples in a way that doesn't make the section overly long.
Searches access a subset of a (table or index) B-tree nodes. Searches limit the amount of nodes they need to access based on query restrictions, such as terms in theWHERE
clause. Seeing aSEARCH
in a query plan is not a guarantee of performance. Searches can vary wildly in the amount of B-tree pages they need to access.
One of the fastest possible searches is atable search that performs exactly one B-tree lookup, and produces at most one record.
The other fastest possible search is acovering index search that also performs one lookup, and produces at most one record.
TODO: Complete this section. Add examples in a way that doesn't make the section overly long.
The following pieces of advice usually come up in code reviews.
The SQLite shell offers quick feedback for converging on valid SQL statement syntax, and avoiding SQLite features that are disabled in Chrome. In addition, theEXPLAIN
andEXPLAIN QUERY PLAN
statements show the results of SQLite's query planner and optimizer, which are very helpful for reasoning about the performance of complex queries. The SQLite shell directive.eqp on
automatically issuesEXPLAIN QUERY PLAN
for all future commands.
The following commands set up SQLite shells using Chrome's build of SQLite.
autoninja-C out/Default sqlite_shell sqlite_dev_shell
sqlite_shell
runs the SQLite build that we ship in Chrome. It offers the ground truth on whether a SQL statement can be used in Chrome code or not.sqlite_dev_shell
enables theEXPLAIN
andEXPLAIN QUERY PLAN
statements, as well as a few features used byPerfetto's analysis tools.SQLite queries are usually embedded as string literals in C++ code. The advice here has the following goals.
Easy to read queries. The best defense against subtle bugs is making the queries very easy to read, so that any bugs become obvious at code review time. SQL string literals don't benefit from our code analysis infrastructure, so the only lines of defense against bugs are testing and code review.
Simplify crash debugging. We will always have a low volume of non-actionable crash reports, because Chrome runs on billions of devices, some of which have faulty RAM or processors.
No unnecessary performance overheads. The C++ optimizer doesn't understand SQL query literals, so the queries end up as written in the Chrome binary. Extra characters cost binary size, as well as CPU time (which turns into battery usage) during query parsing.
Match the embedding language (C++) style guide. This reduces the mental context switch overhead for folks who write and/or review C++ code that contains SQL.
Format statements like so.
staticconstexprchar kOriginInfoSql[]=// clang-format off"CREATE TABLE origin_infos(""origin TEXT NOT NULL,""last_modified INTEGER NOT NULL,""secure INTEGER NOT NULL)";// clang-format onstaticconstexprchar kInsertSql[]=// clang-format off"INSERT INTO infos(origin,last_modified,secure) ""VALUES(?,?,?)";// clang-format onstaticconstexprchar kSelectSql[]=// clang-format off"SELECT origin,last_modified,secure FROM origins ""WHERE last_modified>? ""ORDER BY last_modified";// clang-format on
SQLite keywords should use ALL CAPS. This makes SQL query literals easier to distinguish and search for.
Identifiers, such as table and row names, should use snake_case.
Identifiers, keywords, and parameter placeholders (?
) should be separated by exactly one character. Separators may be spaces (), commas (
,
), or parentheses ((
,)
).
Statement-ending semicolons (;
) are omitted.
SQL statements are stored in variables typedstatic constexpr char[]
, or in string literals passed directly to methods.
INSERT
statements should list all the table columns by name, in the same order as the correspondingCREATE TABLE
statements.
SELECT
statements should list the desired table columns by name, in the same order as the correspondingCREATE TABLE
statements.SELECT *
is strongly discouraged, at least until we have schema checks on database opens.
SELECT
statements that retrieve more than one row should include anORDER BY
clause to clarify the implicit ordering.
WITHOUT ROWID
tables, by the table's primary key.CREATE INDEX
statements should immediately follow theCREATE TABLE
statement for the indexed table.
ExplicitCREATE UNIQUE INDEX
statements should be preferred toUNIQUE
constraints onCREATE TABLE
.
Values must either be embedded in the SQL statement string literal, or bound usingparameters.
Parameter placeholders should always use the?
syntax. Alternative syntaxes, such as?NNN
or:AAAA
, have few benefits in a codebase where theBind
statements are right next to the queries, and are less known to readers.
SQL statements should be embedded in C++ as string literals. Thechar[]
type makes it possible for us to compute query length at compile time in the future. Thestatic
andconstexpr
qualifiers both ensure optimal code generation.
Do not execute multiple SQL statements (e.g., by callingStep()
orRun()
onsql::Statement
) on the same C++ line. It‘s difficult to get more than line numbers from crash reports’ stack traces.
Identifiers (table / index / column names and aliases) must not becurrent SQLite keywords. Identifiers may not start with thesqlite_
prefix, to avoid conflicting with the name of aSQLite internal schema object.
Column types should only be one of the the SQLite storage types (INTEGER
,REAL
,TEXT
,BLOB
), so readers can avoid reasoning about SQLite's type affinity.
Columns that will store boolean values should have theINTEGER
type.
Columns that will storebase::Time
values should have theINTEGER
type. Values should be serialized usingsql::Statement::BindTime()
and deserialized usingsql::Statement::ColumnTime()
.
Column types should not include information ignored by SQLite, such as numeric precision or scale specifiers, or string length specifiers.
Columns should haveNOT NULL
constraints whenever possible. This saves maintainers from having to reason about the less intuitive cases ofNULL
handling.
NOT NULL
constraints must be explicitly stated in column definitions that includePRIMARY KEY
specifiers. For historical reasons, SQLiteallows NULL primary keys in most cases. When a table‘s primary key is composed of multiple columns, each column’s definition should have aNOT NULL
constraint.
Columns should avoidDEFAULT
values. Columns that haveNOT NULL
constraints and lack aDEFAULT
value are easier to review and maintain, as SQLite takes over the burden of checking thatINSERT
statements aren't missing these columns.
Surrogate primary keys should use the column typeINTEGER PRIMARY KEY
, to take advantage of SQLite's rowid optimizations.AUTOINCREMENT
should only be used where primary key reuse would be unacceptable.
SQLite exposes a vast array of functionality via SQL statements, many of which are not a good match for average Chrome feature code. Use them with care and if you know what you're doing.
PRAGMA
statements should never be used directly. Chrome's SQLite abstraction layer should be modified to support the desired effects instead.
DirectPRAGMA
use limits our ability to customize and secure our SQLite build.PRAGMA
statements may turn on code paths with less testing / fuzzing coverage. Furthermore, somePRAGMA
statements invalidate previously compiled queries, reducing the efficiency of Chrome's compiled query cache.
SQL foreign key constraints should not be used. All data validation should be performed using explicitSELECT
statements (generally wrapped as helper methods) inside transactions. Cascading deletions should be performed using explicitDELETE
statements inside transactions.
Chrome features cannot rely on foreign key enforcement, due to the possibility of data corruption. Furthermore, foreign key constraints make it more difficult to reason about system behavior (Chrome feature code + SQLite) when the database gets corrupted. Foreign key constraints also make it more difficult to reason about query performance.
As a result, foreign key constraints are not enforced on SQLite databases opened with Chrome'ssql::Database
infrastructure.
AfterWebSQL is removed from Chrome, we plan to disable SQLite's foreign key support usingSQLITE_OMIT_FOREIGN_KEY.
SQL CHECK constraints should not be used, for the same reasons as foreign key constraints. The equivalent checks should be performed in C++, typically usingDCHECK
.
AfterWebSQL is removed from Chrome, we plan to disable SQLite's CHECK constraint support usingSQLITE_OMIT_CHECK.
SQL triggers should be used thoughtfully.
Use triggers only if theyincrease legibility andreduce query complexity. The vast majority of Chrome features should not need triggers as their SQL queries are typically very simple, and triggers can obfuscate behavior by introducing an easy-to-miss side effect to certain queries. It's generally preferred to “manually” execute a second query with the desired effect.
There are exceptions to this rule, such as when the follow-up query would itself be much more complex than the trigger, and/or a single trigger can take the place of multiple queries.
Triggers are disabled by default, with hopes that this will encourage feature authors to carefully weigh their use against the alternatives, but can be enabled viaDatabaseOptions::set_triggers_enabled()
.
SQL Common Table Expressions (CTEs) should not be used. Chrome's SQL schemas and queries should be simple enough that the factoring afforded byordinary CTEs is not necessary.Recursive CTEs should be implemented in C++.
Common Table Expressions do not open up any query optimizations that would not be available otherwise, and make it more difficult to review / analyze queries.
SQL views, managed by theCREATE VIEW
statement and theDROP VIEW
statement, should not be used. Chrome's SQL schemas and queries should be simple enough that the factoring afforded by views is not necessary.
Views are syntactic sugar, and do not open up any new SQL capabilities. SQL statements on views are more difficult to understand and maintain, because of the extra layer of indirection.
Access to views is disabled by default for SQLite databases opened with Chrome'ssql::Database
infrastructure. This is intended to steer feature developers away from the discouraged feature.
AfterWebSQL is removed from Chrome, we plan to disable SQLite's VIEW support usingSQLITE_OMIT_VIEW.
String literals should always be single-quoted. That being said, string literals should be rare in Chrome code, because any user input must be injected using statement parameters and theStatement::Bind*()
methods.
Double-quoted string literals are non-standard SQL syntax. The SQLite authorscurrently consider this be a misfeature.
SQLite support for double-quoted string literals is disabled for databases opened with Chrome'ssql::Database
infrastructure.
Compound SELECT statements should not be used. Such statements should be broken down intosimple SELECT statements, and the operatorsUNION
,UNION ALL
,INTERSECT
andEXCEPT
should be implemented in C++.
A single compound SELECT statement is more difficult to review and properly unit-test than the equivalent collection of simple SELECT statements. Furthermore, the compound SELECT statement operators can be implemented more efficiently in C++ than in SQLite's bytecode interpreter (VDBE).
AfterWebSQL is removed from Chrome, we plan to disable SQLite's compound SELECT support usingSQLITE_OMIT_COMPOUND_SELECT.
SQLite'sbuilt-in functions should be only be used in SQL statements where they unlock significant performance improvements. Chrome features should store data in a format that leaves the most room for query optimizations, and perform any necessary transformations after reading / before writing the data.
base::Time
functionality.printf()
andtrim()
are best replaced by C++ code that uses the helpers in//base/strings/
.changes()
,last_insert_rowid()
, andtotal_changes()
, are best replaced by functionality insql::Database
andsql::Statement
.sqlite_source_id()
andsqlite_version()
should not be necessary in Chrome code, and may suggest a problem in the feature's design.Math functions andWindow functions are disabled in Chrome's SQLite build.
ATTACH DATABASE
statements should be used thoughtfully. Each Chrome feature should store its data in a single database. Chrome code should not assume that transactions across multiple databases are atomic.
We aim to disable SQLite features that should not be used in Chrome, subject to the constraint of keeping WebSQL's feature set stable. We currently disable all new SQLite features, to avoid expanding the attack surface exposed to WebSQL. This stance may change once WebSQL is removed from Chrome.
The following SQLite features have been disabled in Chrome.
Chrome features should preferprocotol buffers to JSON for on-disk (persistent) serialization of extensible structured data.
Chrome features should store the values used by indexes directly in their own columns, instead of relying onSQLite's JSON support.
SQLite's UPSERT implementation has been disabled in order to avoid increasing WebSQL's attack surface. UPSERT is disabled using theSQLITE_OMIT_UPSERT
macro, which is not currently included inthe SQLite compile-time option list, but exists in the source code.
We currently think that the new UPSERT functionality is not essential to implementing Chrome features efficiently. An example where UPSERT is necessary for the success of a Chrome feature would likely get UPSERT enabled.
Window functions have been disabled primarily because they cause a significant binary size increase, which leads to a corresponding large increase in the attack surface exposed to WebSQL.
Window functions increase the difficulty of reviewing and maintaining the Chrome features that use them, because window functions add complexity to the mental model of query performance.
We currently think that this maintenance overhead of window functions exceeds any convenience and performance benefits (compared to simpler queries coordinated in C++).
CREATE VIRTUAL TABLE
statements are disabled. The desired functionality should be implemented in C++, and access storage using standard SQL statements.
Virtual tables areSQLite's module system. SQL statements on virtual tables are essentially running arbitrary code, which makes them very difficult to reason about and maintain. Furthermore, the virtual table implementations don't receive the same level of fuzzing coverage as the SQLite core.
Chrome's SQLite build has virtual table functionality reduced to the minimum needed to support an internal feature.SQLite's run-time loading mechanism is disabled, and mostbuilt-in virtual tables are disabled as well.
Ideally we would disable SQLite‘s virtual table support usingSQLITE_OMIT_VIRTUALTABLE now thatWebSQL has been removed from Chrome, but virtual table support is required to use SQLite’sbuilt-in corruption recovery module. TheSQLITE_DBPAGE virtual table is also enabled only for corruption recovery and should not be used in Chrome.