Skip to content

inehemiasm/AiAssistant / .agents/skills/firebase-data-connect

firebase-data-connect

Verified

Builds and deploys Firebase SQL Connect (aka Firebase Data Connect) backends with PostgreSQL securely. Use when designing schemas with tables and relations, writing authorized queries and mutations, configuring real-time data updates, or generating type-safe SDKs. Use when you need a relational database with Firebase, or when the user mentions SQL Connect or Data Connect.

FileKindSize
SKILL.mdskill md7.5 KB
examples.mdmarkdown14.4 KB
reference/advanced.mdmarkdown7.2 KB
reference/config.mdmarkdown5.6 KB
reference/native_sql.mdmarkdown6.9 KB
reference/operations.mdmarkdown9.0 KB
reference/realtime.mdmarkdown6.7 KB
reference/schema.mdmarkdown5.9 KB
reference/sdk_admin_node.mdmarkdown4.1 KB
reference/sdk_android.mdmarkdown3.7 KB
reference/sdk_flutter.mdmarkdown3.4 KB
reference/sdk_ios.mdmarkdown4.2 KB
reference/sdk_web.mdmarkdown3.9 KB
reference/security.mdmarkdown7.0 KB
templates.mdmarkdown6.5 KB

reference/advanced.md

View on GitHub
# Advanced Features Reference

