step_realtime_db.dart 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import 'dart:async';
  2. import 'package:path/path.dart';
  3. import 'package:sport/bean/step_realtime_entity.dart';
  4. import 'package:sport/pages/run/location.dart';
  5. import 'package:sport/pages/web/statistics.dart';
  6. import 'package:sqflite/sqflite.dart';
  7. class StepRealtimeDB {
  8. static final StepRealtimeDB _instance = new StepRealtimeDB.internal();
  9. factory StepRealtimeDB() => _instance;
  10. static Database? _db;
  11. StepRealtimeDB.internal();
  12. Future<Database> get db async {
  13. if (_db != null) {
  14. return _db!;
  15. }
  16. _db = await initDb();
  17. return _db!;
  18. }
  19. static const String TABLE = 'step';
  20. initDb() async {
  21. String databasesPath = await getDatabasesPath();
  22. String path = join(databasesPath, 'step_realtime.db');
  23. var db = await openDatabase(path, version: 5, onCreate: _onCreate, onUpgrade: _onUpgrade);
  24. return db;
  25. }
  26. int? rid;
  27. FutureOr<void> _onCreate(Database db, int version) async {
  28. await db.execute("CREATE TABLE $TABLE(" +
  29. "id INTEGER PRIMARY KEY, user_id INTEGER, step INTEGER,motion INTEGER, type INTEGER, target INTEGER," +
  30. "start INTEGER, end INTEGER, data TEXT"
  31. ")");
  32. }
  33. FutureOr<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
  34. if (newVersion > oldVersion) {
  35. try {
  36. await db.execute("drop table $TABLE");
  37. } catch (e) {
  38. print(e);
  39. }
  40. }
  41. await _onCreate(db, newVersion);
  42. }
  43. Future<int> save(StepRealtimeEntity entity) async {
  44. var dbClient = await db;
  45. var id = await dbClient.insert(TABLE, entity.toJson());
  46. return id;
  47. }
  48. Future<int> delete(int id) async {
  49. var dbClient = await db;
  50. await dbClient.delete(TABLE, where: "id = ?", whereArgs: [id]);
  51. return 1;
  52. }
  53. Future<int> deleteAll(int userId) async {
  54. var dbClient = await db;
  55. await dbClient.delete(TABLE, where: "user_id = ?", whereArgs: [userId]);
  56. return 1;
  57. }
  58. Future<List<StepRealtimeEntity>> find(int userId, int type) async {
  59. var dbClient = await db;
  60. return (await dbClient.rawQuery('SELECT * FROM $TABLE WHERE user_id = $userId and motion = $type ORDER BY ID DESC')).map((e) => StepRealtimeEntity.fromJson(e)).toList();
  61. }
  62. }