数据库 — SQLite
Finch 通过 sqlite3 包支持 SQLite。它与 MySQL 共享相同的 API——使用 MTable/MField* 定义模式,使用 Sqler 进行查询。
配置
FinchConfigs(
sqliteConfig: FinchSqliteConfig(
enable: true,
filePath: env['SQLITE_PATH'] ?? './app.sqlite',
),
)
表定义
// lib/db/sqlite_tables.dart
import 'package:finch/finch_sqlite.dart';
MTable postsTable = MTable(
tableName: 'posts',
fields: [
MFieldId(),
MFieldString(name: 'title', length: 255),
MFieldText(name: 'body'),
MFieldBool(name: 'published', defaultValue: false),
MFieldTimestamp(name: 'created_at', defaultNow: true),
],
);
使用 Sqler 进行查询
与 MySQL 相同的 API——只需使用 sqliteDb 代替 mysqlDb:
import 'package:finch/finch_sqlite.dart';
var sqler = Sqler(table: postsTable, db: sqliteDb);
// 获取所有已发布的文章
var posts = await sqler
.where('published', '=', true)
.orderBy('created_at', desc: true)
.get();
// 插入
var id = await sqler.insert({
'title': '第一篇文章',
'body': '文章内容...',
'published': true,
});
// 更新
await sqler.where('id', '=', id).update({'published': false});
// 删除
await sqler.where('id', '=', id).delete();
SQLite 迁移
使用 --sqlite 标志执行迁移命令:
# 应用 SQLite 迁移
finch migrate --init --sqlite
# 创建新的 SQLite 迁移文件
finch migrate --create --name add_posts_table --sqlite
迁移文件位于 pathMigrationSQLite(默认:./migrations_sqlite/)。
与 MySQL 的区别
| 功能 | MySQL | SQLite |
|---|---|---|
| Driver 导入 | finch_mysql.dart |
finch_sqlite.dart |
| db 参数 | mysqlDb |
sqliteDb |
| 迁移标志 | (无标志) | --sqlite |
| 迁移目录 | ./migrations |
./migrations_sqlite |
| 存储 | 独立服务器 | 本地 .sqlite 文件 |