import 'dart:async'; import 'package:chat/data/UserData.dart'; import 'package:chat/utils/sql_util.dart'; import 'package:sqflite/sqflite.dart'; class BaseModel { Database db; final String table = ''; var query; BaseModel(this.db) { query = db.query; } } class Sql extends BaseModel { final String tableName; Sql.setTable(String name) : tableName = name, super(SqlUtil.getCurrentDatabase()); Future get() async { var myId = UserData().basicInfo.userId; return await this.query(tableName, where: 'userId = $myId'); } Future getAll() async { var myId = UserData().basicInfo.userId; var result = await this.query(tableName, where: 'userId = $myId'); return result.toList(); } String getTableName() { return tableName; } Future delete(String value, String key) async { return await this.db.delete(tableName, where: '$key = ? and userId = ?', whereArgs: [value, UserData().basicInfo.userId]); } Future createTable(String tableName, String colums) async { return await this .db .execute('CREATE TABLE IF NOT EXISTS $tableName ($colums)'); } Future clearTable(String tableName) async { return await this.db.delete(tableName); } Future getByCondition({Map conditions}) async { if (conditions == null || conditions.isEmpty) { return this.get(); } String stringConditions = ''; int index = 0; conditions.forEach((key, value) { if (value == null) { return; } if (value.runtimeType == String) { stringConditions = '$stringConditions $key = "$value"'; } if (value.runtimeType == int) { stringConditions = '$stringConditions $key = $value'; } if (index >= 0 && index < conditions.length - 1) { stringConditions = '$stringConditions and'; } index++; }); var myId = UserData().basicInfo.userId; if (stringConditions.length > 0) { stringConditions = '$stringConditions and userId = $myId'; } return await this.query(tableName, where: stringConditions); } Future> insert(Map json) async { var id = await this.db.insert(tableName, json); json['id'] = id; return json; } /// /// 搜索 /// @param Object condition /// @mods [And, Or] default is Or /// search({'name': "hanxu', 'id': 1}; /// Future search( {Map conditions, String mods = 'Or'}) async { if (conditions == null || conditions.isEmpty) { return this.get(); } String stringConditions = ''; int index = 0; conditions.forEach((key, value) { if (value == null) { return; } if (value.runtimeType == String) { stringConditions = '$stringConditions $key like "%$value%"'; } if (value.runtimeType == int) { stringConditions = '$stringConditions $key = "%$value%"'; } if (index >= 0 && index < conditions.length - 1) { stringConditions = '$stringConditions $mods'; } index++; }); var myId = UserData().basicInfo.userId; if (stringConditions.length > 0) { stringConditions = '$stringConditions and userId = $myId'; } return await this.query(tableName, where: stringConditions); } }