Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide guidance when --remote is omitted #10579

Merged
merged 4 commits into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/neat-stingrays-judge.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@astrojs/db": patch
---

Provide guidance when --remote is missing

When running the build `astro build` without the `--remote`, either require a `DATABASE_FILE` variable be defined, which means you are going expert-mode and having your own database, or error suggesting to use the `--remote` flag.
14 changes: 13 additions & 1 deletion packages/db/src/core/integration/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { existsSync } from 'fs';
import { dirname } from 'path';
import { fileURLToPath } from 'url';
import type { AstroIntegration } from 'astro';
import type { AstroConfig, AstroIntegration } from 'astro';
import { mkdir, writeFile } from 'fs/promises';
import { blue, yellow } from 'kleur/colors';
import parseArgs from 'yargs-parser';
Expand All @@ -13,6 +13,7 @@ import { fileURLIntegration } from './file-url.js';
import { typegenInternal } from './typegen.js';
import { type LateSeedFiles, type LateTables, vitePluginDb } from './vite-plugin-db.js';
import { vitePluginInjectEnvTs } from './vite-plugin-inject-env-ts.js';
import { loadEnv } from 'vite';

function astroDBIntegration(): AstroIntegration {
let connectToStudio = false;
Expand All @@ -33,12 +34,14 @@ function astroDBIntegration(): AstroIntegration {
},
};
let command: 'dev' | 'build' | 'preview';
let output: AstroConfig['output'] = 'server';
return {
name: 'astro:db',
hooks: {
'astro:config:setup': async ({ updateConfig, config, command: _command, logger }) => {
command = _command;
root = config.root;
output = config.output;

if (command === 'preview') return;

Expand Down Expand Up @@ -111,6 +114,10 @@ function astroDBIntegration(): AstroIntegration {
});
},
'astro:build:start': async ({ logger }) => {
if(!connectToStudio && !databaseFileEnvDefined() && output === 'server') {
bholmesdev marked this conversation as resolved.
Show resolved Hide resolved
throw new Error(`Attempting to build without the --remote flag or the DATABASE_FILE environment variable defined. You probably want to pass --remote to astro build.`)
bholmesdev marked this conversation as resolved.
Show resolved Hide resolved
}

logger.info('database: ' + (connectToStudio ? yellow('remote') : blue('local database.')));
},
'astro:build:done': async ({}) => {
Expand All @@ -120,6 +127,11 @@ function astroDBIntegration(): AstroIntegration {
};
}

function databaseFileEnvDefined() {
const env = loadEnv('', process.cwd());
return env.DATABASE_FILE != null || process.env.DATABASE_FILE != null;
bholmesdev marked this conversation as resolved.
Show resolved Hide resolved
}

export function integration(): AstroIntegration[] {
return [astroDBIntegration(), fileURLIntegration()];
}
3 changes: 2 additions & 1 deletion packages/db/src/core/integration/vite-plugin-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,8 @@ import { asDrizzleTable, createLocalDatabaseClient } from ${RUNTIME_IMPORT};
${shouldSeed ? `import { seedLocal } from ${RUNTIME_IMPORT};` : ''}
${shouldSeed ? integrationSeedImportStatements.join('\n') : ''}

const dbUrl = ${JSON.stringify(dbUrl)};
const dbUrl = import.meta.env.DATABASE_FILE ?? ${JSON.stringify(dbUrl)};

export const db = createLocalDatabaseClient({ dbUrl });

${
Expand Down
1 change: 1 addition & 0 deletions packages/db/test/basics.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ describe('astro:db', () => {
});

after(async () => {
process.env.ASTRO_STUDIO_APP_TOKEN = '';
await remoteDbServer?.stop();
});

Expand Down
10 changes: 10 additions & 0 deletions packages/db/test/fixtures/local-prod/astro.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import db from '@astrojs/db';
import { defineConfig } from 'astro/config';

// https://astro.build/config
export default defineConfig({
integrations: [db()],
devToolbar: {
enabled: false,
},
});
13 changes: 13 additions & 0 deletions packages/db/test/fixtures/local-prod/db/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { column, defineDb, defineTable } from 'astro:db';

const User = defineTable({
columns: {
id: column.text({ primaryKey: true, optional: false }),
username: column.text({ optional: false, unique: true }),
password: column.text({ optional: false }),
},
});

export default defineDb({
tables: { User },
});
8 changes: 8 additions & 0 deletions packages/db/test/fixtures/local-prod/db/seed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { asDrizzleTable } from '@astrojs/db/utils';
import { User, db } from 'astro:db';

export default async function () {
await db.batch([
db.insert(User).values([{ id: 'mario', username: 'Mario', password: 'itsame' }]),
]);
}
14 changes: 14 additions & 0 deletions packages/db/test/fixtures/local-prod/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "@test/db-local-prod",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview"
},
"dependencies": {
"@astrojs/db": "workspace:*",
"astro": "workspace:*"
}
}
11 changes: 11 additions & 0 deletions packages/db/test/fixtures/local-prod/src/pages/index.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
/// <reference path="../../.astro/db-types.d.ts" />
import { db, User } from 'astro:db';

const users = await db.select().from(User);
---

<h2>Users</h2>
<ul class="users-list">
{users.map((user) => <li>{user.name}</li>)}
</ul>
47 changes: 47 additions & 0 deletions packages/db/test/local-prod.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { expect } from 'chai';
import testAdapter from '../../astro/test/test-adapter.js';
import { loadFixture } from '../../astro/test/test-utils.js';

describe('astro:db local database', () => {
let fixture;
before(async () => {
fixture = await loadFixture({
root: new URL('./fixtures/local-prod/', import.meta.url),
output: 'server',
adapter: testAdapter(),
});
});

describe('build (not remote) with DATABASE_FILE env', () => {
const prodDbPath = new URL('./fixtures/basics/dist/astro.db', import.meta.url).toString();
before(async () => {
process.env.DATABASE_FILE = prodDbPath;
await fixture.build();
});

after(async () => {
delete process.env.DATABASE_FILE;
});

it('Can render page', async () => {
const app = await fixture.loadTestAdapterApp();
const request = new Request('http://example.com/');
const response = await app.render(request);
expect(response.status).to.equal(200);
});
});

describe('build (not remote)', () => {
it('should throw during the build', async () => {
delete process.env.DATABASE_FILE;
let buildError = null;
try {
await fixture.build();
} catch(err) {
buildError = err;
}

expect(buildError).to.be.an('Error');
});
});
});
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading