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
Kysely Type-Safe SQL Queries

Kysely Type-Safe SQL Queries

Type-safe SQL queries with Kysely for Google Antigravity projects including query builders, transactions, and migrations.

kyselysqldatabasetypescriptqueries
by Antigravity Team
⭐0Stars
.antigravity
# Kysely Type-Safe SQL Queries for Google Antigravity

Master type-safe SQL queries with Kysely in your Google Antigravity IDE projects. This comprehensive guide covers query building, transactions, migrations, and advanced patterns optimized for Gemini 3 agentic development.

## Database Types

Define your database types for full type inference:

```typescript
// db/types.ts
import { Generated, Insertable, Selectable, Updateable } from 'kysely';

export interface Database {
  users: UsersTable;
  prompts: PromptsTable;
  stars: StarsTable;
  comments: CommentsTable;
}

interface UsersTable {
  id: Generated<string>;
  email: string;
  name: string | null;
  image: string | null;
  role: 'user' | 'admin' | 'moderator';
  subscription_tier: string | null;
  created_at: Generated<Date>;
  updated_at: Generated<Date>;
}

interface PromptsTable {
  id: Generated<string>;
  slug: string;
  title: string;
  description: string;
  content: string;
  tags: string[];
  author_id: string | null;
  is_approved: Generated<boolean>;
  view_count: Generated<number>;
  star_count: Generated<number>;
  created_at: Generated<Date>;
  updated_at: Generated<Date>;
}

interface StarsTable {
  user_id: string;
  prompt_id: string;
  created_at: Generated<Date>;
}

interface CommentsTable {
  id: Generated<string>;
  prompt_id: string;
  user_id: string;
  content: string;
  parent_id: string | null;
  created_at: Generated<Date>;
  updated_at: Generated<Date>;
}

// Type helpers
export type User = Selectable<UsersTable>;
export type NewUser = Insertable<UsersTable>;
export type UserUpdate = Updateable<UsersTable>;

export type Prompt = Selectable<PromptsTable>;
export type NewPrompt = Insertable<PromptsTable>;
export type PromptUpdate = Updateable<PromptsTable>;
```

## Kysely Configuration

Set up Kysely with PostgreSQL:

```typescript
// db/index.ts
import { Kysely, PostgresDialect } from 'kysely';
import { Pool } from 'pg';
import { Database } from './types';

const dialect = new PostgresDialect({
  pool: new Pool({
    connectionString: process.env.DATABASE_URL,
    max: 10,
  }),
});

export const db = new Kysely<Database>({
  dialect,
  log: process.env.NODE_ENV === 'development' ? ['query', 'error'] : ['error'],
});

// For serverless environments
import { NeonDialect } from 'kysely-neon';
import { neon } from '@neondatabase/serverless';

export const dbServerless = new Kysely<Database>({
  dialect: new NeonDialect({
    connectionString: process.env.DATABASE_URL!,
  }),
});
```

## Query Patterns

Build type-safe queries with full autocompletion:

```typescript
// lib/queries/prompts.ts
import { db } from '@/db';
import { sql, ExpressionBuilder } from 'kysely';
import { Database } from '@/db/types';

// Simple select query
export async function getPromptBySlug(slug: string) {
  return db
    .selectFrom('prompts')
    .where('slug', '=', slug)
    .where('is_approved', '=', true)
    .selectAll()
    .executeTakeFirst();
}

// Join query with type-safe columns
export async function getPromptWithAuthor(slug: string) {
  return db
    .selectFrom('prompts')
    .innerJoin('users', 'users.id', 'prompts.author_id')
    .where('prompts.slug', '=', slug)
    .select([
      'prompts.id',
      'prompts.slug',
      'prompts.title',
      'prompts.description',
      'prompts.content',
      'prompts.tags',
      'prompts.view_count',
      'prompts.star_count',
      'prompts.created_at',
      'users.id as author_id',
      'users.name as author_name',
      'users.image as author_image',
    ])
    .executeTakeFirst();
}

// Dynamic query building
type PromptFilters = {
  search?: string;
  tags?: string[];
  authorId?: string;
  isApproved?: boolean;
};

export async function searchPrompts(filters: PromptFilters, pagination: { page: number; limit: number }) {
  let query = db
    .selectFrom('prompts')
    .leftJoin('users', 'users.id', 'prompts.author_id')
    .select([
      'prompts.id',
      'prompts.slug',
      'prompts.title',
      'prompts.description',
      'prompts.tags',
      'prompts.star_count',
      'prompts.view_count',
      'users.name as author_name',
    ]);

  // Apply filters dynamically
  if (filters.search) {
    query = query.where((eb) =>
      eb.or([
        eb('prompts.title', 'ilike', `%${filters.search}%`),
        eb('prompts.description', 'ilike', `%${filters.search}%`),
      ])
    );
  }

  if (filters.tags && filters.tags.length > 0) {
    query = query.where(
      sql`prompts.tags && ${sql.literal(filters.tags)}::text[]`
    );
  }

  if (filters.authorId) {
    query = query.where('prompts.author_id', '=', filters.authorId);
  }

  if (filters.isApproved !== undefined) {
    query = query.where('prompts.is_approved', '=', filters.isApproved);
  }

  const offset = (pagination.page - 1) * pagination.limit;

  const [results, countResult] = await Promise.all([
    query
      .orderBy('prompts.created_at', 'desc')
      .limit(pagination.limit)
      .offset(offset)
      .execute(),
    db
      .selectFrom('prompts')
      .select(sql<number>`count(*)::int`.as('count'))
      .executeTakeFirst(),
  ]);

  return {
    prompts: results,
    total: countResult?.count ?? 0,
    page: pagination.page,
    limit: pagination.limit,
    totalPages: Math.ceil((countResult?.count ?? 0) / pagination.limit),
  };
}

// Aggregate queries
export async function getPromptStats(promptId: string) {
  return db
    .selectFrom('prompts')
    .where('id', '=', promptId)
    .select((eb) => [
      'id',
      'title',
      'view_count',
      'star_count',
      eb
        .selectFrom('comments')
        .whereRef('comments.prompt_id', '=', 'prompts.id')
        .select(sql<number>`count(*)::int`.as('count'))
        .as('comment_count'),
    ])
    .executeTakeFirst();
}
```