## Contents
- [Vector Similarity Search](#vector-similarity-search)
- [Full-Text Search](#full-text-search)
- [Cloud Functions Integration](#cloud-functions-integration)
- [Data Seeding & Bulk Operations](#data-seeding--bulk-operations)

---

## Vector Similarity Search

Semantic search using Vertex AI embeddings and PostgreSQL's `pgvector`.

### Schema Setup

```graphql
type Movie @table {
  id: UUID! @default(expr: "uuidV4()")
  title: String!
  description: String
  # Vector field for embeddings - size must match model output (768 for gecko)
  descriptionEmbedding: Vector! @col(size: 768)
}
```

### Generate Embeddings in Mutations

Use `_embed` server value to auto-generate embeddings via Vertex AI:

```graphql
mutation CreateMovieWithEmbedding($title: String!, $description: String!) 
  @auth(level: USER) {
  movie_insert(data: {
    title: $title,
    description: $description,
    descriptionEmbedding_embed: {
      model: "textembedding-gecko@003",
      text: $description
    }
  })
}
```

### Similarity Search Query

SQL Connect generates `_similarity` fields for Vector columns:

```graphql
query SearchMovies($query: String!) @auth(level: PUBLIC) {
  movies_descriptionEmbedding_similarity(
    compare_embed: { model: "textembedding-gecko@003", text: $query },
    method: L2,         # L2, COSINE, or INNER_PRODUCT
    within: 2.0,        # Max distance threshold
    limit: 5
  ) {
    id
    title
    description
    _metadata { distance }  # See how close each result is
  }
}
```

### Similarity Parameters

| Parameter | Description |
|-----------|-------------|
| `compare` | Raw Vector to compare against |
| `compare_embed` | Generate embedding from text via Vertex AI |
| `method` | Distance function: `L2`, `COSINE`, `INNER_PRODUCT` |
| `within` | Max distance (results further are excluded) |
| `where` | Additional filters |
| `limit` | Max results to return |

### Custom Embeddings

Pass pre-computed vectors directly:

```graphql
mutation StoreCustomEmbedding($id: UUID!, $embedding: Vector!) @auth(level: USER) {
  movie_update(id: $id, data: { descriptionEmbedding: $embedding })
}

query SearchWithCustomVector($vector: Vector!) @auth(level: PUBLIC) {
  movies_descriptionEmbedding_similarity(
    compare: $vector,
    method: COSINE,
    limit: 10
  ) { id title }
}
```

---

## Full-Text Search

Fast keyword/phrase search using PostgreSQL's full-text capabilities.

### Enable with @searchable

```graphql
type Movie @table {
  title: String! @searchable
  description: String @searchable(language: "english")
  genre: String @searchable
}
```

### Search Query

SQL Connect generates `_search` fields:

```graphql
query SearchMovies($query: String!) @auth(level: PUBLIC) {
  movies_search(
    query: $query,
    queryFormat: QUERY,  # QUERY, PLAIN, PHRASE, or ADVANCED
    limit: 20
  ) {
    id title description
    _metadata { relevance }  # Relevance score
  }
}
```

### Query Formats

| Format | Description |
|--------|-------------|
| `QUERY` | Web-style (default): quotes, AND, OR supported |
| `PLAIN` | Match all words, any order |
| `PHRASE` | Match exact phrase |
| `ADVANCED` | Full tsquery syntax |

### Tuning Results

```graphql
query SearchWithThreshold($query: String!) @auth(level: PUBLIC) {
  movies_search(
    query: $query,
    relevanceThreshold: 0.05,  # Min relevance score
    where: { genre: { eq: "Action" }},
    orderBy: [{ releaseYear: DESC }]
  ) { id title }
}
```

### Supported Languages

`english` (default), `french`, `german`, `spanish`, `italian`, `portuguese`, `dutch`, `danish`, `finnish`, `norwegian`, `swedish`, `russian`, `arabic`, `hindi`, `simple`

---

## Cloud Functions Integration

Trigger Cloud Functions when mutations execute.

### Basic Trigger (Node.js)

```typescript
import { onMutationExecuted } from "firebase-functions/dataconnect";
import { logger } from "firebase-functions";

export const onUserCreate = onMutationExecuted(
  {
    service: "myService",
    connector: "default",
    operation: "CreateUser",
    region: "us-central1"  # Must match SQL Connect location
  },
  (event) => {
    const variables = event.data.payload.variables;
    const returnedData = event.data.payload.data;
    
    logger.info("User created:", returnedData);
    // Send welcome email, sync to analytics, etc.
  }
);
```

### Basic Trigger (Python)

```python
from firebase_functions import dataconnect_fn, logger

@dataconnect_fn.on_mutation_executed(
  service="myService",
  connector="default",
  operation="CreateUser"
)
def on_user_create(event: dataconnect_fn.Event):
  variables = event.data.payload.variables
  returned_data = event.data.payload.data
  logger.info("User created:", returned_data)
```

### Event Data

```typescript
// event.authType: "app_user" | "unauthenticated" | "admin"
// event.authId: Firebase Auth UID (for app_user)
// event.data.payload.variables: mutation input variables
// event.data.payload.data: mutation response data
// event.data.payload.errors: any errors that occurred
```

### Filtering with Wildcards

```typescript
// Trigger on all User* mutations
export const onUserMutation = onMutationExecuted(
  { operation: "User*" },
  (event) => { /* ... */ }
);

// Capture operation name
export const onAnyMutation = onMutationExecuted(
  { service: "myService", operation: "{operationName}" },
  (event) => {
    console.log("Operation:", event.params.operationName);
  }
);
```

### Use Cases

- **Data sync**: Replicate to Firestore, BigQuery, external APIs
- **Notifications**: Send emails, push notifications on events
- **Async workflows**: Image processing, data aggregation
- **Audit logging**: Track all data changes

> ⚠️ **Avoid infinite loops**: Don't trigger mutations that would fire the same trigger. Use filters to exclude self-triggered events.

---

## Data Seeding & Bulk Operations

### Local Prototyping with _insertMany

```graphql
mutation SeedMovies @transaction {
  movie_insertMany(data: [
    { id: "uuid-1", title: "Movie 1", genre: "Action" },
    { id: "uuid-2", title: "Movie 2", genre: "Drama" },
    { id: "uuid-3", title: "Movie 3", genre: "Comedy" }
  ])
}
```

### Reset Data with _upsertMany

```graphql
mutation ResetData {
  movie_upsertMany(data: [
    { id: "uuid-1", title: "Movie 1", genre: "Action" },
    { id: "uuid-2", title: "Movie 2", genre: "Drama" }
  ])
}
```

### Clear All Data

```graphql
mutation ClearMovies {
  movie_deleteMany(all: true)
}
```

### Production: Admin SDK Bulk Operations

```typescript
import { initializeApp } from 'firebase-admin/app';
import { getDataConnect } from 'firebase-admin/data-connect';

const app = initializeApp();
const dc = getDataConnect({ location: "us-central1", serviceId: "my-service" });

const movies = [
  { id: "uuid-1", title: "Movie 1", genre: "Action" },
  { id: "uuid-2", title: "Movie 2", genre: "Drama" }
];

// Bulk insert
await dc.insertMany("movie", movies);

// Bulk upsert
await dc.upsertMany("movie", movies);

// Single operations
await dc.insert("movie", movies[0]);
await dc.upsert("movie", movies[0]);
```

### Emulator Data Persistence

```bash
# Export emulator data
npx -y firebase-tools@latest emulators:export ./seed-data

# Start with saved data
npx -y firebase-tools@latest emulators:start --only dataconnect --import=./seed-data
```
writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deploymentStars: 322kUpdated Claude CodeCodexVerifiedInstall
xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.Stars: 197kUpdated Claude CodeCodexVerifiedInstall
shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release.Stars: 118kUpdated Claude CodeCodexVerifiedInstall