sqfliteTemplate top-level property
This is code to be generated.
Implementation
String sqfliteTemplate = """
/*
* Created by DartGenX CLI tool on ${DateFormat('EEE, dd MMM yyyy, h:mm a').format(DateTime.now())}
*/
import 'dart:async';
import 'dart:developer';
import 'package:sqflite/sqflite.dart';
/// A service class for managing SQLite database operations using the `sqflite` package.
///
/// This class provides a singleton interface to initialize, query, insert, update,
/// and delete data from a SQLite database. It requires a [DbHelper] instance for
/// database configuration such as table name, version, and SQL statements.
///
/// Usage:
/// 1. Call [init] with a [DbHelper] instance before using any other methods.
/// 2. Use [get], [add], [update], and [delete] for CRUD operations.
///
/// Example:
/// ```dart
/// await SqfLiteService.instance.init(myDbHelper);
/// await SqfLiteService.instance.add({'column': 'value'});
/// final data = await SqfLiteService.instance.get();
/// ```
///
/// Throws:
/// - Throws an [Exception] if database is not initialized before use.
/// - Returns a [Future.error] with a descriptive message on operation failures.
class SqfLiteService {
SqfLiteService._();
static final SqfLiteService instance = SqfLiteService._();
Database? _db;
late final DbHelper _helper;
Future<void> init({required DbHelper helper}) async {
try {
_helper = helper;
_db = await _getDatabase();
log("✅ Database initiate successfully", name: 'SqfliteService');
} catch (e) {
log("\$e", name: 'SqfliteService');
}
}
Database get database {
if (_db == null) {
throw Exception("❌ Database is not initialized. Call SqfLiteService.init() first.");
}
return _db!;
}
Future<Database?> _getDatabase() async {
final databaseDirPath = await getDatabasesPath();
final databasePath = "\$databaseDirPath/\${_helper.databaseName}";
try {
final database = await openDatabase(
databasePath,
version: _helper.version,
onCreate: (db, version) async {
await db.execute(_helper.createTable);
},
onDowngrade: _helper.onDowngrade,
onUpgrade: _helper.onUpgrade,
);
return database;
} catch (e) {
return Future.error("🛑 Error in opening database: \$e");
}
}
/// Execute SQL query whenever required
Future<void> executeQuery({required String query}) async {
try {
final db = database;
await db.execute(query);
log("✅ Query Executed Successfully", name: 'SqfliteService');
} catch (e) {
log("🛑 Error while executing query: \$e", name: 'SqfliteService');
}
}
/// Retrieves a list of records from the database table.
///
/// Optional parameters:
/// - [where]: A SQL WHERE clause to filter the results.
/// - [whereArgs]: Arguments for the WHERE clause.
/// - [groupBy]: A SQL GROUP BY clause.
/// - [orderBy]: A SQL ORDER BY clause.
/// - [limit]: Limits the number of returned records.
///
/// Returns a [Future] that completes with a list of maps representing the records.
/// Throws an error if the retrieval fails.
Future<List<Map<String, dynamic>>> get({
String? where,
List<Object?>? whereArgs,
String? groupBy,
String? orderBy,
int? limit,
}) async {
try {
final db = database;
final data = await db.query(
_helper.tableName,
where: where,
whereArgs: whereArgs,
groupBy: groupBy,
limit: limit,
orderBy: orderBy,
);
log("🧩 DATA FETCH SUCCESSFULLY FROM \${_helper.tableName} TABLE => \$data", name: "SqfliteService");
return data;
} catch (e) {
return Future.error("🛑 Error in retrieving the data: \$e");
}
}
/// Inserts a new record into the database table.
///
/// [data]: A map containing the column names and values to insert.
///
/// Returns a [Future] that completes when the operation is done.
/// Throws an error if the insertion fails.
Future<void> add({
required Map<String, Object?> data,
}) async {
try {
final db = database;
await db.insert(_helper.tableName, data);
log("➕ DATA ADDED IN TABLE \${_helper.tableName}.", name: 'SqfliteService');
} catch (e) {
return Future.error("Error in adding the data: \$e");
}
}
/// Updates existing records in the database table.
///
/// [data]: A map containing the column names and new values.
/// [where]: A SQL WHERE clause to specify which records to update.
/// [whereArgs]: Arguments for the WHERE clause.
///
/// Returns a [Future] that completes when the operation is done.
/// Throws an error if the update fails.
Future<void> update({required Map<String, Object?> data, String? where, List<Object?>? whereArgs}) async {
try {
final db = database;
await db.update(_helper.tableName, data, where: where, whereArgs: whereArgs);
log("〽️ DATA UPDATED SUCCESSFULLY.", name: 'SqfliteService');
} catch (e) {
return Future.error("Error in updating the data: \$e");
}
}
/// Deletes records from the database table.
///
/// Optional parameters:
/// - [where]: A SQL WHERE clause to specify which records to delete.
/// - [whereArgs]: Arguments for the WHERE clause.
///
/// Returns a [Future] that completes when the operation is done.
/// Throws an error if the deletion fails.
Future<void> delete({String? where, List<Object?>? whereArgs}) async {
try {
final db = database;
await db.delete(_helper.tableName, where: where, whereArgs: whereArgs);
log("🚫 DATA DELETED FROM TABLE \${_helper.tableName}.", name: 'SqfliteService');
} catch (e) {
return Future.error("Error in deleting data: \$e");
}
}
}
/// An abstract class that defines the contract for database helper implementations
/// using the sqflite package.
///
/// This class provides the necessary properties and callbacks required to manage
/// a SQLite database, including its name, version, table creation SQL, and table name.
/// It also allows specifying custom logic for handling database upgrades and downgrades.
abstract class DbHelper {
String get databaseName;
int get version;
String get createTable;
String get tableName;
Function(Database, int, int)? get onUpgrade;
Function(Database, int, int)? get onDowngrade;
}
""";