## Transactions

Handle complex operations with transactions:

```typescript
// lib/mutations/prompts.ts
import { db } from '@/db';
import { sql } from 'kysely';

export async function starPrompt(userId: string, promptId: string) {
  return db.transaction().execute(async (trx) => {
    // Check if already starred
    const existing = await trx
      .selectFrom('stars')
      .where('user_id', '=', userId)
      .where('prompt_id', '=', promptId)
      .selectAll()
      .executeTakeFirst();

    if (existing) {
      // Remove star
      await trx
        .deleteFrom('stars')
        .where('user_id', '=', userId)
        .where('prompt_id', '=', promptId)
        .execute();

      await trx
        .updateTable('prompts')
        .set({ star_count: sql`star_count - 1` })
        .where('id', '=', promptId)
        .execute();

      return { starred: false };
    }

    // Add star
    await trx
      .insertInto('stars')
      .values({ user_id: userId, prompt_id: promptId })
      .execute();

    await trx
      .updateTable('prompts')
      .set({ star_count: sql`star_count + 1` })
      .where('id', '=', promptId)
      .execute();

    return { starred: true };
  });
}

export async function createPromptWithTags(
  data: NewPrompt,
  userId: string
) {
  return db.transaction().execute(async (trx) => {
    // Insert prompt
    const prompt = await trx
      .insertInto('prompts')
      .values({
        ...data,
        author_id: userId,
        slug: generateSlug(data.title),
      })
      .returningAll()
      .executeTakeFirstOrThrow();

    // Update user prompt count
    await trx
      .updateTable('users')
      .set({ prompt_count: sql`prompt_count + 1` })
      .where('id', '=', userId)
      .execute();

    return prompt;
  });
}
```

## Migrations

Create type-safe migrations:

```typescript
// migrations/001_initial.ts
import { Kysely, sql } from 'kysely';

export async function up(db: Kysely<any>): Promise<void> {
  await db.schema
    .createTable('users')
    .addColumn('id', 'uuid', (col) =>
      col.primaryKey().defaultTo(sql`gen_random_uuid()`)
    )
    .addColumn('email', 'varchar(255)', (col) => col.notNull().unique())
    .addColumn('name', 'varchar(255)')
    .addColumn('image', 'text')
    .addColumn('role', 'varchar(50)', (col) => col.notNull().defaultTo('user'))
    .addColumn('created_at', 'timestamptz', (col) =>
      col.notNull().defaultTo(sql`now()`)
    )
    .addColumn('updated_at', 'timestamptz', (col) =>
      col.notNull().defaultTo(sql`now()`)
    )
    .execute();

  await db.schema
    .createTable('prompts')
    .addColumn('id', 'uuid', (col) =>
      col.primaryKey().defaultTo(sql`gen_random_uuid()`)
    )
    .addColumn('slug', 'varchar(255)', (col) => col.notNull().unique())
    .addColumn('title', 'varchar(255)', (col) => col.notNull())
    .addColumn('description', 'text', (col) => col.notNull())
    .addColumn('content', 'text', (col) => col.notNull())
    .addColumn('tags', sql`text[]`, (col) => col.notNull().defaultTo(sql`'{}'`))
    .addColumn('author_id', 'uuid', (col) =>
      col.references('users.id').onDelete('set null')
    )
    .addColumn('is_approved', 'boolean', (col) => col.notNull().defaultTo(false))
    .addColumn('view_count', 'integer', (col) => col.notNull().defaultTo(0))
    .addColumn('star_count', 'integer', (col) => col.notNull().defaultTo(0))
    .addColumn('created_at', 'timestamptz', (col) =>
      col.notNull().defaultTo(sql`now()`)
    )
    .addColumn('updated_at', 'timestamptz', (col) =>
      col.notNull().defaultTo(sql`now()`)
    )
    .execute();

  // Create indexes
  await db.schema
    .createIndex('prompts_slug_idx')
    .on('prompts')
    .column('slug')
    .execute();

  await db.schema
    .createIndex('prompts_author_idx')
    .on('prompts')
    .column('author_id')
    .execute();

  await db.schema
    .createIndex('prompts_tags_idx')
    .on('prompts')
    .using('gin')
    .column('tags')
    .execute();
}

export async function down(db: Kysely<any>): Promise<void> {
  await db.schema.dropTable('prompts').execute();
  await db.schema.dropTable('users').execute();
}
```

## Best Practices

1. **Define database types** for full type inference
2. **Use transactions** for multi-step operations
3. **Create reusable query builders** for common patterns
4. **Leverage dynamic query building** for filters
5. **Use migrations** for schema changes
6. **Add proper indexes** for query performance
7. **Handle errors gracefully** with try-catch

When to Use This Prompt

This kysely prompt is ideal for developers working on:

  • kysely applications requiring modern best practices and optimal performance
  • Projects that need production-ready kysely code with proper error handling
  • Teams looking to standardize their kysely development workflow
  • Developers wanting to learn industry-standard kysely 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 kysely 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 kysely 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 kysely 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 kysely projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...