An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
fix(db): allow stateless startup without a database (#1005)
Yoshiki Miura3637147b7c08
diff --git a/Dockerfile b/Dockerfileindex ed0667d3..02100bcd 100644--- a/Dockerfile+++ b/Dockerfile@@ -35,13 +35,9 @@ COPY --from=builder /app/drizzle ./drizzleCOPY --from=builder /app/lib/db ./lib/dbCOPY --from=builder /app/drizzle.config.ts ./drizzle.config.ts-# Create entrypoint script for database migration-RUN echo '#!/bin/sh\n\-set -e\n\-echo "Running database migrations..."\n\-bun run migrate\n\-echo "Migrations completed. Starting server..."\n\-exec "$@"\n' > /app/docker-entrypoint.sh && chmod +x /app/docker-entrypoint.sh+# Copy entrypoint script for database migration+COPY docker-entrypoint.sh /app/docker-entrypoint.sh+RUN chmod +x /app/docker-entrypoint.sh# Start production server with migrationENTRYPOINT ["/app/docker-entrypoint.sh"]diff --git a/docker-entrypoint.sh b/docker-entrypoint.shnew file mode 100644index 00000000..e6e4078f--- /dev/null+++ b/docker-entrypoint.sh@@ -0,0 +1,12 @@+#!/bin/sh+set -e++if [ -n "${DATABASE_URL:-}" ] || [ -n "${DATABASE_RESTRICTED_URL:-}" ]; then+ echo "Running database migrations..."+ bun run migrate+ echo "Migrations completed. Starting server..."+else+ echo "Database is not configured. Skipping migrations."+fi++exec "$@"diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex b394dadf..e219d72d 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -13,7 +13,9 @@ This guide covers the optional features and their configuration in Morphic.## Database-Morphic uses PostgreSQL for chat history storage. A database is **optional** for basic usage — without it, Morphic runs in a stateless mode where chat history is not persisted.+Morphic uses PostgreSQL for persistent application data. A database is **optional** for stateless guest chat. To run without a database, set `ENABLE_GUEST_CHAT=true` and do not configure Supabase. Setting `ENABLE_AUTH=false` creates an anonymous user ID that uses the persistent chat path and will fail without a database.++Without a database, chat history, permalinks (`/search/[id]`), file upload, and feedback are unavailable.### Setting Up PostgreSQL@@ -35,7 +37,7 @@ After configuring your database, run migrations to create the necessary tables:bun run migrate```-This command applies all migrations from the `drizzle/` directory. Docker runs migrations automatically on startup.+This command applies all migrations from the `drizzle/` directory. Docker runs migrations automatically on startup when a database connection string is configured. Otherwise, it skips migrations and starts in stateless mode.## AI Providersdiff --git a/lib/db/__tests__/index.test.ts b/lib/db/__tests__/index.test.tsnew file mode 100644index 00000000..43121c32--- /dev/null+++ b/lib/db/__tests__/index.test.ts@@ -0,0 +1,32 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++describe('database configuration', () => {+ afterEach(() => {+ vi.unstubAllEnvs()+ vi.resetModules()+ })++ it('defers the missing connection string error until database access', async () => {+ vi.resetModules()+ vi.stubEnv('NODE_ENV', 'production')+ vi.stubEnv('DATABASE_URL', '')+ vi.stubEnv('DATABASE_RESTRICTED_URL', '')++ const databaseModule = await import('@/lib/db')++ expect(() => databaseModule.db.select).toThrow(+ 'DATABASE_URL or DATABASE_RESTRICTED_URL environment variable is not set'+ )+ })++ it('falls back to DATABASE_URL when the restricted URL is empty', async () => {+ vi.resetModules()+ vi.stubEnv('NODE_ENV', 'production')+ vi.stubEnv('DATABASE_URL', 'postgres://user:pass@localhost:5432/testdb')+ vi.stubEnv('DATABASE_RESTRICTED_URL', '')++ const databaseModule = await import('@/lib/db')++ expect(() => databaseModule.db.select).not.toThrow()+ })+})diff --git a/lib/db/index.ts b/lib/db/index.tsindex 1aef2040..df92858d 100644--- a/lib/db/index.ts+++ b/lib/db/index.ts@@ -10,62 +10,70 @@ import * as schema from './schema'const isDevelopment = process.env.NODE_ENV === 'development'const isTest = process.env.NODE_ENV === 'test'-if (- !process.env.DATABASE_URL &&- !process.env.DATABASE_RESTRICTED_URL &&- !isTest-) {- throw new Error(- 'DATABASE_URL or DATABASE_RESTRICTED_URL environment variable is not set'- )-}-// Connection with connection pooling for server environments// Prefer restricted user for application runtime+const restrictedDatabaseUrl =+ process.env.DATABASE_RESTRICTED_URL?.trim() || undefined+const databaseUrl = process.env.DATABASE_URL?.trim() || undefinedconst connectionString =- process.env.DATABASE_RESTRICTED_URL ?? // Prefer restricted user- process.env.DATABASE_URL ??+ restrictedDatabaseUrl ?? // Prefer restricted user+ databaseUrl ??(isTest ? 'postgres://user:pass@localhost:5432/testdb' : undefined)-if (!connectionString) {- throw new Error(- 'DATABASE_URL or DATABASE_RESTRICTED_URL environment variable is not set'- )-}+const databaseErrorMessage =+ 'DATABASE_URL or DATABASE_RESTRICTED_URL environment variable is not set'-// Log which connection is being used (for debugging)-if (isDevelopment) {- console.log(- '[DB] Using connection:',- process.env.DATABASE_RESTRICTED_URL- ? 'Restricted User (RLS Active)'- : 'Owner User (RLS Bypassed)'- )+const createDatabase = (url: string) => {+ // Log which connection is being used (for debugging)+ if (isDevelopment) {+ console.log(+ '[DB] Using connection:',+ restrictedDatabaseUrl+ ? 'Restricted User (RLS Active)'+ : 'Owner User (RLS Bypassed)'+ )+ }++ // SSL configuration: Use environment variable to control SSL+ // DATABASE_SSL_DISABLED=true disables SSL completely (for local/Docker PostgreSQL)+ // Default is to enable SSL with certificate verification (for cloud databases like Neon, Supabase)+ const sslConfig =+ process.env.DATABASE_SSL_DISABLED === 'true'+ ? false // Disable SSL entirely for local PostgreSQL+ : { rejectUnauthorized: true } // Enable SSL with verification for cloud DBs++ const client = postgres(url, {+ ssl: sslConfig,+ prepare: false,+ max: 20 // Max 20 connections+ })++ return drizzle(client, {+ schema: { ...schema, ...relations }+ })}-// SSL configuration: Use environment variable to control SSL-// DATABASE_SSL_DISABLED=true disables SSL completely (for local/Docker PostgreSQL)-// Default is to enable SSL with certificate verification (for cloud databases like Neon, Supabase)-const sslConfig =- process.env.DATABASE_SSL_DISABLED === 'true'- ? false // Disable SSL entirely for local PostgreSQL- : { rejectUnauthorized: true } // Enable SSL with verification for cloud DBs+type Database = ReturnType<typeof createDatabase>-const client = postgres(connectionString, {- ssl: sslConfig,- prepare: false,- max: 20 // Max 20 connections-})+export const db: Database = connectionString+ ? createDatabase(connectionString)+ : new Proxy({} as Database, {+ get() {+ throw new Error(databaseErrorMessage)+ }+ })-export const db = drizzle(client, {- schema: { ...schema, ...relations }-})+if (!connectionString) {+ console.warn(+ '[DB] Database is not configured. Only guest chat (ENABLE_GUEST_CHAT=true) works without a database.'+ )+}// Helper type for all tablesexport type Schema = typeof schema// Verify restricted user permissions on startup-if (process.env.DATABASE_RESTRICTED_URL && !isTest) {+if (restrictedDatabaseUrl && !isTest) {// Only run verification in server environments, not during buildif (typeof window === 'undefined' && process.env.NODE_ENV !== 'production') {;(async () => {