# Google Sheets Extension

### Overview

The Databar Google Sheets Extension brings the power of Databar's enrichment functionality directly into Google Sheets. Run enrichments and waterfalls using custom formulas or the interactive sidebar, with built-in caching, rate limiting, and batch processing capabilities.

***

### Getting Started

#### Installation

1. Open your Google Sheet
2. Go to **Extensions** > **Apps Script**
3. Copy and paste the Databar extension code files
4. Save and refresh your sheet

#### Configuration

**Setting Up Your API Key**

**Method 1: Via Menu**

1. Click **Databar.ai** in the menu bar
2. Select **Configure API Key**
3. Enter your API key from [databar.ai](https://databar.ai)
4. Click **OK**

**Method 2: Via Sidebar**

1. Open **Databar.ai** > **Open Sidebar**
2. Click **Configure API Key** button
3. Enter your API key
4. The sidebar will update to show "Connected to Databar.ai"

**Managing Your API Key**

* **Edit Key**: Click the **Edit key** button in the sidebar
* **Remove Key**: In the edit dialog, choose **Remove Key**
* **Test Connection**: **Databar.ai** menu > **Test Connection**

***

### Using the Sidebar

The sidebar is your command center for generating formulas and managing enrichments.

#### Opening the Sidebar

**Databar.ai** menu > **Open Sidebar**

#### Main Interface

The sidebar features:

* **API Key Status** - Shows connection status
* **Enrichment search** - Browse and configure enrichments
* **Quick Actions** - Jobs, Help, and Settings
* **Direct Link** - Databar logo links to your tables

#### Enrichment search

**Browsing Enrichments**

1. Open the sidebar
2. Browse the list of available enrichments and waterfalls
3. Use the **search bar** to filter by name or description
4. **Waterfalls appear first** in the list

**Enrichment Cards Show:**

* Name and description
* ID or identifier
* Price (single value or range for waterfalls)
* Data source

### **Configuring an Enrichment**

All enrichments work through formulas.

1. **Click an enrichment card**
2. **Configure Inputs** - Fill in required parameters
   * Type cell references (e.g., `A2`) for dynamic data
   * Type static values for fixed data
   * Required fields marked with `*`
3. **Select Output Format**
   * **Single cell (JSON)** - Returns JSON in one cell
   * **Multiple cells (expanded)** - Headers + values in separate cells
4. **Select Fields** (for expanded format only)
   * Choose which fields to include
   * Use "Select All" to toggle all fields
5. **Copy Formula** - Click the button to copy to clipboard

**Configuring a Waterfall**

Waterfalls have an additional step:

**Select Providers**

1. Check which providers to use in the waterfall
2. **Reorder** providers using ▲ ▼ arrows
   * First provider is tried first
   * Order matters for cost optimization
3. **Uncheck** providers to exclude them
   * Unchecked providers move to the bottom automatically

***

### Enrichment functions

Use these functions directly in your spreadsheet cells.

#### DATABAR\_ENRICH

Run a single enrichment and return JSON.

**Syntax:**

```
=DATABAR_ENRICH(enrichmentId, paramName1, paramValue1, [paramName2, paramValue2, ...], ["BYPASS_CACHE"])
```

**Parameters:**

* `enrichmentId` - The enrichment ID (e.g., `10`)
* `paramName` - Parameter name (e.g., `"email"`)
* `paramValue` - Cell reference or value (e.g., `A2` or `"test@example.com"`)
* `BYPASS_CACHE` - Optional: Force fresh API call, ignore cache

**Examples:**

Basic enrichment:

```
=DATABAR_ENRICH(10, "email", A2)
```

Multiple parameters:

```
=DATABAR_ENRICH(6, "email", A2, "domain", B2)
```

Bypass cache:

```
=DATABAR_ENRICH(10, "email", A2, "BYPASS_CACHE")
```

**Returns:** JSON object with enrichment results

**Usage Tips:**

* Use `DATABAR_JSON_EXTRACT` to extract specific fields
* Results are cached for 24 hours
* Empty parameters show as `{{param_REF}}` placeholders

***

#### DATABAR\_ENRICH\_EXPAND

Run an enrichment and expand results into multiple cells.

**Syntax:**

```
=DATABAR_ENRICH_EXPAND(enrichmentId, paramName1, paramValue1, [...], ["field1,field2"], ["BYPASS_CACHE"])
```

**Parameters:**

* Same as `DATABAR_ENRICH`
* `fields` - Optional: Comma-separated list of fields to return (e.g., `"status,score,domain"`)
* If no fields specified, all fields are returned

**Examples:**

All fields:

```
=DATABAR_ENRICH_EXPAND(10, "email", A2)
```

Specific fields:

```
=DATABAR_ENRICH_EXPAND(10, "email", A2, "status,score,domain")
```

**Returns:**

* Row 1: Field names (headers)
* Row 2: Field values

**Usage Tips:**

* Perfect for creating structured data tables
* Automatically expands to fill multiple columns
* Use field filtering to show only what you need

***

#### DATABAR\_WATERFALL

Run a waterfall enrichment and return concatenated results.

**Syntax:**

```
=DATABAR_WATERFALL(waterfallId, paramName1, paramValue1, [...], "enrichmentIds", ["BYPASS_CACHE"])
```

**Parameters:**

* `waterfallId` - Waterfall identifier (e.g., `"email_getter"`)
* `paramName` / `paramValue` - Parameters for the waterfall
* `enrichmentIds` - **Required**: Comma-separated provider IDs (e.g., `"87,380,612"`)
* `BYPASS_CACHE` - Optional: Force fresh execution

**Examples:**

Email waterfall:

```
=DATABAR_WATERFALL("email_getter", "first_name", A2, "last_name", B2, "company", C2, "612,833,87")
```

With cache bypass:

```
=DATABAR_WATERFALL("email_getter", "first_name", A2, "last_name", B2, "company", C2, "612,833", "BYPASS_CACHE")
```

**Returns:**

* **Cell 1** (where formula is): Concatenated result values (e.g., `"david@databar.ai"`)
* **Cell 2** (next cell right): Full JSON with `enrichment_data`, `result`, and `steps`

**Usage Tips:**

* Order providers by cost (cheapest first) to minimize spending
* First successful provider stops the waterfall
* Use the full JSON to see which provider succeeded and the cost
* Use `DATABAR_JSON_EXTRACT` on the second cell to extract details

**Example with JSON Extract:**

Get the email from the waterfall:

```
=DATABAR_JSON_EXTRACT(B2, "result.email")
```

See which provider succeeded:

```
=DATABAR_JSON_EXTRACT(B2, "steps[0].provider")
```

Check the cost:

```
=DATABAR_JSON_EXTRACT(B2, "steps[0].cost")
```

***

#### DATABAR\_WATERFALL\_EXPAND

Run a waterfall and expand results into multiple cells.

**Syntax:**

```
=DATABAR_WATERFALL_EXPAND(waterfallId, paramName1, paramValue1, [...], "enrichmentIds", ["fields"], ["BYPASS_CACHE"])
```

**Parameters:**

* Same as `DATABAR_WATERFALL`
* `fields` - Optional: Filter to specific output fields

**Returns:**

* Row 1: Field names
* Row 2: Field values
* Includes all fields from the waterfall result

***

#### DATABAR\_JSON\_EXTRACT

Extract specific values from JSON results.

**Syntax:**

```
=DATABAR_JSON_EXTRACT(jsonCell, path)
```

**Parameters:**

* `jsonCell` - Cell containing JSON (from `DATABAR_ENRICH` or `DATABAR_WATERFALL`)
* `path` - Path to value using dot notation and array indices

**Path Syntax:**

* Simple field: `"status"`
* Nested field: `"user.name"`
* Array index: `"items[0]"`
* Complex: `"data.users[0].email"`

**Examples:**

Extract email:

```
=DATABAR_JSON_EXTRACT(A2, "result.email")
```

Get first step action:

```
=DATABAR_JSON_EXTRACT(A2, "steps[0].action")
```

Extract nested data:

```
=DATABAR_JSON_EXTRACT(A2, "enrichment_data.Hunter.io API.email")
```

**Returns:** The extracted value, or `ERROR: Path not found` if path doesn't exist

***

#### DATABAR\_STATUS

Check the status of a long-running enrichment.

**Syntax:**

```
=DATABAR_STATUS(taskId)
```

**Parameters:**

* `taskId` - The task ID from a `PROCESSING` message

**Example:**

```
=DATABAR_STATUS("abc123-def456-ghi789")
```

**Returns:** Current status and result if completed

***

### Batch Enrichment Tool

For processing large datasets without formulas.

#### When to Use Batch Tool

* Processing 100+ rows
* One-time enrichments
* Want static values (no recalculation)
* Maximum credit safety

#### How to Use

1. **Select Input Data**
   * Highlight a column (e.g., `A2:A1000`)
2. **Open Batch Tool**
   * **Databar.ai** menu > **Tools** > **Batch Enrich (Static Values)**
3. **Configure**
   * **Step 1**: Enter enrichment ID
   * **Step 2**: Enter parameter name (e.g., `"email"`)
   * **Step 3**: Review estimated cost
4. **Confirm & Run**
   * Wait for progress updates (every 10 rows)
   * Results written to next column as static values
5. **Review Results**
   * Success/error summary displayed
   * Static values never recalculate

#### Batch Tool Benefits

✅ Static values (never re-run) ✅ Progress tracking ✅ Cost estimation ✅ Error handling per row ✅ No accidental credit burn

***

### Understanding Results

#### Regular Enrichment Results

**JSON Format:**

```json
{
  "status": "valid",
  "score": 95,
  "domain": "example.com",
  "mx_record": "mail.example.com"
}
```

**Expanded Format:**

| status | score | domain      | mx\_record       |
| ------ | ----- | ----------- | ---------------- |
| valid  | 95    | example.com | mail.example.com |

#### Waterfall Results

**Cell 1 (Concatenated):**

```
david@databar.ai
```

**Cell 2 (Full JSON):**

```json
{
  "enrichment_data": {
    "Hunter.io API": {
      "email": "david@databar.ai",
      "score": 95,
      "verification_status": "valid"
    }
  },
  "result": {
    "email": "david@databar.ai"
  },
  "steps": [
    {
      "action": "Tried Hunter.io API",
      "provider": "Hunter.io API",
      "result": "completed",
      "cost": "6.00",
      "provider_logo": "/media/external_source_logo/Hunter.io.png"
    }
  ],
  "result_field": ["email"]
}
```

**What Each Field Means:**

* `enrichment_data` - Full data from the successful provider
* `result` - Final extracted values (what you asked for)
* `steps` - Details about each provider tried
  * `action` - What was attempted
  * `provider` - Which provider was used
  * `result` - Outcome (completed/failed)
  * `cost` - Credits used
* `result_field` - Which fields were extracted

#### No Data Response

When enrichment returns no data:

* Regular enrichments: `"No data"`
* Waterfalls: Cell 1: `"No data"`, Cell 2: Full JSON (shows why)

***

Jobs Panel

Track your enrichment executions:

1. Click the **clipboard icon** in the header
2. View recent jobs with:
   * Enrichment name
   * Status (completed, processing, failed)
   * Timestamp
3. Click **Refresh** to update status
4. Click **X** to close

### Caching System

#### How Caching Works

Results are automatically cached for **24 hours** at three levels:

1. **User Cache** - Your personal cache
2. **Document Cache** - Shared with all collaborators
3. **Script Cache** - Backup cache

**Benefits:**

* ✅ No duplicate API calls
* ✅ Instant results for repeated queries
* ✅ Shared cache across team members
* ✅ 80-90% reduction in API costs

#### Cache Behavior

**Cache Hits:**

* Same input = cached result (no API call)
* Different user on same sheet = cached result
* Sheet reload = cached result

**Cache Miss:**

* New input values
* After 24 hours
* `BYPASS_CACHE` parameter used

#### Bypassing Cache

**Per Formula:**

```
=DATABAR_ENRICH(10, "email", A2, "BYPASS_CACHE")
```

**When to Bypass:**

* Testing different providers
* Data has changed at source
* Need fresh verification

***

### Rate Limiting

The extension automatically manages API rate limits:

* **20 concurrent requests maximum**
* **300 requests per minute maximum**
* **Automatic queuing** when limits reached
* **30-second timeout** for queued requests

**What This Means:**

* Large batches are automatically throttled
* No server overload
* Fair usage across all users
* Some requests may wait briefly during high volume

***

### Credit Management

#### Checking Your Credits

**Via Menu:**

1. **Databar.ai** menu > **Check Credits**
2. View:
   * Current balance
   * Plan name
   * Account email

**Via Button:**

* Click **Buy More Credits** to visit pricing page

#### Estimated Costs

**Regular Enrichments:**

* Cost shown in enrichment card
* Example: "6 cr." per enrichment

**Waterfalls:**

* Price range shown (e.g., "4-22 cr.")
* Actual cost depends on which provider succeeds
* First successful provider determines final cost

**Cost Optimization Tips:**

1. Order waterfall providers cheapest-first
2. Use caching (saves 80-90% of API calls)
3. Test with small samples first
4. Use `BYPASS_CACHE` sparingly

***

### Common Workflows

#### Workflow 1: Verify Email List

**Goal:** Verify 500 emails

**Steps:**

1. Put emails in column A (A2:A501)
2. In B2: `=DATABAR_ENRICH(10, "email", A2)`
3. Drag down to B501
4. Extract status: In C2: `=DATABAR_JSON_EXTRACT(B2, "status")`
5. Drag down to C501

**Result:**

* Column B: Full verification data (JSON)
* Column C: Simple valid/invalid status
* Cached for 24 hours (no re-runs)

***

#### Workflow 2: Find Emails with Waterfall

**Goal:** Find emails for 100 contacts

**Steps:**

1. Put first names in column A
2. Put last names in column B
3. Put companies in column C
4. In D2: `=DATABAR_WATERFALL("email_getter", "first_name", A2, "last_name", B2, "company", C2, "612,833,87,380")`
5. Drag down to D101

**Result:**

* Column D: Found emails (concatenated)
* Column E: Full waterfall data (JSON)
* See which provider found each email in column E

**Cost Analysis:**

```
=DATABAR_JSON_EXTRACT(E2, "steps[0].cost")
```

***

#### Workflow 3: Enrich Company Data

**Goal:** Get company info for 200 domains

**Steps:**

1. Put domains in column A (A2:A201)
2. In B2: `=DATABAR_ENRICH_EXPAND(5, "domain", A2, "name,industry,employees,revenue")`
3. Drag down to B201

**Result:**

* Columns B-E: name, industry, employees, revenue
* Structured data ready for analysis
* Headers automatically added

***

#### Workflow 4: Batch Processing Large Dataset

**Goal:** Process 5,000 contacts (one-time)

**Steps:**

1. Select column with input data (A2:A5001)
2. **Databar.ai** menu > **Tools** > **Batch Enrich (Static Values)**
3. Enter enrichment ID
4. Enter parameter name
5. Review cost estimate: \~30,000 credits
6. Confirm and wait (\~15-20 minutes)
7. Static results in next column

**Benefits:**

* No formulas (faster sheet)
* Never recalculates
* Progress updates every 10 rows
* Error handling per row

***

### Troubleshooting

#### Error: "API key not configured"

**Solution:**

1. **Databar.ai** menu > **Configure API Key**
2. Enter your API key from [databar.ai](https://databar.ai)
3. Test with **Databar.ai** menu > **Test Connection**

***

#### Error: "Invalid cell reference (#REF!)"

**Causes:**

* Deleted a row/column referenced in formula
* Cell reference is broken

**Solution:**

1. Check the formula cell references
2. Update to valid cell references
3. Re-enter the formula

***

#### Error: "Cannot pass a range/array as parameter"

**Cause:** Passing multiple cells (e.g., `A2:A10`) instead of single cell

**Solution:**

```
❌ Wrong: =DATABAR_ENRICH(10, "email", A2:A10)
✅ Right: =DATABAR_ENRICH(10, "email", A2)
```

Then drag the formula down to apply to each row.

***

#### Error: "Parameter cannot be empty"

**Cause:** Required parameter cell is blank

**Solution:**

1. Fill in the required input cells
2. Or use a static value in the formula:

```
=DATABAR_ENRICH(10, "email", "test@example.com")
```

***

#### Formula shows: "PROCESSING (Task: xxx)"

**Cause:** Enrichment taking longer than 30 seconds

**Solution:**

1. Wait a moment and the formula will auto-update (if cache refreshes)
2. OR use: `=DATABAR_STATUS("task-id-from-message")`
3. OR check **Jobs** panel in sidebar

***

#### "No data" result

**Cause:** Enrichment couldn't find data for the input

**Possible reasons:**

* Invalid input (e.g., fake email)
* Data not available from provider
* All waterfall providers failed

**Solution:**

1. Verify input is correct
2. For waterfalls: Check the full JSON to see why each provider failed
3. Try different providers or enrichments

***

#### Results not updating after changing input

**Cause:** Formulas reference cached results

**Solution:** Use `BYPASS_CACHE` to force refresh:

```
=DATABAR_ENRICH(10, "email", A2, "BYPASS_CACHE")
```

**Note:** Remove `BYPASS_CACHE` after testing to avoid wasting credits.

***

#### Sheet is slow with many formulas

**Causes:**

* 500+ formulas in one sheet
* Complex formulas or large JSON results

**Solutions:**

1. **Use Batch Tool instead** - No formulas, static values
2. **Convert to values:**
   * Copy cells with formulas
   * Paste as "Values only"
   * Removes formulas, keeps data
3. **Split across multiple sheets**

***

#### "Rate limit exceeded" error

**Cause:** Too many requests too quickly

**Solution:**

* Wait 30-60 seconds
* Requests are automatically queued
* For large batches, use Batch Tool (handles queuing automatically)

***

### Best Practices

#### 1. Start Small

* Test with 5-10 rows first
* Verify results before scaling up
* Check costs with small samples

#### 2. Use Caching Wisely

* Let cache work (24 hours)
* Only use `BYPASS_CACHE` when needed
* Share sheets to leverage document cache

#### 3. Optimize Waterfall Order

* Put cheapest providers first
* Remove expensive providers you don't need
* Monitor which providers succeed most often

#### 4. Structure Your Data

* Use `DATABAR_ENRICH_EXPAND` for structured tables
* Use `DATABAR_JSON_EXTRACT` to pull specific fields
* Keep raw JSON in hidden columns for reference

#### 5. Batch Large Operations

* Use Batch Tool for 100+ rows
* Avoids formula overhead
* Faster sheet performance

#### 6. Monitor Credits

* Check balance regularly (**Databar.ai** menu > **Check Credits**)
* Set up credit alerts on databar.ai
* Review waterfall costs in full JSON

#### 7. Document Your Formulas

* Add notes explaining complex formulas
* Document which enrichments you use
* Keep a reference sheet with common patterns

***

### Keyboard Shortcuts

| Action               | Shortcut                          |
| -------------------- | --------------------------------- |
| Open menu            | Click **Databar.ai** in menu bar  |
| Copy formula         | Ctrl/Cmd + C in formula generator |
| Refresh sheet        | Ctrl/Cmd + R                      |
| Recalculate formulas | Ctrl/Cmd + Shift + F9             |

***

### Advanced Tips

#### Custom Function Combinations

**Progressive Enrichment:**

```
// Column A: Emails
// Column B: Verify emails
=DATABAR_ENRICH(10, "email", A2)

// Column C: Only enrich valid emails
=IF(DATABAR_JSON_EXTRACT(B2, "status")="valid", 
    DATABAR_ENRICH(20, "email", A2), 
    "Skipped")
```

**Waterfall with Fallback:**

```
// Try waterfall first
=IF(DATABAR_WATERFALL("email_getter", "first_name", A2, "last_name", B2, "company", C2, "612,833")="No data",
    "Not found",
    DATABAR_WATERFALL("email_getter", "first_name", A2, "last_name", B2, "company", C2, "612,833"))
```

#### Extract Multiple Fields at Once

```
// Instead of multiple DATABAR_JSON_EXTRACT calls:
=DATABAR_ENRICH_EXPAND(10, "email", A2, "status,score,domain")

// Then reference the expanded cells normally
```

#### Conditional Enrichment

```
// Only enrich if email is present
=IF(A2<>"", DATABAR_ENRICH(10, "email", A2), "No email")
```

***

### FAQs

**Q: How long are results cached?** A: 24 hours across three cache levels.

**Q: Can multiple users share cache?** A: Yes, document cache is shared across all users of the same sheet.

**Q: What happens if I run out of credits?** A: API will return error. Add more credits at [databar.ai/pricing](https://databar.ai/pricing).

**Q: Can I use this in Google Apps Script?** A: Yes, call functions like `runEnrichment(enrichmentId, params)` directly.

**Q: How do I see my recent jobs?** A: Open sidebar and click the clipboard icon (Jobs panel).

**Q: Can I undo an enrichment?** A: Yes, use Ctrl/Cmd + Z or delete the cells. Credits are not refunded.

**Q: Does this work offline?** A: No, requires internet connection to call Databar API.

**Q: Can I use this on mobile?** A: Yes, Google Sheets mobile app supports custom functions. Sidebar requires desktop.

**Q: How do I report bugs?** A: Contact <support@databar.ai> or use the help panel in the sidebar.

***

### Support

**Need Help?**

* 📧 Email: <support@databar.ai>
* 📖 Docs: [docs.databar.ai](https://docs.databar.ai)
* 💬 In-app: Click **?** icon in sidebar

**Feature Requests:** Share your ideas at <support@databar.ai>

**API Documentation:** Visit [api.databar.ai](https://api.databar.ai) for full API reference.

***

### Version History

**Current Version:** 1.0.0

**Features:**

* ✅ Regular enrichments with JSON and expanded output
* ✅ Waterfall enrichments with provider selection
* ✅ 24-hour multi-level caching
* ✅ Batch processing tool
* ✅ Rate limiting and queuing
* ✅ JSON extraction helper
* ✅ Interactive sidebar with formula generator
* ✅ Jobs tracking and management
* ✅ Credit balance checking
* ✅ Comprehensive error handling

***

*Last updated: November 2024*


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.databar.ai/google-sheets-extension.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
