You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
timemanager/lib/db/timer_entry_database.dart

116 lines
2.9 KiB

import 'package:sqflite/sqflite.dart';
import 'package:timemanage/model/timer_entry.dart';
class TimerEntryDatabase {
static final TimerEntryDatabase instance = TimerEntryDatabase._init();
static Database? _database;
TimerEntryDatabase._init();
/// 以上暂时理解为固定格式
// 获取数据库
Future<Database> get database async {
if (_database != null) {
return _database!;
}
_database = await _initDB('timer_entry.db');
return _database!;
}
// 初始化数据库
Future<Database> _initDB(String filePath) async {
final dbPath = await getDatabasesPath();
final path = dbPath + filePath;
// 打开数据库
return await openDatabase(path, version: 1, onCreate: _createDB);
}
// 创建数据库
Future _createDB(Database db, int version) async {
// 创建表
const idType = 'INTEGER PRIMARY KEY AUTOINCREMENT';
const textType = 'TEXT NOT NULL';
const nullTextType = 'TEXT';
// 创建计时器表
await db.execute('''
CREATE TABLE $tableTimerEntry (
${TimerEntryFields.id} $idType,
${TimerEntryFields.name} $textType,
${TimerEntryFields.createdAt} $textType,
${TimerEntryFields.endAt} $nullTextType,
${TimerEntryFields.isActive} $textType,
${TimerEntryFields.stopWatch} $textType
)
''');
}
/// CRUD
// 创建计时器
Future<TimerEntry> create(TimerEntry timerEntry) async {
final db = await instance.database;
// 获取计时器ID
final id = await db.insert(tableTimerEntry, timerEntry.toJson());
return timerEntry.copy(id: id);
}
// 获取计时器
Future<TimerEntry> read(int id) async {
final db = await instance.database;
final maps = await db.query(tableTimerEntry,
columns: TimerEntryFields.values,
where: '${TimerEntryFields.id} = ?',
whereArgs: [id]);
if (maps.isNotEmpty) {
return TimerEntry.fromJson(maps.first);
} else {
throw Exception('ID $id not found');
}
}
// 获取所有计时器
Future<List<TimerEntry>> readAll() async {
final db = await instance.database;
// 插入一条测试数据
// await db.insert(
// tableTimerEntry,
// TimerEntry(
// name: '测试计时器',
// ).toJson());
final result = await db.query(tableTimerEntry);
return result.map((json) => TimerEntry.fromJson(json)).toList();
}
// 更新计时器
Future<int> update(TimerEntry timerEntry) async {
final db = await instance.database;
return db.update(tableTimerEntry, timerEntry.toJson(),
where: '${TimerEntryFields.id} = ?', whereArgs: [timerEntry.id]);
}
// 删除计时器
Future<int> delete(int id) async {
final db = await instance.database;
return await db.delete(tableTimerEntry,
where: '${TimerEntryFields.id} = ?', whereArgs: [id]);
}
// 关闭数据库
Future close() async {
final db = await instance.database;
db.close();
}
}