### Running the Full Stack Application Source: https://context7.com/drizzle-team/drizzle-trpc-zod/llms.txt Commands to install dependencies, start the tRPC server, and run the client script to demonstrate the full stack integration. ```bash # Install dependencies npm i # Start the tRPC server on http://127.0.0.1:4000 npm run start:server # In a separate terminal — run the client demo npm run start:client # Output: # { id: 1, name: 'Daniel', email: 'daniel@radcliffe.com', projectRole: 'user' } # [ { id: 1, name: 'Daniel', email: 'daniel@radcliffe.com', projectRole: 'user' } ] ``` -------------------------------- ### Start Server and Client Applications Source: https://github.com/drizzle-team/drizzle-trpc-zod/blob/main/readme.md Launches the server and client applications. Ensure the Neon database is prepared and environment variables are set. ```shell npm run start:server npm run start:client ``` -------------------------------- ### Example SQL Migration File Source: https://context7.com/drizzle-team/drizzle-trpc-zod/llms.txt An auto-generated SQL migration file created by drizzle-kit, defining the 'users' table schema. ```sql -- drizzle/20230126114212/migration.sql (auto-generated) CREATE TABLE IF NOT EXISTS "users" ( "id" serial PRIMARY KEY NOT NULL, "name" text NOT NULL, "email" text, "role" text ); ``` -------------------------------- ### Install Node Modules Source: https://github.com/drizzle-team/drizzle-trpc-zod/blob/main/readme.md Installs project dependencies using npm. Ensure Node.js and npm are installed. ```shell npm i ``` -------------------------------- ### Generate SQL Migrations with Drizzle Kit Source: https://github.com/drizzle-team/drizzle-trpc-zod/blob/main/readme.md Automatically generates SQL migrations based on schema changes in `src/schema.ts`. Requires drizzle-kit to be installed. ```shell npm run generate ``` -------------------------------- ### Configure Neon Database Credentials Source: https://github.com/drizzle-team/drizzle-trpc-zod/blob/main/readme.md Sets up environment variables for Neon database connection. Replace placeholders with your actual Neon credentials. ```dotenv ## see https://neon.tech/docs/guides/node/ PGHOST=':' PGDATABASE='' PGUSER='' PGPASSWORD='' ENDPOINT_ID='' ``` -------------------------------- ### Database Connection (Neon + Drizzle ORM) Source: https://context7.com/drizzle-team/drizzle-trpc-zod/llms.txt Establishes a connection to a Neon serverless PostgreSQL database using the `postgres` driver and Drizzle ORM. The connection string is constructed from environment variables, and migrations are run on startup. ```APIDOC ## Database Connection (Neon + Drizzle ORM) Establishes a connection to a Neon serverless PostgreSQL database using the `postgres` driver with SSL required, then wraps it with Drizzle ORM for type-safe query building. The connection string is assembled from environment variables following Neon's recommended format, which includes the `ENDPOINT_ID` as a query parameter. ```typescript // src/server.ts (connection setup excerpt) import { drizzle } from "drizzle-orm/postgres.js"; import { migrate } from "drizzle-orm/postgres.js/migrator"; import postgres from "postgres"; import { config } from "dotenv"; config(); // loads .env const { PGHOST, PGDATABASE, PGUSER, PGPASSWORD, ENDPOINT_ID } = process.env; // Neon connection string format const URL = `postgres://${PGUSER}:${PGPASSWORD}@${PGHOST}/${PGDATABASE}?options=project%3D${ENDPOINT_ID}`; const connection = postgres(URL, { ssl: "require", max: 1 }); const db = drizzle(connection); // Run migrations from the ./drizzle folder on startup await migrate(db, { migrationsFolder: "./drizzle" }); ``` ```ini # .env (required variables) PGHOST='ep-cool-darkness-123456.us-east-2.aws.neon.tech:5432' PGDATABASE='neondb' PGUSER='myuser' PGPASSWORD='mypassword' ENDPOINT_ID='ep-cool-darkness-123456' ``` ``` -------------------------------- ### Automatic Migration Application Source: https://context7.com/drizzle-team/drizzle-trpc-zod/llms.txt Applies database migrations automatically on server startup. Ensure the `migrationsFolder` path is correctly configured. ```typescript // Applied automatically in src/server.ts on startup await migrate(db, { migrationsFolder: "./drizzle" }); ``` -------------------------------- ### Connect to Neon PostgreSQL with Drizzle ORM Source: https://context7.com/drizzle-team/drizzle-trpc-zod/llms.txt Establishes a connection to a Neon serverless PostgreSQL database using the `postgres` driver and Drizzle ORM. Ensure environment variables for connection details are set. Migrations are run on startup. ```typescript // src/server.ts (connection setup excerpt) import { drizzle } from "drizzle-orm/postgres.js"; import { migrate } from "drizzle-orm/postgres.js/migrator"; import postgres from "postgres"; import { config } from "dotenv"; config(); // loads .env const { PGHOST, PGDATABASE, PGUSER, PGPASSWORD, ENDPOINT_ID } = process.env; // Neon connection string format const URL = `postgres://${PGUSER}:${PGPASSWORD}@${PGHOST}/${PGDATABASE}?options=project%3D${ENDPOINT_ID}`; const connection = postgres(URL, { ssl: "require", max: 1 }); const db = drizzle(connection); // Run migrations from the ./drizzle folder on startup await migrate(db, { migrationsFolder: "./drizzle" }); ``` ```ini # .env (required variables) PGHOST='ep-cool-darkness-123456.us-east-2.aws.neon.tech:5432' PGDATABASE='neondb' PGUSER='myuser' PGPASSWORD='mypassword' ENDPOINT_ID='ep-cool-darkness-123456' ``` -------------------------------- ### Database Migration Generation with drizzle-kit Source: https://context7.com/drizzle-team/drizzle-trpc-zod/llms.txt Auto-generates SQL migration files by diffing schema changes. Run `npm run generate` to create timestamped migration SQL files and JSON snapshots. Migrations are applied automatically on server startup. ```bash # Generate a new migration after editing src/schema.ts npm run generate # → drizzle/20230126114212/migration.sql # → drizzle/20230126114212/snapshot.json ``` -------------------------------- ### Create User with tRPC, Drizzle, and Zod Source: https://context7.com/drizzle-team/drizzle-trpc-zod/llms.txt Creates a new user row using Drizzle ORM and validates input against a Zod schema. Uses `.returning()` to return the full inserted row, including the auto-generated ID. Ensure the Zod schema `apiCreateUser` is defined and input adheres to it. ```typescript // Server definition (src/server.ts) createUser: t.procedure.input(apiCreateUser).mutation(async (req) => { return await db.insert(users).values(req.input).returning(); // Returns: Array<{ id: number; name: string; email: string | null; projectRole: "admin" | "user" | null }> }), // Client usage (src/client.ts) const [inserted] = await trpc.createUser.mutate({ name: "Daniel", email: "daniel@radcliffe.com", projectRole: "user", // must be "admin" | "user" — enforced by Zod }); console.log(inserted); // Output: { id: 1, name: "Daniel", email: "daniel@radcliffe.com", projectRole: "user" } // Validation error at runtime if enum constraint is violated: // await trpc.createUser.mutate({ name: "Bob", projectRole: "superuser" }); // ❌ TRPCClientError: [{ "code": "invalid_enum_value", "path": ["projectRole"], ... }] ``` -------------------------------- ### Create User Mutation Source: https://context7.com/drizzle-team/drizzle-trpc-zod/llms.txt Creates a new user in the database using a TRPC mutation. Input is validated against a Zod schema, and the mutation returns the newly inserted row, including the auto-generated ID. ```APIDOC ## createUser.mutate ### Description Creates a new user row in the database. The procedure's input is validated against the `apiCreateUser` Zod schema. On success, it uses Drizzle ORM's `.returning()` to return the full inserted row, including the auto-generated `id`. ### Method MUTATE ### Endpoint `/createUser` ### Parameters #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Optional - The email address of the user. - **projectRole** (string) - Required - The role of the user, must be "admin" or "user". ### Request Example ```typescript // Client usage const [inserted] = await trpc.createUser.mutate({ name: "Daniel", email: "daniel@radcliffe.com", projectRole: "user", }); ``` ### Response #### Success Response (200) - **insertedUser** (object) - An array containing the newly created user object with auto-generated ID. ### Response Example ```json [ { "id": 1, "name": "Daniel", "email": "daniel@radcliffe.com", "projectRole": "user" } ] ``` ``` -------------------------------- ### tRPC Query to List All Users and Client Usage Source: https://context7.com/drizzle-team/drizzle-trpc-zod/llms.txt A tRPC query procedure to fetch all records from the `users` table using Drizzle ORM. The client-side demonstrates how to use the tRPC proxy client to call this query. ```typescript // Server definition (src/server.ts) users: t.procedure.query(async () => { return await db.select(users); // Returns: Array<{ id: number; name: string; email: string | null; projectRole: "admin" | "user" | null }> }), // Client usage (src/client.ts) import { createTRPCProxyClient, httpBatchLink } from "@trpc/client"; import type { AppRouter } from "./server"; const trpc = createTRPCProxyClient({ links: [httpBatchLink({ url: "http://127.0.0.1:4000/trpc" })], }); const all = await trpc.users.query(); console.log(all); // Output: // [ // { id: 1, name: "Daniel", email: "daniel@radcliffe.com", projectRole: "user" }, // { id: 2, name: "Emma", email: "emma@watson.com", projectRole: "admin" } // ] ``` -------------------------------- ### Fetch User by ID with tRPC and Drizzle Source: https://context7.com/drizzle-team/drizzle-trpc-zod/llms.txt Fetches a single user by their numeric ID. Input is validated by tRPC using Zod, and Drizzle ORM performs a WHERE clause filter. Ensure 'drizzle-orm/expressions' is imported for 'eq'. ```typescript // Server definition (src/server.ts) import { eq } from "drizzle-orm/expressions"; userById: t.procedure.input(z.number()).query(async (req) => { const result = await db.select(users).where(eq(users.id, req.input)); return result[0]; // Returns: { id: number; name: string; email: string | null; projectRole: "admin" | "user" | null } | undefined }), // Client usage (src/client.ts) const user = await trpc.userById.query(1); console.log(user); // Output: { id: 1, name: "Daniel", email: "daniel@radcliffe.com", projectRole: "user" } // TypeScript error caught at compile time — passing a string is rejected: // await trpc.userById.query("1"); // ❌ Argument of type 'string' is not assignable to parameter of type 'number' ``` -------------------------------- ### Define PostgreSQL Table and Derive Zod Schemas with drizzle-zod Source: https://context7.com/drizzle-team/drizzle-trpc-zod/llms.txt Defines a PostgreSQL table using Drizzle ORM and automatically derives Zod validation schemas. Use `createInsertSchema` for table insert shapes and `omit` for specific field exclusions. Custom field overrides can be provided. ```typescript // src/schema.ts import { pgTable, serial, text } from "drizzle-orm/pg-core"; import { z } from "zod"; import { createInsertSchema } from "drizzle-zod/pg"; // Define the PostgreSQL table export const users = pgTable("users", { id: serial("id").primaryKey(), name: text("name").notNull(), email: text("email"), projectRole: text<"admin" | "user">("role"), }); // Auto-derive a Zod insert schema from the table definition, // overriding `projectRole` with a strict enum validator. export const apiUser = createInsertSchema(users, { projectRole: z.enum(["admin", "user"]), }); // Schema for the create-user API (id is generated by the DB, so omit it) export const apiCreateUser = apiUser.omit({ id: true }); // apiCreateUser is equivalent to: // z.object({ name: z.string(), email: z.string().optional(), projectRole: z.enum(["admin","user"]).optional() }) ``` -------------------------------- ### tRPC Router - List All Users Source: https://context7.com/drizzle-team/drizzle-trpc-zod/llms.txt A tRPC query procedure that retrieves all records from the `users` table. It uses Drizzle ORM's `db.select(users)` to fetch data and returns a fully typed array of user objects. No input validation is required for this query. ```APIDOC ## tRPC Router — `users.query` Lists all rows from the `users` table. This is a tRPC query procedure (read-only) with no input validation required. It uses Drizzle ORM's `db.select(users)` to fetch every record and returns the full typed array. ```typescript // Server definition (src/server.ts) users: t.procedure.query(async () => { return await db.select(users); // Returns: Array<{ id: number; name: string; email: string | null; projectRole: "admin" | "user" | null }> }), // Client usage (src/client.ts) import { createTRPCProxyClient, httpBatchLink } from "@trpc/client"; import type { AppRouter } from "./server"; const trpc = createTRPCProxyClient({ links: [httpBatchLink({ url: "http://127.0.0.1:4000/trpc" })], }); const all = await trpc.users.query(); console.log(all); // Output: // [ // { id: 1, name: "Daniel", email: "daniel@radcliffe.com", projectRole: "user" }, // { id: 2, name: "Emma", email: "emma@watson.com", projectRole: "admin" } // ] ``` ``` -------------------------------- ### User Query by ID Source: https://context7.com/drizzle-team/drizzle-trpc-zod/llms.txt Fetches a single user by their numeric ID using a TRPC query. Input is validated with Zod, and Drizzle ORM is used for database interaction. ```APIDOC ## userById.query ### Description Fetches a single user by their numeric `id`. The procedure takes a `z.number()` input validator enforced by tRPC, then uses Drizzle ORM's `eq` expression helper to perform a `WHERE id = ?` filter and returns the first (and only) matching row. ### Method QUERY ### Endpoint `/userById` ### Parameters #### Query Parameters - **id** (number) - Required - The numeric ID of the user to fetch. ### Request Example ```typescript // Client usage const user = await trpc.userById.query(1); ``` ### Response #### Success Response (200) - **user** (object) - The user object containing id, name, email, and projectRole. ### Response Example ```json { "id": 1, "name": "Daniel", "email": "daniel@radcliffe.com", "projectRole": "user" } ``` ``` -------------------------------- ### Define Drizzle Schema with Zod Integration Source: https://github.com/drizzle-team/drizzle-trpc-zod/blob/main/readme.md Defines a Drizzle ORM table schema and creates a Zod schema for API user creation, including enum validation for project roles. Requires drizzle-orm-pg, drizzle-zod/pg, and zod. ```typescript import { pgTable, serial, text } from "drizzle-orm-pg"; import { createInsertSchema } from "drizzle-zod/pg"; import { z } from "zod"; export const users = pgTable("users", { id: serial("id").primaryKey(), name: text("name").notNull(), email: text("email"), projectRole: text<"admin" | "user">("role"), }); export const apiUser = createInsertSchema(users, { projectRole: z.enum(["admin", "user"]), }); // zod schema for API user creation export const apiCreateUser = apiUser.omit({ id: true }) ``` -------------------------------- ### Schema Definition with drizzle-zod Source: https://context7.com/drizzle-team/drizzle-trpc-zod/llms.txt Defines a PostgreSQL table using Drizzle ORM and automatically derives Zod validation schemas. The `createInsertSchema` function generates a Zod schema from the Drizzle table definition, which can be customized. The `apiCreateUser` schema is derived by omitting the `id` field, suitable for API input. ```APIDOC ## Schema Definition with `drizzle-zod` Defines the `users` PostgreSQL table using Drizzle ORM and automatically derives Zod validation schemas from it via `drizzle-zod`. `createInsertSchema` generates a Zod schema matching the table's insert shape; custom field overrides (e.g., `projectRole` as a strict enum) can be passed as a second argument. The resulting schemas are exported and reused directly in tRPC procedure input validators, ensuring the database shape and API validation are always in sync. ```typescript // src/schema.ts import { pgTable, serial, text } from "drizzle-orm/pg-core"; import { z } from "zod"; import { createInsertSchema } from "drizzle-zod/pg"; // Define the PostgreSQL table export const users = pgTable("users", { id: serial("id").primaryKey(), name: text("name").notNull(), email: text("email"), projectRole: text<"admin" | "user">("role"), }); // Auto-derive a Zod insert schema from the table definition, // overriding `projectRole` with a strict enum validator. export const apiUser = createInsertSchema(users, { projectRole: z.enum(["admin", "user"]), }); // Schema for the create-user API (id is generated by the DB, so omit it) export const apiCreateUser = apiUser.omit({ id: true }); // apiCreateUser is equivalent to: // z.object({ name: z.string(), email: z.string().optional(), projectRole: z.enum(["admin","user"]).optional() }) ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.