db4ai
v0.3.4
Published
Declarative schema DSL for AI-powered databases with automatic JSON Schema generation
Maintainers
Readme
db4ai
A declarative schema DSL for AI-powered databases. Define your data model and let AI generate structured content on-demand.
Installation
npm install db4aiQuick Start
import { DB } from 'db4ai'
const db = DB({
$id: 'my-blog-app', // Required: namespace for your schema
Blog: {
title: 'Short memorable blog name',
description: 'Brief tagline for SEO meta tags',
purpose: 'Core mission and value proposition',
audience: 'Target reader persona',
style: 'Tone and writing style',
topics: ['List 5 PascalCase topics covered ->Topic'],
posts: ['<-Post'],
},
Topic: {
name: '1-2 word PascalCase name',
description: '1 sentence description',
titles: ['List 3 blog post titles ->Post'],
},
Post: {
title: 'SEO-optimized title without punctuation',
synopsis: '1 sentence overview',
content: 'Markdown content (title prepended automatically)',
},
})
// Generate a complete blog with topics and posts
const blog = await db.Blog('mystartup.ai/blog', {
audience: 'Early stage startup founders',
style: 'provocative',
})Namespace Configuration
Every schema requires a namespace via $id or $context. This determines where your data is stored and enables composition of multiple schemas.
Using $id
// Simple namespace (uses https://db4ai.dev by default)
const db = DB({
$id: 'my-app',
User: { name: 'User name' },
})
// Full URL for custom backends
const db = DB({
$id: 'https://db.sb/my-app',
User: { name: 'User name' },
})Using $context for Composable Schemas
$context is ideal when you have multiple DB() definitions that should share a namespace:
// StartupBuilder.ts
export const StartupBuilder = DB({
$context: 'startups',
Startup: {
name: 'Startup name',
idea: '->Idea',
founders: '->Founder[]',
},
Idea: { concept: 'Business concept' },
Founder: { name: 'Founder name', background: 'Background' },
})
// SalesBuilder.ts
export const SalesBuilder = DB({
$context: 'startups', // Same context - shares namespace!
Lead: {
name: 'Lead name',
startup: '->Startup', // Can reference StartupBuilder types
},
Deal: { value: 'Deal value', lead: '->Lead' },
})
// ServiceBuilder.ts
export const ServiceBuilder = DB({
$context: 'startups', // Same context
Service: { name: 'Service name' },
Client: { name: 'Client name', services: '->Service[]' },
})All three schemas share the startups namespace at https://db4ai.dev/startups, allowing cross-references between types.
Result Properties
const db = DB({ $context: 'my-app', User: { name: '' } })
db.namespace // 'my-app' - the resolved namespace
db.baseUrl // 'https://db4ai.dev' - API base URL
db.context // 'my-app' - from $context (if used)
db.id // undefined - from $id (if used)Schema DSL
Field Descriptions
Every field value is a generation prompt. Empty strings infer the prompt from context:
DB({
Product: {
name: '', // Infer from context
tagline: '< 10 words', // Short constraint
description: 'Detailed product description for landing page',
},
})References (->)
Link to other types. Referenced objects are generated recursively:
DB({
Post: {
author: '->User', // Single reference
tags: '->Tag[]', // Array of references
reviewer: '->User?', // Optional reference
},
})Fuzzy References (~>)
Match existing objects by semantic similarity, generate if no match:
DB({
Article: {
industry: '~>Industry', // Match to taxonomy
topic: '~>Category?', // Optional fuzzy match
},
})Inline References (['... ->Type'])
Generate array items that are also references:
DB({
Blog: {
// Generate 5 topic names AND create Topic objects for each
topics: ['List 5 PascalCase topics ->Topic'],
},
Topic: {
name: '1-2 word PascalCase name',
},
})Back References (['<-Type'])
Collect objects that reference this one:
DB({
Blog: {
posts: ['<-Post'], // All Posts referencing this Blog
},
Post: {
blog: '->Blog', // Post belongs to Blog
title: 'Post title',
},
})Union Types (|)
Reference multiple possible types:
DB({
Comment: {
target: '->Post|Product', // Reference Post OR Product
},
})Arrays
String arrays with generation prompts:
DB({
Post: {
tags: ['List 3-5 relevant tags'],
keyPoints: ['Main takeaways from the content'],
},
})Nested Objects
Inline object structures:
DB({
User: {
profile: {
bio: 'Short biography',
links: ['Social media URLs'],
},
},
})Optional Fields (?)
Fields not required in output:
DB({
User: {
name: 'Full name',
nickname: '?', // Optional, infer if provided
avatar: '->Image?', // Optional reference
},
})API
DB(schema)
Create a schema and get typed accessors:
const db = DB({
User: { name: '', email: '' },
Post: { title: '', author: '->User' },
})
db.schema // Original definition
db.types // Parsed type metadata
db.hash // Deterministic schema hash
db.toJSONSchema('User') // JSON Schema for validationdb.Type(id, args?)
Generate or retrieve an object:
// Generate with context
const blog = await db.Blog('my-blog', {
audience: 'developers',
style: 'technical',
})
// Retrieve cached (same args = same result)
const sameBlog = await db.Blog('my-blog', {
audience: 'developers',
style: 'technical',
})Low-level Functions
import { parseSchema, parseFieldType, toJSONSchema } from 'db4ai'
// Parse entire schema
const { types, hash } = parseSchema({ User: { name: '' } })
// Parse single field
parseFieldType('->User[]')
// { type: 'reference', ref: 'User', isArray: true }
parseFieldType(['List 3 items ->Tag'])
// { type: 'array', items: { type: 'string' }, description: '...', refs: ['Tag'] }
// Generate JSON Schema
const jsonSchema = toJSONSchema(types.User)Field Reference
| Pattern | Description | Example |
|---------|-------------|---------|
| '' | Infer from context | name: '' |
| 'prompt' | Generate with prompt | bio: 'Short bio' |
| '->Type' | Reference | author: '->User' |
| '~>Type' | Fuzzy reference | category: '~>Topic' |
| '->Type[]' | Reference array | tags: '->Tag[]' |
| '->Type?' | Optional reference | image: '->Image?' |
| '->A\|B' | Union reference | owner: '->User\|Org' |
| ['prompt'] | String array | tags: ['Keywords'] |
| ['... ->Type'] | Inline refs | items: ['List 3 ->Item'] |
| ['<-Type'] | Back refs | posts: ['<-Post'] |
| { k: 'v' } | Nested object | meta: { title: '' } |
| '?' | Optional infer | nickname: '?' |
CLI
The db4ai package includes a command-line interface for local development and data management.
Installation
npm install -g db4ai
# or use with npx
npx db4aiAvailable Commands
scan
Scan your project for schema definitions, seed files, and workflows.
db4ai scanOptions:
--root <path>- Root directory to scan--include <glob>- Glob pattern for files to include--exclude <glob>- Glob pattern for files to exclude--json- Output as JSON
Discovers:
- Schema files (
.schema.ts,.db.ts) - Seed files (
.seed.ts,.seed.mdx) - Workflow files (
.workflow.ts) - Project configuration (
db4.config.ts)
seed
Execute static and generated seed operations with progress tracking.
db4ai seed <seed-name>Supports:
- Static seeds: Load data from inline JSON or external APIs
- Generated seeds: Use LLM to generate test data
- Cascading entity generation
- Resume tokens for interrupted operations
- Concurrency control and field mapping
workflow
Execute event-triggered and manual workflows with integration support.
db4ai workflow <workflow-name>Features:
- Event-triggered and scheduled workflows
- Concurrency control and retry logic
- Database context and relationship management
- Logging and error handling
sync
Synchronize data between local runtime and cloud backend.
db4ai syncEnables:
- Bidirectional data sync
- Conflict resolution
- Transaction support
dashboard
Interactive terminal UI for monitoring seeds, workflows, and data generation.
db4ai dashboardDisplays:
- Real-time progress tracking
- Type and entity statistics
- Activity feed and event logs
- Cascade tree visualization
- Search and filtering
Project Configuration
Create a db4.config.ts file in your project root to configure defaults:
export default {
namespace: 'my-app',
ai: {
model: 'claude-3-5-sonnet-20241022',
temperature: 0.7,
maxTokens: 4096,
},
scan: {
include: ['src/**/*.ts'],
exclude: ['**/*.test.ts'],
},
}TypeScript
import type {
SchemaDefinition,
ParsedSchema,
ParsedType,
ParsedField,
StringField,
ReferenceField,
ArrayField,
ObjectField,
JSONSchema,
} from 'db4ai'License
MIT
