Skip to content

Commit

Permalink
Use our own logger to log the SQL statements for consistency
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesChenX committed Dec 15, 2024
1 parent c53f290 commit fa62569
Show file tree
Hide file tree
Showing 3 changed files with 137 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import 'package:drift/drift.dart';
import 'package:drift/native.dart';

import '../../io/path_utils.dart';
import 'sql_logging_query_executor.dart';

class DatabaseUtils {
DatabaseUtils._();
Expand All @@ -14,20 +15,26 @@ class DatabaseUtils {
bool inMemory = false,
required bool logStatements,
}) {
QueryExecutor database;
if (inMemory) {
return NativeDatabase.memory(logStatements: logStatements);
}
return LazyDatabase(() async {
database = NativeDatabase.memory();
} else {
final path = isAppDatabase
? PathUtils.joinPathInAppScope(['database', '$dbName.sqlite'])
: PathUtils.joinPathInUserScope(['database', '$dbName.sqlite']);
final file = File(path);
return NativeDatabase.createInBackground(file, setup: (database) {
// Configure for better performance.
database
..execute('PRAGMA journal_mode=WAL;')
..execute('PRAGMA synchronous=NORMAL;');
}, logStatements: logStatements);
});
database = LazyDatabase(() async {
final file = File(path);
return NativeDatabase.createInBackground(file, setup: (database) {
// Configure for better performance.
database
..execute('PRAGMA journal_mode=WAL;')
..execute('PRAGMA synchronous=NORMAL;');
});
});
}
if (logStatements) {
database = database.interceptWith(SqlLoggingQueryInterceptor());
}
return database;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import 'package:drift/backends.dart';
import 'package:drift/drift.dart';
import 'package:drift/web.dart';

import 'sql_logging_query_executor.dart';

class DatabaseUtils {
DatabaseUtils._();

Expand All @@ -9,12 +11,15 @@ class DatabaseUtils {
required bool isAppDatabase,
bool inMemory = false,
required bool logStatements,
}) =>
inMemory
? WebDatabase.withStorage(DriftWebStorage.volatile(),
logStatements: logStatements,
// We set this to true because we need to store int64
readIntsAsBigInt: true)
: WebDatabase('$dbName.sqlite',
logStatements: logStatements, readIntsAsBigInt: true);
}) {
QueryExecutor database = inMemory
? WebDatabase.withStorage(DriftWebStorage.volatile(),
// We set this to true because we need to store int64
readIntsAsBigInt: true)
: WebDatabase('$dbName.sqlite', readIntsAsBigInt: true);
if (logStatements) {
database = database.interceptWith(SqlLoggingQueryInterceptor());
}
return database;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import 'dart:async';

import 'package:drift/drift.dart';

import '../../logging/logger.dart';

class SqlLoggingQueryInterceptor extends QueryInterceptor {
SqlLoggingQueryInterceptor();

@override
TransactionExecutor beginTransaction(QueryExecutor parent) {
logger.debug('[Drift] Start transaction');
return super.beginTransaction(parent);
}

@override
Future<void> commitTransaction(TransactionExecutor inner) =>
_run('Commit transaction', () => inner.send());

@override
Future<void> rollbackTransaction(TransactionExecutor inner) =>
_run('Rollback transaction', () => inner.rollback());

@override
Future<void> runBatched(
QueryExecutor executor,
BatchedStatements statements,
) =>
_run(
'Run ${statements.statements}. Args: ${statements.arguments}}',
() => executor.runBatched(statements),
);

@override
Future<int> runInsert(
QueryExecutor executor,
String statement,
List<Object?> args,
) =>
_run(
'Run `$statement`. Args $args',
() => executor.runInsert(statement, args),
);

@override
Future<int> runUpdate(
QueryExecutor executor,
String statement,
List<Object?> args,
) =>
_run(
'Run `$statement`. Args $args',
() => executor.runUpdate(statement, args),
);

@override
Future<int> runDelete(
QueryExecutor executor,
String statement,
List<Object?> args,
) =>
_run(
'Run `$statement`. Args $args',
() => executor.runDelete(statement, args),
);

@override
Future<void> runCustom(
QueryExecutor executor,
String statement,
List<Object?> args,
) =>
_run(
'Run `$statement`. Args $args',
() => executor.runCustom(statement, args),
);

@override
Future<List<Map<String, Object?>>> runSelect(
QueryExecutor executor,
String statement,
List<Object?> args,
) =>
_run(
'Run `$statement`. Args $args',
() => executor.runSelect(statement, args),
);

Future<T> _run<T>(
String description,
FutureOr<T> Function() operation,
) async {
final stopwatch = Stopwatch()..start();
try {
final result = await operation();
logger.debug(
'[Drift] $description. Took: ${stopwatch.elapsedMilliseconds}');
return result;
} catch (e) {
logger.error(
'[Drift] $description. Took: ${stopwatch.elapsedMilliseconds}. Cause: ($e)');
rethrow;
}
}
}

0 comments on commit fa62569

Please sign in to comment.