Advertisement
DVS_studio

dart db

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