insertOrReplace method
Implementation
Future<int?> insertOrReplace(SqliteBaseTableData data) async {
await _initialize();
bool isTableExists = await _isTableExists(data.tableName());
if (!isTableExists) {
await _createTable(data.getValues(), data.tableName());
}
var list = data.getValues().where((element) => element.isPrimaryKey);
String where = "";
List<dynamic> whereArgs = [];
for (var element in list) {
where = "$where${element.key} = ?";
whereArgs.add(element.value);
}
var existingRecord = await _database?.query(data.tableName(),
where: where, whereArgs: whereArgs);
if (existingRecord != null && existingRecord.isNotEmpty) {
try {
return await _database?.update(
data.tableName(), _getData(data.getValues()));
} catch (e) {
var columns = existingRecord.first.keys.toList();
List<ValueProperty> addValueProperty = [];
data.getValues().forEach((element) {
bool isContainer = false;
for (String key in columns) {
if (key == element.key) {
isContainer = true;
}
}
if (!isContainer) {
addValueProperty.add(element);
}
});
if (addValueProperty.isNotEmpty) {
await _updateTab(addValueProperty, data.tableName());
}
return await _database?.update(
data.tableName(), _getData(data.getValues()));
}
} else {
return await _database?.insert(
data.tableName(), _getData(data.getValues()));
}
}