Database Schema
Define and manage your database schema using PocketSync’s schema classes
PocketSync provides a set of classes to define and manage your database schema in a type-safe way. This approach gives you better control over your database structure and helps prevent errors.
Overview
The schema system allows you to:
- Define table structures with strongly-typed columns
- Create indexes for better query performance
- Define relationships between tables
- Generate SQL statements for creating tables and indexes
Core components
ColumnType
An enum representing the supported data types for database columns.
TableColumn
Represents a column in a database table with its properties and constraints.
Factory constructors
TableColumn
provides several factory constructors for creating columns of different types:
Constructor | Description |
---|---|
TableColumn.primaryKey() | Creates a primary key column |
TableColumn.text() | Creates a text column |
TableColumn.integer() | Creates an integer column |
TableColumn.real() | Creates a real (floating point) column |
TableColumn.boolean() | Creates a boolean column (stored as INTEGER) |
TableColumn.blob() | Creates a blob column |
TableColumn.datetime() | Creates a datetime column (stored as INTEGER timestamp) |
TableColumn.foreignKey() | Creates a foreign key column |
TableReference
Represents a reference to another table and column, used for defining foreign keys.
Index
Represents an index on a database table for improved query performance.
TableSchema
Represents the schema for a database table, including its columns and indexes.
Virtual Tables
SQLite supports virtual tables for special use cases like full-text search. You can create a virtual table schema using the TableSchema.virtual()
constructor:
DatabaseSchema
Represents the complete schema for a database, including all tables.
Using schemas with PocketSync
You can use the schema classes to define your database structure and generate SQL statements for creating tables and indexes:
Best practices
-
Define schemas in a central location: Keep all your table schemas in a dedicated file or class for better organization.
-
Use meaningful names: Choose clear, descriptive names for tables, columns, and indexes.
-
Add indexes for frequently queried columns: This improves query performance, especially for large tables.
-
Use foreign keys for relationships: This helps maintain data integrity between related tables.
-
Consider using a repository pattern: Combine schemas with a repository pattern for a clean, maintainable data access layer.