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 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 _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 _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 insert(PartItem item) async { var dbClient = await db; var result = await dbClient.insert(TABLE, item.toJson(), conflictAlgorithm: ConflictAlgorithm.replace); return result; } Future insertAll(List items) async { var dbClient = await db; var batch = dbClient.batch(); items.forEach((item) { batch.insert(TABLE, item.toJson(), conflictAlgorithm: ConflictAlgorithm.replace); }); batch.commit(); } Future>> 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>> 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 delete(int time, String id) async { var dbClient = await db; return await dbClient.delete(TABLE, where: "time <= ? and shoe = ?", whereArgs: [time, id]); } Future deleteAll() async { var dbClient = await db; return await dbClient.delete(TABLE); } }