execute method

  1. @override
Future<DatabaseResponse> execute(
  1. String sql, [
  2. List bindings = const []
])
override

Executes a raw SQL query with optional parameter bindings.

Example:

await connection.execute('SELECT * FROM users WHERE id = ?', [1]);

Implementation

@override
Future<DatabaseResponse> execute(
  String sql, [
  List<dynamic> bindings = const [],
]) async {
  if (_db == null) await connect();

  final preparedBindings = _prepareBindings(bindings);

  try {
    final stmt = _db!.prepare(sql);

    try {
      // Simple heuristic: check if it starts with SELECT (case insensitive)
      final isSelect =
          sql.trim().toUpperCase().startsWith('SELECT') ||
          sql.trim().toUpperCase().startsWith('PRAGMA');

      if (isSelect) {
        final result = stmt.select(preparedBindings);

        final data = result
            .map((row) => Map<String, dynamic>.from(row))
            .toList();
        return DatabaseResponse(data: data);
      } else {
        stmt.execute(preparedBindings);

        return DatabaseResponse(
          data: [],
          insertId: _db!.lastInsertRowId,
          affectedRows: _db!.updatedRows,
        );
      }
    } finally {
      stmt.dispose();
    }
  } catch (e) {
    throw DatabaseException(
      'SQLite Error: $e\nQuery: $sql\nBindings: $preparedBindings',
    );
  }
}