mirror of
https://github.com/bitbaum/botsmann.git
synced 2026-12-04 06:08:38 +01:00
/api/health has returned 503 because `public.consultations` does not exist. It
never did. Botsmann shares one self-hosted Supabase database with orangecat,
which owns `public` and its 128 tables; ours were nowhere, because all eleven
migrations were unapplied.
The schema half is fixed in the deploy pipeline (fleetcrown#398): botsmann now
declares `supabase:botsmann` and its migrations apply into a schema of its own,
exactly as printcraft's do. That has run — all 11 tags are recorded and the 12
tables exist.
This is the other half. A Supabase client that is not told the schema queries
`public`, so it would still get PGRST205. Measured against production just now:
GET /rest/v1/consultations -> 404 PGRST205
GET /rest/v1/consultations Accept-Profile: botsmann -> 200 []
`db: { schema }` is what sends that header, and it was missing from all four
client factories — anon, service-role, browser and route-handler.
The schema name is one constant in lib/constants.ts, not four literals. The
second copy is how the first goes stale, and this repo has just spent a day
proving what duplicated configuration costs.
Two things this also removes:
* `scripts/run-migration.ts` and `scripts/migrate-via-api.ts` applied SQL
through the service-role client with no schema set. They are from the era
when migrations were run by hand; now they would create our tables inside
orangecat's `public`. Schema is the pipeline's job, and a second way to do
it is a second way to do it wrong. Nothing references them.
* The bare `SupabaseClient` type hardcodes `'public'`, so annotating with it
silently asserts we query orangecat's tables — and rejects the client we
actually build. The type is now derived from the factory, which keeps the
two in step and survives supabase-js reordering its generics.
New test pins it per file, by count: every `createClient` call in a client file
must set the schema, from the shared constant, with comments stripped first so
the guard cannot be fooled by prose. Adding a fifth unscoped factory fails the
test instead of production. Mutation-checked: unscoping the browser client
fails it.
verify green: 237 tests, lint, typecheck, build.
Claude-Session: https://claude.ai/code/session_01HVwg8DKHQktxJuHeLM3xpG
Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
163 lines
4.4 KiB
TypeScript
163 lines
4.4 KiB
TypeScript
#!/usr/bin/env tsx
|
|
/**
|
|
* Test Supabase Database Connection
|
|
*
|
|
* This script verifies that:
|
|
* 1. Connection to Supabase works
|
|
* 2. All expected tables exist
|
|
* 3. RLS policies are properly configured
|
|
*/
|
|
|
|
import { createClient } from '@supabase/supabase-js';
|
|
import { DB_SCHEMA } from '../lib/constants';
|
|
import * as dotenv from 'dotenv';
|
|
import * as path from 'path';
|
|
|
|
// Load environment variables
|
|
dotenv.config({ path: path.join(process.cwd(), '.env.local') });
|
|
|
|
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
|
|
const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
|
|
|
|
if (!supabaseUrl || !supabaseKey) {
|
|
console.error('❌ Missing Supabase credentials in .env.local');
|
|
process.exit(1);
|
|
}
|
|
|
|
// Our tables live in our own schema, not orangecat's `public` — without this
|
|
// the diagnostic reports every table missing and looks like a broken database.
|
|
const supabase = createClient(supabaseUrl, supabaseKey, { db: { schema: DB_SCHEMA } });
|
|
|
|
async function testConnection() {
|
|
console.log('🔍 Testing Supabase Connection...\n');
|
|
console.log(`📍 URL: ${supabaseUrl}\n`);
|
|
|
|
// Test 1: Check if we can connect
|
|
console.log('Test 1: Basic Connection');
|
|
try {
|
|
const { data, error } = await supabase.from('consultations').select('count');
|
|
if (error) throw error;
|
|
console.log('✅ Connection successful\n');
|
|
} catch (error) {
|
|
console.error('❌ Connection failed:', error);
|
|
process.exit(1);
|
|
}
|
|
|
|
// Test 2: Verify all tables exist
|
|
console.log('Test 2: Verify Tables Exist');
|
|
const expectedTables = [
|
|
'consultations',
|
|
'user_settings',
|
|
'documents',
|
|
'document_chunks',
|
|
'custom_bots',
|
|
'bot_knowledge_chunks',
|
|
];
|
|
|
|
for (const table of expectedTables) {
|
|
try {
|
|
const { error } = await supabase.from(table).select('*').limit(0);
|
|
if (error) throw error;
|
|
console.log(`✅ ${table}`);
|
|
} catch (error: any) {
|
|
console.error(`❌ ${table}: ${error.message}`);
|
|
}
|
|
}
|
|
|
|
console.log('\n');
|
|
|
|
// Test 3: Check extensions
|
|
console.log('Test 3: Verify PostgreSQL Extensions');
|
|
try {
|
|
const { data, error } = await supabase
|
|
.rpc('pg_extension_installed', {
|
|
extension_name: 'vector',
|
|
})
|
|
.catch(() => {
|
|
// If function doesn't exist, check manually
|
|
return supabase
|
|
.from('pg_available_extensions')
|
|
.select('name, installed_version')
|
|
.eq('name', 'vector');
|
|
});
|
|
|
|
console.log('✅ Checking extensions (vector for embeddings)');
|
|
} catch (error) {
|
|
console.log('⚠️ Could not verify extensions');
|
|
}
|
|
|
|
console.log('\n');
|
|
|
|
// Test 4: Test a simple insert/delete to consultations
|
|
console.log('Test 4: Test Insert/Delete Operations');
|
|
try {
|
|
const testData = {
|
|
name: 'Test User',
|
|
email: 'test@example.com',
|
|
message: 'Test message',
|
|
status: 'new' as const,
|
|
};
|
|
|
|
const { data: inserted, error: insertError } = await supabase
|
|
.from('consultations')
|
|
.insert(testData)
|
|
.select()
|
|
.single();
|
|
|
|
if (insertError) throw insertError;
|
|
console.log('✅ Insert operation successful');
|
|
|
|
if (inserted) {
|
|
const { error: deleteError } = await supabase
|
|
.from('consultations')
|
|
.delete()
|
|
.eq('id', inserted.id);
|
|
|
|
if (deleteError) throw deleteError;
|
|
console.log('✅ Delete operation successful');
|
|
}
|
|
} catch (error: any) {
|
|
console.error('❌ Insert/Delete failed:', error.message);
|
|
}
|
|
|
|
console.log('\n');
|
|
|
|
// Test 5: Check RLS is enabled
|
|
console.log('Test 5: Verify Row Level Security (RLS)');
|
|
const rlsTables = [
|
|
'user_settings',
|
|
'documents',
|
|
'document_chunks',
|
|
'custom_bots',
|
|
'bot_knowledge_chunks',
|
|
];
|
|
|
|
try {
|
|
const { data, error } = await supabase
|
|
.from('pg_tables')
|
|
.select('tablename, rowsecurity')
|
|
.in('tablename', rlsTables);
|
|
|
|
if (error) {
|
|
console.log('⚠️ Could not verify RLS settings directly');
|
|
} else {
|
|
console.log('✅ RLS is configured on protected tables');
|
|
}
|
|
} catch (error) {
|
|
console.log('⚠️ RLS verification requires additional permissions');
|
|
}
|
|
|
|
console.log('\n✨ Database connection test complete!\n');
|
|
}
|
|
|
|
// Run the test
|
|
testConnection()
|
|
.then(() => {
|
|
console.log('🎉 All tests passed! Botsmann is connected to Supabase.');
|
|
process.exit(0);
|
|
})
|
|
.catch((error) => {
|
|
console.error('💥 Test failed:', error);
|
|
process.exit(1);
|
|
});
|