分页结果类
import 'package:kittlenapp/module/base/page_param.dart' ;
import 'package:kittlenapp/utils/base/collection_util.dart' ;
import 'package:kittlenapp/utils/base/map_util.dart' ;
typedef RecordToEmptyFunc < T > = T Function ( Map < dynamic , dynamic > oneRecord) ;
class PageBean < T > {
late int currentPage;
late int numPerPage;
late int totalCount;
late List < T > ? recordList;
late int pageCount;
PageBean ( this . currentPage, this . numPerPage, this . totalCount, this . recordList,
this . pageCount) ;
PageBean . from ( this . totalCount, this . recordList, PageParam pageParam) {
currentPage = pageParam. pageNum;
numPerPage = pageParam. numPerPage;
pageCount = ( totalCount + numPerPage - 1 ) ~/ numPerPage;
}
PageBean . fromByMap ( Map map, RecordToEmptyFunc < T > mapToEmptyFunc) {
List < Map > result = CollectionUtil . toListMap ( map[ 'recordList' ] ) ;
currentPage = MapUtil . mapGetOrDef ( map, 'currentPage' , 1 ) ;
numPerPage = MapUtil . mapGetOrDef ( map, 'numPerPage' , 10 ) ;
totalCount = MapUtil . mapGetOrDef ( map, 'totalCount' , result. length) ;
recordList = result. map ( ( e) = > mapToEmptyFunc ( e) ) . toList ( ) ;
pageCount = MapUtil . mapGetOrDef ( map, 'pageCount' , 1 ) ;
}
}
分页入参类
class PageParam {
int pageNum;
int numPerPage;
PageParam ( { this . pageNum = 1 , this . numPerPage = 10 } )
: assert ( pageNum > 0 && numPerPage > 0 ) ;
String toJson ( ) {
return '{"pageNum": $ pageNum ,"numPerPage": $ numPerPage }' ;
}
}
缓存的基础实体
abstract class CacheSqlLiteBaseEntity {
String table ( ) ;
String createTableSql ( ) ;
String getIdKey ( ) ;
String getId ( ) ;
Map < String , dynamic > toInsertParamsMap ( ) ;
}
工具
import 'dart:io' ;
import 'package:path/path.dart' ;
import 'package:path_provider/path_provider.dart' ;
import 'package:kittlenapp/module/base/cache_sql_lite_base_entity.dart' ;
import 'package:kittlenapp/module/base/page_bean.dart' ;
import 'package:kittlenapp/module/base/page_param.dart' ;
import 'package:kittlenapp/utils/base/collection_util.dart' ;
import 'package:kittlenapp/utils/base/json_util.dart' ;
import 'package:kittlenapp/utils/base/log_util.dart' ;
import 'package:kittlenapp/utils/base/map_util.dart' ;
import 'package:sqflite/sqflite.dart' ;
import 'package:sqflite_common/src/value_utils.dart' ;
typedef CustomDbRum < T > = Future < T > Function ( DBManager ) ;
typedef ResultToEntity < T > = T Function ( Map ) ;
class SqlLiteUtil {
static final DBManager _dbManager = DBManager ( )
. . db. then ( ( value) {
LogUtil . debug ( "sqlLite: db初始化完成" ) ;
} ) ;
static Future < T > transaction< T > ( Future < T > Function ( Transaction txn) action, { bool? exclusive} ) async {
return _dbManager. transaction ( action, exclusive: exclusive) ;
}
static Future < T > customRun< T > ( CustomDbRum < T > customDbRun) {
return customDbRun ( _dbManager) ;
}
Future execute ( String sql, [ List < Object ? > ? arguments] ) async {
return _dbManager. execute ( sql, arguments) ;
}
static Future createTable< T extends CacheSqlLiteBaseEntity > ( String tableSql) {
LogUtil . debug ( "sqlLite: createTable $ tableSql " ) ;
return _dbManager. execute ( tableSql) ;
}
static Future < int> insert< T extends CacheSqlLiteBaseEntity > ( T entity, { ConflictAlgorithm conflictAlgorithm = ConflictAlgorithm . replace} ) async {
Map < String , dynamic > map = entity. toInsertParamsMap ( ) ;
try {
LogUtil . debugFunc ( ( ) {
return "sqlLite: insert ${ entity. table ( ) } params: ${ JsonUtil . toJson ( map) } " ;
} ) ;
return _dbManager. insert ( entity. table ( ) , map, conflictAlgorithm: conflictAlgorithm) ;
} catch ( e) {
return Future . error ( "添加数据失败" ) ;
}
}
static Future batchInsert< T extends CacheSqlLiteBaseEntity > ( Iterable < T > entitys, { ConflictAlgorithm ? conflictAlgorithm} ) async {
if ( CollectionUtil . isEmpty ( entitys) ) {
return Future ( ( ) = > 0 ) ;
}
Map < Type , List < CacheSqlLiteBaseEntity > > mapList = entitys. fold< Map < Type , List < CacheSqlLiteBaseEntity > > > ( { } , ( map, e) {
List < CacheSqlLiteBaseEntity > list = map[ e. runtimeType] ? ? [ ] ;
list. add ( e) ;
map[ e. runtimeType] = list;
return map;
} ) ;
Iterable < _BatchInsertParams? > iterable =
mapList. values. map ( ( e) = > _buildBatchInsertParams ( entitys, conflictAlgorithm: conflictAlgorithm) ) . where ( ( element) = > element != null ) ;
return _dbManager. transaction ( ( txn) {
for ( _BatchInsertParams? params in iterable) {
if ( params != null ) {
txn. rawInsert ( params. sql, params. paraps) ;
}
}
return Future . value ( null ) ;
} ) ;
}
static _BatchInsertParams? _buildBatchInsertParams< T extends CacheSqlLiteBaseEntity > ( Iterable < T > entitys, { ConflictAlgorithm ? conflictAlgorithm} ) {
if ( CollectionUtil . isEmpty ( entitys) ) {
return null ;
}
CacheSqlLiteBaseEntity entity = entitys. first;
List < Map < String , dynamic ? > > mapList = entitys. map ( ( e) = > e. toInsertParamsMap ( ) ) . toList ( ) ;
Map < String , dynamic > entityMap = mapList[ 0 ] ;
List < dynamic > params = [ ] ;
List < String > keys = [ ] ;
StringBuffer insert = StringBuffer ( " insert " ) ;
if ( conflictAlgorithm != null ) {
insert. write ( ' ${ _conflictValues[ conflictAlgorithm. index] } ' ) ;
}
insert. write ( " into ${ entity. table ( ) } ( " ) ;
bool ifFirst = true ;
for ( String key in entityMap. keys) {
keys. add ( key) ;
if ( ifFirst) {
ifFirst = false ;
insert. write ( " $ key " ) ;
} else {
insert. write ( ", $ key " ) ;
}
}
insert. write ( " ) " ) ;
insert. write ( " values " ) ;
bool ifValueFirst = true ;
for ( Map < String , dynamic ? > value in mapList) {
if ( ifValueFirst) {
insert. write ( " ( " ) ;
ifValueFirst = false ;
} else {
insert. write ( ", ( " ) ;
}
ifFirst = true ;
for ( String key in keys) {
if ( ifFirst) {
ifFirst = false ;
insert. write ( " ? " ) ;
} else {
insert. write ( ", ? " ) ;
}
params. add ( value[ key] ) ;
}
insert. write ( " ) " ) ;
}
String sql = insert. toString ( ) ;
LogUtil . debugFunc ( ( ) {
return "sqlLite: $ sql params: ${ JsonUtil . toJson ( params) } " ;
} ) ;
return _BatchInsertParams ( sql, params) ;
}
static Future < int> updateByEntity< T extends CacheSqlLiteBaseEntity > (
T entity,
Map < String , dynamic > updateParams, {
bool igonWhereParamsNull = false ,
} ) {
try {
_WhereValue where = _WhereValue. buildWhereValue ( { entity. getIdKey ( ) : entity. getId ( ) } , igonWhereParamsNull) ;
LogUtil . debugFunc ( ( ) {
return "sqlLite: update ${ entity. table ( ) } params: ${ JsonUtil . toJson ( updateParams) } where: ${ JsonUtil . toJson ( where) } " ;
} ) ;
return _dbManager. update ( entity. table ( ) , updateParams, where: where. whereSql, whereArgs: where. whereArgs) ;
} catch ( e) {
return Future . error ( "修改数据失败 $ e " ) ;
}
}
static Future < int> update ( String table, Map < String , dynamic > updateParams, { Map < String , dynamic > ? whereParams, bool igonWhereParamsNull = false } ) {
try {
_WhereValue where = _WhereValue. buildWhereValue ( whereParams, igonWhereParamsNull) ;
LogUtil . debugFunc ( ( ) {
return "sqlLite: update ${ table } params: ${ JsonUtil . toJson ( updateParams) } where: ${ JsonUtil . toJson ( where) } " ;
} ) ;
return _dbManager. update ( table, updateParams, where: where. whereSql, whereArgs: where. whereArgs) ;
} catch ( e) {
return Future . error ( "修改数据失败 $ e " ) ;
}
}
static Future < int> delete< T extends CacheSqlLiteBaseEntity > ( T entity, Map < String , dynamic > ? whereParams, { bool igonWhereParamsNull = false } ) {
try {
_WhereValue where = _WhereValue. buildWhereValue ( whereParams, igonWhereParamsNull) ;
LogUtil . debugFunc ( ( ) {
return "sqlLite: delete ${ entity. table ( ) } where: ${ JsonUtil . toJson ( where) } " ;
} ) ;
return _dbManager. delete ( entity. table ( ) , where: where. whereSql, whereArgs: where. whereArgs) ;
} catch ( e) {
return Future . error ( "删除数据失败" ) ;
}
}
static Future < int> deleteById< T extends CacheSqlLiteBaseEntity > ( T entity) {
return delete ( entity, { entity. getIdKey ( ) : entity. getId ( ) } ) ;
}
static Future < R ? > getById< R > ( String table, String id,
{ String idKey = "id" ,
List < String > ? retParams,
Map < String , dynamic > ? whereParams,
bool igonWhereParamsNull = false ,
bool distinct = true ,
String ? groupBy,
String ? having,
String ? orderBy,
ResultToEntity < R > ? resultToEntity} ) {
return query ( table, retParams: retParams, whereParams: { idKey: id} , distinct: distinct, groupBy: groupBy, having: having, orderBy: orderBy)
. then ( ( value) {
if ( CollectionUtil . isNotEmpty ( value) ) {
return resultToEntity != null ? resultToEntity ( value[ 0 ] ) : value[ 0 ] ;
} else {
return null ;
}
} ) ;
}
static Future < List < Map < String , Object ? > > ? > rawQuery ( String sql, { List < Object ? > ? arguments} ) {
LogUtil . debug ( "query: $ sql arg: ${ arguments == null ? { } : JsonUtil . toJson ( arguments) } " ) ;
return _dbManager. findBySQL ( sql, arguments: arguments) ;
}
static Future < List < R > > rawEntityQuery< R > ( String sql, ResultToEntity < R > resultToEntity, { List < Object ? > ? arguments} ) {
return rawQuery ( sql, arguments: arguments) . then ( ( value) {
if ( CollectionUtil . isEmpty ( value) ) {
return [ ] ;
} else {
return value! . map ( ( e) {
return resultToEntity ( e) ;
} ) . toList ( ) ;
}
} ) ;
}
static Future < List < R > > entityQuery< R > ( String table, ResultToEntity < R > resultToEntity,
{ List < String > ? retParams,
Map < String , dynamic > ? whereParams,
bool igonWhereParamsNull = false ,
bool distinct = true ,
String ? groupBy,
String ? having,
String ? orderBy} ) {
return query ( table,
retParams: retParams,
whereParams: whereParams,
igonWhereParamsNull: igonWhereParamsNull,
distinct: distinct,
groupBy: groupBy,
having: having,
orderBy: orderBy)
. then ( ( value) {
return value. map ( ( e) {
return resultToEntity ( e) ;
} ) . toList ( ) ;
} ) ;
}
static Future < List > query ( String table,
{ List < String > ? retParams,
Map < String , dynamic > ? whereParams,
bool igonWhereParamsNull = false ,
bool distinct = true ,
String ? groupBy,
String ? having,
String ? orderBy} ) {
try {
_WhereValue where = _WhereValue. buildWhereValue ( whereParams, igonWhereParamsNull) ;
LogUtil . debugFunc ( ( ) {
return "sqlLite: query ${ table } params: ${retParams == null ? " all" : JsonUtil.toJson(retParams)} where: ${ JsonUtil . toJson ( where) } " ;
} ) ;
return _dbManager. findBy ( table,
distinct: distinct,
columns: retParams,
where: where. whereSql,
whereArgs: where. whereArgs,
groupBy: groupBy,
having: having,
orderBy: orderBy) ;
} catch ( e) {
return Future . error ( "查询数据失败 $ e " ) ;
}
}
static Future < PageBean < R > > pageQuery< R > ( String table, PageParam pageParam,
{ List < String > ? retParams,
Map < String , dynamic > ? whereParams,
bool igonWhereParamsNull = false ,
bool distinct = true ,
String ? groupBy,
String ? having,
String ? orderBy,
ResultToEntity < R > ? resultToEntity} ) {
try {
_WhereValue where = _WhereValue. buildWhereValue ( whereParams, igonWhereParamsNull) ;
LogUtil . debugFunc ( ( ) {
return "sqlLite: pageQuery ${ table } retPrams: ${retParams == null ? " all" : JsonUtil.toJson(retParams)} where: ${ JsonUtil . toJson ( where ? ? { } ) } pageParam: ${ JsonUtil . toJson ( pageParam) } " ;
} ) ;
int offset = ( pageParam. pageNum - 1 ) * pageParam. numPerPage;
int limit = pageParam. numPerPage;
return _dbManager
. findBy ( table,
distinct: distinct,
columns: retParams,
where: where. whereSql,
whereArgs: where. whereArgs,
limit: limit,
offset: offset,
groupBy: groupBy,
having: having,
orderBy: orderBy)
. then ( ( value) {
dynamic nResult;
if ( resultToEntity != null ) {
nResult = value. map ( resultToEntity) . toList ( ) ;
} else {
nResult = value;
}
return _dbManager
. countQuery ( table, distinct: distinct, where: where. whereSql, whereArgs: where. whereArgs, groupBy: groupBy, having: having)
. then ( ( count) {
return PageBean . from ( count, nResult, pageParam) ;
} ) ;
} ) ;
} catch ( e) {
return Future . error ( "查询数据失败 $ e " ) ;
}
}
static Future < int> queryCount ( String table, PageParam pageParam,
{ Map < String , dynamic > ? whereParams, bool igonWhereParamsNull = false , bool distinct = true , String ? groupBy, String ? having, String ? orderBy} ) {
try {
_WhereValue where = _WhereValue. buildWhereValue ( whereParams, igonWhereParamsNull) ;
LogUtil . debugFunc ( ( ) {
return "sqlLite: queryCount ${ table } pageParam: ${ JsonUtil . toJson ( pageParam ? ? { } ) } where: ${ JsonUtil . toJson ( where ? ? { } ) } " ;
} ) ;
return _dbManager. countQuery ( table,
where: where. whereSql, whereArgs: where. whereArgs, distinct: distinct, groupBy: groupBy, having: having, orderBy: orderBy) ;
} catch ( e) {
return Future . error ( "查询数据失败 $ e " ) ;
}
}
static final List < String > _conflictValues = < String > [ 'OR ROLLBACK' , 'OR ABORT' , 'OR FAIL' , 'OR IGNORE' , 'OR REPLACE' ] ;
}
class _BatchInsertParams {
String sql;
List < dynamic > paraps;
_BatchInsertParams ( this . sql, this . paraps) ;
}
class _WhereValue {
String ? whereSql;
List < dynamic ? > ? whereArgs;
_WhereValue ( this . whereSql, this . whereArgs) ;
String toJson ( ) {
return JsonUtil . toJson ( { "whereSql" : whereSql, "whereArgs" : whereArgs} ) ;
}
static _WhereValue buildWhereValue ( Map < String , dynamic ? > ? whereParams, bool igonNullParams) {
StringBuffer ? whereSql;
List < dynamic > ? whereArgs;
if ( CollectionUtil . isNotEmpty ( whereParams) ) {
bool isFirst = true ;
whereSql = StringBuffer ( ) ;
whereArgs = [ ] ;
for ( MapEntry < String , dynamic > entity in whereParams! . entries) {
String key = entity. key;
dynamic value = entity. value;
if ( isFirst) {
isFirst = false ;
} else {
whereSql. write ( " and " ) ;
}
if ( value is Iterable ) {
_checkValue ( value) ;
value = value. map ( ( e) {
if ( e is String ) {
return "' $ e '" ;
} else {
return e. toString ( ) ;
}
} ) ;
whereSql. write ( " $ key in ( ${ value. join ( ',' ) } ) " ) ;
} else {
if ( value == null ) {
if ( ! igonNullParams) {
whereSql. write ( " $ key IS NULL " ) ;
}
} else {
_checkValue ( value) ;
whereSql. write ( " $ key =? " ) ;
whereArgs. add ( value) ;
}
}
}
}
return _WhereValue ( whereSql? . toString ( ) , whereArgs) ;
}
static void _checkValue ( dynamic value) {
if ( value == null ) {
return ;
}
if ( value is String ) {
if ( value. contains ( "}" ) || value. contains ( "{" ) || value. contains ( "'" ) || value. contains ( "\"" ) || value. contains ( "(" ) || value. contains ( ")" ) ) {
throw Exception ( "value不能包含特殊符号及括号 $ value " ) ;
}
}
if ( value is List ) {
value. forEach ( ( element) {
_checkValue ( element) ;
} ) ;
}
if ( value is Map ) {
for ( MapEntry entry in value. entries) {
_checkValue ( entry. key) ;
_checkValue ( entry. value) ;
}
}
return ;
}
}
class DBManager {
final String _dbName = "db_kittlen_app" ;
final int _version = 1 ;
static final DBManager _instance = DBManager . _ ( ) ;
factory DBManager ( ) {
return _instance;
}
DBManager . _ ( ) ;
static Database ? _db;
Future < Database > get db async {
return _db ? ? = await _initDB ( ) ;
}
Future < Database > _initDB ( ) async {
Directory directory = await getApplicationDocumentsDirectory ( ) ;
String path = join ( directory. path, _dbName) ;
return await openDatabase (
path,
version: _version,
onCreate: _onCreate,
onUpgrade: _onUpgrade,
) ;
}
Future _onCreate ( Database db, int version) async { }
Future _onUpgrade ( Database db, int oldVersion, int newVersion) async { }
Future < T > transaction< T > ( Future < T > Function ( Transaction txn) action, { bool? exclusive} ) async {
Database database = await db;
return database. transaction ( action, exclusive: exclusive) ;
}
Future < int> insert ( String table, Map < String , Object ? > values, { String ? nullColumnHack, ConflictAlgorithm ? conflictAlgorithm} ) async {
Database database = await db;
return await database. insert ( table, values, nullColumnHack: nullColumnHack, conflictAlgorithm: conflictAlgorithm) ;
}
Future rawInsert ( String sql, List < Object ? > ? arguments) async {
Database database = await db;
return await database. rawInsert ( sql, arguments) ;
}
Future < List < Map < String , Object ? > > > findAll ( String table) async {
Database ? database = await db;
return database. query ( table) ;
}
Future < List < Map < String , Object ? > > > findBy ( String table,
{ bool? distinct,
List < String > ? columns,
String ? where,
List < Object ? > ? whereArgs,
String ? groupBy,
String ? having,
String ? orderBy,
int? limit,
int? offset} ) async {
Database ? database = await db;
return database. query ( table,
distinct: distinct,
columns: columns,
where: where,
whereArgs: whereArgs,
groupBy: groupBy,
having: having,
orderBy: orderBy,
limit: limit,
offset: offset) ;
}
Future < int> countQuery ( String table, { bool? distinct, String ? where, List < Object ? > ? whereArgs, String ? groupBy, String ? having, String ? orderBy} ) {
checkWhereArgs ( whereArgs) ;
final query = StringBuffer ( ) ;
query. write ( "select " ) ;
if ( distinct == true ) {
query. write ( ' DISTINCT ' ) ;
}
query. write ( " count(*) as c from " ) ;
query. write ( table) ;
_writeClause ( query, ' WHERE ' , where) ;
_writeClause ( query, ' GROUP BY ' , groupBy) ;
_writeClause ( query, ' HAVING ' , having) ;
_writeClause ( query, ' ORDER BY ' , orderBy) ;
List < Object ? > ? arguments = whereArgs != null ? List < Object ? > . from ( whereArgs) : null ;
return findBySQL ( query. toString ( ) , arguments: arguments) . then ( ( value) {
if ( CollectionUtil . isEmpty ( value) ) {
return 0 ;
}
return MapUtil . mapGetOrDef ( value! . first, "c" , 0 ) ;
} ) ;
}
Future < List < Map < String , Object ? > > ? > findBySQL ( String sql, { List < Object ? > ? arguments} ) async {
Database ? database = await db;
return database. rawQuery ( sql, arguments) ;
}
Future < int> update ( String table, Map < String , Object ? > values,
{ String ? where, List < Object ? > ? whereArgs, ConflictAlgorithm ? conflictAlgorithm} ) async {
Database ? database = await db;
return database. update ( table, values, where: where, whereArgs: whereArgs, conflictAlgorithm: conflictAlgorithm) ;
}
Future < int> rawUpdate ( String sql, [ List < Object ? > ? arguments] ) async {
Database ? database = await db;
return database. rawUpdate ( sql, arguments) ;
}
Future < int> delete ( String table, { String ? where, List < Object ? > ? whereArgs} ) async {
Database ? database = await db;
return database. delete ( table, where: where, whereArgs: whereArgs) ;
}
Future < int> rawDelete ( String sql, [ List < Object ? > ? arguments] ) async {
Database ? database = await db;
return database. rawDelete ( sql, arguments) ;
}
Future execute ( String sql, [ List < Object ? > ? arguments] ) async {
Database ? database = await db;
return database. execute ( sql, arguments) ;
}
void _writeClause ( StringBuffer s, String name, String ? clause) {
if ( clause != null ) {
s. write ( name) ;
s. write ( clause) ;
}
}
}