12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- import 'dart:async';
- import 'package:path/path.dart';
- import 'package:sport/provider/bluetooth.dart';
- import 'package:sqflite/sqflite.dart';
- class StepDB {
- static final StepDB _instance = new StepDB.internal();
- factory StepDB() => _instance;
- static Database? _db;
- StepDB.internal();
- Future<Database> get db async {
- if (_db != null) {
- return _db!;
- }
- _db = await initDb();
- return _db!;
- }
- final String TABLE = 'step';
- initDb() async {
- String databasesPath = await getDatabasesPath();
- String path = join(databasesPath, 'step.db');
- var db = await openDatabase(path, version: 5, onCreate: _onCreate, onUpgrade: _onUpgrade);
- return db;
- }
- FutureOr<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
- if (newVersion > oldVersion) {
- try {
- await db.execute("drop table $TABLE");
- } catch (e) {
- print(e);
- }
- }
- await _onCreate(db, newVersion);
- }
- FutureOr<void> _onCreate(Database db, int version) async {
- await db.execute(
- 'CREATE TABLE $TABLE(time INTEGER PRIMARY KEY, step INTEGER, absolute INTEGER, distance INTEGER, shoe VARCHAR)');
- }
- Future<int> insert(PartItem item) async {
- var dbClient = await db;
- var result = await dbClient.insert(TABLE, item.toJson(), conflictAlgorithm: ConflictAlgorithm.replace);
- return result;
- }
- Future insertAll(List<PartItem> items) async {
- var dbClient = await db;
- var batch = dbClient.batch();
- items.forEach((item) {
- batch.insert(TABLE, item.toJson(), conflictAlgorithm: ConflictAlgorithm.replace);
- });
- batch.commit();
- }
- Future<List<Map<String, dynamic>>> find(int start, String id) async {
- var dbClient = await db;
- return await dbClient.rawQuery(
- 'SELECT step as st, distance as di, time FROM $TABLE where time >= $start and shoe = "$id" ORDER BY time');
- }
- Future<List<Map<String, dynamic>>> findHistory(int start, String id) async {
- var dbClient = await db;
- return await dbClient.rawQuery(
- 'SELECT step, absolute as st, distance as di, time FROM $TABLE where time < $start and shoe = "$id" ORDER BY time desc limit 1');
- }
- Future<int> delete(int time, String id) async {
- var dbClient = await db;
- return await dbClient.delete(TABLE, where: "time <= ? and shoe = ?", whereArgs: [time, id]);
- }
- Future<int> deleteAll() async {
- var dbClient = await db;
- return await dbClient.delete(TABLE);
- }
- }
|