execute method
override
Executes a raw SQL query and returns the results as a QueryResult.
sql can contain named parameters like @id.
params is an optional map of parameter names to values.
Implementation
@override
Future<QueryResult> execute(
String sql, [
Map<String, dynamic>? params,
]) async {
try {
String processedSql = sql;
List<dynamic> positionalParams = [];
if (params != null && params.isNotEmpty) {
final translation = _translateSql(sql, params);
processedSql = translation.sql;
positionalParams = translation.params;
} else {
// Even without params, we might need to strip RETURNING
processedSql = _stripReturning(sql);
}
final isQuery =
processedSql.trimLeft().toLowerCase().startsWith('select') ||
processedSql.trimLeft().toLowerCase().startsWith('pragma');
if (_log.isLoggable(Level.FINE)) {
_log.fine('Executing SQL: $processedSql');
if (positionalParams.isNotEmpty) {
_log.fine('Parameters: $positionalParams');
}
}
if (positionalParams.isNotEmpty) {
final stmt = _db.prepare(processedSql);
try {
if (isQuery) {
final result = stmt.select(positionalParams);
return QueryResult(
rows: result
.map<Map<String, dynamic>>(
(row) => Map<String, dynamic>.from(row),
)
.toList(),
affectedRows: _db.updatedRows,
lastInsertId: _db.lastInsertRowId,
);
} else {
stmt.execute(positionalParams);
return QueryResult(
affectedRows: _db.updatedRows,
lastInsertId: _db.lastInsertRowId,
);
}
} finally {
stmt.dispose();
}
} else {
if (isQuery) {
final result = _db.select(processedSql);
return QueryResult(
rows: result
.map<Map<String, dynamic>>(
(row) => Map<String, dynamic>.from(row),
)
.toList(),
affectedRows: _db.updatedRows,
lastInsertId: _db.lastInsertRowId,
);
} else {
_db.execute(processedSql);
return QueryResult(
affectedRows: _db.updatedRows,
lastInsertId: _db.lastInsertRowId,
);
}
}
} catch (e) {
throw QueryException('SQLite Error: $e', sql: sql);
}
}