generateDatabaseInstance method

void generateDatabaseInstance(
  1. String pathPackageLocal2dart
)

Implementation

void generateDatabaseInstance(String pathPackageLocal2dart) {
  final String dirDatabase = local2dart['dir_database'] ?? 'morpheme';
  final bool foreignKeyConstrainSupport =
      local2dart['foreign_key_constrain_support'] ?? true;
  final dir = join(pathPackageLocal2dart, 'lib', 'utils');
  DirectoryHelper.createDir(dir);
  join(dir, 'database_instance.dart')
      .write('''import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class DatabaseInstance {
static DatabaseInstance? _instance;
final Database db;

static Future<DatabaseInstance> getInstance() async {
  if (_instance == null) {
    final db = await _open();
    _instance = DatabaseInstance._(db);
  }
  return _instance!;
}

DatabaseInstance._(Database database) : db = database;

static Future<String> pathDatabase() async {
  final databasesPath = await getDatabasesPath();
  return join(databasesPath, '$dirDatabase', 'local2dart.db');
}

static Future<Database> _open() async {
  return await openDatabase(
    await pathDatabase(),
    version: ${local2dart['version']},
    onConfigure: (db) => db.execute("PRAGMA foreign_keys = ${foreignKeyConstrainSupport ? 'ON' : 'OFF'}"),
    onCreate: (Database db, int version) async {
      ${generateTable()}
      ${generateView()}
      ${generateTrigger()}

      ${generateSeed()}
    },
  );
}

static Future<void> close() async {
  if (_instance?.db.isOpen ?? false) {
    await _instance?.db.close();
    _instance = null;
  }
}
}''');
}