buildInsertSqlFromModel<TModel extends TetherModel<TModel>> static method

SqlStatement buildInsertSqlFromModel<TModel extends TetherModel<TModel>>(
  1. List<TModel> models,
  2. String tableName
)

Generates a structured INSERT statement for a list of models.

Implementation

static SqlStatement buildInsertSqlFromModel<TModel extends TetherModel<TModel>>(
  List<TModel> models,
  String tableName,
) {
  if (models.isEmpty) {
    throw ArgumentError(
      'Cannot build INSERT statement from empty model list.',
    );
  }
  final firstModelMap = models.first.toSqlite();
  if (firstModelMap.isEmpty) {
    throw ArgumentError(
      'Cannot build INSERT statement: First model has no data.',
    );
  }
  final columns = firstModelMap.keys.toList();
  final columnCount = columns.length;
  final valuePlaceholderGroup =
      '(${List.filled(columnCount, '?').join(', ')})';
  final allPlaceholders = List.filled(
    models.length,
    valuePlaceholderGroup,
  ).join(', ');
  final allArguments = <Object?>[];

  for (final model in models) {
    final map = model.toSqlite();
    if (map.length != columnCount ||
        map.keys.join(',') != columns.join(',')) {
      throw ArgumentError(
        'Inconsistent model structure detected for bulk INSERT.',
      );
    }
    allArguments.addAll(map.values);
  }

  return SqlStatement(
    operationType: SqlOperationType.insert,
    tableName: tableName,
    insertColumns: columns,
    insertValuesPlaceholders: allPlaceholders,
    insertArguments: allArguments,
  );
}