Created
January 17, 2019 17:54
-
-
Save hjJunior/f3664317189cb02af4fb1a4932dd3095 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'dart:async'; | |
| import 'package:sqflite/sqflite.dart'; | |
| import 'package:reflectable/reflectable.dart'; | |
| Database db; | |
| /// A Model abstract class | |
| abstract class Model<T> { | |
| static String primaryKey; | |
| static String table; | |
| Map<String, String> mapDatabase; | |
| /// Define if already exists on database | |
| bool _exists; | |
| Future<int> save() { | |
| /// If the model already exists in the database we can just update our record | |
| /// that is already in this database using the current IDs in this "where" | |
| /// clause to only update this model. Otherwise, we'll just insert them. | |
| if (_exists) { | |
| return _performUpdate(); | |
| } else { | |
| return _performInsert(); | |
| } | |
| } | |
| Future<int> delete() { | |
| if (!_exists) { | |
| return null; | |
| } | |
| return _performDelete(); | |
| } | |
| /// Gets the actual data on mapDatabase and insert on database | |
| Future<int> _performInsert() => db.insert( | |
| table, | |
| mapDatabase, | |
| conflictAlgorithm: ConflictAlgorithm.replace | |
| ); | |
| /// Using the primary key filter where to update the data | |
| /// and set the new data de according with mapDatabase data | |
| Future<int> _performUpdate() => db.update( | |
| table, | |
| mapDatabase, | |
| where: "$primaryKey = ?", | |
| whereArgs: [mapDatabase[primaryKey]], | |
| conflictAlgorithm: ConflictAlgorithm.replace | |
| ); | |
| /// Delete the | |
| Future<int> _performDelete() => db.delete( | |
| table, | |
| where: "$primaryKey = ?", | |
| whereArgs: [mapDatabase[primaryKey]] | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment