There are two ways to define a table in Drift - using Dart code or using SQL code.
Dart code is easier, but SQL code is more powerful and decouples the table definition from the Dart code.
Generally, SQL code is preferred.
See how to define tables using Dart code and SQL code below.
SQL code is defined in .drift files. The following example defines the same table as above:
To make code generation work, you must point to the .drift file or dart Table in the @DriftDatabase annotation:
Column types
Drift supports the following column types:
INTEGER - INTEGER
double - REAL
bool - INTEGER (0 or 1)
String - TEXT
DateTime - INTEGER (Unix timestamp) or TEXT
Uint8List - BLOB
Enum - INTEGER
Keys
Keys are used to enforce uniqueness of rows and to reference rows from other tables.
Drift supports the following keys:
Primary Key
Primary key is a column or a set of columns that uniquely identify a row in a table.
It is used to enforce uniqueness of rows and to reference rows from other tables.
Drift automatically defines a primary key if you use autoIncrement():
Foreign key is a column (or collection of columns) in one table that uniquely identifies a row of another table.
The role of a foreign key is to enforce referential integrity within the database.
To reference a column from another table, use references:
Auto-incrementing columns are used to automatically generate a unique value for each new row.
To define an auto-incrementing column, use autoIncrement:
In a one-to-one relationship between two tables, there can exist either zero or one record on each side of the relationship for a given primary key value.
This means each primary key value in one table relates to at most one record in the other table.
Consider the following code that defines a one-to-one relationship between Persons and Passports:
In a many-to-many relationship between two tables, a row in one table can have multiple matching rows in the other table, and vice versa.
Creating a many-to-many relationship involves three tables: two main tables and a junction table that links the records in the main tables.
Let’s consider an example with two entities, authors and books, where an author can write many books and a book can have many authors.
Dart code is known for its simplicity and beginner-friendly nature.
However, SQL, with its numerous benefits, stands as a preferable choice in many scenarios.
It’s recommended to invest time in understanding SQL, given its superior capabilities.
SQL’s strength lies in its ability to separate table definitions from Dart code, granting access to the full spectrum of SQL’s features.
In situations demanding the creation of intricate tables or the formulation of extensive queries, SQL’s performance surpasses that of Dart code.
Moreover, SQL’s syntax is not only more legible but also simpler to manage and maintain over time.