diff --git a/lib/database/database_helper.dart b/lib/database/database_helper.dart new file mode 100644 index 0000000..2e1b389 --- /dev/null +++ b/lib/database/database_helper.dart @@ -0,0 +1,93 @@ +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; +import 'package:path/path.dart'; +import '../models/contact.dart'; + +class DatabaseHelper { + static final DatabaseHelper _instance = DatabaseHelper._internal(); + static Database? _database; + + factory DatabaseHelper() { + return _instance; + } + + DatabaseHelper._internal(); + + Future get database async { + if (_database != null) { + return _database!; + } + _database = await _initDatabase(); + return _database!; + } + + Future _initDatabase() async { + sqfliteFfiInit(); + var databaseFactory = databaseFactoryFfi; + + final databasePath = await getDatabasesPath(); + final path = join(databasePath, 'contacts.db'); + + return await databaseFactory.openDatabase( + path, + options: OpenDatabaseOptions( + version: 1, + onCreate: (db, version) async { + await db.execute(''' + CREATE TABLE contacts( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + phone TEXT, + email TEXT, + address TEXT, + company TEXT, + notes TEXT + ) + '''); + }, + ), + ); + } + + Future insertContact(Contact contact) async { + final db = await database; + return await db.insert( + 'contacts', + contact.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + Future> getContacts() async { + final db = await database; + final List> maps = await db.query( + 'contacts', + orderBy: 'name ASC', + ); // Order by name for display + return List.generate(maps.length, (i) { + return Contact.fromMap(maps[i]); + }); + } + + Future updateContact(Contact contact) async { + final db = await database; + return await db.update( + 'contacts', + contact.toMap(), + where: 'id = ?', + whereArgs: [contact.id], + ); + } + + Future deleteContact(int id) async { + final db = await database; + return await db.delete('contacts', where: 'id = ?', whereArgs: [id]); + } + + Future closeDatabase() async { + final db = await _database; + if (db != null && db.isOpen) { + await db.close(); + _database = null; // Clear the instance + } + } +}