Savvi Studio

Basic Database Usage Examples

These examples demonstrate the fundamental patterns for using generated database wrappers with type safety.

Referenced by: best-practices.md, patterns.md

Example 1: Simple Query

import { withClient } from '@/lib/db';
import { getResource } from '@db/graph';

const resources = await withClient(async (client) => {
    return await getResource(client, { p_id: BigInt(123) });
});

Example 2: Create Resource

import { withClient } from '@/lib/db';
import { createResource } from '@db/graph';

const id = await withClient(async (client) => {
    return await createResource(client, {
        p_type_namespace: 'user.profile',
        p_external_id: 'alice',
        p_data: { name: 'Alice', role: 'admin' }
    });
});

Example 3: Create and Verify

import { withClient } from '@/lib/db';
import { createResource, getResource } from '@db/graph';

const result = await withClient(async (client) => {
    // Create
    const id = await createResource(client, {
        p_type_namespace: 'user.profile',
        p_external_id: 'alice',
        p_data: { name: 'Alice' }
    });
    
    // Verify
    const resources = await getResource(client, { p_id: id });
    return resources[0];
});
import { withClient } from '@/lib/db';
import { createResource, getResource } from '@db/graph';

const result = await withClient(async (client) => {
    // Reuse connection for related operations
    const id = await createResource(client, {
        p_type_namespace: 'doc.document',
        p_external_id: 'doc-1'
    });
    
    const resources = await getResource(client, { p_id: id });
    
    return {
        id,
        resource: resources[0]
    };
});

Example 5: Authentication Flow

import { withClient } from '@/lib/db';
import { login } from '@db/studio';
import { sessionId, subjectId } from '@db/auth';

const session = await withClient(async (client) => {
    // Login
    await login(client, { p_jwt_token: token });
    
    // Get session info
    return {
        sessionId: await sessionId(client),
        subjectId: await subjectId(client)
    };
});

Example 6: Logout Flow

import { withClient } from '@/lib/db';
import { logout } from '@db/studio';

await withClient(async (client) => {
    await logout(client);
});

Example 7: Session Check

import { withClient } from '@/lib/db';
import { sessionId } from '@db/auth';

const sid = await withClient(async (client) => {
    return await sessionId(client);
});

const isAuthenticated = sid !== null;