electrify<DB extends GeneratedDatabase> function

Future<ElectricClient<DB>> electrify<DB extends GeneratedDatabase>({
  1. required String dbName,
  2. required DB db,
  3. required ElectricMigrations migrations,
  4. required ElectricConfig config,
  5. ElectrifyOptions? opts,
})

Implementation

Future<ElectricClient<DB>> electrify<DB extends GeneratedDatabase>({
  required String dbName,
  required DB db,
  required ElectricMigrations migrations,
  required ElectricConfig config,
  ElectrifyOptions? opts,
}) async {
  final adapter = opts?.adapter ?? DriftAdapter(db);
  final socketFactory = opts?.socketFactory ?? getDefaultSocketFactory();

  final sqliteMigrations = migrations.sqliteMigrations;
  final pgMigrations = migrations.pgMigrations;

  final dbDescription = DBSchemaDrift(
    db: db,
    migrations: sqliteMigrations,
    pgMigrations: pgMigrations,
  );

  final Dialect dialect = driftDialectToElectric(db);

  Migrator migrator;
  if (opts?.migrator != null) {
    migrator = opts!.migrator!;
  } else {
    migrator = dialect == Dialect.sqlite
        ? SqliteBundleMigrator(adapter: adapter, migrations: sqliteMigrations)
        : PgBundleMigrator(adapter: adapter, migrations: pgMigrations);
  }

  final namespace = await electrify_lib.electrifyBase(
    dbName: dbName,
    dbDescription: dbDescription,
    config: ElectricConfigWithDialect.from(
      config: config,
      dialect: dialect,
    ),
    adapter: adapter,
    socketFactory: socketFactory,
    opts: ElectrifyBaseOptions(
      migrator: migrator,
      notifier: opts?.notifier,
      registry: opts?.registry,
      // In postgres, we don't want to run the default prepare function
      // that enables FK constraints, as Postgres already has them enabled.
      prepare: dialect == Dialect.postgres ? (_) async {} : null,
    ),
  );

  final driftClient = DriftElectricClient(namespace as ElectricClientImpl, db);
  driftClient.init();

  return driftClient;
}