Advertisement
DVS_studio

SQLiteDart

Dec 10th, 2018
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 10.27 KB | None | 0 0
  1. import 'dart:async';
  2. import 'dart:io';
  3.  
  4. import 'package:path/path.dart';
  5. import 'package:path_provider/path_provider.dart';
  6. import 'package:sqflite/sqflite.dart';
  7.  
  8. String dbName = "db";
  9. int dbVersion = 1;
  10.  
  11. class DataBase {
  12.   static Database db;
  13.  
  14.   Future<bool> open() async {
  15.     Directory documentsDirectory = await getApplicationDocumentsDirectory();
  16.     String path = context.join(documentsDirectory.path, dbName + ".db");
  17.     var needRecreate = false;
  18.     db = await openDatabase(path, version: dbVersion, onCreate: (Database db, int version) {
  19.       db.execute('''CREATE TABLE config (`key` text primary key not null, `value` text default null)''');
  20.     }, onUpgrade: (Database db, int versionOld, int versionNew) async {
  21.       if (versionOld < 4) needRecreate = true;
  22.     });
  23.     if (needRecreate) {
  24.       await close();
  25.       await deleteDatabase(path);
  26.       return false;
  27.     }
  28.     return true;
  29.   }
  30.  
  31.   Future close() async => db.close();
  32.  
  33.   String _table = '';
  34.   List<String> _select = ['i.*'];
  35.  
  36.   String _join = '';
  37.   String _where = '';
  38.   String _whereSeparator = 'AND';
  39.   String _groupBy = '';
  40.   String _orderBy = '';
  41.   String _limit = '1000';
  42.   int _perpage = 50;
  43.  
  44.   bool _keepFilters = false;
  45.   bool _filterOn = false;
  46.  
  47.   DataBase select(String field, {String as}) {
  48.     _select.add(as != null ? field + ' as `' + as + '`' : field);
  49.     return this;
  50.   }
  51.  
  52.   DataBase selectOnly(String field, {String as}) {
  53.     _select = [];
  54.     _select.add(as != null ? field + ' as `' + as + '`' : field);
  55.     return this;
  56.   }
  57.  
  58.   DataBase join(String tableName, as, on) {
  59.     return this.joinInner(tableName, as, on);
  60.   }
  61.  
  62.   DataBase joinInner(tableName, as, on) {
  63.     _join += 'INNER JOIN ' + tableName + ' as ' + as + ' ON ' + on;
  64.     return this;
  65.   }
  66.  
  67.   DataBase joinLeft(tableName, as, on) {
  68.     _join += 'LEFT OUTER JOIN ' + tableName + ' as ' + as + ' ON ' + on;
  69.     return this;
  70.   }
  71.  
  72.   DataBase joinCross(tableName, as) {
  73.     _join += 'CROSS JOIN ' + tableName + ' as ' + as;
  74.     return this;
  75.   }
  76.  
  77.   DataBase groupBy(String field) {
  78.     if (!field.contains("\.")) field = 'i.`' + field + '`';
  79.     _groupBy = field;
  80.     return this;
  81.   }
  82.  
  83.   DataBase orderBy(String field, {String direction = 'asc'}) {
  84.     if (field.contains("(")) {
  85.       return this;
  86.     }
  87.     if (!field.contains("\.")) field = 'i.`' + field + '`';
  88.     _orderBy = field + ' ' + direction;
  89.     return this;
  90.   }
  91.  
  92.   DataBase limit(int from, {int count = 0}) {
  93.     _limit = from.toString();
  94.     if (from < 0) {
  95.       _limit = '0';
  96.     }
  97.     if (count != 0) {
  98.       if (count <= 0) {
  99.         count = 15;
  100.       }
  101.       _limit += ', ' + count.toString();
  102.     }
  103.     return this;
  104.   }
  105.  
  106.   DataBase limitPage(int page, {int perpage = 0}) {
  107.     if (perpage <= 0) {
  108.       perpage = _perpage;
  109.     }
  110.     this.limit((page - 1) * perpage, count: perpage);
  111.     return this;
  112.   }
  113.  
  114.   DataBase limitPagePlus(int page, {int perpage = 0}) {
  115.     if (perpage <= 0) {
  116.       perpage = _perpage;
  117.     }
  118.     this.limit((page - 1) * perpage, count: perpage + 1);
  119.     return this;
  120.   }
  121.  
  122.   DataBase setPerPage(perpage) {
  123.     _perpage = perpage;
  124.     return this;
  125.   }
  126.  
  127.   DataBase lockFilters() {
  128.     _keepFilters = true;
  129.     return this;
  130.   }
  131.  
  132.   DataBase unlockFilters() {
  133.     _keepFilters = false;
  134.     return this;
  135.   }
  136.  
  137.   DataBase resetFilters() {
  138.     _select = ['i.*'];
  139.     _groupBy = '';
  140.     _orderBy = '';
  141.     _limit = '';
  142.     _join = '';
  143.     if (_keepFilters) {
  144.       return this;
  145.     }
  146.     _filterOn = false;
  147.     _where = '';
  148.     return this;
  149.   }
  150.  
  151.   DataBase filter(String condition) {
  152.     if (_filterOn) {
  153.       _where += ' ' + _whereSeparator + ' (' + condition + ')';
  154.     } else {
  155.       _where += '(' + condition + ')';
  156.       _filterOn = true;
  157.     }
  158.     _whereSeparator = ' AND ';
  159.     return this;
  160.   }
  161.  
  162.   DataBase filterStart() {
  163.     if (_filterOn) {
  164.       _where += ' ' + _whereSeparator + ' (';
  165.     } else {
  166.       _where += '(';
  167.     }
  168.     _filterOn = false;
  169.     return this;
  170.   }
  171.  
  172.   DataBase filterEnd() {
  173.     _where += ' ) ';
  174.     return this;
  175.   }
  176.  
  177.   DataBase filterAnd() {
  178.     _whereSeparator = ' AND ';
  179.     return this;
  180.   }
  181.  
  182.   DataBase filterOr() {
  183.     _whereSeparator = ' OR ';
  184.     return this;
  185.   }
  186.  
  187.   DataBase filterNotNull(field) {
  188.     if (!field.contains("\.")) field = 'i.`$field`';
  189.     this.filter(field + ' IS NOT NULL');
  190.     return this;
  191.   }
  192.  
  193.   DataBase filterIsNull(String field) {
  194.     if (!field.contains("\.")) field = 'i.`$field`';
  195.     this.filter(field + ' IS NULL');
  196.     return this;
  197.   }
  198.  
  199.   DataBase filterEqual(String field, value) {
  200.     if (!field.contains("\.")) field = 'i.`$field`';
  201.     if (value == null) {
  202.       this.filter(field + ' IS NULL');
  203.     } else {
  204.       this.filter("$field = '${value.toString()}'");
  205.     }
  206.     return this;
  207.   }
  208.  
  209.   DataBase filterNotEqual(String field, String value) {
  210.     if (!field.contains("\.")) field = 'i.`$field`';
  211.     if (value == null) {
  212.       this.filter(field + ' IS NOT NULL');
  213.     } else {
  214.       this.filter("$field <> '$value'");
  215.     }
  216.     return this;
  217.   }
  218.  
  219.   DataBase filterGt(String field, String value) {
  220.     if (!field.contains("\.")) field = 'i.`$field`';
  221.     this.filter("$field > '$value'");
  222.     return this;
  223.   }
  224.  
  225.   DataBase filterLt(String field, String value) {
  226.     if (!field.contains("\.")) field = 'i.`$field`';
  227.     this.filter("$field < '$value'");
  228.     return this;
  229.   }
  230.  
  231.   DataBase filterGtEqual(String field, String value) {
  232.     if (!field.contains("\.")) field = 'i.`$field`';
  233.     this.filter("$field >= '$value'");
  234.     return this;
  235.   }
  236.  
  237.   DataBase filterLtEqual(String field, String value) {
  238.     if (!field.contains("\.")) field = 'i.`$field`';
  239.     this.filter("$field <= '$value'");
  240.     return this;
  241.   }
  242.  
  243.   DataBase filterLike(String field, String value) {
  244.     if (!field.contains("\.")) field = 'i.`$field`';
  245.     this.filter("$field LIKE '$value'");
  246.     return this;
  247.   }
  248.  
  249.   DataBase filterBetween(String field, String start, String end) {
  250.     if (!field.contains("\.")) field = 'i.`$field`';
  251.     this.filter("$field BETWEEN '$start' AND '$end'");
  252.     return this;
  253.   }
  254.  
  255.   String getSQL() {
  256.     String select = _select.join(", ");
  257.     String sql = "SELECT $select FROM $_table i ";
  258.     if (_join.length > 0) {
  259.       sql += _join + " ";
  260.     }
  261.     if (_where.length > 0) {
  262.       sql += 'WHERE ' + _where + " ";
  263.     }
  264.     if (_groupBy.length > 0) {
  265.       sql += 'GROUP BY ' + _groupBy + " ";
  266.     }
  267.     if (_orderBy.length > 0) {
  268.       sql += 'ORDER BY ' + _orderBy + " ";
  269.     }
  270.     if (_limit.length > 0) {
  271.       sql += 'LIMIT ' + _limit;
  272.     }
  273.     return sql;
  274.   }
  275.  
  276.   Future<dynamic> getField(String table, String rowId, String field, {String filterField = 'id'}) {
  277.     this.filterEqual(filterField, rowId);
  278.     return this.getFieldFiltered(table, field);
  279.   }
  280.  
  281.   Future<dynamic> getFieldFiltered(String table, String field) async {
  282.     _select = ['i.' + field + ' as ' + field];
  283.     _table = table;
  284.     this.limit(1);
  285.     String sql = this.getSQL();
  286.     this.resetFilters();
  287.     List<Map> result = await db.rawQuery(sql);
  288.     if (result.length == 0) return null;
  289.  
  290.     return result[0][field];
  291.   }
  292.  
  293.   Future<T> getItem<T>(String table, {T callback(Map<String, dynamic> item)}) async {
  294.     _table = table;
  295.     this.limit(1);
  296.     String sql = this.getSQL();
  297.  
  298.     this.resetFilters();
  299.     List<Map> result = await db.rawQuery(sql);
  300.     if (result.length == 0) return null;
  301.     Map item = result[0];
  302.     if (callback != null) return callback(item);
  303.     return item as T;
  304.   }
  305.  
  306.   Future<T> getItemById<T>(String table, int id, {T callback(Map<String, dynamic> item)}) {
  307.     this.filterEqual('id', id);
  308.     return this.getItem<T>(table, callback: callback);
  309.   }
  310.  
  311.   Future<T> getItemByField<T>(String table, String field, value, {T callback(Map<String, dynamic> item)}) {
  312.     this.filterEqual(field, value);
  313.     return this.getItem<T>(table, callback: callback);
  314.   }
  315.  
  316.   Future<List<T>> get<T>(String table, {T callback(Map<String, dynamic> item)}) async {
  317.     _table = table;
  318.     String sql = this.getSQL();
  319.     this.resetFilters();
  320.     List<Map> result = await db.rawQuery(sql);
  321.     if (result.length == 0) return [];
  322.     List<T> ret = [];
  323.     for (Map<String, dynamic> item in result) {
  324.       if (callback != null)
  325.         ret.add(callback(item));
  326.       else
  327.         ret.add(item as T);
  328.     }
  329.     return ret;
  330.   }
  331.  
  332.   Future<int> delete(String table, value, {String field = 'id'}) {
  333.     this.filterEqual(field, value);
  334.     return this.deleteFiltered(table);
  335.   }
  336.  
  337.   Future<int> deleteFiltered(table) {
  338.     String where = _where;
  339.     this.resetFilters();
  340.  
  341.     String sql = "DELETE FROM $table WHERE ${where.replaceAll("i\.", "")};";
  342.     return db.rawDelete(sql);
  343.   }
  344.  
  345.   Future<int> truncate(table) {
  346.     return db.rawDelete("DELETE FROM $table;");
  347.   }
  348.  
  349.   Future<int> update(String table, value, Map<String, dynamic> data, {String field = 'id'}) {
  350.     this.filterEqual(field, value);
  351.     return this.updateFiltered(table, data);
  352.   }
  353.  
  354.   Future<int> updateFiltered(String table, Map<String, dynamic> data) {
  355.     String where = _where;
  356.     this.resetFilters();
  357.     List keys = data.keys.map((var l) => "`$l`=?").toList();
  358.     String sql = "UPDATE $table SET ${keys.join(",")} WHERE ${where.replaceAll("i\.", "")};";
  359.     return db.rawUpdate(sql, data.values.toList());
  360.   }
  361.  
  362.   Future insertList(String table, List<Map<String, dynamic>> dataset) async {
  363.     List keys = dataset.first.keys.map((var l) => "`$l`").toList();
  364.     List vals = keys.map((var l) => "?").toList();
  365.     String sql = "INSERT OR REPLACE INTO `$table` ( ${keys.join(",")} ) VALUES ( ${vals.join(",")} );";
  366.     return db.transaction((txn) async {
  367.       var batch = txn.batch();
  368.       for (Map<String, dynamic> data in dataset) {
  369.         batch.execute(sql, data.values.toList());
  370.       }
  371.       await batch.commit();
  372.     });
  373.   }
  374.  
  375.   Future<int> insert(String table, Map data) async {
  376.     return await db.insert(table, data);
  377.   }
  378.  
  379.   Future<int> updateOrInsert(String table, Map data) async {
  380.     List keys = data.keys.map((var l) => "`$l`").toList();
  381.     List vals = keys.map((var l) => "?").toList();
  382.     String sql = "INSERT OR REPLACE INTO `$table` ( ${keys.join(",")} ) VALUES ( ${vals.join(",")} );";
  383.     return db.rawInsert(sql, data.values.toList());
  384.   }
  385. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement