Skip to content

Commit

Permalink
Initialize engine when needed (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
leo authored Dec 19, 2024
1 parent 2f71a57 commit cab472b
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 31 deletions.
Binary file modified bun.lockb
Binary file not shown.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@
"license": "Apache-2.0",
"dependencies": {
"@iarna/toml": "2.2.5",
"@ronin/engine": "0.0.16",
"@inquirer/prompts": "7.2.0",
"@ronin/compiler": "0.12.4",
"@ronin/engine": "0.0.16",
"chalk-template": "1.1.0",
"get-port": "7.1.0",
"ini": "5.0.0",
Expand Down
12 changes: 9 additions & 3 deletions src/commands/migration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ import fs from 'node:fs';
import path from 'node:path';
import type { parseArgs } from 'node:util';
import { readConfig, saveConfig } from '@/src/utils/config';
import { db } from '@/src/utils/database';
import { initializeDatabase } from '@/src/utils/database';
import { diffModels } from '@/src/utils/migration';
import { type BaseFlags, getModelDefinitions, logTableDiff } from '@/src/utils/misc';
import { getModels } from '@/src/utils/model';
import { Protocol } from '@/src/utils/protocol';
import { getSpaces } from '@/src/utils/space';
import type { Model } from '@ronin/compiler';
import type { Database } from '@ronin/engine';

export const MIGRATION_FLAGS = {
reset: { type: 'boolean', short: 'r', default: false },
Expand Down Expand Up @@ -64,6 +65,7 @@ export default async function main(
const applyMigrationStatements = async (
appToken: string | undefined,
flags: Flags,
db: Database,
statements: Array<{ statement: string }>,
slug: string,
): Promise<void> => {
Expand Down Expand Up @@ -104,6 +106,8 @@ const create = async (
let status: Status = 'readingConfig';
const spinner = ora('Reading configuration').start();

const db = await initializeDatabase();

try {
const { slug } = await getOrSelectSpaceId(sessionToken, spinner);
status = 'comparing';
Expand Down Expand Up @@ -162,7 +166,7 @@ const create = async (
path.join(migrationsPath, `migration-${paddedNum}.ts`),
);

await applyMigrationStatements(appToken, flags, statements, slug);
await applyMigrationStatements(appToken, flags, db, statements, slug);
}

process.exit(0);
Expand All @@ -185,6 +189,8 @@ const apply = async (
const spinner = ora('Applying migration').start();
const migrationFilePath = positionals[positionals.indexOf('migration') + 2];

const db = await initializeDatabase();

try {
const { slug } = await getOrSelectSpaceId(sessionToken, spinner);
const existingModels = await getModels(db, appToken, slug, flags.prod);
Expand All @@ -201,7 +207,7 @@ const apply = async (
path.join(migrationsPath, path.basename(latestProtocolFile)),
);

await applyMigrationStatements(appToken, flags, statements, slug);
await applyMigrationStatements(appToken, flags, db, statements, slug);

spinner.succeed('Successfully applied migration');
process.exit(0);
Expand Down
50 changes: 25 additions & 25 deletions src/utils/database.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
import fs from 'node:fs';
import { ROOT_MODEL, Transaction } from '@ronin/compiler';
import { Engine } from '@ronin/engine';
import { type Database, Engine } from '@ronin/engine';
import { MemoryResolver } from '@ronin/engine/resolvers/memory';

const engine = new Engine({
resolvers: [(engine) => new MemoryResolver(engine)],
});
export const initializeDatabase = async (
fsPath = '.ronin/db.sqlite',
): Promise<Database> => {
const engine = new Engine({
resolvers: [(engine) => new MemoryResolver(engine)],
});

const transaction = new Transaction([
{
create: { model: ROOT_MODEL },
},
]);
const transaction = new Transaction([
{
create: { model: ROOT_MODEL },
},
]);

export const db = await engine.createDatabase({ id: 'local' });
const db = await engine.createDatabase({ id: 'local' });

let DB_LOCATION = '.ronin/db.sqlite';
if (fs.existsSync(fsPath)) {
const file = fs.readFileSync(fsPath);
const buffer = new Uint8Array(file);
await db.replaceContents(buffer);
}

if (process.env.NODE_ENV === 'test') {
DB_LOCATION = './tests/fixtures/minimal.db';
}
try {
await db.query(transaction.statements.map((statement) => statement.statement));
} catch (_error) {
console.log('ronin_schema already exists');
}

if (fs.existsSync(DB_LOCATION)) {
const file = fs.readFileSync(DB_LOCATION);
const buffer = new Uint8Array(file);
await db.replaceContents(buffer);
}

try {
await db.query(transaction.statements.map((statement) => statement.statement));
} catch (_error) {
console.log('ronin_schema already exists');
}
return db;
};
3 changes: 2 additions & 1 deletion tests/utils/database.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { describe, expect, test } from 'bun:test';
import { initializeDatabase } from '@/src/utils/database';

describe('database', () => {
test('should initialize database', async () => {
const { db } = await import('@/src/utils/database');
const db = await initializeDatabase('./tests/fixtures/minimal.db');
const results = await db.query([
"SELECT name FROM sqlite_master WHERE type='table';",
]);
Expand Down
4 changes: 3 additions & 1 deletion tests/utils/model.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { db } from '@/src/utils/database';
import { initializeDatabase } from '@/src/utils/database';
import { getModels } from '@/src/utils/model';
import { clearMocks, mock } from 'bun-bagel';

const db = await initializeDatabase('./tests/fixtures/minimal.db');

describe('models', () => {
describe('local', () => {
test('get models from local but there are no models', async () => {
Expand Down

0 comments on commit cab472b

Please sign in to comment.