step_db.dart 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import 'dart:async';
  2. import 'package:path/path.dart';
  3. import 'package:sport/provider/bluetooth.dart';
  4. import 'package:sqflite/sqflite.dart';
  5. class StepDB {
  6. static final StepDB _instance = new StepDB.internal();
  7. factory StepDB() => _instance;
  8. static Database? _db;
  9. StepDB.internal();
  10. Future<Database> get db async {
  11. if (_db != null) {
  12. return _db!;
  13. }
  14. _db = await initDb();
  15. return _db!;
  16. }
  17. final String TABLE = 'step';
  18. initDb() async {
  19. String databasesPath = await getDatabasesPath();
  20. String path = join(databasesPath, 'step.db');
  21. var db = await openDatabase(path, version: 5, onCreate: _onCreate, onUpgrade: _onUpgrade);
  22. return db;
  23. }
  24. FutureOr<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
  25. if (newVersion > oldVersion) {
  26. try {
  27. await db.execute("drop table $TABLE");
  28. } catch (e) {
  29. print(e);
  30. }
  31. }
  32. await _onCreate(db, newVersion);
  33. }
  34. FutureOr<void> _onCreate(Database db, int version) async {
  35. await db.execute(
  36. 'CREATE TABLE $TABLE(time INTEGER PRIMARY KEY, step INTEGER, absolute INTEGER, distance INTEGER, shoe VARCHAR)');
  37. }
  38. Future<int> insert(PartItem item) async {
  39. var dbClient = await db;
  40. var result = await dbClient.insert(TABLE, item.toJson(), conflictAlgorithm: ConflictAlgorithm.replace);
  41. return result;
  42. }
  43. Future insertAll(List<PartItem> items) async {
  44. var dbClient = await db;
  45. var batch = dbClient.batch();
  46. items.forEach((item) {
  47. batch.insert(TABLE, item.toJson(), conflictAlgorithm: ConflictAlgorithm.replace);
  48. });
  49. batch.commit();
  50. }
  51. Future<List<Map<String, dynamic>>> find(int start, String id) async {
  52. var dbClient = await db;
  53. return await dbClient.rawQuery(
  54. 'SELECT step as st, distance as di, time FROM $TABLE where time >= $start and shoe = "$id" ORDER BY time');
  55. }
  56. Future<List<Map<String, dynamic>>> findHistory(int start, String id) async {
  57. var dbClient = await db;
  58. return await dbClient.rawQuery(
  59. 'SELECT step, absolute as st, distance as di, time FROM $TABLE where time < $start and shoe = "$id" ORDER BY time desc limit 1');
  60. }
  61. Future<int> delete(int time, String id) async {
  62. var dbClient = await db;
  63. return await dbClient.delete(TABLE, where: "time <= ? and shoe = ?", whereArgs: [time, id]);
  64. }
  65. Future<int> deleteAll() async {
  66. var dbClient = await db;
  67. return await dbClient.delete(TABLE);
  68. }
  69. }