### Generate with Formatting Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-cli.md Formats the output using Prettier based on the project's Prettier configuration. Requires Prettier to be installed. ```bash drizzle-zero generate --format ``` -------------------------------- ### CLI Usage Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/module-exports.md Provides examples of using the drizzle-zero CLI with different options. ```bash drizzle-zero generate --help drizzle-zero generate --config ./drizzle-zero.config.ts ``` -------------------------------- ### Install Drizzle Zero Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/README.md Install the drizzle-zero package using npm, pnpm, or bun. ```bash npm install drizzle-zero # or pnpm add drizzle-zero # or bun add drizzle-zero ``` -------------------------------- ### Install drizzle-zero Source: https://github.com/rocicorp/drizzle-zero/blob/main/README.md Install the drizzle-zero package using your preferred package manager. ```bash npm install drizzle-zero # or bun add drizzle-zero # or yarn add drizzle-zero # or pnpm add drizzle-zero ``` -------------------------------- ### CLI Installation Configuration Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/module-exports.md Defines the drizzle-zero CLI entry point in the package.json 'bin' field for installation as a script. ```json { "bin": { "drizzle-zero": "./dist/cli/index.js" } } ``` -------------------------------- ### Custom Configuration File Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-cli.md Specifies a custom configuration file for the schema generation process. ```bash drizzle-zero generate --config ./config/zero-schema.config.ts ``` -------------------------------- ### CLI Example with Multiple Options Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/DOCUMENTATION_INDEX.txt Combines several CLI options to demonstrate a more complex command for generating the schema. ```bash npx drizzle-zero generate --config ./drizzle.config.ts --output ./generated/schema.ts --debug ``` -------------------------------- ### Configuration: Basic drizzle-zero.config.ts Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/DOCUMENTATION_INDEX.txt A minimal example of a drizzle-zero.config.ts file. ```typescript import { drizzleZeroConfig } from "@drizzle-zero/core"; export default drizzleZeroConfig({ tables: { /* ... your tables ... */ }, manyToMany: { /* ... your manyToMany relations ... */ }, casing: "camelCase" }); ``` -------------------------------- ### Custom Output Path Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-cli.md Specifies a custom path for the generated Zero schema file. ```bash drizzle-zero generate --output ./src/generated/zero.ts ``` -------------------------------- ### Basic Generation Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-cli.md Generates `zero-schema.gen.ts` from `drizzle-zero.config.ts` using default `tsconfig.json`. ```bash drizzle-zero generate ``` -------------------------------- ### Generate with Legacy Mutators and Queries Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-cli.md Enables legacy CRUD mutators and queries in the generated schema. ```bash drizzle-zero generate --enable-legacy-mutators --enable-legacy-queries ``` -------------------------------- ### Install Prettier Dev Dependency Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-cli.md Install Prettier as a development dependency using npm to resolve 'Prettier could not be found' errors. ```bash npm install -D prettier ``` -------------------------------- ### Configuration: Common Pattern - Simple Tables Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/DOCUMENTATION_INDEX.txt A common configuration pattern demonstrating the setup of simple, independent tables. ```typescript import { drizzleZeroConfig } from "@drizzle-zero/core"; export default drizzleZeroConfig({ tables: { users: { columns: { id: { primaryKey: true, type: "uuid" }, name: { type: "string" } } }, products: { columns: { id: { primaryKey: true, type: "uuid" }, name: { type: "string" } } } } }); ``` -------------------------------- ### npm Scripts for Schema Generation Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-cli.md Example `package.json` scripts for running the `drizzle-zero generate` command with different options, including a `postinstall` script. ```json { "scripts": { "generate": "drizzle-zero generate --format", "generate:debug": "drizzle-zero generate --debug --format", "postinstall": "npm run generate" } } ``` -------------------------------- ### Querying Relationships: One-to-One Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/DOCUMENTATION_INDEX.txt Example of how to query a one-to-one relationship using the generated query builder. ```typescript import { builder } from "./zero-schema.gen"; // Assuming 'user' is a user object fetched previously const userProfile = await builder.userProfile.findFirst({ where: { userId: user.id } }); ``` -------------------------------- ### Minimal drizzle.config.ts Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/configuration.md A basic Drizzle Kit configuration file specifying the schema and output directories. Drizzle-zero can read this if no drizzle-zero.config.ts is present. ```typescript import { defineConfig } from 'drizzle-kit'; export default defineConfig({ schema: './db/schema.ts', out: './db/drizzle', }); ``` -------------------------------- ### Basic Configuration for drizzleZeroConfig Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-drizzle-zero-config.md Configure which tables and columns to include in the Zero schema. This is a common starting point for most projects. ```typescript import { drizzleZeroConfig } from 'drizzle-zero'; import * as drizzleSchema from './db/schema'; export default drizzleZeroConfig(drizzleSchema, { tables: { users: { id: true, name: true, email: true, }, posts: { id: true, title: true, content: true, authorId: true, }, }, }); ``` -------------------------------- ### ColumnsConfig Usage Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/types.md Demonstrates how to use ColumnsConfig to specify column inclusion and exclusion, including custom mapping with ColumnBuilder. ```typescript const config: ColumnsConfig = { id: true, name: true, email: true, password: false, // exclude password }; ``` -------------------------------- ### Add Generation Scripts to package.json Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/README.md Add scripts to your `package.json` for generating the Zero schema and to run generation automatically after installation. ```json { "scripts": { "generate": "drizzle-zero generate --format", "postinstall": "npm run generate" } } ``` -------------------------------- ### Example Usage of Query Builder Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/generated-schema.md Shows how to use the type-safe query builder ('z') to construct queries for fetching user and post data. This enables autocompletion and compile-time checks. ```typescript import { z } from './zero-schema.gen'; const userQuery = syncedQuery( z.query.user.where('id', '=', '123').one(), ); const postsQuery = syncedQuery( z.query.post.where('authorId', '=', '123').all(), ); ``` -------------------------------- ### Force Overwrite Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-cli.md Overwrites the output file even if it has been manually modified. Use with caution. ```bash drizzle-zero generate --force ``` -------------------------------- ### Type Mapping: PostgreSQL to Zero Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/DOCUMENTATION_INDEX.txt Example showing the mapping from a PostgreSQL data type to a Drizzle Zero type. ```typescript // PostgreSQL: VARCHAR(n) // Zero: string ``` -------------------------------- ### Full Drizzle Zero Configuration Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/README.md Example of a comprehensive Drizzle Zero configuration object, specifying tables, many-to-many relationships, casing, and debug settings. ```typescript export default drizzleZeroConfig(schema, { // Which tables and columns to include tables: { users: { id: true, email: true, // password is excluded }, posts: false, // Entire table excluded }, // Many-to-many through junction tables manyToMany: { users: { groups: ['usersToGroups', 'groups'], }, }, // Apply casing transformation casing: 'camelCase', // Enable debug logging debug: true, // Hide database default warnings suppressDefaultsWarning: true, }); ``` -------------------------------- ### Create Zero Table Builder with Default Mapping Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-create-zero-table-builder.md This example shows how to use createZeroTableBuilder with a Drizzle table definition to create a Zero table builder with default column mappings. Ensure you import necessary functions from 'drizzle-zero' and 'drizzle-orm/pg-core'. ```typescript import { createZeroTableBuilder } from 'drizzle-zero'; import { pgTable, text, integer } from 'drizzle-orm/pg-core'; const usersTable = pgTable('users', { id: text('id').primaryKey(), name: text('name').notNull(), age: integer('age'), }); // Create table builder with default mapping const zeroTable = createZeroTableBuilder('users', usersTable); ``` -------------------------------- ### Graph Relationships (Self-Referential) Schema, Config, and Query Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/relationships.md Example of setting up and querying self-referential many-to-many relationships, like a user following system. ```typescript // Schema users -> followers (through follower relationship) // Configuration manyToMany: { user: { followers: [ { sourceField: ['id'], destTable: 'follower', destField: ['followingId'], }, { sourceField: ['followerId'], destTable: 'user', destField: ['id'], }, ], } } // Query const user = z.query.user.where('id', '=', userId).related('followers').one(); ``` -------------------------------- ### CLI Debug Mode Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/DOCUMENTATION_INDEX.txt Shows how to enable debug mode for the drizzle-zero CLI to get more verbose output during generation. ```bash npx drizzle-zero generate --debug ``` -------------------------------- ### Configuration: Column Type Overrides Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/DOCUMENTATION_INDEX.txt Example of overriding default column types using ColumnBuilder in the configuration file. ```typescript import { drizzleZeroConfig, ColumnBuilder } from "@drizzle-zero/core"; export default drizzleZeroConfig({ tables: { products: { columns: { price: new ColumnBuilder({ type: "decimal(10, 2)" }) } } } }); ``` -------------------------------- ### Example Usage of Row Types Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/generated-schema.md Demonstrates how to import and use the generated TypeScript row types for 'user' and 'post' tables. This ensures type correctness when working with data. ```typescript import { UserRow, PostRow } from './zero-schema.gen'; const user: UserRow = { id: '123', name: 'John', email: 'john@example.com', }; const post: PostRow = { id: 'post-1', title: 'My Post', authorId: '123', }; ``` -------------------------------- ### Column Name Mapping with Casing Transformation Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-create-zero-table-builder.md Demonstrates how to map database column names to JavaScript fields using createZeroTableBuilder, including applying casing transformations. This example shows mapping 'created_at' to 'createdAt' using 'snake_case'. ```typescript const usersTable = pgTable('users', { id: text('id').primaryKey(), createdAt: timestamp('created_at').notNull(), }); const builder = createZeroTableBuilder('users', usersTable, undefined, false, 'snake_case'); // Database column 'created_at' maps to JavaScript field 'createdAt' // Applies casing transformation as specified ``` -------------------------------- ### tsconfig.json Include Paths Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/configuration.md Example of common include paths in tsconfig.json, ensuring Drizzle schema and config files are recognized. Critical for schema generation. ```json { "include": [ "src/**/*", // Source code "db/**/*", // Database schemas "drizzle-zero.config.ts", // drizzle-zero config "drizzle.config.ts" // Drizzle Kit config ] } ``` -------------------------------- ### Drizzle-Zero: Querying Many-to-Many Relationships Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/configuration.md Example of how to query data across a many-to-many relationship configured with drizzle-zero. This demonstrates accessing related data directly. ```typescript // Simple format - direct query across tables const userQuery = syncedQuery( z.query.user.where('id', '=', '1').related('groups').one(), ); const [user] = useQuery(userQuery()); console.log(user.groups); // Array of group objects, junction table skipped ``` -------------------------------- ### One-to-One Relationship Definition Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/relationships.md Illustrates the definition of a one-to-one relationship where a post has one author. Specifies source and destination fields and schema. ```plaintext relationship.author: sourceField: ['authorId'] (column in posts) destField: ['id'] (column in users) destSchema: 'users' cardinality: 'one' ``` -------------------------------- ### Debug Mode with Custom TypeScript Config Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-cli.md Enables verbose logging for debugging and specifies a custom TypeScript configuration file for type resolution. ```bash drizzle-zero generate --debug --tsconfig ./tsconfig.build.json ``` -------------------------------- ### Type Inference Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/generated-schema.md Demonstrates type inference for mutations and queries using the module augmentation. The return type of mutations and the type of query results are inferred correctly. ```typescript // Type inference from module augmentation const result = await z.mutate.user.insert({ name: 'Jane', email: 'jane@example.com', }); // Inferred return type includes proper typing const users = await z.query.user.all(); // Inferred type: UserRow[] ``` -------------------------------- ### Generate from Drizzle Schema Without Config Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-cli.md Uses `drizzle.config.ts` to resolve the schema file and generates all tables and columns when no specific drizzle-zero config is provided. ```bash drizzle-zero generate --schema ./db/schema.ts ``` -------------------------------- ### One-to-Many Relationship Drizzle Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/relationships.md Defines a one-to-many relationship between 'users' and 'posts'. Users can have many posts, and each post has one author. ```typescript export const users = pgTable('users', { id: text('id').primaryKey(), name: text('name').notNull(), }); export const posts = pgTable('posts', { id: text('id').primaryKey(), title: text('title').notNull(), authorId: text('author_id').references(() => users.id), }); export const usersRelations = relations(users, ({ many }) => ({ posts: many(posts), })); export const postsRelations = relations(posts, ({ one }) => ({ author: one(users, { fields: [posts.authorId], references: [users.id], }), })); ``` -------------------------------- ### Parent-Child (One-to-Many) Schema and Queries Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/relationships.md Example schema and query patterns for parent-child relationships, where one entity has multiple related entities. ```typescript // Schema users -> posts users -> comments posts -> comments // Queries const user = z.query.user.where('id', '=', userId).related('posts').one(); const post = z.query.post.where('id', '=', postId).related('comments').one(); const comment = z.query.comment.where('id', '=', commentId).related('author').one(); ``` -------------------------------- ### One-to-Many Relationship Definition Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/relationships.md Illustrates the definition of a one-to-many relationship where a user can have multiple posts. Specifies source and destination fields and schema for the reverse relationship. ```plaintext relationship.posts (reverse): sourceField: ['id'] (column in users) destField: ['authorId'] (column in posts) destSchema: 'posts' cardinality: 'many' ``` -------------------------------- ### Schema-Qualified Table Names Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-create-zero-table-builder.md Shows how createZeroTableBuilder automatically handles schema qualification for tables. This example defines a 'users' table within the 'public' schema and demonstrates the builder's ability to manage this. ```typescript const usersTable = pgTable('users', { /* columns */ }, (table) => { schema: 'public', }, ); const builder = createZeroTableBuilder('users', usersTable); // Automatically handles schema qualification: 'public.users' ``` -------------------------------- ### Many-to-Many Relationship Definition Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/relationships.md Illustrates the definition of a many-to-many relationship through a junction table. Shows the two legs of the relationship, from users to the junction table and from the junction table to groups. ```plaintext relationship.groups: [0]: sourceField: ['id'] (column in users) destField: ['userId'] (column in userToGroup) destSchema: 'userToGroup' cardinality: 'many' [1]: sourceField: ['groupId'] (column in userToGroup) destField: ['id'] (column in group) destSchema: 'group' cardinality: 'many' ``` -------------------------------- ### Export Tables and Relations from Drizzle Schema Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/errors-and-troubleshooting.md When configuring drizzle-zero, ensure you export both tables and relations from your Drizzle schema. This example demonstrates the correct way to pass schema objects to `drizzleZeroConfig`. ```typescript // CORRECT: Export tables from Drizzle schema export const users = pgTable('users', { /* columns */ }); export const posts = pgTable('posts', { /* columns */ }); export default drizzleZeroConfig( { users, posts, usersRelations, postsRelations }, // Include tables { /* config */ } ); // INCORRECT: Only relations, no tables export default drizzleZeroConfig( { usersRelations, postsRelations }, // Missing tables! { /* config */ } ); ``` -------------------------------- ### One-to-One Relationship Drizzle Example Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/relationships.md Defines a one-to-one relationship between 'users' and 'profiles' tables. The 'profiles' table has a unique foreign key 'userId' referencing 'users.id'. ```typescript export const users = pgTable('users', { id: text('id').primaryKey(), name: text('name').notNull(), }); export const profiles = pgTable('profiles', { id: text('id').primaryKey(), userId: text('user_id').references(() => users.id).notNull().unique(), bio: text('bio'), }); export const profilesRelations = relations(profiles, ({ one }) => ({ user: one(users, { fields: [profiles.userId], references: [users.id], }), })); ``` -------------------------------- ### Add Schema Generation Script to package.json Source: https://github.com/rocicorp/drizzle-zero/blob/main/README.md Add a script to your package.json to generate Zero schemas from your Drizzle schema. The postinstall script ensures generation upon installation. ```json { "scripts": { "generate": "drizzle-zero generate --format", "postinstall": "npm generate" } } ``` -------------------------------- ### Basic Table Configuration Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/00_START_HERE.md Configure which tables and columns to include in the Zero schema. Ensure the schema is imported correctly. ```typescript import { drizzleZeroConfig } from 'drizzle-zero'; import * as schema from './db/schema'; export default drizzleZeroConfig(schema, { tables: { users: { id: true, name: true, email: true }, posts: { id: true, title: true, authorId: true }, }, }); ``` -------------------------------- ### Type Mapping: PostgreSQL Array to Zero Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/DOCUMENTATION_INDEX.txt Example illustrating how PostgreSQL array types are mapped to Drizzle Zero. ```typescript // PostgreSQL: VARCHAR[] // Zero: string[] ``` -------------------------------- ### npm Scripts for Generation Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/module-exports.md Shows how to configure npm scripts in package.json to run the drizzle-zero generate command. ```json { "scripts": { "generate": "drizzle-zero generate", "generate:debug": "drizzle-zero generate --debug", "postinstall": "npm run generate" } } ``` -------------------------------- ### CLI: Use Custom Config File Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/configuration.md Command-line option to specify a custom configuration file path for drizzle-zero generate. ```bash drizzle-zero generate --config ./config/zero.config.ts ``` -------------------------------- ### CLI Basic Usage Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/DOCUMENTATION_INDEX.txt Shows a basic command for the drizzle-zero CLI, likely for generating schema files. ```bash npx drizzle-zero generate ``` -------------------------------- ### Package.json Files Included Configuration Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/module-exports.md Lists the files and directories to be included in the npm package in package.json. ```json { "files": [ "dist/", "README.md", "LICENSE" ] } ``` -------------------------------- ### Configuration: Using drizzle.config.ts Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/DOCUMENTATION_INDEX.txt Shows how Drizzle Zero can discover and use a standard drizzle.config.ts file. ```typescript // drizzle.config.ts import { defineConfig } from "@drizzle-utils/core"; export default defineConfig({ // Drizzle ORM specific configurations // Drizzle Zero will look for this file and use its schema definition }); ``` -------------------------------- ### Create Zero Table Builder with Column Selection Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-create-zero-table-builder.md Demonstrates using createZeroTableBuilder to selectively include columns in the Zero schema. Columns not explicitly included or set to 'true' will be excluded, except for primary keys. Debugging and casing options are available. ```typescript import { createZeroTableBuilder } from 'drizzle-zero'; import { pgTable, text, integer } from 'drizzle-orm/pg-core'; const usersTable = pgTable('users', { id: text('id').primaryKey(), name: text('name').notNull(), age: integer('age'), }); // With column selection const zeroTable = createZeroTableBuilder( 'users', usersTable, { id: true, name: true, // age is excluded }, ); ``` -------------------------------- ### Querying Many-to-Many Relationships in Drizzle Zero Source: https://github.com/rocicorp/drizzle-zero/blob/main/README.md Example of querying a many-to-many relationship after configuring it with `drizzleZeroConfig`. The junction table is skipped in the query. ```tsx const userQuery = syncedQuery( z.query.user.where('id', '=', '1').related('groups').one(), ); const [user] = useQuery(userQuery()); console.log(user); // { // id: "user_1", // name: "User 1", // groups: [ // { id: "group_1", name: "Group 1" }, // { id: "group_2", name: "Group 2" }, // ], // } ``` -------------------------------- ### ColumnNames Type Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/types.md Gets all column names from a Drizzle table type as a union type. Useful for referencing column names programmatically. ```typescript export type ColumnNames = keyof Columns; type UserColumns = ColumnNames; // Resolves to: 'id' | 'name' | 'email' | ... ``` -------------------------------- ### Common Pattern: Graph Relationship Query Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/DOCUMENTATION_INDEX.txt Example of querying complex, graph-like relationships, potentially involving multiple joins or recursive queries. ```typescript import { builder } from "./zero-schema.gen"; // Example: Fetching a node and its direct neighbors const nodeWithNeighbors = await builder.nodes.findUnique({ where: { id: 'some-node-id' }, include: { neighbors: true // Assuming 'neighbors' is a relation name } }); ``` -------------------------------- ### Specify Config File Path Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/errors-and-troubleshooting.md When using the `-c` flag, ensure the path to the config file is correct. Use `ls -la` to verify the file exists. ```bash # Check file exists ls -la drizzle-zero.config.ts # Use correct path drizzle-zero generate --config ./drizzle-zero.config.ts ``` -------------------------------- ### Basic createZeroTableBuilder Usage Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/DOCUMENTATION_INDEX.txt Demonstrates the fundamental usage of the createZeroTableBuilder function to define a table schema. ```typescript import { createZeroTableBuilder } from "@drizzle-zero/core"; const UserTable = createZeroTableBuilder({ columns: { id: { primaryKey: true, type: "uuid" }, name: { type: "string" } } }); export type User = typeof UserTable.columns; ``` -------------------------------- ### Import drizzleZeroConfig (CommonJS) Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/module-exports.md Shows how to import the drizzleZeroConfig function using CommonJS module system. ```javascript // CommonJS const { drizzleZeroConfig } = require('drizzle-zero'); ``` -------------------------------- ### Create Zero Table Builder with Debug Mode Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-create-zero-table-builder.md Shows how to enable debug logging for the table conversion process when using createZeroTableBuilder. Pass 'true' as the fourth argument to activate debug mode. ```typescript import { createZeroTableBuilder } from 'drizzle-zero'; import { pgTable, text, integer } from 'drizzle-orm/pg-core'; const usersTable = pgTable('users', { id: text('id').primaryKey(), name: text('name').notNull(), age: integer('age'), }); // With debug mode const zeroTable = createZeroTableBuilder( 'users', usersTable, undefined, true, // enable debug ); ``` -------------------------------- ### Override Column Type with JSON Builder Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/configuration.md Example of overriding a column's type to JSON using the `column.json()` builder within the `tables` configuration. ```typescript import { drizzleZeroConfig } from 'drizzle-zero'; import { column } from '@rocicorp/zero'; import * as schema from './db/schema'; export default drizzleZeroConfig(schema, { tables: { posts: { id: true, title: true, metadata: column.json(), // Override to json type tags: column.string().optional(), // Override to optional string score: column.number(), // Override to number }, }, }); ``` -------------------------------- ### CLI: Use Custom Drizzle Schema Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/configuration.md Command-line option to directly specify the Drizzle schema file path. ```bash drizzle-zero generate --schema ./db/my-schema.ts ``` -------------------------------- ### CLI Configuration File Detection Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/DOCUMENTATION_INDEX.txt Illustrates how the drizzle-zero CLI detects configuration files, showing a command that specifies a custom config path. ```bash npx drizzle-zero generate --config ./path/to/drizzle-zero.config.ts ``` -------------------------------- ### Package.json Main Exports Configuration Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/module-exports.md Specifies the main entry points for the drizzle-zero package in package.json, including CommonJS, ESM, and types. ```json { "main": "dist/index.cjs", "module": "dist/index.js", "types": "dist/index.d.ts", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs" }, "./package.json": "./package.json" } } ``` -------------------------------- ### Basic drizzleZeroConfig Usage Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/DOCUMENTATION_INDEX.txt Demonstrates the most basic usage of the drizzleZeroConfig function to set up Drizzle Zero. ```typescript import { drizzleZeroConfig } from "@drizzle-zero/core"; export default drizzleZeroConfig({ // Your Drizzle Zero configuration goes here }); ``` -------------------------------- ### Peer Dependencies Configuration Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/module-exports.md Lists the peer dependencies required by drizzle-zero, including optional dependencies. ```json { "peerDependencies": { "@rocicorp/zero": "", "@types/pg": "", "drizzle-orm": ">=0.36.0", "pg": "", "postgres": "", "prettier": ">=3.0.0" }, "peerDependenciesMeta": { "pg": { "optional": true }, "prettier": { "optional": true }, "@types/pg": { "optional": true }, "postgres": { "optional": true } } } ``` -------------------------------- ### Extended Many-to-Many Self-Referential Relationship Configuration Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/relationships.md Configure a self-referential many-to-many relationship for users, where 'friends' are defined through a 'friendships' table. This example uses custom field mappings. ```typescript export const users = pgTable('users', { id: text('id').primaryKey(), name: text('name').notNull(), }); export const friendships = pgTable( 'friendships', { requestingUserId: text('requesting_user_id').references(() => users.id), acceptingUserId: text('accepting_user_id').references(() => users.id), }, (table) => ({ pk: primaryKey({ columns: [table.requestingUserId, table.acceptingUserId], }), }), ); ``` ```typescript export default drizzleZeroConfig(drizzleSchema, { tables: { user: { id: true, name: true }, friendship: { requestingUserId: true, acceptingUserId: true, }, }, manyToMany: { user: { friends: [ // First leg: user -> friendship (via requestingUserId) { sourceField: ['id'], destTable: 'friendship', destField: ['requestingUserId'], }, // Second leg: friendship -> user (via acceptingUserId) { sourceField: ['acceptingUserId'], destTable: 'user', destField: ['id'], }, ], }, }, }); ``` -------------------------------- ### Usage of ColumnBuilder Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/module-exports.md Demonstrates how to import and use the ColumnBuilder type for defining custom JSON columns. ```typescript import { column, type ColumnBuilder } from '@rocicorp/zero'; const myColumn: ColumnBuilder<{type: 'json', optional: false, customType: any}> = column.json(); ``` -------------------------------- ### Drizzle Zero: One-to-Many Relationship Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/README.md Sets up a one-to-many relationship where users can have multiple posts, and demonstrates querying a user's posts. ```typescript // Drizzle const posts = pgTable('posts', { authorId: text('author_id').references(() => users.id), }); export const postsRelations = relations(posts, ({ one }) => ({ author: one(users), })); export const usersRelations = relations(users, ({ many }) => ({ posts: many(posts), })); // Query const user = await z.query.user.related('posts').one(); console.log(user.posts); // Array of posts ``` -------------------------------- ### Casing drizzleZeroConfig Usage Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/DOCUMENTATION_INDEX.txt Shows how to configure casing conventions for table and column names using drizzleZeroConfig. ```typescript import { drizzleZeroConfig } from "@drizzle-zero/core"; export default drizzleZeroConfig({ casing: "camelCase", tables: { users: { columns: { id: { primaryKey: true, type: "uuid" }, userName: { type: "string" } } } } }); ``` -------------------------------- ### Selective Table and Column Sync Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/configuration.md Configure Drizzle Zero to sync only specific tables and columns. This allows for phased synchronization, starting with critical data and expanding over time. ```typescript // Start: Only sync critical user data export default drizzleZeroConfig(drizzleSchema, { tables: { users: { id: true, name: true, email: true, // Staging columns not yet synced }, }, }); ``` ```typescript // After migration: Add more columns export default drizzleZeroConfig(drizzleSchema, { tables: { users: { id: true, name: true, email: true, avatar: true, // Add // Staging columns still not synced }, }, }); ``` ```typescript // Contract: All synced, can add more tables export default drizzleZeroConfig(drizzleSchema, { tables: { users: { id: true, name: true, email: true, avatar: true, }, posts: { id: true, title: true, authorId: true, }, }, }); ``` -------------------------------- ### Type Inference with createZeroTableBuilder Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-create-zero-table-builder.md Demonstrates how createZeroTableBuilder provides strong type inference for table columns. It shows how to define a Drizzle table and then create a builder, highlighting the inferred types for columns like 'id', 'name', and 'email'. ```typescript import { createZeroTableBuilder } from 'drizzle-zero'; import { pgTable, text, integer } from 'drizzle-orm/pg-core'; const usersTable = pgTable('users', { id: text('id').primaryKey(), name: text('name').notNull(), email: text('email').$type<`${string}@${string}`>(), }); const builder = createZeroTableBuilder('users', usersTable); // Type inference: // - Column 'id' is non-optional string // - Column 'name' is non-optional string // - Column 'email' is optional email string type // - Can only use valid column names from usersTable ``` -------------------------------- ### CLI: Enable Debug Mode Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/configuration.md Command-line option to enable debug logging during schema generation. ```bash drizzle-zero generate --debug ``` -------------------------------- ### Define Primary Key for Tables Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/errors-and-troubleshooting.md Every table must have a primary key defined, either as a single column or a composite key. Examples show correct single and composite primary key definitions. ```typescript // CORRECT: Single primary key const users = pgTable('users', { id: text('id').primaryKey(), name: text('name'), }); // CORRECT: Composite primary key const orders = pgTable( 'orders', { customerId: text('customer_id').notNull(), orderId: text('order_id').notNull(), }, (t) => ({ pk: primaryKey({ columns: [t.customerId, t.orderId] }), }), ); // INCORRECT: No primary key const users = pgTable('users', { id: text('id'), // Missing .primaryKey() name: text('name'), }); ``` -------------------------------- ### Import drizzleZeroConfig (ESM) Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/module-exports.md Demonstrates how to import the drizzleZeroConfig function using ECMAScript Modules (ESM). ```typescript // ESM import { drizzleZeroConfig } from 'drizzle-zero'; ``` -------------------------------- ### Drizzle Zero CLI: Custom Output File Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/README.md Defines a custom file path for the generated schema output. ```bash drizzle-zero generate --output ./src/zero-schema.ts ``` -------------------------------- ### Basic drizzle-zero Configuration Structure Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/configuration.md This is the fundamental structure for a `drizzle-zero.config.ts` file. It requires importing `drizzleZeroConfig` and your schema, then exporting the configuration. ```typescript import { drizzleZeroConfig } from 'drizzle-zero'; import * as drizzleSchema from './db/schema'; export default drizzleZeroConfig(drizzleSchema, { // configuration options }); ``` -------------------------------- ### One-to-One Query Usage Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/relationships.md Demonstrates how to query a profile and access its related user data using Drizzle-Zero's query builder and hooks. ```typescript const profileQuery = syncedQuery( z.query.profile.where('id', '=', profileId).related('user').one(), ); const [profile] = useQuery(profileQuery()); // Type: { id: string, userId: string, bio?: string, user: UserRow } console.log(profile.user.name); ``` -------------------------------- ### Tags/Categories (Many-to-Many) Schema, Config, and Queries Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/relationships.md Demonstrates schema, configuration, and query patterns for many-to-many relationships, using junction tables to link entities. ```typescript // Schema posts <-> tags (through post_tags junction) tags <-> categories (through tag_categories junction) // Configuration manyToMany: { post: { tags: ['postTags', 'tag'], }, tag: { categories: ['tagCategories', 'category'], }, } // Queries const post = z.query.post.where('id', '=', postId).related('tags').one(); const tag = z.query.tag.where('id', '=', tagId).related('categories').one(); ``` -------------------------------- ### One-to-Many Query Usage (Forward) Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/relationships.md Demonstrates querying a post and accessing its related author using Drizzle-Zero. ```typescript const postQuery = syncedQuery( z.query.post.where('id', '=', postId).related('author').one(), ); const [post] = useQuery(postQuery()); console.log(post.author.name); ``` -------------------------------- ### Drizzle Zero CLI Command Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/00_START_HERE.md Use the drizzle-zero CLI to generate your Zero sync engine schemas. This command initiates the schema generation process based on your configuration. ```bash drizzle-zero generate [options] ``` -------------------------------- ### Run Drizzle Zero Generation Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/README.md Execute the npm script to generate the Zero schema and types. This command creates `zero-schema.gen.ts`. ```bash npm run generate ``` -------------------------------- ### Enable Eager Loading with Environment Variable Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/configuration.md Set the DRIZZLE_ZERO_EAGER_LOADING environment variable to enable eager loading of all tsconfig files. This is useful for complex monorepos where type resolution requires all configurations to be loaded upfront. ```bash export DRIZZLE_ZERO_EAGER_LOADING=1 drizzle-zero generate ``` -------------------------------- ### Main Entry Point Exports Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/module-exports.md These are the primary exports from the 'drizzle-zero' package, re-exported from internal modules. They provide access to configuration and table building utilities. ```typescript export { drizzleZeroConfig } from './relations'; export type { CustomType, DrizzleToZeroSchema, ZeroCustomType } from './relations'; // Re-exports from src/tables.ts export { createZeroTableBuilder } from './tables'; export type { ColumnBuilder, ReadonlyJSONValue, TableBuilderWithColumns } from './tables'; export type { ZeroColumns, ZeroTableBuilder } from './tables'; ``` -------------------------------- ### Querying Relationships: One-to-Many (Forward) Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/DOCUMENTATION_INDEX.txt Demonstrates querying the 'many' side of a one-to-many relationship. ```typescript import { builder } from "./zero-schema.gen"; // Assuming 'user' is a user object fetched previously const userPosts = await builder.posts.findMany({ where: { authorId: user.id } }); ``` -------------------------------- ### CLI: Custom tsconfig Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/configuration.md Command-line option to specify a custom TypeScript configuration file path. ```bash drizzle-zero generate --tsconfig ./tsconfig.build.json ``` -------------------------------- ### CLI: Customize Drizzle Kit Config Location Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/configuration.md Command-line option to specify a custom location for the Drizzle Kit configuration file. ```bash drizzle-zero generate --drizzle-kit-config ./config/drizzle.ts ``` -------------------------------- ### Minimal Drizzle Zero Configuration Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/README.md A minimal configuration for `drizzleZeroConfig` that includes all tables and columns from the Drizzle schema. ```typescript // Include all tables and columns export default drizzleZeroConfig(schema); ``` -------------------------------- ### Drizzle Zero: Custom Type Mapping Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/README.md Demonstrates how to preserve custom TypeScript types for columns like email and metadata using the $type() method. ```typescript // Preserve custom TypeScript types export const users = pgTable('users', { email: text('email').$type<`${string}@${string}`>(), metadata: jsonb('metadata').$type(), }); // Generated types include custom types export type UserRow = { email: `${string}@${string}`; metadata: UserMetadata; }; ``` -------------------------------- ### Handling Composite Primary Keys Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-create-zero-table-builder.md Illustrates how createZeroTableBuilder correctly identifies composite primary keys. This snippet defines an 'orders' table with two primary key columns and shows the builder recognizing both. ```typescript const ordersTable = pgTable( 'orders', { customerId: text('customer_id').notNull(), orderId: text('order_id').notNull(), total: integer('total'), }, (table) => ({ pk: primaryKey({columns: [table.customerId, table.orderId]}), }), ); const builder = createZeroTableBuilder('orders', ordersTable); // Correctly identifies both customerId and orderId as primary keys ``` -------------------------------- ### Drizzle-Zero: Include All Tables Configuration Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/configuration.md When no `tables` option is provided in the configuration, drizzle-zero includes all tables and columns by default. This snippet shows the minimal configuration for that behavior. ```typescript // No tables option needed export default drizzleZeroConfig(drizzleSchema); ``` -------------------------------- ### Zero Framework Import Statements Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/generated-schema.md Essential import statements for using the Zero framework, including `createSchema` and `createBuilder`. Also shows the module augmentation declaration for `Tables`. ```typescript import { createSchema } from '@rocicorp/zero'; import { createBuilder } from '@rocicorp/zero'; declare module '@rocicorp/zero' { interface Tables { /* ... */ } } ``` -------------------------------- ### Standard Usage with drizzleZeroConfig Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/api-create-zero-table-builder.md This snippet shows the standard usage of drizzleZeroConfig, which internally calls createZeroTableBuilder. It demonstrates how to configure which columns to include or exclude for a table. ```typescript import { drizzleZeroConfig } from 'drizzle-zero'; import * as schema from './db/schema'; export default drizzleZeroConfig(schema, { tables: { users: { id: true, name: true, age: false, // excluded via config }, }, }); // Internally calls createZeroTableBuilder for 'users' table ``` -------------------------------- ### CLI Generation Commands Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/00_START_HERE.md Commands for generating Zero schemas using the Drizzle Zero CLI. Options include basic generation, formatting, debugging, and forcing overwrites. ```bash # Basic generation drizzle-zero generate ``` ```bash # With formatting drizzle-zero generate --format ``` ```bash # Debug mode drizzle-zero generate --debug ``` ```bash # Force overwrite drizzle-zero generate --force ``` -------------------------------- ### Correct Column Configuration Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/errors-and-troubleshooting.md Use `true` for columns that should be included and `false` to exclude them. For custom configurations, use `column.json()` or other ColumnBuilder methods. ```typescript // CORRECT tables: { users: { id: true, name: true, password: false, metadata: column.json(), }, } ``` -------------------------------- ### One-to-Many Query Usage (Reverse) Source: https://github.com/rocicorp/drizzle-zero/blob/main/_autodocs/relationships.md Demonstrates querying a user and accessing their related posts using Drizzle-Zero. ```typescript const userQuery = syncedQuery( z.query.user.where('id', '=', userId).related('posts').all(), ); const [user] = useQuery(userQuery()); console.log(user.posts.length); // Number of posts ```