bulkInsert method
Future<bool>
bulkInsert(
- List<
Map< data, {String, dynamic> > - ConflictAction conflictAction = ConflictAction.ignore,
- List<
String> ? conflictColumns, - List<
String> ? updateColumns, - int batchSize = 1000,
- bool returnIds = false,
inherited
Implementation
@override
Future<bool> bulkInsert(
List<Map<String, dynamic>> data, {
ConflictAction conflictAction = ConflictAction.ignore,
List<String>? conflictColumns,
List<String>? updateColumns,
int batchSize = 1000,
bool returnIds = false,
}) async {
if (data.isEmpty) {
throw InvalidArgumentException(
'Data cannot be empty for bulk insert operation');
}
try {
final conn = await getConnection();
for (int i = 0; i < data.length; i += batchSize) {
final batch = data.skip(i).take(batchSize).toList();
final paramBindings = <String, dynamic>{};
final columns = batch.first.keys.toList();
final valueGroups = <String>[];
for (var row in batch) {
final placeholders = columns.map((column) {
final paramName = _nextParamName();
paramBindings[paramName] = row[column];
return ":$paramName";
}).join(", ");
valueGroups.add("($placeholders)");
}
String sql =
"INSERT INTO $getTable (${columns.join(', ')}) VALUES ${valueGroups.join(', ')}";
if (conflictAction == ConflictAction.ignore) {
sql =
"INSERT IGNORE INTO $getTable (${columns.join(', ')}) VALUES ${valueGroups.join(', ')}";
} else if (conflictAction == ConflictAction.update &&
conflictColumns != null) {
final updateCols = updateColumns ??
columns.where((col) => !conflictColumns.contains(col)).toList();
final updateSets =
updateCols.map((col) => "$col = VALUES($col)").join(', ');
sql += " ON DUPLICATE KEY UPDATE $updateSets";
} else if (conflictAction == ConflictAction.replace) {
sql =
"REPLACE INTO $getTable (${columns.join(', ')}) VALUES ${valueGroups.join(', ')}";
}
await conn.execute(sql, paramBindings);
}
return true;
} catch (e) {
rethrow;
}
}