### Drizzle-GraphQL Integration with Apollo Server Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Sets up Drizzle-GraphQL with Apollo Server to leverage advanced GraphQL features like introspection and plugins. It initializes a PostgreSQL database, builds the GraphQL schema using drizzle-graphql, and starts a standalone Apollo Server with request context. ```typescript import { ApolloServer } from '@apollo/server' import { startStandaloneServer } from '@apollo/server/standalone' import { buildSchema } from 'drizzle-graphql' import { drizzle } from 'drizzle-orm/postgres-js' import postgres from 'postgres' import * as schema from './schema' // Initialize database const client = postgres('postgresql://user:password@host:5432/db') const db = drizzle(client, { schema }) // Generate GraphQL schema const { schema: gqlSchema } = buildSchema(db) // Create Apollo Server const server = new ApolloServer({ schema: gqlSchema, introspection: true, // Enable GraphQL Playground plugins: [ // Add custom plugins for logging, authentication, etc. ] }) // Start server with context const { url } = await startStandaloneServer(server, { listen: { port: 4000 }, context: async ({ req }) => ({ // Add authentication, user info, etc. token: req.headers.authorization, db // Make database available in resolvers if using custom schema }) }) console.log(`Server ready at ${url}`) ``` -------------------------------- ### Multi-Database Setup with Drizzle-GraphQL Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Configures separate GraphQL schemas for PostgreSQL, MySQL, and SQLite databases within a single application. It uses drizzle-orm for database connections and drizzle-graphql to build schemas, then combines them into a unified GraphQLSchema. ```typescript import { buildSchema } from 'drizzle-graphql' import { GraphQLObjectType, GraphQLSchema } from 'graphql' // PostgreSQL setup import { drizzle as pgDrizzle } from 'drizzle-orm/postgres-js' import postgres from 'postgres' import * as pgSchema from './schemas/postgres' const pgClient = postgres('postgresql://user:pass@localhost:5432/pgdb') const pgDb = pgDrizzle(pgClient, { schema: pgSchema }) const { entities: pgEntities } = buildSchema(pgDb) // MySQL setup import { drizzle as mysqlDrizzle } from 'drizzle-orm/mysql2' import mysql from 'mysql2/promise' import * as mysqlSchema from './schemas/mysql' const mysqlConnection = await mysql.createConnection({ host: 'localhost', user: 'user', password: 'pass', database: 'mysqldb' }) const mysqlDb = mysqlDrizzle(mysqlConnection, { schema: mysqlSchema }) const { entities: mysqlEntities } = buildSchema(mysqlDb) // SQLite setup import { drizzle as sqliteDrizzle } from 'drizzle-orm/better-sqlite3' import Database from 'better-sqlite3' import * as sqliteSchema from './schemas/sqlite' const sqliteClient = new Database('sqlite.db') const sqliteDb = sqliteDrizzle(sqliteClient, { schema: sqliteSchema }) const { entities: sqliteEntities } = buildSchema(sqliteDb) // Combine into unified schema const unifiedSchema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'Query', fields: { // PostgreSQL queries pgUsers: pgEntities.queries.users, // MySQL queries mysqlProducts: mysqlEntities.queries.products, // SQLite queries sqliteSettings: sqliteEntities.queries.settings } }), mutation: new GraphQLObjectType({ name: 'Mutation', fields: { createPgUser: pgEntities.mutations.insertIntoUsersSingle, createMysqlProduct: mysqlEntities.mutations.insertIntoProductsSingle, updateSqliteSetting: sqliteEntities.mutations.updateSettings } }) }) ``` -------------------------------- ### GraphQL Fragments for Reusable Queries Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Defines and utilizes GraphQL fragments to create reusable query patterns and improve code organization. This example shows fragments for user and post fields, combining them into a 'UserWithPosts' fragment, and using them in queries. ```graphql # Define reusable fragments fragment UserFields on UsersSelectItem { id name email profession isConfirmed } fragment PostFields on PostsSelectItem { id content authorId } fragment UserWithPosts on UsersSelectItem { ...UserFields posts { ...PostFields } } # Use fragments in queries query GetActiveUsers { users(where: { isConfirmed: { eq: true } }) { ...UserWithPosts } } query GetDevelopers { developers: users(where: { profession: { eq: "Developer" } }) { ...UserFields } } # Expected response { "data": { "users": [ { "id": 1, "name": "John Doe", "email": "john@example.com", "profession": "Developer", "isConfirmed": true, "posts": [ { "id": 1, "content": "First post", "authorId": 1 } ] } ] } } ``` -------------------------------- ### Example Error Response Structure Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt This JSON structure represents a typical error response from a GraphQL API, detailing the error message, location within the query, the affected field, and an internal error code. ```json { "errors": [ { "message": "duplicate key value violates unique constraint \"users_email_key\"", "locations": [{ "line": 2, "column": 3 }], "path": ["insertIntoUsersSingle"], "extensions": { "code": "INTERNAL_SERVER_ERROR" } } ], "data": null } ``` -------------------------------- ### GraphQL Query: Traversing Relations (One-to-Many, Many-to-One) Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt This snippet illustrates how Drizzle-GraphQL automatically generates nested queries to traverse table relations. It shows examples of querying a one-to-many relationship (users and their posts) and a many-to-one relationship (posts and their authors). It also includes examples of filtering and ordering within related data and the expected JSON response for a user with their associated posts. ```graphql # Query with one-to-many relation { users { id name posts { id content } } } # Query with filtered relations { users(where: { profession: { eq: "Developer" } }) { id name posts( where: { content: { like: "%GraphQL%" } }, orderBy: { id: { priority: 1, direction: desc } }, limit: 5 ) { id content } } } # Query with many-to-one relation { posts { id content author { id name email } } } # Expected response { "data": { "users": [ { "id": 1, "name": "John Doe", "posts": [ { "id": 1, "content": "Learning GraphQL" }, { "id": 2, "content": "GraphQL with Drizzle" } ] } ] } } ``` -------------------------------- ### GraphQL Queries: Fetching, Filtering, Ordering, and Pagination Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt This snippet illustrates automatically generated GraphQL queries for fetching multiple records from the 'users' table. It showcases basic selection, filtering using various operators (e.g., `eq`), ordering by fields like `createdAt`, and applying pagination with `limit` and `offset`. The expected response format for a paginated query is also provided. ```graphql # Basic query { users { id name email createdAt profession isConfirmed } } # Query with filtering { users(where: { profession: { eq: "Developer" }, isConfirmed: { eq: true } }) { id name email } } # Query with ordering { users( orderBy: { createdAt: { priority: 1, direction: desc } } ) { id name createdAt } } # Query with pagination { users( limit: 10, offset: 20 ) { id name } } # Expected response { "data": { "users": [ { "id": 21, "name": "John Doe" }, { "id": 22, "name": "Jane Smith" } ] } } ``` -------------------------------- ### GraphQL Error Handling with Drizzle-GraphQL Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Demonstrates how to handle common GraphQL errors, such as queries returning null for non-existent records and mutations failing due to database constraint violations (e.g., unique email). ```graphql # Query that might return null { usersSingle(where: { id: { eq: 999 } }) { id name } } # Response when no record found { "data": { "usersSingle": null } } # Mutation with constraint violation mutation { insertIntoUsersSingle( values: { name: "Duplicate User" email: "existing@example.com" # Assuming unique constraint } ) { id name } } ``` -------------------------------- ### Build GraphQL Schema with Drizzle ORM and GraphQL Yoga Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt This snippet demonstrates the main entry point `buildSchema` function, which generates a complete GraphQL schema from a Drizzle database instance. It sets up Drizzle ORM with PostgreSQL, defines table schemas with relations, and integrates with GraphQL Yoga to create a server. The generated schema supports CRUD operations, filtering, ordering, and pagination. ```typescript import { createServer } from 'node:http' import { createYoga } from 'graphql-yoga' import { buildSchema } from 'drizzle-graphql' import { drizzle } from 'drizzle-orm/postgres-js' import postgres from 'postgres' import { pgTable, serial, text, timestamp, varchar, boolean, integer } from 'drizzle-orm/pg-core' import { relations } from 'drizzle-orm' // Define Drizzle schema const Users = pgTable('users', { id: serial('id').primaryKey(), name: text('name').notNull(), email: text('email'), createdAt: timestamp('created_at').notNull().defaultNow(), profession: varchar('profession', { length: 20 }), isConfirmed: boolean('is_confirmed'), }) const Posts = pgTable('posts', { id: serial('id').primaryKey(), content: text('content'), authorId: integer('author_id'), }) const usersRelations = relations(Users, ({ many }) => ({ posts: many(Posts), })) const postsRelations = relations(Posts, ({ one }) => ({ author: one(Users, { fields: [Posts.authorId], references: [Users.id], }), })) const schema = { Users, Posts, usersRelations, postsRelations } // Initialize database and generate GraphQL schema const client = postgres('postgresql://user:password@host:5432/db') const db = drizzle(client, { schema }) const { schema: gqlSchema } = buildSchema(db) // Create GraphQL server const yoga = createYoga({ schema: gqlSchema }) const server = createServer(yoga) server.listen(4000, () => { console.info('Server running on http://localhost:4000/graphql') }) ``` -------------------------------- ### GraphQL Query: Fetching a Single Record Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt This snippet demonstrates the GraphQL query for fetching a single record, specifically a user, using the `usersSingle` field. It includes all available fields for the user and shows the expected JSON response structure for a single user object, including its ID, name, email, creation timestamp, profession, and confirmation status. ```graphql # Get single user { usersSingle { id name email createdAt profession isConfirmed } } # Expected response { "data": { "usersSingle": { "id": 1, "name": "John Doe", "email": "john@example.com", "createdAt": "2025-11-16T10:30:00.000Z", "profession": "Developer", "isConfirmed": true } } } ``` -------------------------------- ### Generate GraphQL Schema with Drizzle-GraphQL Source: https://github.com/drizzle-team/drizzle-graphql/blob/main/README.md This snippet demonstrates how to use `drizzle-graphql` to automatically build a GraphQL schema from a Drizzle database instance. The generated schema can be directly used with GraphQL servers like GraphQL Yoga. It requires a Drizzle database instance as input and outputs a `schema` object. ```typescript import { createServer } from 'node:http' import { createYoga } from 'graphql-yoga' import { buildSchema } from 'drizzle-graphql' // db - your drizzle instance import { db } from './database' const { schema } = buildSchema(db) const yoga = createYoga({ schema }) server.listen(4000, () => { console.info('Server is running on http://localhost:4000/graphql') }) ``` -------------------------------- ### GraphQL: Combined filters with OR logic Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Filters users based on a combination of exact matches and OR conditions. This demonstrates complex filtering by combining equality checks with OR logic for email or name patterns. ```graphql { users(where: { profession: { eq: "Developer" }, isConfirmed: { eq: true }, OR: [ { email: { like: "%@company.com" } }, { name: { ilike: "%senior%" } } ] }) { id name email profession } } ``` -------------------------------- ### Build Custom Drizzle GraphQL Schema with Selective Operations Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Constructs a custom GraphQL schema by selectively including generated queries and mutations from Drizzle entities, and allows defining custom queries using generated types. Requires 'drizzle-graphql', 'drizzle-orm', and 'graphql' packages. ```typescript import { buildSchema } from 'drizzle-graphql' import { GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLSchema } from 'graphql' import { drizzle } from 'drizzle-orm/postgres-js' import postgres from 'postgres' import * as schema from './schema' const client = postgres('postgresql://user:password@host:5432/db') const db = drizzle(client, { schema }) // Generate entities instead of complete schema const { entities } = buildSchema(db) // Build custom schema with selected operations const customSchema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'Query', fields: { // Include only specific queries users: entities.queries.users, usersSingle: entities.queries.usersSingle, posts: entities.queries.posts, // Create custom query using generated types featuredUsers: { type: new GraphQLList(new GraphQLNonNull(entities.types.UsersSelectItem)), resolve: async () => { return await db.query.Users.findMany({ where: (users, { eq }) => eq(users.isConfirmed, true), limit: 10 }) } } } }), mutation: new GraphQLObjectType({ name: 'Mutation', fields: { // Include only specific mutations createUser: entities.mutations.insertIntoUsersSingle, updateUser: entities.mutations.updateUsers, // Exclude delete operations for safety } }), types: [...Object.values(entities.types), ...Object.values(entities.inputs)] }) // Use the custom schema with your GraphQL server import { createYoga } from 'graphql-yoga' import { createServer } from 'node:http' const yoga = createYoga({ schema: customSchema }) const server = createServer(yoga) server.listen(4000) ``` -------------------------------- ### GraphQL: Filter users by email pattern (like) Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Finds users whose email addresses match a specific pattern, in this case, ending with '@gmail.com'. This showcases string pattern matching using the 'like' operator. ```graphql { users(where: { email: { like: "%@gmail.com" } }) { id name email } } ``` -------------------------------- ### Customize GraphQL Schema with Drizzle-GraphQL Entities Source: https://github.com/drizzle-team/drizzle-graphql/blob/main/README.md This snippet illustrates how to leverage the `entities` object generated by `drizzle-graphql` to create a custom GraphQL schema. It allows developers to select specific queries, mutations, and types from the Drizzle schema, and even define custom query resolvers. It takes a Drizzle database instance and returns `entities` for manual schema construction. ```typescript import { createServer } from 'node:http' import { GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLSchema } from 'graphql' import { createYoga } from 'graphql-yoga' import { buildSchema } from 'drizzle-graphql' // Schema contains 'Users' and 'Customers' tables import { db } from './database' const { entities } = buildSchema(db) // You can customize which parts of queries or mutations you want const schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'Query', fields: { // Select only wanted queries out of all generated users: entities.queries.users, customer: entities.queries.customersSingle, // Create a custom one customUsers: { // You can reuse and customize types from original schema type: new GraphQLList(new GraphQLNonNull(entities.types.UsersItem)), args: { // You can reuse inputs as well where: { type: entities.inputs.UsersFilters } }, resolve: async (source, args, context, info) => { // Your custom logic goes here... const result = await db.select(schema.Users).where()... return result } } } }), // Same rules apply to mutations mutation: new GraphQLObjectType({ name: 'Mutation', fields: entities.mutations }), // In case you need types inside your schema types: [...Object.values(entities.types), ...Object.values(entities.inputs)] }) const yoga = createYoga({ schema }) server.listen(4000, () => { console.info('Server is running on http://localhost:4000/graphql') }) ``` -------------------------------- ### GraphQL: Case-insensitive user name search (ilike) Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Searches for users whose names contain a specific substring, ignoring case differences. The 'ilike' operator facilitates case-insensitive string matching. ```graphql { users(where: { name: { ilike: "%john%" } }) { id name } } ``` -------------------------------- ### GraphQL: Filter posts using OR logic Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Retrieves posts that satisfy at least one of the conditions specified in the OR clause. This allows for flexible filtering based on multiple criteria. ```graphql { posts(where: { OR: [ { id: { lte: 3 } }, { authorId: { eq: 5 } }, { content: { like: "%important%" } } ] }) { id authorId content } } ``` -------------------------------- ### GraphQL Mutation: Insert a single user record Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Inserts a new user record into the 'users' table with specified details and returns the created record, including its ID and creation timestamp. This mutation is designed for adding one record at a time. ```graphql mutation { insertIntoUsersSingle( values: { name: "John Doe" email: "john@example.com" profession: "Developer" isConfirmed: true } ) { id name email createdAt profession isConfirmed } } ``` -------------------------------- ### GraphQL Mutation: Insert multiple user records Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Inserts multiple user records into the 'users' table in a single operation. This is efficient for bulk data entry and returns the IDs and names of the newly created records. ```graphql mutation { insertIntoUsers( values: [ { name: "Alice Johnson" email: "alice@example.com" profession: "Designer" isConfirmed: true } { name: "Bob Smith" email: "bob@example.com" profession: "Manager" isConfirmed: false } { name: "Carol White" email: "carol@example.com" profession: "Developer" isConfirmed: true } ] ) { id name email profession } } ``` -------------------------------- ### GraphQL: Filter posts by ID range (gte, lte) Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Retrieves posts where the ID is greater than or equal to a specified minimum and less than or equal to a specified maximum. This demonstrates the use of comparison operators for range filtering. ```graphql { posts(where: { id: { gte: 10, lte: 20 } }) { id content } } ``` -------------------------------- ### GraphQL Mutation: Update users based on criteria Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Updates existing user records that match the specified 'where' conditions. It sets new values for 'isConfirmed' and 'profession', and returns the updated records. ```graphql mutation { updateUsers( where: { profession: { eq: "Developer" }, isConfirmed: { eq: false } }, set: { isConfirmed: true, profession: "Senior Developer" } ) { id name profession isConfirmed } } ``` -------------------------------- ### GraphQL Mutation: Update posts using OR logic Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Updates post records that meet at least one of the conditions specified in the OR clause (e.g., author ID or content pattern). It modifies the 'content' field for matching posts. ```graphql mutation { updatePosts( where: { OR: [ { authorId: { eq: 1 } }, { content: { like: "%draft%" } } ] }, set: { content: "Updated content" } ) { id content authorId } } ``` -------------------------------- ### Limit Relation Depth in Drizzle GraphQL Schema Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Configures the maximum nesting depth for relations in the generated GraphQL schema to prevent circular dependencies and control query complexity. A depth of 0 disables relations entirely. Requires 'drizzle-graphql' and 'drizzle-orm'. ```typescript import { buildSchema } from 'drizzle-graphql' import { drizzle } from 'drizzle-orm/postgres-js' import postgres from 'postgres' import * as schema from './schema' const client = postgres('postgresql://user:password@host:5432/db') const db = drizzle(client, { schema }) // Limit relations to 2 levels deep const { schema: gqlSchema } = buildSchema(db, { relationsDepthLimit: 2 }) // With limit of 2, this query works: // users { posts { author { name } } } // But this query would fail (3 levels deep): // users { posts { author { posts { content } } } } // Disable relations entirely const { schema: noRelations } = buildSchema(db, { relationsDepthLimit: 0 }) ``` -------------------------------- ### GraphQL: Filter users with non-NULL email (isNotNull) Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Selects users who have a value set for their email address, excluding those where the email is NULL. This is useful for ensuring data completeness. ```graphql { users(where: { email: { isNotNull: true } }) { id name email } } ``` -------------------------------- ### GraphQL: Filter users by ID in array (inArray) Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Retrieves users whose IDs are present within a specified list of values. This demonstrates filtering based on array membership. ```graphql { users(where: { id: { inArray: [1, 2, 3, 5, 8] } }) { id name } } ``` -------------------------------- ### GraphQL Mutation: Delete users with complex filters Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Deletes user records based on a combination of OR logic (unconfirmed or no email) and a date condition (created before a specific date). This allows for precise deletion of records. ```graphql mutation { deleteFromUsers( where: { OR: [ { isConfirmed: { eq: false } }, { email: { isNull: true } } ], createdAt: { lt: "2025-01-01T00:00:00.000Z" } } ) { id name email } } ``` -------------------------------- ### Disable Mutations in Drizzle GraphQL Schema Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Generates a read-only GraphQL schema that excludes all mutation operations (insert, update, delete). This is useful for public APIs or interfaces that only require data retrieval. It requires the 'drizzle-graphql' and 'drizzle-orm' packages. ```typescript import { buildSchema } from 'drizzle-graphql' import { drizzle } from 'drizzle-orm/postgres-js' import postgres from 'postgres' import * as schema from './schema' const client = postgres('postgresql://user:password@host:5432/db') const db = drizzle(client, { schema }) // Generate schema without mutations const { schema: gqlSchema } = buildSchema(db, { mutations: false }) // The resulting schema will only have queries, no insert/update/delete operations // Useful for public APIs or read-only interfaces ``` -------------------------------- ### GraphQL Mutation: Delete posts by author ID Source: https://context7.com/drizzle-team/drizzle-graphql/llms.txt Deletes all post records associated with a specific author ID. This mutation returns the deleted records, including their IDs, content, and author IDs. ```graphql mutation { deleteFromPosts( where: { authorId: { eq: 1 } } ) { id content authorId } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.