Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Drizzle ORM Advanced Patterns

Drizzle ORM Advanced Patterns

Advanced Drizzle ORM patterns for Google Antigravity projects including relations, transactions, and query optimization.

drizzleormpostgresdatabasetypescript
by Antigravity Team
⭐0Stars
.antigravity
# Drizzle ORM Advanced Patterns for Google Antigravity

Master advanced Drizzle ORM patterns in your Google Antigravity IDE projects. This comprehensive guide covers schema design, relations, transactions, and query optimization techniques optimized for Gemini 3 agentic development.

## Schema Definition

Define type-safe database schemas with Drizzle:

```typescript
// db/schema.ts
import {
  pgTable,
  text,
  varchar,
  timestamp,
  integer,
  boolean,
  jsonb,
  uuid,
  index,
  uniqueIndex,
  primaryKey,
} from 'drizzle-orm/pg-core';
import { relations, sql } from 'drizzle-orm';

// Users table
export const users = pgTable(
  'users',
  {
    id: uuid('id').defaultRandom().primaryKey(),
    email: varchar('email', { length: 255 }).notNull().unique(),
    name: varchar('name', { length: 255 }),
    image: text('image'),
    emailVerified: timestamp('email_verified', { mode: 'date' }),
    role: varchar('role', { length: 50 }).default('user').notNull(),
    subscriptionTier: varchar('subscription_tier', { length: 50 }),
    subscriptionStatus: varchar('subscription_status', { length: 50 }),
    metadata: jsonb('metadata').$type<UserMetadata>(),
    createdAt: timestamp('created_at').defaultNow().notNull(),
    updatedAt: timestamp('updated_at').defaultNow().notNull(),
  },
  (table) => ({
    emailIdx: uniqueIndex('users_email_idx').on(table.email),
    roleIdx: index('users_role_idx').on(table.role),
  })
);

// Prompts table
export const prompts = pgTable(
  'prompts',
  {
    id: uuid('id').defaultRandom().primaryKey(),
    slug: varchar('slug', { length: 255 }).notNull().unique(),
    title: varchar('title', { length: 255 }).notNull(),
    description: text('description').notNull(),
    content: text('content').notNull(),
    tags: text('tags').array().notNull().default(sql`ARRAY[]::text[]`),
    authorId: uuid('author_id').references(() => users.id),
    isApproved: boolean('is_approved').default(false).notNull(),
    viewCount: integer('view_count').default(0).notNull(),
    starCount: integer('star_count').default(0).notNull(),
    copyCount: integer('copy_count').default(0).notNull(),
    createdAt: timestamp('created_at').defaultNow().notNull(),
    updatedAt: timestamp('updated_at').defaultNow().notNull(),
  },
  (table) => ({
    slugIdx: uniqueIndex('prompts_slug_idx').on(table.slug),
    authorIdx: index('prompts_author_idx').on(table.authorId),
    approvedIdx: index('prompts_approved_idx').on(table.isApproved),
    tagsIdx: index('prompts_tags_idx').using('gin', table.tags),
  })
);

// Stars table (many-to-many)
export const stars = pgTable(
  'stars',
  {
    userId: uuid('user_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    promptId: uuid('prompt_id')
      .notNull()
      .references(() => prompts.id, { onDelete: 'cascade' }),
    createdAt: timestamp('created_at').defaultNow().notNull(),
  },
  (table) => ({
    pk: primaryKey({ columns: [table.userId, table.promptId] }),
    userIdx: index('stars_user_idx').on(table.userId),
    promptIdx: index('stars_prompt_idx').on(table.promptId),
  })
);

// Define relations
export const usersRelations = relations(users, ({ many }) => ({
  prompts: many(prompts),
  stars: many(stars),
}));

export const promptsRelations = relations(prompts, ({ one, many }) => ({
  author: one(users, {
    fields: [prompts.authorId],
    references: [users.id],
  }),
  stars: many(stars),
}));

export const starsRelations = relations(stars, ({ one }) => ({
  user: one(users, {
    fields: [stars.userId],
    references: [users.id],
  }),
  prompt: one(prompts, {
    fields: [stars.promptId],
    references: [prompts.id],
  }),
}));

// TypeScript types
export type User = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;
export type Prompt = typeof prompts.$inferSelect;
export type NewPrompt = typeof prompts.$inferInsert;
```

## Database Connection

Configure database connection with connection pooling:

```typescript
// db/index.ts
import { drizzle } from 'drizzle-orm/neon-http';
import { neon } from '@neondatabase/serverless';
import * as schema from './schema';

const sql = neon(process.env.DATABASE_URL!);

export const db = drizzle(sql, { schema });

// For transactions, use the pool client
import { drizzle as drizzlePool } from 'drizzle-orm/neon-serverless';
import { Pool } from '@neondatabase/serverless';

const pool = new Pool({ connectionString: process.env.DATABASE_URL });
export const dbPool = drizzlePool(pool, { schema });
```

## Advanced Queries

Implement complex queries with type safety:

```typescript
// lib/queries/prompts.ts
import { db } from '@/db';
import { prompts, users, stars } from '@/db/schema';
import { eq, and, desc, sql, ilike, or, arrayContains } from 'drizzle-orm';

export async function getPromptWithAuthor(slug: string) {
  const result = await db.query.prompts.findFirst({
    where: eq(prompts.slug, slug),
    with: {
      author: {
        columns: {
          id: true,
          name: true,
          image: true,
        },
      },
      stars: true,
    },
  });

  return result;
}

export async function searchPrompts({
  query,
  tags,
  limit = 20,
  offset = 0,
}: {
  query?: string;
  tags?: string[];
  limit?: number;
  offset?: number;
}) {
  const conditions = [eq(prompts.isApproved, true)];

  if (query) {
    conditions.push(
      or(
        ilike(prompts.title, `%${query}%`),
        ilike(prompts.description, `%${query}%`)
      )!
    );
  }

  if (tags && tags.length > 0) {
    conditions.push(arrayContains(prompts.tags, tags));
  }

  const results = await db
    .select({
      prompt: prompts,
      author: {
        id: users.id,
        name: users.name,
        image: users.image,
      },
      starCount: sql<number>`count(${stars.userId})::int`,
    })
    .from(prompts)
    .leftJoin(users, eq(prompts.authorId, users.id))
    .leftJoin(stars, eq(prompts.id, stars.promptId))
    .where(and(...conditions))
    .groupBy(prompts.id, users.id)
    .orderBy(desc(prompts.createdAt))
    .limit(limit)
    .offset(offset);

  return results;
}

export async function getTrendingPrompts(days: number = 7) {
  const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000);

  return db
    .select({
      prompt: prompts,
      recentStars: sql<number>`
        count(${stars.userId}) filter (where ${stars.createdAt} > ${since})
      `::int,
    })
    .from(prompts)
    .leftJoin(stars, eq(prompts.id, stars.promptId))
    .where(eq(prompts.isApproved, true))
    .groupBy(prompts.id)
    .orderBy(desc(sql`recent_stars`))
    .limit(10);
}
```

## Transactions

Handle complex operations with transactions:

```typescript
// lib/mutations/prompts.ts
import { dbPool } from '@/db';
import { prompts, stars, notifications } from '@/db/schema';
import { eq, sql } from 'drizzle-orm';

export async function starPrompt(userId: string, promptId: string) {
  return dbPool.transaction(async (tx) => {
    // Check if already starred
    const existing = await tx.query.stars.findFirst({
      where: and(
        eq(stars.userId, userId),
        eq(stars.promptId, promptId)
      ),
    });

    if (existing) {
      // Remove star
      await tx.delete(stars).where(
        and(eq(stars.userId, userId), eq(stars.promptId, promptId))
      );

      await tx
        .update(prompts)
        .set({ starCount: sql`${prompts.starCount} - 1` })
        .where(eq(prompts.id, promptId));

      return { starred: false };
    }

    // Add star
    await tx.insert(stars).values({ userId, promptId });

    const [prompt] = await tx
      .update(prompts)
      .set({ starCount: sql`${prompts.starCount} + 1` })
      .where(eq(prompts.id, promptId))
      .returning();

    // Create notification for author
    if (prompt.authorId && prompt.authorId !== userId) {
      await tx.insert(notifications).values({
        userId: prompt.authorId,
        type: 'star',
        title: 'New star on your prompt',
        message: `Someone starred your prompt "${prompt.title}"`,
        metadata: { promptId, promptSlug: prompt.slug },
      });
    }

    return { starred: true };
  });
}
```

## Best Practices

1. **Use relations** for type-safe eager loading
2. **Create indexes** for frequently queried columns
3. **Use transactions** for multi-step operations
4. **Leverage prepared statements** for repeated queries
5. **Implement soft deletes** for important data
6. **Use database-level constraints** for data integrity
7. **Monitor query performance** with explain analyze

When to Use This Prompt

This drizzle prompt is ideal for developers working on:

  • drizzle applications requiring modern best practices and optimal performance
  • Projects that need production-ready drizzle code with proper error handling
  • Teams looking to standardize their drizzle development workflow
  • Developers wanting to learn industry-standard drizzle patterns and techniques

By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their drizzle implementations.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the drizzle code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this drizzle prompt commercially?

Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.

Which AI assistants work best with this prompt?

This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.

How do I customize this prompt for my specific needs?

You can modify the prompt by adding specific requirements, constraints, or preferences. For drizzle projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...