Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(snowflake): query, manage and load data from flows and AI agents, with SQL safety fixes (#16458)

Odai Ahmad87787db6ba19
diff --git a/bun.lock b/bun.lock
index 48cd0f54c1b..50c05910c08 100644
--- a/bun.lock
+++ b/bun.lock
@@ -8698,16 +8698,22 @@
},
"packages/pieces/community/snowflake": {
"name": "@activepieces/piece-snowflake",
- "version": "0.3.6",
+ "version": "0.4.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
+ "deepmerge-ts": "8.0.2",
+ "form-data": "4.0.6",
+ "ipaddr.js": "2.3.0",
+ "nanoid": "3.3.18",
"snowflake-sdk": "2.3.4",
+ "zod": "4.3.6",
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/soap": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index b42c511b470..9d701e181ed 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,24 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### Snowflake 0.4.0: Update Row needs a WHERE condition, stricter limits, query timeout and stage paths
+
+From Snowflake 0.4.0 several actions validate their inputs where they used to pass them straight to Snowflake:
+
+- **Update Row** fails when the WHERE condition is empty, instead of updating every row in the table. A new **Update All Rows** toggle allows it.
+- **Search Rows** fails when **Row Limit** is not a whole number between 1 and 10,000. Before, any value went into `LIMIT`.
+- **Run Query** and **Run Multiple Queries**: the **Query Timeout (ms)** value used to be passed to the Snowflake driver as its connection timeout, so long queries were not stopped. It now sets Snowflake's `STATEMENT_TIMEOUT_IN_SECONDS`, which cancels any query that runs longer than the value (30 seconds by default, at most 540 seconds).
+- **Load Data from Stage**: the stage path is now parsed and checked. User (`@~`) and table (`@%`) stages are rejected, the stage name must be a valid (optionally qualified) name, and the folder part may only contain letters, digits, spaces and `- _ . / = + % ~` (no `..`).
+
+#### What you need to do
+
+- Update Row: if a step is meant to change every row, turn on **Update All Rows**; otherwise add a WHERE condition.
+- Search Rows: keep **Row Limit** between 1 and 10,000. For more rows, use **Run Query** with your own `LIMIT`.
+- Run Query and Run Multiple Queries: if a query takes longer than 30 seconds, raise **Query Timeout (ms)** (up to 540 000). Queries that need more than 540 seconds should run outside the flow, for example as a Snowflake task.
+- Load Data from Stage: use a named stage (`@stage_name/folder/` or `@schema.stage_name/folder/`). For user or table stages, or paths with other characters, use **Run Query** with your own `COPY INTO`.
+
+Steps keep running on the version they were built with until you upgrade them.
+
#### Pdfcrowd 0.3.0: Convert URL to PDF and Convert HTML to PDF are builder-only
Convert URL to PDF and Convert HTML to PDF are no longer offered to AI agents. They keep working in flows, but an agent that used them as tools loses them after the upgrade.
diff --git a/packages/pieces/community/snowflake/package.json b/packages/pieces/community/snowflake/package.json
index 4c24a9bd205..5635e4149f8 100644
--- a/packages/pieces/community/snowflake/package.json
+++ b/packages/pieces/community/snowflake/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-snowflake",
- "version": "0.3.6",
+ "version": "0.4.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"dependencies": {
@@ -8,14 +8,21 @@
"@activepieces/pieces-framework": "workspace:*",
"snowflake-sdk": "2.3.4",
"@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "@activepieces/core-utils": "workspace:*",
+ "zod": "4.3.6",
+ "deepmerge-ts": "8.0.2",
+ "form-data": "4.0.6",
+ "ipaddr.js": "2.3.0",
+ "nanoid": "3.3.18"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
},
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
}
}
diff --git a/packages/pieces/community/snowflake/src/i18n/translation.json b/packages/pieces/community/snowflake/src/i18n/translation.json
index 60d96cda29e..7e9ece97bf1 100644
--- a/packages/pieces/community/snowflake/src/i18n/translation.json
+++ b/packages/pieces/community/snowflake/src/i18n/translation.json
@@ -14,6 +14,36 @@
"Execute Stored Procedure": "Execute Stored Procedure",
"Create / Refresh Dynamic Table": "Create / Refresh Dynamic Table",
"Load Data from Stage": "Load Data from Stage",
+ "Call Procedure": "Call Procedure",
+ "Cancel Query": "Cancel Query",
+ "Copy Stage Files into Table": "Copy Stage Files into Table",
+ "Count Rows": "Count Rows",
+ "Delete Row by Key": "Delete Row by Key",
+ "Delete Rows by Filter": "Delete Rows by Filter",
+ "Describe Table": "Describe Table",
+ "Explain Query": "Explain Query",
+ "Find Rows": "Find Rows",
+ "Get Current Session": "Get Current Session",
+ "Get Query Status": "Get Query Status",
+ "Get Row by Key": "Get Row by Key",
+ "Get View Definition": "Get View Definition",
+ "Insert Row (JSON)": "Insert Row (JSON)",
+ "Insert Rows (JSON)": "Insert Rows (JSON)",
+ "List Columns": "List Columns",
+ "List Databases": "List Databases",
+ "List Procedures": "List Procedures",
+ "List Query History": "List Query History",
+ "List Roles": "List Roles",
+ "List Schemas": "List Schemas",
+ "List Stage Files": "List Stage Files",
+ "List Stages": "List Stages",
+ "List Tables (by Name)": "List Tables (by Name)",
+ "List Views": "List Views",
+ "List Warehouses": "List Warehouses",
+ "Run Select Query": "Run Select Query",
+ "Update Row by Key": "Update Row by Key",
+ "Update Rows by Filter": "Update Rows by Filter",
+ "Upsert Row by Key": "Upsert Row by Key",
"Execute a SQL query against your Snowflake database and return the results as rows.": "Execute a SQL query against your Snowflake database and return the results as rows.",
"Execute multiple SQL statements in sequence against your Snowflake database. Optionally wrap them in a transaction so all changes are rolled back if any statement fails.": "Execute multiple SQL statements in sequence against your Snowflake database. Optionally wrap them in a transaction so all changes are rolled back if any statement fails.",
"Insert a row into a table.": "Insert a row into a table.",
@@ -28,6 +58,36 @@
"Call a stored procedure in Snowflake and return its result.": "Call a stored procedure in Snowflake and return its result.",
"Create or replace a Snowflake Dynamic Table that automatically refreshes based on a query. Dynamic Tables are a declarative way to define a table whose content is derived from a query, updated on a schedule.": "Create or replace a Snowflake Dynamic Table that automatically refreshes based on a query. Dynamic Tables are a declarative way to define a table whose content is derived from a query, updated on a schedule.",
"Load data into a Snowflake table from a named internal or external stage using COPY INTO.": "Load data into a Snowflake table from a named internal or external stage using COPY INTO.",
+ "Call a stored procedure with positional arguments.": "Call a stored procedure with positional arguments.",
+ "Cancel a running query by its query ID.": "Cancel a running query by its query ID.",
+ "Load files from a named stage into a table (COPY INTO).": "Load files from a named stage into a table (COPY INTO).",
+ "Count the rows of a table that match optional filters.": "Count the rows of a table that match optional filters.",
+ "Delete the one row whose key column equals a value.": "Delete the one row whose key column equals a value.",
+ "Delete every row that matches the filters, up to a safety limit.": "Delete every row that matches the filters, up to a safety limit.",
+ "Get the columns of a table by name.": "Get the columns of a table by name.",
+ "Show the execution plan of a read-only query without running it.": "Show the execution plan of a read-only query without running it.",
+ "Find rows in a table using structured filters, sort and paging.": "Find rows in a table using structured filters, sort and paging.",
+ "Show the user, role, warehouse, database and schema this connection uses.": "Show the user, role, warehouse, database and schema this connection uses.",
+ "Get the status of a query by its query ID, and its rows once it succeeded.": "Get the status of a query by its query ID, and its rows once it succeeded.",
+ "Get one row of a table where a key column equals a value.": "Get one row of a table where a key column equals a value.",
+ "Get the CREATE VIEW statement (DDL) of a view.": "Get the CREATE VIEW statement (DDL) of a view.",
+ "Insert one row given as a column-to-value object.": "Insert one row given as a column-to-value object.",
+ "Insert up to 500 rows given as an array of objects with the same keys.": "Insert up to 500 rows given as an array of objects with the same keys.",
+ "Search columns across the tables of a database.": "Search columns across the tables of a database.",
+ "List the databases visible to the current role.": "List the databases visible to the current role.",
+ "List stored procedures in a schema or database.": "List stored procedures in a schema or database.",
+ "List recent queries visible to the current role.": "List recent queries visible to the current role.",
+ "List the roles visible to the current role.": "List the roles visible to the current role.",
+ "List the schemas in a database.": "List the schemas in a database.",
+ "List the files in a named stage.": "List the files in a named stage.",
+ "List stages in a schema or database.": "List stages in a schema or database.",
+ "List tables in a schema or database by name.": "List tables in a schema or database by name.",
+ "List views in a schema or database.": "List views in a schema or database.",
+ "List the virtual warehouses visible to the current role.": "List the virtual warehouses visible to the current role.",
+ "Run one read-only SQL query (SELECT, WITH, SHOW, DESCRIBE or EXPLAIN).": "Run one read-only SQL query (SELECT, WITH, SHOW, DESCRIBE or EXPLAIN).",
+ "Update the one row whose key column equals a value.": "Update the one row whose key column equals a value.",
+ "Update every row that matches the filters, up to a safety limit.": "Update every row that matches the filters, up to a safety limit.",
+ "Insert a row, or update the existing row with the same key values (MERGE).": "Insert a row, or update the existing row with the same key values (MERGE).",
"SQL Query": "SQL Query",
"Parameters": "Parameters",
"Query Timeout (ms)": "Query Timeout (ms)",
@@ -40,6 +100,7 @@
"Row Data": "Row Data",
"Columns to Update": "Columns to Update",
"WHERE Condition": "WHERE Condition",
+ "Update All Rows": "Update All Rows",
"Match Column": "Match Column",
"Rows": "Rows",
"ID Column": "ID Column",
@@ -59,29 +120,52 @@
"Skip Header Rows": "Skip Header Rows",
"Fail on Column Count Mismatch": "Fail on Column Count Mismatch",
"On Error": "On Error",
+ "Procedure": "Procedure",
+ "Limit": "Limit",
+ "Query ID": "Query ID",
+ "Stage": "Stage",
+ "Path": "Path",
+ "Pattern": "Pattern",
+ "Filters": "Filters",
+ "Key Column": "Key Column",
+ "Key Value": "Key Value",
+ "Max Rows": "Max Rows",
+ "SQL": "SQL",
+ "Columns": "Columns",
+ "Sort": "Sort",
+ "Offset": "Offset",
+ "Include Results": "Include Results",
+ "View": "View",
+ "Row": "Row",
+ "Column Pattern": "Column Pattern",
+ "Name Pattern": "Name Pattern",
+ "Status": "Status",
+ "Values": "Values",
+ "Key Columns": "Key Columns",
"The SQL statement to execute. Use `:1`, `:2`… or `?` as placeholders for the **Parameters** values below to safely pass dynamic values without SQL injection risk.": "The SQL statement to execute. Use `:1`, `:2`… or `?` as placeholders for the **Parameters** values below to safely pass dynamic values without SQL injection risk.",
"Values to bind to the placeholders (`:1`, `:2`…, or `?`) in the SQL query. Provide them in the same order they appear in the query. Using parameters is the safe way to pass dynamic values — never concatenate user input directly into the SQL.": "Values to bind to the placeholders (`:1`, `:2`…, or `?`) in the SQL query. Provide them in the same order they appear in the query. Using parameters is the safe way to pass dynamic values — never concatenate user input directly into the SQL.",
- "Maximum time in milliseconds to wait for the query to complete before cancelling it. Defaults to 30 000 ms (30 seconds).": "Maximum time in milliseconds to wait for the query to complete before cancelling it. Defaults to 30 000 ms (30 seconds).",
+ "Maximum time in milliseconds the query may run before Snowflake cancels it (applied as STATEMENT_TIMEOUT_IN_SECONDS, capped at 540 seconds). Defaults to 30 000 ms (30 seconds).": "Maximum time in milliseconds the query may run before Snowflake cancels it (applied as STATEMENT_TIMEOUT_IN_SECONDS, capped at 540 seconds). Defaults to 30 000 ms (30 seconds).",
"An optional label sent to Snowflake to identify this client. Visible in query history under **Monitoring → Query History → Client Application**. Useful for auditing which automation triggered a query.": "An optional label sent to Snowflake to identify this client. Visible in query history under **Monitoring → Query History → Client Application**. Useful for auditing which automation triggered a query.",
"List of SQL statements to run in order. Use `:1`, `:2`… placeholders to reference shared **Parameters** values. Avoid `?` placeholders when running multiple queries — use numbered placeholders instead to prevent unexpected behaviour.": "List of SQL statements to run in order. Use `:1`, `:2`… placeholders to reference shared **Parameters** values. Avoid `?` placeholders when running multiple queries — use numbered placeholders instead to prevent unexpected behaviour.",
"Values shared across all queries for the numbered placeholders (`:1`, `:2`…). Provide them in order. Unused parameters are allowed.": "Values shared across all queries for the numbered placeholders (`:1`, `:2`…). Provide them in order. Unused parameters are allowed.",
"When enabled, all queries run inside a single transaction. If any query fails, every preceding change in this batch is rolled back automatically.": "When enabled, all queries run inside a single transaction. If any query fails, every preceding change in this batch is rolled back automatically.",
- "Maximum time in milliseconds to wait for each query to complete before cancelling it. Defaults to 30 000 ms (30 seconds).": "Maximum time in milliseconds to wait for each query to complete before cancelling it. Defaults to 30 000 ms (30 seconds).",
+ "Maximum time in milliseconds each query may run before Snowflake cancels it (applied as STATEMENT_TIMEOUT_IN_SECONDS, capped at 540 seconds). Defaults to 30 000 ms (30 seconds).": "Maximum time in milliseconds each query may run before Snowflake cancels it (applied as STATEMENT_TIMEOUT_IN_SECONDS, capped at 540 seconds). Defaults to 30 000 ms (30 seconds).",
"An optional label sent to Snowflake to identify this client. Visible in query history under **Monitoring → Query History → Client Application**.": "An optional label sent to Snowflake to identify this client. Visible in query history under **Monitoring → Query History → Client Application**.",
"Select the Snowflake database to use. Databases are listed under **Data → Databases** in the Snowflake console.": "Select the Snowflake database to use. Databases are listed under **Data → Databases** in the Snowflake console.",
"Select the schema within the chosen database. Schemas are listed under **Data → Databases → [your database]** in the Snowflake console.": "Select the schema within the chosen database. Schemas are listed under **Data → Databases → [your database]** in the Snowflake console.",
"Select the table to work with.": "Select the table to work with.",
"Enter the value for each column in the new row.": "Enter the value for each column in the new row.",
"Only filled columns will be updated. Leave a column empty to keep its existing value.": "Only filled columns will be updated. Leave a column empty to keep its existing value.",
- "A SQL condition to filter which rows to update (e.g. `id = 42` or `status = 'active'`). Leave empty to update ALL rows in the table (use with caution). **Security note:** this value is embedded directly in SQL. Only use static values or data from trusted, internal steps — never pass unvalidated end-user input here.": "A SQL condition to filter which rows to update (e.g. `id = 42` or `status = 'active'`). Leave empty to update ALL rows in the table (use with caution). **Security note:** this value is embedded directly in SQL. Only use static values or data from trusted, internal steps — never pass unvalidated end-user input here.",
+ "A SQL condition to filter which rows to update (e.g. `id = 42` or `status = 'active'`). To update every row, leave this empty and turn on **Update All Rows**. **Security note:** this value is embedded directly in SQL. Only use static values or data from trusted, internal steps — never pass unvalidated end-user input here.": "A SQL condition to filter which rows to update (e.g. `id = 42` or `status = 'active'`). To update every row, leave this empty and turn on **Update All Rows**. **Security note:** this value is embedded directly in SQL. Only use static values or data from trusted, internal steps — never pass unvalidated end-user input here.",
+ "Confirm that an empty WHERE condition should update every row in the table.": "Confirm that an empty WHERE condition should update every row in the table.",
"A SQL condition to filter which rows to delete (e.g. `id = 42` or `status = 'archived'`). This field is required to prevent accidental deletion of all rows. **Security note:** this value is embedded directly in SQL. Only use static values or data from trusted, internal steps — never pass unvalidated end-user input here.": "A SQL condition to filter which rows to delete (e.g. `id = 42` or `status = 'archived'`). This field is required to prevent accidental deletion of all rows. **Security note:** this value is embedded directly in SQL. Only use static values or data from trusted, internal steps — never pass unvalidated end-user input here.",
"The column used to identify whether a row already exists (e.g. the primary key or a unique identifier column).": "The column used to identify whether a row already exists (e.g. the primary key or a unique identifier column).",
- "One item per row. Each item must be a JSON object with column names as keys. Example: `{\"name\": \"Alice\", \"age\": 30}`. When mapping from a previous step, pass the entire array directly.": "One item per row. Each item must be a JSON object with column names as keys. Example: `{\"name\": \"Alice\", \"age\": 30}`. When mapping from a previous step, pass the entire array directly.",
+ "One item per row. Each item must be a JSON object with column names as keys. Example: `{\"name\": \"Alice\", \"age\": 30}`. When mapping from a previous step, pass the entire array directly. Object or array values are stored as JSON (VARIANT).": "One item per row. Each item must be a JSON object with column names as keys. Example: `{\"name\": \"Alice\", \"age\": 30}`. When mapping from a previous step, pass the entire array directly. Object or array values are stored as JSON (VARIANT).",
"The column to search in (e.g. the primary key or unique identifier column).": "The column to search in (e.g. the primary key or unique identifier column).",
"The value to look up in the ID column.": "The value to look up in the ID column.",
"Optional SQL WHERE condition to narrow down results (e.g. `status = 'active' AND age > 18`). Leave empty to return all rows (subject to the row limit). **Security note:** this value is embedded directly in SQL. Only use static values or data from trusted, internal steps — never pass unvalidated end-user input here.": "Optional SQL WHERE condition to narrow down results (e.g. `status = 'active' AND age > 18`). Leave empty to return all rows (subject to the row limit). **Security note:** this value is embedded directly in SQL. Only use static values or data from trusted, internal steps — never pass unvalidated end-user input here.",
"Optional column(s) to sort results by (SQL ORDER BY clause). Examples: `created_at DESC` sorts newest first; `name ASC, age DESC` sorts by name then age. **Security note:** this value is embedded directly in SQL. Only use static values or data from trusted, internal steps — never pass unvalidated end-user input here.": "Optional column(s) to sort results by (SQL ORDER BY clause). Examples: `created_at DESC` sorts newest first; `name ASC, age DESC` sorts by name then age. **Security note:** this value is embedded directly in SQL. Only use static values or data from trusted, internal steps — never pass unvalidated end-user input here.",
- "Maximum number of rows to return. Defaults to 100.": "Maximum number of rows to return. Defaults to 100.",
+ "Maximum number of rows to return (1–10 000). Defaults to 100.": "Maximum number of rows to return (1–10 000). Defaults to 100.",
"Select the stored procedure to call.": "Select the stored procedure to call.",
"Positional arguments to pass to the stored procedure in order. Leave empty if the procedure takes no arguments.": "Positional arguments to pass to the stored procedure in order. Leave empty if the procedure takes no arguments.",
"The name for the new dynamic table (e.g. `DAILY_SALES_SUMMARY`). Only letters, digits, underscores, and `$` are allowed.": "The name for the new dynamic table (e.g. `DAILY_SALES_SUMMARY`). Only letters, digits, underscores, and `$` are allowed.",
@@ -92,8 +176,54 @@
"The file format of the data files in the stage.": "The file format of the data files in the stage.",
"Optional regular expression to load only files whose names match the pattern (e.g. `.*\\.csv` loads only `.csv` files, `sales_2024.*` loads files that start with `sales_2024`). Leave empty to load all files in the stage path.": "Optional regular expression to load only files whose names match the pattern (e.g. `.*\\.csv` loads only `.csv` files, `sales_2024.*` loads files that start with `sales_2024`). Leave empty to load all files in the stage path.",
"Number of rows to skip at the top of each CSV file (e.g. `1` to skip a column-header row). Only applies to CSV files. Defaults to 0.": "Number of rows to skip at the top of each CSV file (e.g. `1` to skip a column-header row). Only applies to CSV files. Defaults to 0.",
- "When enabled, the load fails if the number of columns in a file does not match the number of columns in the target table. Disable to allow files with fewer columns.": "When enabled, the load fails if the number of columns in a file does not match the number of columns in the target table. Disable to allow files with fewer columns.",
+ "When enabled, the load fails if the number of columns in a file does not match the number of columns in the target table. Disable to allow files with fewer columns. Only applies to CSV files.": "When enabled, the load fails if the number of columns in a file does not match the number of columns in the target table. Disable to allow files with fewer columns. Only applies to CSV files.",
"What to do when a row fails validation during loading.": "What to do when a row fails validation during loading.",
+ "Procedure name, optionally qualified as DATABASE.SCHEMA.PROCEDURE (no parentheses).": "Procedure name, optionally qualified as DATABASE.SCHEMA.PROCEDURE (no parentheses).",
+ "Positional argument values, in the order of the procedure signature.": "Positional argument values, in the order of the procedure signature.",
+ "Maximum number of items to return (1–1000). Defaults to 100.": "Maximum number of items to return (1–1000). Defaults to 100.",
+ "The query ID (UUID) to cancel.": "The query ID (UUID) to cancel.",
+ "Target table, optionally qualified as DATABASE.SCHEMA.TABLE.": "Target table, optionally qualified as DATABASE.SCHEMA.TABLE.",
+ "Named stage, optionally qualified, e.g. `MY_DB.PUBLIC.MY_STAGE`.": "Named stage, optionally qualified, e.g. `MY_DB.PUBLIC.MY_STAGE`.",
+ "Optional folder or file inside the stage.": "Optional folder or file inside the stage.",
+ "Optional regular expression on file paths, e.g. `.*\\.csv`.": "Optional regular expression on file paths, e.g. `.*\\.csv`.",
+ "CSV only: header rows to skip per file.": "CSV only: header rows to skip per file.",
+ "Table name, optionally qualified as DATABASE.SCHEMA.TABLE (e.g. `ANALYTICS.PUBLIC.ORDERS`). An unqualified name uses the connection default database and schema. Unquoted names are case-insensitive; wrap a name in double quotes for exact case.": "Table name, optionally qualified as DATABASE.SCHEMA.TABLE (e.g. `ANALYTICS.PUBLIC.ORDERS`). An unqualified name uses the connection default database and schema. Unquoted names are case-insensitive; wrap a name in double quotes for exact case.",
+ "Conditions combined with AND. Each has a column, an operator (=, !=, <, <=, >, >=, IN, NOT IN, LIKE, ILIKE, IS NULL, IS NOT NULL) and a value. For IN / NOT IN pass a list or comma-separated values; IS NULL / IS NOT NULL take no value.": "Conditions combined with AND. Each has a column, an operator (=, !=, <, <=, >, >=, IN, NOT IN, LIKE, ILIKE, IS NULL, IS NOT NULL) and a value. For IN / NOT IN pass a list or comma-separated values; IS NULL / IS NOT NULL take no value.",
+ "The unique key column, e.g. `ID`.": "The unique key column, e.g. `ID`.",
+ "The key value of the row to delete.": "The key value of the row to delete.",
+ "Conditions combined with AND. Each has a column, an operator (=, !=, <, <=, >, >=, IN, NOT IN, LIKE, ILIKE, IS NULL, IS NOT NULL) and a value. For IN / NOT IN pass a list or comma-separated values; IS NULL / IS NOT NULL take no value. At least one filter is required.": "Conditions combined with AND. Each has a column, an operator (=, !=, <, <=, >, >=, IN, NOT IN, LIKE, ILIKE, IS NULL, IS NOT NULL) and a value. For IN / NOT IN pass a list or comma-separated values; IS NULL / IS NOT NULL take no value. At least one filter is required.",
+ "Refuse (and roll back) if more rows than this would be deleted (1–10000). Defaults to 100.": "Refuse (and roll back) if more rows than this would be deleted (1–10000). Defaults to 100.",
+ "One SELECT or WITH query. Use ? placeholders for values.": "One SELECT or WITH query. Use ? placeholders for values.",
+ "Values for the ? placeholders, in order.": "Values for the ? placeholders, in order.",
+ "Columns to return. Leave empty for all columns.": "Columns to return. Leave empty for all columns.",
+ "Sort order; each entry has a column and a direction (ASC or DESC). Set a sort when paging so pages are stable.": "Sort order; each entry has a column and a direction (ASC or DESC). Set a sort when paging so pages are stable.",
+ "Number of rows to skip, for paging. Use nextOffset from the previous call.": "Number of rows to skip, for paging. Use nextOffset from the previous call.",
+ "The query ID (UUID) from a previous action or from List Query History.": "The query ID (UUID) from a previous action or from List Query History.",
+ "Fetch the result rows when the query succeeded.": "Fetch the result rows when the query succeeded.",
+ "The key value to look up.": "The key value to look up.",
+ "View name, optionally qualified as DATABASE.SCHEMA.VIEW.": "View name, optionally qualified as DATABASE.SCHEMA.VIEW.",
+ "Column names mapped to values, e.g. {\"ID\": 7, \"EMAIL\": \"[email protected]\", \"TAGS\": [\"a\", \"b\"]}.": "Column names mapped to values, e.g. {\"ID\": 7, \"EMAIL\": \"[email protected]\", \"TAGS\": [\"a\", \"b\"]}.",
+ "Array of row objects with identical keys, e.g. [{\"ID\": 1, \"NAME\": \"A\"}, {\"ID\": 2, \"NAME\": \"B\"}].": "Array of row objects with identical keys, e.g. [{\"ID\": 1, \"NAME\": \"A\"}, {\"ID\": 2, \"NAME\": \"B\"}].",
+ "Database name, as returned by List Databases.": "Database name, as returned by List Databases.",
+ "Only columns in this schema.": "Only columns in this schema.",
+ "Only columns of this table.": "Only columns of this table.",
+ "Case-insensitive LIKE pattern on the column name, e.g. `%EMAIL%`.": "Case-insensitive LIKE pattern on the column name, e.g. `%EMAIL%`.",
+ "Maximum number of items to return (1–1000). Defaults to 200.": "Maximum number of items to return (1–1000). Defaults to 200.",
+ "Optional case-insensitive SQL LIKE pattern on the name, e.g. `%ORDER%`. Leave empty to list all.": "Optional case-insensitive SQL LIKE pattern on the name, e.g. `%ORDER%`. Leave empty to list all.",
+ "Database name, as returned by List Databases. Leave empty to use the connection default.": "Database name, as returned by List Databases. Leave empty to use the connection default.",
+ "Schema name, optionally qualified as DATABASE.SCHEMA (e.g. `ANALYTICS.PUBLIC`). Leave empty to use the connection default.": "Schema name, optionally qualified as DATABASE.SCHEMA (e.g. `ANALYTICS.PUBLIC`). Leave empty to use the connection default.",
+ "Only return queries with this execution status.": "Only return queries with this execution status.",
+ "Maximum number of items to return (1–1000). Defaults to 50.": "Maximum number of items to return (1–1000). Defaults to 50.",
+ "Named stage, optionally qualified, e.g. `MY_DB.PUBLIC.MY_STAGE` (a leading @ is optional).": "Named stage, optionally qualified, e.g. `MY_DB.PUBLIC.MY_STAGE` (a leading @ is optional).",
+ "Optional folder inside the stage, e.g. `exports/2026/`.": "Optional folder inside the stage, e.g. `exports/2026/`.",
+ "Optional regular expression on the full file path, e.g. `.*\\.csv`.": "Optional regular expression on the full file path, e.g. `.*\\.csv`.",
+ "One read-only statement, e.g. `SELECT ID, EMAIL FROM ANALYTICS.PUBLIC.USERS WHERE CREATED_AT > ?`. Use ? placeholders for values.": "One read-only statement, e.g. `SELECT ID, EMAIL FROM ANALYTICS.PUBLIC.USERS WHERE CREATED_AT > ?`. Use ? placeholders for values.",
+ "The key value of the row to update.": "The key value of the row to update.",
+ "Column names mapped to new values, e.g. {\"STATUS\": \"shipped\"}.": "Column names mapped to new values, e.g. {\"STATUS\": \"shipped\"}.",
+ "Column names mapped to new values, e.g. {\"STATUS\": \"archived\"}.": "Column names mapped to new values, e.g. {\"STATUS\": \"archived\"}.",
+ "Refuse (and roll back) if more rows than this would be updated (1–10000). Defaults to 100.": "Refuse (and roll back) if more rows than this would be updated (1–10000). Defaults to 100.",
+ "Column(s) that identify the row, e.g. [\"ID\"].": "Column(s) that identify the row, e.g. [\"ID\"].",
+ "Column names mapped to values, including the key column(s).": "Column names mapped to values, including the key column(s).",
"CSV": "CSV",
"JSON": "JSON",
"PARQUET": "PARQUET",
@@ -103,6 +233,15 @@
"Abort statement (default)": "Abort statement (default)",
"Continue (skip bad rows)": "Continue (skip bad rows)",
"Skip file": "Skip file",
+ "ABORT_STATEMENT": "ABORT_STATEMENT",
+ "CONTINUE": "CONTINUE",
+ "SKIP_FILE": "SKIP_FILE",
+ "SUCCESS": "SUCCESS",
+ "FAILED_WITH_ERROR": "FAILED_WITH_ERROR",
+ "RUNNING": "RUNNING",
+ "QUEUED": "QUEUED",
+ "BLOCKED": "BLOCKED",
+ "FAILED_WITH_INCIDENT": "FAILED_WITH_INCIDENT",
"New Row": "New Row",
"New or Updated Row": "New or Updated Row",
"New Column": "New Column",
diff --git a/packages/pieces/community/snowflake/src/index.ts b/packages/pieces/community/snowflake/src/index.ts
index ed099564bce..099667e9f88 100644
--- a/packages/pieces/community/snowflake/src/index.ts
+++ b/packages/pieces/community/snowflake/src/index.ts
@@ -14,6 +14,36 @@ import { listTablesAction } from './lib/actions/list-tables';
import { executeStoredProcedureAction } from './lib/actions/execute-stored-procedure';
import { createDynamicTableAction } from './lib/actions/create-dynamic-table';
import { loadDataFromStageAction } from './lib/actions/load-data-from-stage';
+import { callProcedureAction } from './lib/actions/ai/call-procedure';
+import { cancelQueryAction } from './lib/actions/ai/cancel-query';
+import { copyStageIntoTableAction } from './lib/actions/ai/copy-stage-into-table';
+import { countRowsAction } from './lib/actions/ai/count-rows';
+import { deleteRowByKeyAction } from './lib/actions/ai/delete-row-by-key';
+import { deleteRowsByFilterAction } from './lib/actions/ai/delete-rows-by-filter';
+import { describeTableAction } from './lib/actions/ai/describe-table';
+import { explainQueryAction } from './lib/actions/ai/explain-query';
+import { findRowsAction } from './lib/actions/ai/find-rows';
+import { getCurrentSessionAction } from './lib/actions/ai/get-current-session';
+import { getQueryStatusAction } from './lib/actions/ai/get-query-status';
+import { getRowByKeyAction } from './lib/actions/ai/get-row-by-key';
+import { getViewDefinitionAction } from './lib/actions/ai/get-view-definition';
+import { insertRowJsonAction } from './lib/actions/ai/insert-row-json';
+import { insertRowsJsonAction } from './lib/actions/ai/insert-rows-json';
+import { listColumnsAction } from './lib/actions/ai/list-columns';
+import { listDatabasesAction } from './lib/actions/ai/list-databases';
+import { listProceduresAction } from './lib/actions/ai/list-procedures';
+import { listQueryHistoryAction } from './lib/actions/ai/list-query-history';
+import { listRolesAction } from './lib/actions/ai/list-roles';
+import { listSchemasAction } from './lib/actions/ai/list-schemas';
+import { listStageFilesAction } from './lib/actions/ai/list-stage-files';
+import { listStagesAction } from './lib/actions/ai/list-stages';
+import { listTablesAiAction } from './lib/actions/ai/list-tables-ai';
+import { listViewsAction } from './lib/actions/ai/list-views';
+import { listWarehousesAction } from './lib/actions/ai/list-warehouses';
+import { runSelectQueryAction } from './lib/actions/ai/run-select-query';
+import { updateRowByKeyAction } from './lib/actions/ai/update-row-by-key';
+import { updateRowsByFilterAction } from './lib/actions/ai/update-rows-by-filter';
+import { upsertRowByKeyAction } from './lib/actions/ai/upsert-row-by-key';
import { snowflakeAuth } from './lib/auth';
import { newColumnTrigger } from './lib/triggers/new-column';
import { newTableTrigger } from './lib/triggers/new-table';
@@ -26,7 +56,7 @@ export const snowflake = createPiece({
description: 'Data warehouse built for the cloud',
auth: snowflakeAuth,
- minimumSupportedRelease: '0.27.1',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/snowflake.png',
categories: [PieceCategory.DEVELOPER_TOOLS],
authors: [
@@ -50,6 +80,36 @@ export const snowflake = createPiece({
executeStoredProcedureAction,
createDynamicTableAction,
loadDataFromStageAction,
+ callProcedureAction,
+ cancelQueryAction,
+ copyStageIntoTableAction,
+ countRowsAction,
+ deleteRowByKeyAction,
+ deleteRowsByFilterAction,
+ describeTableAction,
+ explainQueryAction,
+ findRowsAction,
+ getCurrentSessionAction,
+ getQueryStatusAction,
+ getRowByKeyAction,
+ getViewDefinitionAction,
+ insertRowJsonAction,
+ insertRowsJsonAction,
+ listColumnsAction,
+ listDatabasesAction,
+ listProceduresAction,
+ listQueryHistoryAction,
+ listRolesAction,
+ listSchemasAction,
+ listStageFilesAction,
+ listStagesAction,
+ listTablesAiAction,
+ listViewsAction,
+ listWarehousesAction,
+ runSelectQueryAction,
+ updateRowByKeyAction,
+ updateRowsByFilterAction,
+ upsertRowByKeyAction,
],
triggers: [
newRowTrigger,
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/call-procedure.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/call-procedure.ts
new file mode 100644
index 00000000000..c9fbe2d652c
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/call-procedure.ts
@@ -0,0 +1,64 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import {
+ aiProps,
+ READ_DEFAULT_LIMIT,
+ READ_MAX_LIMIT,
+} from '../../common/ai-props';
+import { callProcedureOutputSchema } from '../../common/output-schemas';
+import { buildCall } from '../../common/procedures';
+import { boundedInteger } from '../../common/sql';
+
+export const callProcedureAction = createAction({
+ name: 'call_procedure',
+ classification: 'WRITE',
+ displayName: 'Call Procedure',
+ description: 'Call a stored procedure with positional arguments.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'CALLs a stored procedure by name with positional arguments (objects and arrays are passed as JSON) and returns its return value plus any result rows. Check the signature with List Procedures first. A procedure can change data on every call, so treat retries as repeating its effect.',
+ idempotent: false,
+ },
+ outputSchema: callProcedureOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ procedure: Property.ShortText({
+ displayName: 'Procedure',
+ description:
+ 'Procedure name, optionally qualified as DATABASE.SCHEMA.PROCEDURE (no parentheses).',
+ required: true,
+ }),
+ arguments: Property.Array({
+ displayName: 'Arguments',
+ description:
+ 'Positional argument values, in the order of the procedure signature.',
+ required: false,
+ }),
+ limit: aiProps.limit(READ_DEFAULT_LIMIT, READ_MAX_LIMIT),
+ },
+ async run(context) {
+ const { procedure, arguments: args, limit } = context.propsValue;
+ const max = boundedInteger({
+ value: limit,
+ defaultValue: READ_DEFAULT_LIMIT,
+ min: 1,
+ max: READ_MAX_LIMIT,
+ label: 'Limit',
+ });
+ const { sql, binds } = buildCall({ procedure, args: args ?? [] });
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql, binds, maxRows: max }),
+ });
+ const first = result.rows[0];
+ return {
+ result: first ? Object.values(first)[0] ?? null : null,
+ rows: result.rows,
+ rowCount: result.rows.length,
+ truncated: result.truncated,
+ queryId: result.queryId,
+ };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/cancel-query.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/cancel-query.ts
new file mode 100644
index 00000000000..2b2fea80451
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/cancel-query.ts
@@ -0,0 +1,49 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { cancelQueryOutputSchema } from '../../common/output-schemas';
+import { QUERY_ID } from '../../common/query-id';
+
+export const cancelQueryAction = createAction({
+ name: 'cancel_query',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Cancel Query',
+ description: 'Cancel a running query by its query ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Cancels a running or queued query by query ID (SYSTEM$CANCEL_QUERY) and returns Snowflake's message. Work done by the cancelled statement is rolled back. Cancelling a query that already finished only returns a message, so a retry is harmless.",
+ idempotent: true,
+ },
+ outputSchema: cancelQueryOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ queryId: Property.ShortText({
+ displayName: 'Query ID',
+ description: 'The query ID (UUID) to cancel.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const id = context.propsValue.queryId.trim();
+ if (!QUERY_ID.test(id)) {
+ throw new Error(
+ 'Query ID must be a Snowflake query UUID such as 01b2c3d4-0000-1234-0000-0001a2b3c4d5.'
+ );
+ }
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ session.query({
+ sql: 'SELECT SYSTEM$CANCEL_QUERY(?) AS "message"',
+ binds: [id],
+ maxRows: 1,
+ }),
+ });
+ const row = result.rows[0] ?? {};
+ return {
+ queryId: id,
+ message: String(row['message'] ?? Object.values(row)[0] ?? ''),
+ };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/copy-stage-into-table.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/copy-stage-into-table.ts
new file mode 100644
index 00000000000..008f631d032
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/copy-stage-into-table.ts
@@ -0,0 +1,97 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import { mapCopyFile } from '../../common/mappers';
+import { copyIntoOutputSchema } from '../../common/output-schemas';
+import {
+ buildCopyInto,
+ FILE_FORMAT_TYPES,
+ ON_ERROR_VALUES,
+ stageReference,
+} from '../../common/stage';
+
+export const copyStageIntoTableAction = createAction({
+ name: 'copy_stage_into_table',
+ classification: 'WRITE',
+ displayName: 'Copy Stage Files into Table',
+ description: 'Load files from a named stage into a table (COPY INTO).',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Loads files from a named stage path into an existing table with COPY INTO and returns per-file status and rows loaded. Snowflake skips files it already loaded into this table in the last 64 days, but new files in the path are loaded on a retry. Use List Stage Files first.',
+ idempotent: false,
+ },
+ outputSchema: copyIntoOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ table: aiProps.table(
+ 'Target table, optionally qualified as DATABASE.SCHEMA.TABLE.'
+ ),
+ stage: Property.ShortText({
+ displayName: 'Stage',
+ description:
+ 'Named stage, optionally qualified, e.g. `MY_DB.PUBLIC.MY_STAGE`.',
+ required: true,
+ }),
+ path: Property.ShortText({
+ displayName: 'Path',
+ description: 'Optional folder or file inside the stage.',
+ required: false,
+ }),
+ fileFormat: Property.StaticDropdown({
+ displayName: 'File Format',
+ required: true,
+ defaultValue: 'CSV',
+ options: {
+ options: FILE_FORMAT_TYPES.map((value) => ({ label: value, value })),
+ },
+ }),
+ pattern: Property.ShortText({
+ displayName: 'Pattern',
+ description:
+ 'Optional regular expression on file paths, e.g. `.*\\.csv`.',
+ required: false,
+ }),
+ skipHeader: Property.Number({
+ displayName: 'Skip Header Rows',
+ description: 'CSV only: header rows to skip per file.',
+ required: false,
+ defaultValue: 0,
+ }),
+ onError: Property.StaticDropdown({
+ displayName: 'On Error',
+ required: false,
+ defaultValue: 'ABORT_STATEMENT',
+ options: {
+ options: ON_ERROR_VALUES.map((value) => ({ label: value, value })),
+ },
+ }),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const sql = buildCopyInto({
+ table: p.table,
+ stage: stageReference({ stage: p.stage, path: p.path }),
+ fileFormat: p.fileFormat,
+ pattern: p.pattern,
+ skipHeader: p.skipHeader,
+ onError: p.onError,
+ });
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql }),
+ });
+ const files = result.rows
+ .filter((row) => row['file'] !== undefined)
+ .map(mapCopyFile);
+ return {
+ filesProcessed: files.length,
+ rowsLoaded: files.reduce(
+ (sum, file) => sum + (Number(file.rows_loaded) || 0),
+ 0
+ ),
+ files,
+ };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/count-rows.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/count-rows.ts
new file mode 100644
index 00000000000..cae7e168e6a
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/count-rows.ts
@@ -0,0 +1,37 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import { countRowsOutputSchema } from '../../common/output-schemas';
+import { buildWhere, qualifiedName } from '../../common/sql';
+
+export const countRowsAction = createAction({
+ name: 'count_rows',
+ classification: 'READ',
+ displayName: 'Count Rows',
+ description: 'Count the rows of a table that match optional filters.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the number of rows in a table that match all given filters (or all rows when no filter is given). Use before Update/Delete Rows by Filter to check how many rows a filter hits. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: countRowsOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ table: aiProps.table(),
+ filters: aiProps.filters(false),
+ },
+ async run(context) {
+ const where = buildWhere(context.propsValue.filters);
+ const sql = `SELECT COUNT(*) AS "count" FROM ${qualifiedName({
+ value: context.propsValue.table,
+ label: 'Table',
+ })}${where.clause}`;
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql, binds: where.binds, maxRows: 1 }),
+ });
+ return { count: Number(result.rows[0]?.['count'] ?? 0) };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/delete-row-by-key.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/delete-row-by-key.ts
new file mode 100644
index 00000000000..99871c17320
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/delete-row-by-key.ts
@@ -0,0 +1,56 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import { guardedWrite } from '../../common/operations';
+import { deleteByKeyOutputSchema } from '../../common/output-schemas';
+import { identifier, qualifiedName } from '../../common/sql';
+
+export const deleteRowByKeyAction = createAction({
+ name: 'delete_row_by_key',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Row by Key',
+ description: 'Delete the one row whose key column equals a value.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes the single row whose key column equals Key Value. Returns alreadyDeleted=true when no row matches (so a retry is harmless) and rolls back with an error if more than one row matches.',
+ idempotent: true,
+ },
+ outputSchema: deleteByKeyOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ table: aiProps.table(),
+ keyColumn: Property.ShortText({
+ displayName: 'Key Column',
+ description: 'The unique key column, e.g. `ID`.',
+ required: true,
+ }),
+ keyValue: Property.ShortText({
+ displayName: 'Key Value',
+ description: 'The key value of the row to delete.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { table, keyColumn, keyValue } = context.propsValue;
+ const sql = `DELETE FROM ${qualifiedName({
+ value: table,
+ label: 'Table',
+ })} WHERE ${identifier({ name: keyColumn, label: 'Key column' })} = ?`;
+ const deleted = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ guardedWrite({
+ session,
+ sql,
+ binds: [keyValue],
+ countKey: 'number of rows deleted',
+ maxRows: 1,
+ tooManyMessage: (count) =>
+ `${count} rows have ${keyColumn} = ${keyValue}, so it is not a unique key. Nothing was deleted; use Delete Rows by Filter instead.`,
+ }),
+ });
+ return { deleted: deleted > 0, alreadyDeleted: deleted === 0 };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/delete-rows-by-filter.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/delete-rows-by-filter.ts
new file mode 100644
index 00000000000..61102ba5878
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/delete-rows-by-filter.ts
@@ -0,0 +1,71 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import {
+ aiProps,
+ WRITE_GUARD_DEFAULT,
+ WRITE_GUARD_MAX,
+} from '../../common/ai-props';
+import { guardedWrite } from '../../common/operations';
+import { deleteByFilterOutputSchema } from '../../common/output-schemas';
+import { boundedInteger, buildWhere, qualifiedName } from '../../common/sql';
+
+export const deleteRowsByFilterAction = createAction({
+ name: 'delete_rows_by_filter',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Rows by Filter',
+ description:
+ 'Delete every row that matches the filters, up to a safety limit.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes all rows matching every filter (at least one filter required). Runs in a transaction and rolls back with an error if more than Max Rows would be deleted; check with Count Rows first. A retry deletes nothing more.',
+ idempotent: true,
+ },
+ outputSchema: deleteByFilterOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ table: aiProps.table(),
+ filters: aiProps.filters(true),
+ maxRows: Property.Number({
+ displayName: 'Max Rows',
+ description: `Refuse (and roll back) if more rows than this would be deleted (1–${WRITE_GUARD_MAX}). Defaults to ${WRITE_GUARD_DEFAULT}.`,
+ required: false,
+ defaultValue: WRITE_GUARD_DEFAULT,
+ }),
+ },
+ async run(context) {
+ const { table, filters, maxRows } = context.propsValue;
+ const where = buildWhere(filters);
+ if (where.clause === '') {
+ throw new Error(
+ 'Provide at least one filter; deleting a whole table is not allowed here.'
+ );
+ }
+ const limit = boundedInteger({
+ value: maxRows,
+ defaultValue: WRITE_GUARD_DEFAULT,
+ min: 1,
+ max: WRITE_GUARD_MAX,
+ label: 'Max Rows',
+ });
+ const sql = `DELETE FROM ${qualifiedName({
+ value: table,
+ label: 'Table',
+ })}${where.clause}`;
+ const rowsDeleted = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ guardedWrite({
+ session,
+ sql,
+ binds: where.binds,
+ countKey: 'number of rows deleted',
+ maxRows: limit,
+ tooManyMessage: (count) =>
+ `The filters match ${count} rows, more than Max Rows (${limit}). Nothing was deleted; narrow the filters or raise Max Rows.`,
+ }),
+ });
+ return { rowsDeleted };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/describe-table.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/describe-table.ts
new file mode 100644
index 00000000000..51a82546690
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/describe-table.ts
@@ -0,0 +1,46 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import { describeTableOutputSchema } from '../../common/output-schemas';
+import { qualifiedName } from '../../common/sql';
+
+export const describeTableAction = createAction({
+ name: 'describe_table_ai',
+ classification: 'READ',
+ displayName: 'Describe Table',
+ description: 'Get the columns of a table by name.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the columns of a table or view (DESCRIBE TABLE) with name, data type, nullability, default, key flags and comment. Use before inserting, filtering or updating so column names and types are right. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: describeTableOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ table: aiProps.table(),
+ },
+ async run(context) {
+ const table = qualifiedName({
+ value: context.propsValue.table,
+ label: 'Table',
+ });
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql: `DESCRIBE TABLE ${table}` }),
+ });
+ return {
+ table,
+ columns: result.rows.map((col) => ({
+ name: col['name'] ?? null,
+ type: col['type'] ?? null,
+ nullable: col['null?'] === 'Y',
+ default: col['default'] ?? null,
+ primaryKey: col['primary key'] === 'Y',
+ uniqueKey: col['unique key'] === 'Y',
+ comment: col['comment'] ?? null,
+ })),
+ };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/explain-query.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/explain-query.ts
new file mode 100644
index 00000000000..b6696d9f35c
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/explain-query.ts
@@ -0,0 +1,64 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { explainOutputSchema } from '../../common/output-schemas';
+import {
+ assertReadOnlyStatement,
+ firstKeyword,
+ toBind,
+} from '../../common/sql';
+
+export const explainQueryAction = createAction({
+ name: 'explain_query',
+ classification: 'READ',
+ displayName: 'Explain Query',
+ description:
+ 'Show the execution plan of a read-only query without running it.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the Snowflake execution plan (EXPLAIN USING JSON) of one SELECT or WITH query without running it, to check cost (partitions, bytes) or validity before Run Select Query. Uses no warehouse credits for the query itself. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: explainOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ sql: Property.LongText({
+ displayName: 'SQL',
+ description: 'One SELECT or WITH query. Use ? placeholders for values.',
+ required: true,
+ }),
+ parameters: Property.Array({
+ displayName: 'Parameters',
+ description: 'Values for the ? placeholders, in order.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const statement = assertReadOnlyStatement(context.propsValue.sql);
+ const first = firstKeyword(statement);
+ if (first !== 'SELECT' && first !== 'WITH') {
+ throw new Error('Explain Query only accepts SELECT or WITH queries.');
+ }
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ session.query({
+ sql: `EXPLAIN USING JSON ${statement}`,
+ binds: (context.propsValue.parameters ?? []).map(toBind),
+ maxRows: 1,
+ }),
+ });
+ const row = result.rows[0] ?? {};
+ const raw = row['content'] ?? Object.values(row)[0] ?? null;
+ let plan: unknown = raw;
+ if (typeof raw === 'string') {
+ try {
+ plan = JSON.parse(raw);
+ } catch {
+ plan = raw;
+ }
+ }
+ return { plan };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/find-rows.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/find-rows.ts
new file mode 100644
index 00000000000..49b383791b8
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/find-rows.ts
@@ -0,0 +1,112 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import {
+ aiProps,
+ READ_DEFAULT_LIMIT,
+ READ_MAX_LIMIT,
+} from '../../common/ai-props';
+import { findRowsOutputSchema } from '../../common/output-schemas';
+import {
+ boundedInteger,
+ buildOrderBy,
+ buildWhere,
+ identifier,
+ parseStringList,
+ qualifiedName,
+} from '../../common/sql';
+
+export const findRowsAction = createAction({
+ name: 'find_rows',
+ classification: 'SEARCH',
+ displayName: 'Find Rows',
+ description:
+ 'Find rows in a table using structured filters, sort and paging.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns rows of a table that match all given filters (column, operator, value), optionally sorted and limited to chosen columns, with offset paging (hasMore, nextOffset). Values are sent as bound parameters. Use Count Rows for totals and Get Row by Key for one row. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: findRowsOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ table: aiProps.table(),
+ filters: aiProps.filters(false),
+ columns: Property.Array({
+ displayName: 'Columns',
+ description: 'Columns to return. Leave empty for all columns.',
+ required: false,
+ }),
+ sort: Property.Array({
+ displayName: 'Sort',
+ description:
+ 'Sort order; each entry has a column and a direction (ASC or DESC). Set a sort when paging so pages are stable.',
+ required: false,
+ properties: {
+ column: Property.ShortText({ displayName: 'Column', required: true }),
+ direction: Property.StaticDropdown({
+ displayName: 'Direction',
+ required: false,
+ defaultValue: 'ASC',
+ options: {
+ options: [
+ { label: 'ASC', value: 'ASC' },
+ { label: 'DESC', value: 'DESC' },
+ ],
+ },
+ }),
+ },
+ }),
+ limit: aiProps.limit(READ_DEFAULT_LIMIT, READ_MAX_LIMIT),
+ offset: Property.Number({
+ displayName: 'Offset',
+ description:
+ 'Number of rows to skip, for paging. Use nextOffset from the previous call.',
+ required: false,
+ defaultValue: 0,
+ }),
+ },
+ async run(context) {
+ const { table, filters, columns, sort, limit, offset } = context.propsValue;
+ const max = boundedInteger({
+ value: limit,
+ defaultValue: READ_DEFAULT_LIMIT,
+ min: 1,
+ max: READ_MAX_LIMIT,
+ label: 'Limit',
+ });
+ const skip = boundedInteger({
+ value: offset,
+ defaultValue: 0,
+ min: 0,
+ max: 10000000,
+ label: 'Offset',
+ });
+ const where = buildWhere(filters);
+ const columnNames = parseStringList({ value: columns, label: 'Columns' });
+ const select =
+ columnNames.length > 0
+ ? columnNames
+ .map((column) => identifier({ name: column, label: 'Column' }))
+ .join(', ')
+ : '*';
+ const sql = `SELECT ${select} FROM ${qualifiedName({
+ value: table,
+ label: 'Table',
+ })}${where.clause}${buildOrderBy(sort)} LIMIT ${max + 1} OFFSET ${skip}`;
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ session.query({ sql, binds: where.binds, maxRows: max + 1 }),
+ });
+ const hasMore = result.rows.length > max;
+ const rows = result.rows.slice(0, max);
+ return {
+ rows,
+ rowCount: rows.length,
+ hasMore,
+ nextOffset: hasMore ? skip + max : null,
+ };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/get-current-session.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/get-current-session.ts
new file mode 100644
index 00000000000..046a7962222
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/get-current-session.ts
@@ -0,0 +1,42 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { sessionOutputSchema } from '../../common/output-schemas';
+
+export const getCurrentSessionAction = createAction({
+ name: 'get_current_session',
+ classification: 'READ',
+ displayName: 'Get Current Session',
+ description:
+ 'Show the user, role, warehouse, database and schema this connection uses.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the current user, role, warehouse, database, schema, account, region and Snowflake version of the connection. Use first to learn the defaults that unqualified table names resolve against, or to verify the connection works. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: sessionOutputSchema,
+ auth: snowflakeAuth,
+ props: {},
+ async run(context) {
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ session.query({
+ sql: 'SELECT CURRENT_USER() AS "user", CURRENT_ROLE() AS "role", CURRENT_WAREHOUSE() AS "warehouse", CURRENT_DATABASE() AS "database", CURRENT_SCHEMA() AS "schema", CURRENT_ACCOUNT() AS "account", CURRENT_REGION() AS "region", CURRENT_VERSION() AS "version"',
+ maxRows: 1,
+ }),
+ });
+ const row = result.rows[0] ?? {};
+ return {
+ user: row['user'] ?? null,
+ role: row['role'] ?? null,
+ warehouse: row['warehouse'] ?? null,
+ database: row['database'] ?? null,
+ schema: row['schema'] ?? null,
+ account: row['account'] ?? null,
+ region: row['region'] ?? null,
+ version: row['version'] ?? null,
+ };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/get-query-status.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/get-query-status.ts
new file mode 100644
index 00000000000..ccda24b5a81
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/get-query-status.ts
@@ -0,0 +1,101 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import {
+ aiProps,
+ READ_DEFAULT_LIMIT,
+ READ_MAX_LIMIT,
+} from '../../common/ai-props';
+import { queryStatusOutputSchema } from '../../common/output-schemas';
+import { boundedInteger } from '../../common/sql';
+import { QUERY_ID } from '../../common/query-id';
+
+const RUNNING = [
+ 'RUNNING',
+ 'QUEUED',
+ 'RESUMING_WAREHOUSE',
+ 'QUEUED_REPARING_WAREHOUSE',
+ 'NO_DATA',
+ 'BLOCKED',
+];
+const ERROR = [
+ 'ABORTING',
+ 'FAILED_WITH_ERROR',
+ 'ABORTED',
+ 'FAILED_WITH_INCIDENT',
+ 'DISCONNECTED',
+];
+
+export const getQueryStatusAction = createAction({
+ name: 'get_query_status',
+ classification: 'READ',
+ displayName: 'Get Query Status',
+ description:
+ 'Get the status of a query by its query ID, and its rows once it succeeded.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the status (RUNNING, SUCCESS, FAILED_WITH_ERROR, ABORTED, …) of a query by query ID, and when Include Results is on and it succeeded, up to Limit result rows via RESULT_SCAN. Only queries run by the same user in the last 24 hours are visible. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: queryStatusOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ queryId: Property.ShortText({
+ displayName: 'Query ID',
+ description:
+ 'The query ID (UUID) from a previous action or from List Query History.',
+ required: true,
+ }),
+ includeResults: Property.Checkbox({
+ displayName: 'Include Results',
+ description: 'Fetch the result rows when the query succeeded.',
+ required: false,
+ defaultValue: false,
+ }),
+ limit: aiProps.limit(READ_DEFAULT_LIMIT, READ_MAX_LIMIT),
+ },
+ async run(context) {
+ const { queryId, includeResults, limit } = context.propsValue;
+ const id = queryId.trim();
+ if (!QUERY_ID.test(id)) {
+ throw new Error(
+ 'Query ID must be a Snowflake query UUID such as 01b2c3d4-0000-1234-0000-0001a2b3c4d5.'
+ );
+ }
+ const maxRows = boundedInteger({
+ value: limit,
+ defaultValue: READ_DEFAULT_LIMIT,
+ min: 1,
+ max: READ_MAX_LIMIT,
+ label: 'Limit',
+ });
+ return withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: async (session) => {
+ const status = await session.getQueryStatus(id);
+ const rows: Record<string, unknown>[] = [];
+ const output = {
+ queryId: id,
+ status,
+ isRunning: RUNNING.includes(status),
+ isError: ERROR.includes(status),
+ rows,
+ rowCount: 0,
+ truncated: false,
+ };
+ if (includeResults && status === 'SUCCESS') {
+ const result = await session.query({
+ sql: 'SELECT * FROM TABLE(RESULT_SCAN(?))',
+ binds: [id],
+ maxRows,
+ });
+ output.rows = result.rows;
+ output.rowCount = result.rows.length;
+ output.truncated = result.truncated;
+ }
+ return output;
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/get-row-by-key.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/get-row-by-key.ts
new file mode 100644
index 00000000000..6a089f55c37
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/get-row-by-key.ts
@@ -0,0 +1,55 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import { getRowOutputSchema } from '../../common/output-schemas';
+import { identifier, qualifiedName } from '../../common/sql';
+
+export const getRowByKeyAction = createAction({
+ name: 'get_row_by_key',
+ classification: 'READ',
+ displayName: 'Get Row by Key',
+ description: 'Get one row of a table where a key column equals a value.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the row whose key column equals the given value as {found, row}; found is false and row null when nothing matches. Fails if more than one row matches, since the column is then not a unique key; use Find Rows for that. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: getRowOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ table: aiProps.table(),
+ keyColumn: Property.ShortText({
+ displayName: 'Key Column',
+ description: 'The unique key column, e.g. `ID`.',
+ required: true,
+ }),
+ keyValue: Property.ShortText({
+ displayName: 'Key Value',
+ description: 'The key value to look up.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { table, keyColumn, keyValue } = context.propsValue;
+ const sql = `SELECT * FROM ${qualifiedName({
+ value: table,
+ label: 'Table',
+ })} WHERE ${identifier({
+ name: keyColumn,
+ label: 'Key column',
+ })} = ? LIMIT 2`;
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql, binds: [keyValue], maxRows: 2 }),
+ });
+ if (result.rows.length > 1) {
+ throw new Error(
+ `More than one row has ${keyColumn} = ${keyValue}; ${keyColumn} is not a unique key. Use Find Rows instead.`
+ );
+ }
+ const row = result.rows[0];
+ return { found: row !== undefined, row: row ?? null };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/get-view-definition.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/get-view-definition.ts
new file mode 100644
index 00000000000..2715bb72881
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/get-view-definition.ts
@@ -0,0 +1,43 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { viewDefinitionOutputSchema } from '../../common/output-schemas';
+import { qualifiedName } from '../../common/sql';
+
+export const getViewDefinitionAction = createAction({
+ name: 'get_view_definition',
+ classification: 'READ',
+ displayName: 'Get View Definition',
+ description: 'Get the CREATE VIEW statement (DDL) of a view.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the full CREATE VIEW statement of a view (GET_DDL), to understand how a view is built before querying it. Secure views only return DDL to their owner role. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: viewDefinitionOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ view: Property.ShortText({
+ displayName: 'View',
+ description: 'View name, optionally qualified as DATABASE.SCHEMA.VIEW.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const view = qualifiedName({
+ value: context.propsValue.view,
+ label: 'View',
+ });
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ session.query({
+ sql: `SELECT GET_DDL('VIEW', ?) AS "ddl"`,
+ binds: [view],
+ maxRows: 1,
+ }),
+ });
+ return { view, ddl: String(result.rows[0]?.['ddl'] ?? '') };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/insert-row-json.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/insert-row-json.ts
new file mode 100644
index 00000000000..4e23ec56f0b
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/insert-row-json.ts
@@ -0,0 +1,44 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import { buildInsert, dmlCount } from '../../common/operations';
+import { insertResultOutputSchema } from '../../common/output-schemas';
+import { parseObject } from '../../common/sql';
+
+export const insertRowJsonAction = createAction({
+ name: 'insert_row_json',
+ classification: 'WRITE',
+ displayName: 'Insert Row (JSON)',
+ description: 'Insert one row given as a column-to-value object.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Inserts one row into a table from an object of column names to values; object or array values are stored as JSON (VARIANT). Use Insert Rows (JSON) for several rows and Upsert Row by Key to avoid duplicates. Each call adds a new row, so a retry duplicates it.',
+ idempotent: false,
+ },
+ outputSchema: insertResultOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ table: aiProps.table(),
+ row: aiProps.values(
+ 'Row',
+ 'Column names mapped to values, e.g. {"ID": 7, "EMAIL": "[email protected]", "TAGS": ["a", "b"]}.'
+ ),
+ },
+ async run(context) {
+ const row = parseObject({ value: context.propsValue.row, label: 'Row' });
+ const { sql, binds } = buildInsert({
+ table: context.propsValue.table,
+ rows: [row],
+ });
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql, binds }),
+ });
+ return {
+ rowsInserted: dmlCount({ result, key: 'number of rows inserted' }),
+ queryId: result.queryId,
+ };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/insert-rows-json.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/insert-rows-json.ts
new file mode 100644
index 00000000000..4dd3893e8fc
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/insert-rows-json.ts
@@ -0,0 +1,55 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import { buildInsert, dmlCount } from '../../common/operations';
+import { insertResultOutputSchema } from '../../common/output-schemas';
+import { parseRowArray } from '../../common/sql';
+
+const MAX_ROWS = 500;
+
+export const insertRowsJsonAction = createAction({
+ name: 'insert_rows_json',
+ classification: 'WRITE',
+ displayName: 'Insert Rows (JSON)',
+ description:
+ 'Insert up to 500 rows given as an array of objects with the same keys.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Inserts 1–500 rows into a table in one statement; every object must have the same column keys, and object or array values are stored as JSON. All rows are inserted or none. Each call adds the rows again, so a retry duplicates them.',
+ idempotent: false,
+ },
+ outputSchema: insertResultOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ table: aiProps.table(),
+ rows: aiProps.values(
+ 'Rows',
+ 'Array of row objects with identical keys, e.g. [{"ID": 1, "NAME": "A"}, {"ID": 2, "NAME": "B"}].'
+ ),
+ },
+ async run(context) {
+ const rows = parseRowArray({
+ value: context.propsValue.rows,
+ label: 'Rows',
+ });
+ if (rows.length === 0 || rows.length > MAX_ROWS) {
+ throw new Error(
+ `Rows must contain between 1 and ${MAX_ROWS} objects; got ${rows.length}.`
+ );
+ }
+ const { sql, binds } = buildInsert({
+ table: context.propsValue.table,
+ rows,
+ });
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql, binds }),
+ });
+ return {
+ rowsInserted: dmlCount({ result, key: 'number of rows inserted' }),
+ queryId: result.queryId,
+ };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/list-columns.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/list-columns.ts
new file mode 100644
index 00000000000..d76012a9ba5
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/list-columns.ts
@@ -0,0 +1,82 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import type { Bind } from 'snowflake-sdk';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import { columnsQueryResult } from '../../common/columns';
+import { listColumnsOutputSchema } from '../../common/output-schemas';
+import {
+ boundedInteger,
+ identifierValue,
+ qualifiedName,
+} from '../../common/sql';
+
+export const listColumnsAction = createAction({
+ name: 'list_columns',
+ classification: 'SEARCH',
+ displayName: 'List Columns',
+ description: 'Search columns across the tables of a database.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Searches INFORMATION_SCHEMA.COLUMNS of one database for columns, optionally narrowed to a schema, a table and a column name pattern (ILIKE). Use to find which tables hold a field such as EMAIL. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: listColumnsOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ database: aiProps.database(true),
+ schema: Property.ShortText({
+ displayName: 'Schema',
+ description: 'Only columns in this schema.',
+ required: false,
+ }),
+ table: Property.ShortText({
+ displayName: 'Table',
+ description: 'Only columns of this table.',
+ required: false,
+ }),
+ columnPattern: Property.ShortText({
+ displayName: 'Column Pattern',
+ description:
+ 'Case-insensitive LIKE pattern on the column name, e.g. `%EMAIL%`.',
+ required: false,
+ }),
+ limit: aiProps.limit(200, 1000),
+ },
+ async run(context) {
+ const { database, schema, table, columnPattern, limit } =
+ context.propsValue;
+ const max = boundedInteger({
+ value: limit,
+ defaultValue: 200,
+ min: 1,
+ max: 1000,
+ label: 'Limit',
+ });
+ const conditions: string[] = [`TABLE_SCHEMA <> 'INFORMATION_SCHEMA'`];
+ const binds: Bind[] = [];
+ if (schema && schema.trim() !== '') {
+ conditions.push('TABLE_SCHEMA = ?');
+ binds.push(identifierValue(schema));
+ }
+ if (table && table.trim() !== '') {
+ conditions.push('TABLE_NAME = ?');
+ binds.push(identifierValue(table));
+ }
+ if (columnPattern && columnPattern.trim() !== '') {
+ conditions.push('COLUMN_NAME ILIKE ?');
+ binds.push(columnPattern.trim());
+ }
+ const sql = `SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COMMENT FROM ${qualifiedName(
+ { value: database ?? '', maxParts: 1, label: 'Database' }
+ )}.INFORMATION_SCHEMA.COLUMNS WHERE ${conditions.join(
+ ' AND '
+ )} ORDER BY TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION LIMIT ${max + 1}`;
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql, binds, maxRows: max + 1 }),
+ });
+ return columnsQueryResult({ rows: result.rows, max });
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/list-databases.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/list-databases.ts
new file mode 100644
index 00000000000..26b1e0ff9cd
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/list-databases.ts
@@ -0,0 +1,55 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import {
+ likeClause,
+ listShow,
+ normaliseTimestamp,
+ pick,
+} from '../../common/operations';
+import { listDatabasesOutputSchema } from '../../common/output-schemas';
+import { boundedInteger } from '../../common/sql';
+
+export const listDatabasesAction = createAction({
+ name: 'list_databases',
+ classification: 'SEARCH',
+ displayName: 'List Databases',
+ description: 'List the databases visible to the current role.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists databases the current role can see (SHOW DATABASES), with owner, kind and comment; filter with a LIKE name pattern. Use to find a database name for other actions. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: listDatabasesOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ namePattern: aiProps.namePattern,
+ limit: aiProps.limit(100, 1000),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const limit = boundedInteger({
+ value: p.limit,
+ defaultValue: 100,
+ min: 1,
+ max: 1000,
+ label: 'Limit',
+ });
+ const sql = `SHOW DATABASES${likeClause(p.namePattern)}`;
+ return withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ listShow({
+ session,
+ sql,
+ limit,
+ map: (row) => ({
+ ...pick({ row, keys: ['name', 'owner', 'kind', 'comment'] }),
+ created_on: normaliseTimestamp(row['created_on']),
+ }),
+ }),
+ });
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/list-procedures.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/list-procedures.ts
new file mode 100644
index 00000000000..30548b9136e
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/list-procedures.ts
@@ -0,0 +1,67 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import {
+ isUserDefined,
+ likeClause,
+ listShow,
+ normaliseTimestamp,
+ pick,
+ scopeClause,
+} from '../../common/operations';
+import { listProceduresOutputSchema } from '../../common/output-schemas';
+import { boundedInteger } from '../../common/sql';
+
+export const listProceduresAction = createAction({
+ name: 'list_procedures',
+ classification: 'SEARCH',
+ displayName: 'List Procedures',
+ description: 'List stored procedures in a schema or database.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists stored procedures (SHOW PROCEDURES) in a schema, a whole database, or the connection default schema, with their signature (argument types) and description; filter with a LIKE name pattern. Use before Call Procedure. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: listProceduresOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ database: aiProps.database(false),
+ schema: aiProps.schema(false),
+ namePattern: aiProps.namePattern,
+ limit: aiProps.limit(100, 1000),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const limit = boundedInteger({
+ value: p.limit,
+ defaultValue: 100,
+ min: 1,
+ max: 1000,
+ label: 'Limit',
+ });
+ const sql = `SHOW PROCEDURES${likeClause(p.namePattern)}${scopeClause({
+ database: p.database,
+ schema: p.schema,
+ })}`;
+ return withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ listShow({
+ session,
+ sql,
+ limit,
+ include: isUserDefined,
+ map: (row) => ({
+ ...pick({
+ row,
+ keys: ['name', 'schema_name', 'arguments', 'description'],
+ }),
+ database_name: row['catalog_name'] ?? null,
+ created_on: normaliseTimestamp(row['created_on']),
+ }),
+ }),
+ });
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/list-query-history.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/list-query-history.ts
new file mode 100644
index 00000000000..57fb6792a5b
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/list-query-history.ts
@@ -0,0 +1,87 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import { normaliseTimestamp } from '../../common/operations';
+import { queryHistoryOutputSchema } from '../../common/output-schemas';
+import { boundedInteger, qualifiedName } from '../../common/sql';
+
+const STATUSES = [
+ 'SUCCESS',
+ 'FAILED_WITH_ERROR',
+ 'RUNNING',
+ 'QUEUED',
+ 'BLOCKED',
+ 'FAILED_WITH_INCIDENT',
+];
+
+export const listQueryHistoryAction = createAction({
+ name: 'list_query_history',
+ classification: 'SEARCH',
+ displayName: 'List Query History',
+ description: 'List recent queries visible to the current role.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists recent queries (last 7 days, newest first) from INFORMATION_SCHEMA.QUERY_HISTORY with ID, text, status, user, warehouse, timing and error. Use to find a query ID for Get Query Status or to inspect failures; optionally filter by status. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: queryHistoryOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ database: aiProps.database(false),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ description: 'Only return queries with this execution status.',
+ required: false,
+ options: { options: STATUSES.map((value) => ({ label: value, value })) },
+ }),
+ limit: aiProps.limit(50, 1000),
+ },
+ async run(context) {
+ const { database, status, limit } = context.propsValue;
+ const max = boundedInteger({
+ value: limit,
+ defaultValue: 50,
+ min: 1,
+ max: 1000,
+ label: 'Limit',
+ });
+ if (status && !STATUSES.includes(status)) {
+ throw new Error(`Status must be one of ${STATUSES.join(', ')}.`);
+ }
+ const prefix =
+ database && database.trim() !== ''
+ ? `${qualifiedName({
+ value: database,
+ maxParts: 1,
+ label: 'Database',
+ })}.`
+ : '';
+ const binds: (string | number)[] = [status ? 10000 : max];
+ let sql = `SELECT QUERY_ID, QUERY_TEXT, EXECUTION_STATUS, USER_NAME, ROLE_NAME, WAREHOUSE_NAME, START_TIME, END_TIME, TOTAL_ELAPSED_TIME, ROWS_PRODUCED, ERROR_MESSAGE FROM TABLE(${prefix}INFORMATION_SCHEMA.QUERY_HISTORY(RESULT_LIMIT => ?))`;
+ if (status) {
+ sql += ' WHERE EXECUTION_STATUS = ?';
+ binds.push(status);
+ }
+ sql += ` ORDER BY START_TIME DESC LIMIT ${max}`;
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql, binds, maxRows: max }),
+ });
+ const items = result.rows.map((row) => ({
+ query_id: row['QUERY_ID'] ?? null,
+ query_text: row['QUERY_TEXT'] ?? null,
+ execution_status: row['EXECUTION_STATUS'] ?? null,
+ user_name: row['USER_NAME'] ?? null,
+ role_name: row['ROLE_NAME'] ?? null,
+ warehouse_name: row['WAREHOUSE_NAME'] ?? null,
+ start_time: normaliseTimestamp(row['START_TIME']),
+ end_time: normaliseTimestamp(row['END_TIME']),
+ total_elapsed_time: row['TOTAL_ELAPSED_TIME'] ?? null,
+ rows_produced: row['ROWS_PRODUCED'] ?? null,
+ error_message: row['ERROR_MESSAGE'] ?? null,
+ }));
+ return { items, count: items.length, truncated: items.length === max };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/list-roles.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/list-roles.ts
new file mode 100644
index 00000000000..f73d34f453f
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/list-roles.ts
@@ -0,0 +1,66 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import {
+ likeClause,
+ listShow,
+ normaliseTimestamp,
+ pick,
+} from '../../common/operations';
+import { listRolesOutputSchema } from '../../common/output-schemas';
+import { boundedInteger } from '../../common/sql';
+
+export const listRolesAction = createAction({
+ name: 'list_roles',
+ classification: 'SEARCH',
+ displayName: 'List Roles',
+ description: 'List the roles visible to the current role.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists roles (SHOW ROLES) with whether each is current or default and how many grants it has; filter with a LIKE name pattern. Read-only: it does not grant or revoke. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: listRolesOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ namePattern: aiProps.namePattern,
+ limit: aiProps.limit(100, 1000),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const limit = boundedInteger({
+ value: p.limit,
+ defaultValue: 100,
+ min: 1,
+ max: 1000,
+ label: 'Limit',
+ });
+ const sql = `SHOW ROLES${likeClause(p.namePattern)}`;
+ return withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ listShow({
+ session,
+ sql,
+ limit,
+ map: (row) => ({
+ ...pick({
+ row,
+ keys: [
+ 'name',
+ 'is_current',
+ 'is_default',
+ 'granted_to_roles',
+ 'granted_roles',
+ 'owner',
+ 'comment',
+ ],
+ }),
+ created_on: normaliseTimestamp(row['created_on']),
+ }),
+ }),
+ });
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/list-schemas.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/list-schemas.ts
new file mode 100644
index 00000000000..ff690d3ed92
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/list-schemas.ts
@@ -0,0 +1,62 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import {
+ likeClause,
+ listShow,
+ normaliseTimestamp,
+ pick,
+ scopeClause,
+} from '../../common/operations';
+import { listSchemasOutputSchema } from '../../common/output-schemas';
+import { boundedInteger } from '../../common/sql';
+
+export const listSchemasAction = createAction({
+ name: 'list_schemas',
+ classification: 'SEARCH',
+ displayName: 'List Schemas',
+ description: 'List the schemas in a database.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists schemas in a database (SHOW SCHEMAS), with owner and comment; filter with a LIKE name pattern. Use to find a schema before listing tables. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: listSchemasOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ database: aiProps.database(false),
+ namePattern: aiProps.namePattern,
+ limit: aiProps.limit(100, 1000),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const limit = boundedInteger({
+ value: p.limit,
+ defaultValue: 100,
+ min: 1,
+ max: 1000,
+ label: 'Limit',
+ });
+ const sql = `SHOW SCHEMAS${likeClause(p.namePattern)}${scopeClause({
+ database: p.database,
+ })}`;
+ return withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ listShow({
+ session,
+ sql,
+ limit,
+ map: (row) => ({
+ ...pick({
+ row,
+ keys: ['name', 'database_name', 'owner', 'comment'],
+ }),
+ created_on: normaliseTimestamp(row['created_on']),
+ }),
+ }),
+ });
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/list-stage-files.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/list-stage-files.ts
new file mode 100644
index 00000000000..79c8a81d898
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/list-stage-files.ts
@@ -0,0 +1,71 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import { listShow } from '../../common/operations';
+import { listStageFilesOutputSchema } from '../../common/output-schemas';
+import { stageReference } from '../../common/stage';
+import { boundedInteger, sqlString } from '../../common/sql';
+
+export const listStageFilesAction = createAction({
+ name: 'list_stage_files',
+ classification: 'SEARCH',
+ displayName: 'List Stage Files',
+ description: 'List the files in a named stage.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists files in a named stage (LIST @stage) with size, MD5 and last-modified time, optionally under a path and matching a regular expression. Use before Copy Stage Files into Table. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: listStageFilesOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ stage: Property.ShortText({
+ displayName: 'Stage',
+ description:
+ 'Named stage, optionally qualified, e.g. `MY_DB.PUBLIC.MY_STAGE` (a leading @ is optional).',
+ required: true,
+ }),
+ path: Property.ShortText({
+ displayName: 'Path',
+ description: 'Optional folder inside the stage, e.g. `exports/2026/`.',
+ required: false,
+ }),
+ pattern: Property.ShortText({
+ displayName: 'Pattern',
+ description:
+ 'Optional regular expression on the full file path, e.g. `.*\\.csv`.',
+ required: false,
+ }),
+ limit: aiProps.limit(100, 1000),
+ },
+ async run(context) {
+ const { stage, path, pattern, limit } = context.propsValue;
+ const max = boundedInteger({
+ value: limit,
+ defaultValue: 100,
+ min: 1,
+ max: 1000,
+ label: 'Limit',
+ });
+ let sql = `LIST ${stageReference({ stage, path })}`;
+ if (pattern && pattern.trim() !== '')
+ sql += ` PATTERN = ${sqlString(pattern.trim())}`;
+ return withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ listShow({
+ session,
+ sql,
+ limit: max,
+ map: (row) => ({
+ name: row['name'] ?? null,
+ size: row['size'] ?? null,
+ md5: row['md5'] ?? null,
+ last_modified: row['last_modified'] ?? null,
+ }),
+ }),
+ });
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/list-stages.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/list-stages.ts
new file mode 100644
index 00000000000..86ba9f72ef3
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/list-stages.ts
@@ -0,0 +1,72 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import {
+ likeClause,
+ listShow,
+ normaliseTimestamp,
+ pick,
+ scopeClause,
+} from '../../common/operations';
+import { listStagesOutputSchema } from '../../common/output-schemas';
+import { boundedInteger } from '../../common/sql';
+
+export const listStagesAction = createAction({
+ name: 'list_stages',
+ classification: 'SEARCH',
+ displayName: 'List Stages',
+ description: 'List stages in a schema or database.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists named stages (SHOW STAGES) in a schema, a whole database, or the connection default schema, with type (internal/external) and URL; filter with a LIKE name pattern. Use before List Stage Files. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: listStagesOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ database: aiProps.database(false),
+ schema: aiProps.schema(false),
+ namePattern: aiProps.namePattern,
+ limit: aiProps.limit(100, 1000),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const limit = boundedInteger({
+ value: p.limit,
+ defaultValue: 100,
+ min: 1,
+ max: 1000,
+ label: 'Limit',
+ });
+ const sql = `SHOW STAGES${likeClause(p.namePattern)}${scopeClause({
+ database: p.database,
+ schema: p.schema,
+ })}`;
+ return withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ listShow({
+ session,
+ sql,
+ limit,
+ map: (row) => ({
+ ...pick({
+ row,
+ keys: [
+ 'name',
+ 'database_name',
+ 'schema_name',
+ 'type',
+ 'url',
+ 'owner',
+ 'comment',
+ ],
+ }),
+ created_on: normaliseTimestamp(row['created_on']),
+ }),
+ }),
+ });
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/list-tables-ai.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/list-tables-ai.ts
new file mode 100644
index 00000000000..bcb919971a9
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/list-tables-ai.ts
@@ -0,0 +1,53 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { mapTable } from '../../common/mappers';
+import { aiProps } from '../../common/ai-props';
+import { likeClause, listShow, scopeClause } from '../../common/operations';
+import { listTablesAiOutputSchema } from '../../common/output-schemas';
+import { boundedInteger } from '../../common/sql';
+
+export const listTablesAiAction = createAction({
+ name: 'list_tables_ai',
+ classification: 'SEARCH',
+ displayName: 'List Tables (by Name)',
+ description: 'List tables in a schema or database by name.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists tables (SHOW TABLES) in a schema, a whole database, or the connection default schema, with kind, row and byte counts and owner; filter with a LIKE name pattern. Use to find a table name for the row actions. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: listTablesAiOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ database: aiProps.database(false),
+ schema: aiProps.schema(false),
+ namePattern: aiProps.namePattern,
+ limit: aiProps.limit(100, 1000),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const limit = boundedInteger({
+ value: p.limit,
+ defaultValue: 100,
+ min: 1,
+ max: 1000,
+ label: 'Limit',
+ });
+ const sql = `SHOW TABLES${likeClause(p.namePattern)}${scopeClause({
+ database: p.database,
+ schema: p.schema,
+ })}`;
+ return withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ listShow({
+ session,
+ sql,
+ limit,
+ map: mapTable,
+ }),
+ });
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/list-views.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/list-views.ts
new file mode 100644
index 00000000000..792c3ff8c5a
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/list-views.ts
@@ -0,0 +1,53 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { mapView } from '../../common/mappers';
+import { aiProps } from '../../common/ai-props';
+import { likeClause, listShow, scopeClause } from '../../common/operations';
+import { listViewsOutputSchema } from '../../common/output-schemas';
+import { boundedInteger } from '../../common/sql';
+
+export const listViewsAction = createAction({
+ name: 'list_views',
+ classification: 'SEARCH',
+ displayName: 'List Views',
+ description: 'List views in a schema or database.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists views (SHOW VIEWS) in a schema, a whole database, or the connection default schema, with owner, secure and materialized flags and definition text; filter with a LIKE name pattern. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: listViewsOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ database: aiProps.database(false),
+ schema: aiProps.schema(false),
+ namePattern: aiProps.namePattern,
+ limit: aiProps.limit(100, 1000),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const limit = boundedInteger({
+ value: p.limit,
+ defaultValue: 100,
+ min: 1,
+ max: 1000,
+ label: 'Limit',
+ });
+ const sql = `SHOW VIEWS${likeClause(p.namePattern)}${scopeClause({
+ database: p.database,
+ schema: p.schema,
+ })}`;
+ return withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ listShow({
+ session,
+ sql,
+ limit,
+ map: mapView,
+ }),
+ });
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/list-warehouses.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/list-warehouses.ts
new file mode 100644
index 00000000000..a254a111b9f
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/list-warehouses.ts
@@ -0,0 +1,68 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import {
+ likeClause,
+ listShow,
+ normaliseTimestamp,
+ pick,
+} from '../../common/operations';
+import { listWarehousesOutputSchema } from '../../common/output-schemas';
+import { boundedInteger } from '../../common/sql';
+
+export const listWarehousesAction = createAction({
+ name: 'list_warehouses',
+ classification: 'SEARCH',
+ displayName: 'List Warehouses',
+ description: 'List the virtual warehouses visible to the current role.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists virtual warehouses (SHOW WAREHOUSES) with state, size, auto-suspend and whether each is the current one; filter with a LIKE name pattern. Read-only: it does not start, stop or resize warehouses. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: listWarehousesOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ namePattern: aiProps.namePattern,
+ limit: aiProps.limit(100, 1000),
+ },
+ async run(context) {
+ const p = context.propsValue;
+ const limit = boundedInteger({
+ value: p.limit,
+ defaultValue: 100,
+ min: 1,
+ max: 1000,
+ label: 'Limit',
+ });
+ const sql = `SHOW WAREHOUSES${likeClause(p.namePattern)}`;
+ return withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ listShow({
+ session,
+ sql,
+ limit,
+ map: (row) => ({
+ ...pick({
+ row,
+ keys: [
+ 'name',
+ 'state',
+ 'type',
+ 'size',
+ 'auto_suspend',
+ 'auto_resume',
+ 'is_current',
+ 'owner',
+ 'comment',
+ ],
+ }),
+ created_on: normaliseTimestamp(row['created_on']),
+ }),
+ }),
+ });
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/run-select-query.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/run-select-query.ts
new file mode 100644
index 00000000000..8184017599e
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/run-select-query.ts
@@ -0,0 +1,72 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import {
+ aiProps,
+ READ_DEFAULT_LIMIT,
+ READ_MAX_LIMIT,
+} from '../../common/ai-props';
+import { queryResultOutputSchema } from '../../common/output-schemas';
+import {
+ assertReadOnlyStatement,
+ boundedInteger,
+ toBind,
+} from '../../common/sql';
+
+export const runSelectQueryAction = createAction({
+ name: 'run_select_query',
+ classification: 'READ',
+ displayName: 'Run Select Query',
+ description:
+ 'Run one read-only SQL query (SELECT, WITH, SHOW, DESCRIBE or EXPLAIN).',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Runs exactly one read-only statement (SELECT, WITH, SHOW, DESCRIBE, EXPLAIN) and returns up to Limit rows plus a truncated flag and the query ID. Statements that change data, multiple statements and SYSTEM$ functions are rejected; use the row actions to write. Pass values through Parameters with ? placeholders. Safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: queryResultOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ sql: Property.LongText({
+ displayName: 'SQL',
+ description:
+ 'One read-only statement, e.g. `SELECT ID, EMAIL FROM ANALYTICS.PUBLIC.USERS WHERE CREATED_AT > ?`. Use ? placeholders for values.',
+ required: true,
+ }),
+ parameters: Property.Array({
+ displayName: 'Parameters',
+ description: 'Values for the ? placeholders, in order.',
+ required: false,
+ }),
+ limit: aiProps.limit(READ_DEFAULT_LIMIT, READ_MAX_LIMIT),
+ },
+ async run(context) {
+ const { sql, parameters, limit } = context.propsValue;
+ const statement = assertReadOnlyStatement(sql);
+ const maxRows = boundedInteger({
+ value: limit,
+ defaultValue: READ_DEFAULT_LIMIT,
+ min: 1,
+ max: READ_MAX_LIMIT,
+ label: 'Limit',
+ });
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ session.query({
+ sql: statement,
+ binds: (parameters ?? []).map(toBind),
+ maxRows,
+ }),
+ });
+ return {
+ columns: result.columns,
+ rows: result.rows,
+ rowCount: result.rows.length,
+ totalRows: result.totalRows,
+ truncated: result.truncated,
+ queryId: result.queryId,
+ };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/update-row-by-key.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/update-row-by-key.ts
new file mode 100644
index 00000000000..40f5354289f
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/update-row-by-key.ts
@@ -0,0 +1,66 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import { buildSetClause, guardedWrite } from '../../common/operations';
+import { updateByKeyOutputSchema } from '../../common/output-schemas';
+import { identifier, parseObject, qualifiedName } from '../../common/sql';
+
+export const updateRowByKeyAction = createAction({
+ name: 'update_row_by_key',
+ classification: 'WRITE',
+ displayName: 'Update Row by Key',
+ description: 'Update the one row whose key column equals a value.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Sets the given column values on the single row whose key column equals Key Value; returns found=false when no row matches and rolls back with an error if more than one row matches. Setting the same values again changes nothing, so it is safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: updateByKeyOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ table: aiProps.table(),
+ keyColumn: Property.ShortText({
+ displayName: 'Key Column',
+ description: 'The unique key column, e.g. `ID`.',
+ required: true,
+ }),
+ keyValue: Property.ShortText({
+ displayName: 'Key Value',
+ description: 'The key value of the row to update.',
+ required: true,
+ }),
+ values: aiProps.values(
+ 'Values',
+ 'Column names mapped to new values, e.g. {"STATUS": "shipped"}.'
+ ),
+ },
+ async run(context) {
+ const { table, keyColumn, keyValue } = context.propsValue;
+ const set = buildSetClause(
+ parseObject({ value: context.propsValue.values, label: 'Values' })
+ );
+ const sql = `UPDATE ${qualifiedName({
+ value: table,
+ label: 'Table',
+ })} SET ${set.clause} WHERE ${identifier({
+ name: keyColumn,
+ label: 'Key column',
+ })} = ?`;
+ const rowsAffected = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ guardedWrite({
+ session,
+ sql,
+ binds: [...set.binds, keyValue],
+ countKey: 'number of rows updated',
+ maxRows: 1,
+ tooManyMessage: (count) =>
+ `${count} rows have ${keyColumn} = ${keyValue}, so it is not a unique key. Nothing was changed; use Update Rows by Filter instead.`,
+ }),
+ });
+ return { found: rowsAffected > 0, rowsAffected };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/update-rows-by-filter.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/update-rows-by-filter.ts
new file mode 100644
index 00000000000..2a35be905d3
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/update-rows-by-filter.ts
@@ -0,0 +1,81 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import {
+ aiProps,
+ WRITE_GUARD_DEFAULT,
+ WRITE_GUARD_MAX,
+} from '../../common/ai-props';
+import { buildSetClause, guardedWrite } from '../../common/operations';
+import { updateByFilterOutputSchema } from '../../common/output-schemas';
+import {
+ boundedInteger,
+ buildWhere,
+ parseObject,
+ qualifiedName,
+} from '../../common/sql';
+
+export const updateRowsByFilterAction = createAction({
+ name: 'update_rows_by_filter',
+ classification: 'WRITE',
+ displayName: 'Update Rows by Filter',
+ description:
+ 'Update every row that matches the filters, up to a safety limit.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Sets the given column values on all rows matching every filter (at least one filter required). Runs in a transaction and rolls back with an error if more than Max Rows would change; check with Count Rows first. Setting the same values again changes nothing, so it is safe to retry.',
+ idempotent: true,
+ },
+ outputSchema: updateByFilterOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ table: aiProps.table(),
+ filters: aiProps.filters(true),
+ values: aiProps.values(
+ 'Values',
+ 'Column names mapped to new values, e.g. {"STATUS": "archived"}.'
+ ),
+ maxRows: Property.Number({
+ displayName: 'Max Rows',
+ description: `Refuse (and roll back) if more rows than this would be updated (1–${WRITE_GUARD_MAX}). Defaults to ${WRITE_GUARD_DEFAULT}.`,
+ required: false,
+ defaultValue: WRITE_GUARD_DEFAULT,
+ }),
+ },
+ async run(context) {
+ const { table, filters, values, maxRows } = context.propsValue;
+ const where = buildWhere(filters);
+ if (where.clause === '') {
+ throw new Error(
+ 'Provide at least one filter; updating a whole table is not allowed here.'
+ );
+ }
+ const limit = boundedInteger({
+ value: maxRows,
+ defaultValue: WRITE_GUARD_DEFAULT,
+ min: 1,
+ max: WRITE_GUARD_MAX,
+ label: 'Max Rows',
+ });
+ const set = buildSetClause(parseObject({ value: values, label: 'Values' }));
+ const sql = `UPDATE ${qualifiedName({
+ value: table,
+ label: 'Table',
+ })} SET ${set.clause}${where.clause}`;
+ const rowsAffected = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ guardedWrite({
+ session,
+ sql,
+ binds: [...set.binds, ...where.binds],
+ countKey: 'number of rows updated',
+ maxRows: limit,
+ tooManyMessage: (count) =>
+ `The filters match ${count} rows, more than Max Rows (${limit}). Nothing was changed; narrow the filters or raise Max Rows.`,
+ }),
+ });
+ return { rowsAffected };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/ai/upsert-row-by-key.ts b/packages/pieces/community/snowflake/src/lib/actions/ai/upsert-row-by-key.ts
new file mode 100644
index 00000000000..cf6bd40a67e
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/actions/ai/upsert-row-by-key.ts
@@ -0,0 +1,57 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { snowflakeAuth } from '../../auth';
+import { toAuthValue, withSnowflake } from '../../common';
+import { aiProps } from '../../common/ai-props';
+import { buildMerge } from '../../common/merge';
+import { dmlCount } from '../../common/operations';
+import { upsertOutputSchema } from '../../common/output-schemas';
+import { parseObject, parseStringList } from '../../common/sql';
+
+export const upsertRowByKeyAction = createAction({
+ name: 'upsert_row_by_key',
+ classification: 'WRITE',
+ displayName: 'Upsert Row by Key',
+ description:
+ 'Insert a row, or update the existing row with the same key values (MERGE).',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates or updates one row with MERGE, matching on the given key column(s), which must also appear in Row. Returns how many rows were inserted and updated. Running it again with the same values leaves the same row, so it is safe to retry. Key values must not be null.',
+ idempotent: true,
+ },
+ outputSchema: upsertOutputSchema,
+ auth: snowflakeAuth,
+ props: {
+ table: aiProps.table(),
+ keyColumns: Property.Array({
+ displayName: 'Key Columns',
+ description: 'Column(s) that identify the row, e.g. ["ID"].',
+ required: true,
+ }),
+ row: aiProps.values(
+ 'Row',
+ 'Column names mapped to values, including the key column(s).'
+ ),
+ },
+ async run(context) {
+ const keyColumns = parseStringList({
+ value: context.propsValue.keyColumns,
+ label: 'Key Columns',
+ });
+ const values = parseObject({ value: context.propsValue.row, label: 'Row' });
+ const { sql, binds } = buildMerge({
+ table: context.propsValue.table,
+ keyColumns,
+ values,
+ });
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql, binds }),
+ });
+ return {
+ rowsInserted: dmlCount({ result, key: 'number of rows inserted' }),
+ rowsUpdated: dmlCount({ result, key: 'number of rows updated' }),
+ queryId: result.queryId,
+ };
+ },
+});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/create-dynamic-table.ts b/packages/pieces/community/snowflake/src/lib/actions/create-dynamic-table.ts
index 4dd78446666..6a31ee1bc24 100644
--- a/packages/pieces/community/snowflake/src/lib/actions/create-dynamic-table.ts
+++ b/packages/pieces/community/snowflake/src/lib/actions/create-dynamic-table.ts
@@ -1,26 +1,25 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { snowflakeAuth } from '../auth';
-import {
- configureConnection,
- connect,
- destroy,
- execute,
- snowflakeCommonProps,
- SnowflakeAuthValue,
-} from '../common';
+import { snowflakeCommonProps, toAuthValue, withSnowflake } from '../common';
+import { dynamicTableOutputSchema } from '../common/output-schemas';
+import { identifier, qualifiedName } from '../common/sql';
+
+const TARGET_LAG = /^(DOWNSTREAM|\d{1,6}\s+(seconds?|minutes?|hours?|days?))$/i;
export const createDynamicTableAction = createAction({
name: 'create_dynamic_table',
+ classification: 'WRITE',
displayName: 'Create / Refresh Dynamic Table',
description:
'Create or replace a Snowflake Dynamic Table that automatically refreshes based on a query. ' +
'Dynamic Tables are a declarative way to define a table whose content is derived from a query, updated on a schedule.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
- 'Creates or replaces a Snowflake Dynamic Table whose contents are derived from a SELECT query and auto-refresh on a target-lag schedule, using a specified warehouse. Use to set up or redefine a declarative, self-refreshing derived table. Effectively idempotent in result via CREATE OR REPLACE (re-running with the same inputs yields the same table definition), though REPLACE drops and recreates the object.',
+ 'CREATE OR REPLACE DYNAMIC TABLE from a SELECT query with a target lag and warehouse. Human-only DDL. Re-running with the same inputs recreates the same definition (REPLACE drops and rebuilds the table).',
idempotent: true,
},
+ outputSchema: dynamicTableOutputSchema,
auth: snowflakeAuth,
props: {
database: snowflakeCommonProps.database,
@@ -50,51 +49,45 @@ export const createDynamicTableAction = createAction({
async run(context) {
const { database, schema, table_name, target_lag, warehouse, query } =
context.propsValue;
-
const identifierRegex = /^[A-Za-z_][A-Za-z0-9_$]*$/;
if (!identifierRegex.test(table_name)) {
throw new Error(
'Invalid table name: only letters, digits, underscores, and $ are allowed.'
);
}
- if (target_lag.includes("'")) {
+ const lag = target_lag.trim();
+ if (!TARGET_LAG.test(lag)) {
throw new Error(
- 'Invalid target_lag value: single quotes are not allowed.'
+ 'Invalid Refresh Interval. Use a number and unit such as "5 minutes" or "1 hour", or DOWNSTREAM.'
);
}
-
const effectiveWarehouse =
- warehouse || (context.auth as SnowflakeAuthValue).props?.warehouse;
+ warehouse || toAuthValue(context.auth).props.warehouse;
if (!effectiveWarehouse) {
throw new Error(
'A warehouse is required. Provide it in the action props or set a default in your connection.'
);
}
- if (!identifierRegex.test(effectiveWarehouse)) {
- throw new Error(
- 'Invalid warehouse name: only letters, digits, underscores, and $ are allowed.'
- );
- }
-
- const sql = `
-CREATE OR REPLACE DYNAMIC TABLE ${database}.${schema}.${table_name}
- TARGET_LAG = '${target_lag}'
- WAREHOUSE = ${effectiveWarehouse}
- AS ${query}
- `.trim();
-
- const connection = configureConnection(context.auth as SnowflakeAuthValue);
- await connect(connection);
- try {
- await execute(connection, sql, []);
- return {
- success: true,
- table: `${database}.${schema}.${table_name}`,
- target_lag,
- warehouse: effectiveWarehouse,
- };
- } finally {
- await destroy(connection);
- }
+ const target = `${qualifiedName({
+ value: `${database}.${schema}`,
+ maxParts: 2,
+ label: 'Schema',
+ })}.${table_name}`;
+ const lagSql =
+ lag.toUpperCase() === 'DOWNSTREAM' ? 'DOWNSTREAM' : `'${lag}'`;
+ const sql = `CREATE OR REPLACE DYNAMIC TABLE ${target}
+ TARGET_LAG = ${lagSql}
+ WAREHOUSE = ${identifier({ name: effectiveWarehouse, label: 'Warehouse' })}
+ AS ${query}`;
+ await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql }),
+ });
+ return {
+ success: true,
+ table: `${database}.${schema}.${table_name}`,
+ target_lag: lag,
+ warehouse: effectiveWarehouse,
+ };
},
});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/delete-row.ts b/packages/pieces/community/snowflake/src/lib/actions/delete-row.ts
index f44c61a7679..603f62abd4b 100644
--- a/packages/pieces/community/snowflake/src/lib/actions/delete-row.ts
+++ b/packages/pieces/community/snowflake/src/lib/actions/delete-row.ts
@@ -1,25 +1,23 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { snowflakeAuth } from '../auth';
-import {
- configureConnection,
- connect,
- destroy,
- execute,
- snowflakeCommonProps,
- SnowflakeAuthValue,
-} from '../common';
+import { snowflakeCommonProps, toAuthValue, withSnowflake } from '../common';
+import { dmlCount } from '../common/operations';
+import { legacyDeleteOutputSchema } from '../common/output-schemas';
+import { qualifiedName } from '../common/sql';
export const deleteRowAction = createAction({
name: 'delete_row',
+ classification: 'DESTRUCTIVE',
displayName: 'Delete Row',
description:
'Delete one or more rows from a Snowflake table that match a WHERE condition.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
- 'Runs a DELETE on a Snowflake table, removing every row matching the required WHERE condition. Use to remove records; the condition is mandatory to guard against wiping the whole table, and it is embedded directly into SQL so pass only trusted values. Re-running after the matching rows are gone deletes nothing further, but treat this as a destructive mutating operation.',
+ 'Runs a DELETE with a hand-written, required WHERE condition on a table picked from dropdowns. Human-only; agents use Delete Row by Key or Delete Rows by Filter. Deleted rows cannot be restored by a retry.',
idempotent: false,
},
+ outputSchema: legacyDeleteOutputSchema,
auth: snowflakeAuth,
props: {
database: snowflakeCommonProps.database,
@@ -36,19 +34,21 @@ export const deleteRowAction = createAction({
},
async run(context) {
const { table, where_clause } = context.propsValue;
-
- const sql = `DELETE FROM ${table} WHERE ${where_clause}`;
-
- const connection = configureConnection(context.auth as SnowflakeAuthValue);
- await connect(connection);
- try {
- const result = await execute(connection, sql, []);
- return {
- success: true,
- rows_deleted: result?.[0]?.['number of rows deleted'] ?? null,
- };
- } finally {
- await destroy(connection);
+ const where = (where_clause ?? '').trim();
+ if (where === '') {
+ throw new Error('The WHERE condition is required to delete rows.');
}
+ const sql = `DELETE FROM ${qualifiedName({
+ value: table,
+ label: 'Table',
+ })} WHERE ${where}`;
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql }),
+ });
+ return {
+ success: true,
+ rows_deleted: dmlCount({ result, key: 'number of rows deleted' }),
+ };
},
});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/execute-stored-procedure.ts b/packages/pieces/community/snowflake/src/lib/actions/execute-stored-procedure.ts
index 45d59a111d6..34e1bd02ed5 100644
--- a/packages/pieces/community/snowflake/src/lib/actions/execute-stored-procedure.ts
+++ b/packages/pieces/community/snowflake/src/lib/actions/execute-stored-procedure.ts
@@ -1,24 +1,23 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { snowflakeAuth } from '../auth';
-import {
- configureConnection,
- connect,
- destroy,
- execute,
- snowflakeCommonProps,
- SnowflakeAuthValue,
-} from '../common';
+import { snowflakeCommonProps, toAuthValue, withSnowflake } from '../common';
+import { legacyProcedureOutputSchema } from '../common/output-schemas';
+import { isUserDefined } from '../common/operations';
+import { buildCall, parseSignatureArgTypes } from '../common/procedures';
+import { qualifiedName } from '../common/sql';
export const executeStoredProcedureAction = createAction({
name: 'execute_stored_procedure',
+ classification: 'WRITE',
displayName: 'Execute Stored Procedure',
description: 'Call a stored procedure in Snowflake and return its result.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
- 'Calls a named stored procedure in a Snowflake database/schema with optional positional arguments and returns its result (CALL). Use to invoke server-side procedural logic rather than ad-hoc SQL. Idempotency depends on what the procedure does internally; assume not idempotent since a procedure may mutate data or have side effects on each call.',
+ 'CALLs a stored procedure picked from dropdowns with positional arguments. Human-only; agents use Call Procedure. A procedure may change data on every call.',
idempotent: false,
},
+ outputSchema: legacyProcedureOutputSchema,
auth: snowflakeAuth,
props: {
database: snowflakeCommonProps.database,
@@ -44,27 +43,36 @@ export const executeStoredProcedureAction = createAction({
placeholder: 'Please select a database and schema first',
};
}
- const connection = configureConnection(auth as SnowflakeAuthValue);
- await connect(connection);
- let result;
try {
- result = await execute(
- connection,
- `SHOW PROCEDURES IN SCHEMA ${database}.${schema}`,
- []
- );
- } finally {
- await destroy(connection);
+ const result = await withSnowflake({
+ auth: toAuthValue(auth),
+ statementTimeoutSeconds: 60,
+ fn: (session) =>
+ session.query({
+ sql: `SHOW PROCEDURES IN SCHEMA ${qualifiedName({
+ value: `${database}.${schema}`,
+ maxParts: 2,
+ label: 'Schema',
+ })}`,
+ maxRows: 5000,
+ }),
+ });
+ return {
+ disabled: false,
+ options: result.rows.filter(isUserDefined).map((proc) => {
+ const value = String(proc['arguments'] ?? proc['name'] ?? '');
+ return { label: value, value };
+ }),
+ };
+ } catch (error) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: `Could not load procedures: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ };
}
- return {
- disabled: false,
- options: result
- ? (result as Record<string, unknown>[]).map((proc) => ({
- label: String(proc['arguments'] ?? proc['name'] ?? ''),
- value: String(proc['arguments'] ?? proc['name'] ?? ''),
- }))
- : [],
- };
},
}),
arguments: Property.Array({
@@ -82,28 +90,27 @@ export const executeStoredProcedureAction = createAction({
procedure_name,
arguments: args,
} = context.propsValue;
-
- // procedure_name is the full signature string (e.g. "MY_PROC(NUMBER) RETURN VARCHAR")
- // Extract just the bare name before the first '('
const bareName = procedure_name.includes('(')
? procedure_name.substring(0, procedure_name.indexOf('(')).trim()
: procedure_name.trim();
-
- const argPlaceholders =
- args && args.length > 0
- ? (args as string[]).map(() => '?').join(', ')
- : '';
-
- const sql = `CALL ${database}.${schema}.${bareName}(${argPlaceholders})`;
- const binds = args && args.length > 0 ? (args as string[]) : [];
-
- const connection = configureConnection(context.auth as SnowflakeAuthValue);
- await connect(connection);
- try {
- const result = await execute(connection, sql, binds);
- return { result: result ?? null };
- } finally {
- await destroy(connection);
- }
+ const { sql, binds } = buildCall({
+ procedure: `${qualifiedName({
+ value: `${database}.${schema}`,
+ maxParts: 2,
+ label: 'Schema',
+ })}.${qualifiedName({
+ value: bareName,
+ maxParts: 1,
+ label: 'Procedure',
+ })}`,
+ args: args ?? [],
+ preQualified: true,
+ argTypes: parseSignatureArgTypes(procedure_name),
+ });
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql, binds }),
+ });
+ return { result: result.rows };
},
});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/get-row-by-id.ts b/packages/pieces/community/snowflake/src/lib/actions/get-row-by-id.ts
index b622e6eb8c8..3424cb7eb30 100644
--- a/packages/pieces/community/snowflake/src/lib/actions/get-row-by-id.ts
+++ b/packages/pieces/community/snowflake/src/lib/actions/get-row-by-id.ts
@@ -1,26 +1,27 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { snowflakeAuth } from '../auth';
import {
- configureConnection,
- connect,
- destroy,
- execute,
getTableColumnOptions,
snowflakeCommonProps,
- SnowflakeAuthValue,
+ toAuthValue,
+ withSnowflake,
} from '../common';
+import { getRowByIdOutputSchema } from '../common/output-schemas';
+import { identifier, qualifiedName } from '../common/sql';
export const getRowByIdAction = createAction({
name: 'get_row_by_id',
+ classification: 'READ',
displayName: 'Get Row by ID',
description:
'Retrieve a single row from a Snowflake table by matching a column value.',
audience: 'both',
aiMetadata: {
description:
- 'Looks up and returns a single row from a Snowflake table where the chosen ID column equals a given value (the first match, LIMIT 1). Use for a targeted point lookup by primary key or unique identifier; for multi-row or condition-based queries use Search Rows. Read-only and idempotent.',
+ 'Returns the first row of a table whose chosen column equals a value; the row columns are spread next to found=true, or only found=false when nothing matches. For free-text table names use Get Row by Key. Read-only and safe to retry.',
idempotent: true,
},
+ outputSchema: getRowByIdOutputSchema,
auth: snowflakeAuth,
props: {
database: snowflakeCommonProps.database,
@@ -48,10 +49,10 @@ export const getRowByIdAction = createAction({
placeholder: 'Please select a table first',
};
}
- return getTableColumnOptions(
- auth as SnowflakeAuthValue,
- table as string
- );
+ return getTableColumnOptions({
+ auth: toAuthValue(auth),
+ table: String(table),
+ });
},
}),
id_value: Property.ShortText({
@@ -62,20 +63,21 @@ export const getRowByIdAction = createAction({
},
async run(context) {
const { table, id_column, id_value } = context.propsValue;
-
- const sql = `SELECT * FROM ${table} WHERE ${id_column} = ? LIMIT 1`;
-
- const connection = configureConnection(context.auth as SnowflakeAuthValue);
- await connect(connection);
- try {
- const result = await execute(connection, sql, [id_value]);
- if (!result || result.length === 0) {
- return { found: false };
- }
- const row = result[0] as Record<string, unknown>;
- return { found: true, ...row };
- } finally {
- await destroy(connection);
+ const sql = `SELECT * FROM ${qualifiedName({
+ value: table,
+ label: 'Table',
+ })} WHERE ${identifier({
+ name: id_column,
+ label: 'ID column',
+ })} = ? LIMIT 1`;
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql, binds: [id_value], maxRows: 1 }),
+ });
+ const row = result.rows[0];
+ if (!row) {
+ return { found: false };
}
+ return { found: true, ...row };
},
});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/get-table-schema.ts b/packages/pieces/community/snowflake/src/lib/actions/get-table-schema.ts
index fecef380720..14a0580d1a6 100644
--- a/packages/pieces/community/snowflake/src/lib/actions/get-table-schema.ts
+++ b/packages/pieces/community/snowflake/src/lib/actions/get-table-schema.ts
@@ -1,25 +1,22 @@
import { createAction } from '@activepieces/pieces-framework';
import { snowflakeAuth } from '../auth';
-import {
- configureConnection,
- connect,
- destroy,
- execute,
- snowflakeCommonProps,
- SnowflakeAuthValue,
-} from '../common';
+import { snowflakeCommonProps, toAuthValue, withSnowflake } from '../common';
+import { tableSchemaOutputSchema } from '../common/output-schemas';
+import { qualifiedName } from '../common/sql';
export const getTableSchemaAction = createAction({
name: 'get_table_schema',
+ classification: 'READ',
displayName: 'Get Table Schema',
description:
'Retrieve the column definitions (name, data type, nullability, default) for a Snowflake table.',
audience: 'both',
aiMetadata: {
description:
- "Describes a Snowflake table, returning its column definitions (name, data type, nullability, default, key flags, comment) via DESCRIBE TABLE. Use to discover a table's structure before building inserts, updates, or queries against it. Read-only and idempotent.",
+ 'Returns the column definitions (name, type, nullability, default, key flags, comment) of a table chosen from dropdowns. For a free-text table name use Describe Table. Read-only and safe to retry.',
idempotent: true,
},
+ outputSchema: tableSchemaOutputSchema,
auth: snowflakeAuth,
props: {
database: snowflakeCommonProps.database,
@@ -28,28 +25,27 @@ export const getTableSchemaAction = createAction({
},
async run(context) {
const { table } = context.propsValue;
-
- const connection = configureConnection(context.auth as SnowflakeAuthValue);
- await connect(connection);
- try {
- const result = await execute(connection, `DESCRIBE TABLE ${table}`, []);
- if (!result) return { columns: [] };
-
- const columns = (result as Record<string, unknown>[]).map((col) => ({
- column_name: col['name'] ?? null,
- data_type: col['type'] ?? null,
- nullable: col['null?'] ?? null,
- default_value: col['default'] ?? null,
- primary_key: col['primary key'] ?? null,
- unique_key: col['unique key'] ?? null,
- check: col['check'] ?? null,
- expression: col['expression'] ?? null,
- comment: col['comment'] ?? null,
- }));
-
- return { table, columns };
- } finally {
- await destroy(connection);
- }
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ session.query({
+ sql: `DESCRIBE TABLE ${qualifiedName({
+ value: table,
+ label: 'Table',
+ })}`,
+ }),
+ });
+ const columns = result.rows.map((col) => ({
+ column_name: col['name'] ?? null,
+ data_type: col['type'] ?? null,
+ nullable: col['null?'] ?? null,
+ default_value: col['default'] ?? null,
+ primary_key: col['primary key'] ?? null,
+ unique_key: col['unique key'] ?? null,
+ check: col['check'] ?? null,
+ expression: col['expression'] ?? null,
+ comment: col['comment'] ?? null,
+ }));
+ return { table, columns };
},
});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/insert-multiple-rows.ts b/packages/pieces/community/snowflake/src/lib/actions/insert-multiple-rows.ts
index b0d36062f6a..ddedae7b97c 100644
--- a/packages/pieces/community/snowflake/src/lib/actions/insert-multiple-rows.ts
+++ b/packages/pieces/community/snowflake/src/lib/actions/insert-multiple-rows.ts
@@ -1,25 +1,23 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { snowflakeAuth } from '../auth';
-import {
- configureConnection,
- connect,
- destroy,
- execute,
- snowflakeCommonProps,
- SnowflakeAuthValue,
-} from '../common';
+import { snowflakeCommonProps, toAuthValue, withSnowflake } from '../common';
+import { buildInsert, dmlCount } from '../common/operations';
+import { legacyInsertManyOutputSchema } from '../common/output-schemas';
+import { parseRowArray } from '../common/sql';
export const insertMultipleRowsAction = createAction({
name: 'insert_multiple_rows',
+ classification: 'WRITE',
displayName: 'Insert Multiple Rows',
description:
'Insert multiple rows into a Snowflake table in a single operation.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
- 'Bulk-inserts an array of rows into a Snowflake table in one INSERT statement. Use when adding several records at once (e.g. mapping an array from a previous step); for a single record use Insert Row. Every row object must share the same set of column keys as the first row. Not idempotent: each call appends the rows again, duplicating them unless the table enforces uniqueness.',
+ 'Bulk-inserts an array of same-keyed row objects into a table picked from dropdowns, in one INSERT. Human-only; agents use Insert Rows (JSON). Each call appends the rows again.',
idempotent: false,
},
+ outputSchema: legacyInsertManyOutputSchema,
auth: snowflakeAuth,
props: {
database: snowflakeCommonProps.database,
@@ -30,73 +28,31 @@ export const insertMultipleRowsAction = createAction({
description:
'One item per row. Each item must be a JSON object with column names as keys. ' +
'Example: `{"name": "Alice", "age": 30}`. ' +
- 'When mapping from a previous step, pass the entire array directly.',
+ 'When mapping from a previous step, pass the entire array directly. Object or array values are stored as JSON (VARIANT).',
required: true,
}),
},
async run(context) {
const { table, rows } = context.propsValue;
-
if (!Array.isArray(rows) || rows.length === 0) {
throw new Error('Rows must be a non-empty array.');
}
-
- const parsedRows = (rows as unknown[]).map((item) => {
- if (typeof item === 'string') {
- try {
- return JSON.parse(item) as Record<string, unknown>;
- } catch {
- throw new Error(`Invalid JSON in row: ${item}`);
- }
- }
- return item as Record<string, unknown>;
+ const parsedRows = parseRowArray({ value: rows, label: 'Row' });
+ const { sql, binds } = buildInsert({
+ table,
+ rows: parsedRows,
+ exactColumnNames: true,
});
-
- const columns = Object.keys(parsedRows[0]);
- if (columns.length === 0) {
- throw new Error(
- 'Each row object must have at least one key (column name).'
- );
- }
-
- const columnSet = new Set(columns);
- parsedRows.forEach((row, i) => {
- const rowKeys = Object.keys(row);
- const missing = columns.filter((col) => !(col in row));
- const extra = rowKeys.filter((k) => !columnSet.has(k));
- if (missing.length > 0 || extra.length > 0) {
- throw new Error(
- `Row ${i + 1} has a different column set than the first row.` +
- (missing.length > 0 ? ` Missing: ${missing.join(', ')}.` : '') +
- (extra.length > 0 ? ` Extra: ${extra.join(', ')}.` : '')
- );
- }
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql, binds }),
});
-
- const rowPlaceholders = parsedRows
- .map(() => `(${columns.map(() => '?').join(', ')})`)
- .join(', ');
-
- const binds = parsedRows.flatMap((row) =>
- columns.map((col) => row[col])
- ) as string[];
-
- const quotedColumns = columns
- .map((col) => `"${col.replace(/"/g, '""')}"`)
- .join(', ');
- const sql = `INSERT INTO ${table} (${quotedColumns}) VALUES ${rowPlaceholders}`;
-
- const connection = configureConnection(context.auth as SnowflakeAuthValue);
- await connect(connection);
- try {
- const result = await execute(connection, sql, binds);
- return {
- success: true,
- rows_inserted:
- result?.[0]?.['number of rows inserted'] ?? parsedRows.length,
- };
- } finally {
- await destroy(connection);
- }
+ return {
+ success: true,
+ rows_inserted:
+ result.rows.length > 0
+ ? dmlCount({ result, key: 'number of rows inserted' })
+ : parsedRows.length,
+ };
},
});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/insert-row.ts b/packages/pieces/community/snowflake/src/lib/actions/insert-row.ts
index 0dd1ea17bf6..6bc1ba072a5 100644
--- a/packages/pieces/community/snowflake/src/lib/actions/insert-row.ts
+++ b/packages/pieces/community/snowflake/src/lib/actions/insert-row.ts
@@ -1,24 +1,21 @@
import { createAction } from '@activepieces/pieces-framework';
import { snowflakeAuth } from '../auth';
-import {
- configureConnection,
- connect,
- destroy,
- execute,
- snowflakeCommonProps,
- SnowflakeAuthValue,
-} from '../common';
+import { snowflakeCommonProps, toAuthValue, withSnowflake } from '../common';
+import { buildInsert } from '../common/operations';
+import { legacyInsertOutputSchema } from '../common/output-schemas';
export const insertRowAction = createAction({
name: 'insert-row',
+ classification: 'WRITE',
displayName: 'Insert Row',
description: 'Insert a row into a table.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
- 'Inserts a single new row into a specified Snowflake table (database, schema, table, and a map of column values). Use when adding one record; for many rows at once use Insert Multiple Rows. Not idempotent: each call issues an INSERT, so repeating it appends a duplicate row unless the table enforces uniqueness.',
+ 'Inserts one row into a table picked from dropdowns, with one input per column. Human-only; agents use Insert Row (JSON). Each call appends a new row, so retries duplicate it.',
idempotent: false,
},
+ outputSchema: legacyInsertOutputSchema,
auth: snowflakeAuth,
props: {
database: snowflakeCommonProps.database,
@@ -27,25 +24,15 @@ export const insertRowAction = createAction({
table_column_values: snowflakeCommonProps.table_column_values,
},
async run(context) {
- const tableName = context.propsValue.table;
- const tableColumnValues = context.propsValue.table_column_values;
-
- const columns = Object.keys(tableColumnValues).join(',');
- const valuePlaceholders = Object.keys(tableColumnValues)
- .map(() => '?')
- .join(', ');
- const statement = `INSERT INTO ${tableName}(${columns}) VALUES(${valuePlaceholders})`;
-
- const connection = configureConnection(context.auth as SnowflakeAuthValue);
- await connect(connection);
-
- const response = await execute(
- connection,
- statement,
- Object.values(tableColumnValues)
- );
- await destroy(connection);
-
- return response;
+ const { table, table_column_values } = context.propsValue;
+ const { sql, binds } = buildInsert({
+ table,
+ rows: [Object.fromEntries(Object.entries(table_column_values))],
+ });
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql, binds }),
+ });
+ return result.rows;
},
});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/list-tables.ts b/packages/pieces/community/snowflake/src/lib/actions/list-tables.ts
index 1173d42fceb..c4bf74b632b 100644
--- a/packages/pieces/community/snowflake/src/lib/actions/list-tables.ts
+++ b/packages/pieces/community/snowflake/src/lib/actions/list-tables.ts
@@ -1,24 +1,22 @@
import { createAction } from '@activepieces/pieces-framework';
import { snowflakeAuth } from '../auth';
-import {
- configureConnection,
- connect,
- destroy,
- execute,
- snowflakeCommonProps,
- SnowflakeAuthValue,
-} from '../common';
+import { snowflakeCommonProps, toAuthValue, withSnowflake } from '../common';
+import { mapTable } from '../common/mappers';
+import { listTablesOutputSchema } from '../common/output-schemas';
+import { qualifiedName } from '../common/sql';
export const listTablesAction = createAction({
name: 'list_tables',
+ classification: 'SEARCH',
displayName: 'List Tables',
description: 'List all tables in a Snowflake schema.',
audience: 'both',
aiMetadata: {
description:
- "Lists the tables in a given Snowflake database and schema (via SHOW TABLES), returning each table's name, kind, row/byte counts, owner, and creation time. Use to discover what tables exist before querying or to enumerate a schema. Read-only and idempotent.",
+ 'Lists every table in a database and schema chosen from dropdowns, with kind, row and byte counts, owner and creation time. For free-text names or a name pattern use List Tables (by name). Read-only.',
idempotent: true,
},
+ outputSchema: listTablesOutputSchema,
auth: snowflakeAuth,
props: {
database: snowflakeCommonProps.database,
@@ -26,30 +24,17 @@ export const listTablesAction = createAction({
},
async run(context) {
const { database, schema } = context.propsValue;
-
- const connection = configureConnection(context.auth as SnowflakeAuthValue);
- await connect(connection);
- try {
- const result = await execute(
- connection,
- `SHOW TABLES IN SCHEMA ${database}.${schema}`,
- []
- );
- if (!result) return [];
-
- return (result as Record<string, unknown>[]).map((t) => ({
- table_name: t['name'] ?? null,
- database_name: t['database_name'] ?? null,
- schema_name: t['schema_name'] ?? null,
- kind: t['kind'] ?? null,
- rows: t['rows'] ?? null,
- bytes: t['bytes'] ?? null,
- owner: t['owner'] ?? null,
- comment: t['comment'] ?? null,
- created_on: t['created_on'] ?? null,
- }));
- } finally {
- await destroy(connection);
- }
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) =>
+ session.query({
+ sql: `SHOW TABLES IN SCHEMA ${qualifiedName({
+ value: `${database}.${schema}`,
+ maxParts: 2,
+ label: 'Schema',
+ })}`,
+ }),
+ });
+ return result.rows.map(mapTable);
},
});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/load-data-from-stage.ts b/packages/pieces/community/snowflake/src/lib/actions/load-data-from-stage.ts
index 3599c882cf4..12350c2ee8f 100644
--- a/packages/pieces/community/snowflake/src/lib/actions/load-data-from-stage.ts
+++ b/packages/pieces/community/snowflake/src/lib/actions/load-data-from-stage.ts
@@ -1,25 +1,23 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { snowflakeAuth } from '../auth';
-import {
- configureConnection,
- connect,
- destroy,
- execute,
- snowflakeCommonProps,
- SnowflakeAuthValue,
-} from '../common';
+import { snowflakeCommonProps, toAuthValue, withSnowflake } from '../common';
+import { mapCopyFile } from '../common/mappers';
+import { legacyLoadOutputSchema } from '../common/output-schemas';
+import { buildCopyInto, stageReference } from '../common/stage';
export const loadDataFromStageAction = createAction({
name: 'load_data_from_stage',
+ classification: 'WRITE',
displayName: 'Load Data from Stage',
description:
'Load data into a Snowflake table from a named internal or external stage using COPY INTO.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
- 'Bulk-loads files from a named internal or external Snowflake stage into a target table via COPY INTO, with configurable file format, file-name pattern, header skipping, and on-error behavior. Use to ingest staged CSV/JSON/Parquet/etc. data. By default COPY INTO skips files it has already loaded, but re-running may load newly added files; treat as a mutating load (not strictly idempotent).',
+ 'COPY INTO a table picked from dropdowns from a named stage path. Human-only; agents use Copy Stage Files into Table. Snowflake skips files it already loaded in the last 64 days, but new files in the path are loaded on a re-run.',
idempotent: false,
},
+ outputSchema: legacyLoadOutputSchema,
auth: snowflakeAuth,
props: {
database: snowflakeCommonProps.database,
@@ -67,7 +65,7 @@ export const loadDataFromStageAction = createAction({
error_on_column_count_mismatch: Property.Checkbox({
displayName: 'Fail on Column Count Mismatch',
description:
- 'When enabled, the load fails if the number of columns in a file does not match the number of columns in the target table. Disable to allow files with fewer columns.',
+ 'When enabled, the load fails if the number of columns in a file does not match the number of columns in the target table. Disable to allow files with fewer columns. Only applies to CSV files.',
required: false,
defaultValue: true,
}),
@@ -86,60 +84,31 @@ export const loadDataFromStageAction = createAction({
}),
},
async run(context) {
- const {
- table,
- stage_path,
- file_format_type,
- file_pattern,
- skip_header,
- error_on_column_count_mismatch,
- on_error,
- } = context.propsValue;
-
- let fileFormatClause = `TYPE = '${file_format_type}'`;
- if (skip_header)
- fileFormatClause += ` SKIP_HEADER = ${Number(skip_header)}`;
- if (error_on_column_count_mismatch !== undefined) {
- fileFormatClause += ` ERROR_ON_COLUMN_COUNT_MISMATCH = ${
- error_on_column_count_mismatch ? 'TRUE' : 'FALSE'
- }`;
- }
-
- let sql = `COPY INTO ${table} FROM ${stage_path} FILE_FORMAT = (${fileFormatClause})`;
- if (file_pattern) sql += ` PATTERN = '${file_pattern.replace(/'/g, "''")}'`;
- sql += ` ON_ERROR = '${on_error ?? 'ABORT_STATEMENT'}'`;
-
- const connection = configureConnection(context.auth as SnowflakeAuthValue);
- await connect(connection);
- try {
- const result = await execute(connection, sql, []);
- if (!result || result.length === 0) {
- return { success: true, files_processed: 0, rows_loaded: 0 };
- }
-
- const summary = (result as Record<string, unknown>[]).map((row) => ({
- file: row['file'] ?? null,
- status: row['status'] ?? null,
- rows_parsed: row['rows_parsed'] ?? null,
- rows_loaded: row['rows_loaded'] ?? null,
- error_limit: row['error_limit'] ?? null,
- errors_seen: row['errors_seen'] ?? null,
- first_error: row['first_error'] ?? null,
- }));
-
- const totalLoaded = summary.reduce(
- (sum, r) => sum + (Number(r.rows_loaded) || 0),
+ const p = context.propsValue;
+ const sql = buildCopyInto({
+ table: p.table,
+ stage: stageReference({ stage: p.stage_path }),
+ fileFormat: p.file_format_type,
+ pattern: p.file_pattern,
+ skipHeader: p.skip_header,
+ errorOnColumnCountMismatch: p.error_on_column_count_mismatch,
+ onError: p.on_error,
+ });
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql }),
+ });
+ const files = result.rows
+ .filter((row) => row['file'] !== undefined)
+ .map(mapCopyFile);
+ return {
+ success: true,
+ files_processed: files.length,
+ rows_loaded: files.reduce(
+ (sum, file) => sum + (Number(file.rows_loaded) || 0),
0
- );
-
- return {
- success: true,
- files_processed: summary.length,
- rows_loaded: totalLoaded,
- files: summary,
- };
- } finally {
- await destroy(connection);
- }
+ ),
+ files,
+ };
},
});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/run-multiple-queries.ts b/packages/pieces/community/snowflake/src/lib/actions/run-multiple-queries.ts
index d5369e2dcaa..28a39e78c7b 100644
--- a/packages/pieces/community/snowflake/src/lib/actions/run-multiple-queries.ts
+++ b/packages/pieces/community/snowflake/src/lib/actions/run-multiple-queries.ts
@@ -1,25 +1,28 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import snowflake, { RowStatement, SnowflakeError } from 'snowflake-sdk';
import { snowflakeAuth } from '../auth';
-import { configureConnection, SnowflakeAuthValue } from '../common';
+import {
+ DEFAULT_APPLICATION_NAME,
+ toAuthValue,
+ withSnowflake,
+} from '../common';
+import { multipleQueriesOutputSchema } from '../common/output-schemas';
+import { toBind } from '../common/sql';
-type QueryResult = unknown[] | undefined;
-type QueryResults = { query: string; result: QueryResult }[];
-
-const DEFAULT_APPLICATION_NAME = 'ActivePieces';
const DEFAULT_QUERY_TIMEOUT = 30000;
export const runMultipleQueries = createAction({
name: 'runMultipleQueries',
+ classification: 'WRITE',
displayName: 'Run Multiple Queries',
description:
'Execute multiple SQL statements in sequence against your Snowflake database. Optionally wrap them in a transaction so all changes are rolled back if any statement fails.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
- 'Runs an ordered list of SQL statements against Snowflake in a single connection, with an option to wrap the whole batch in one transaction so a failure rolls back all preceding changes. Use this for multi-statement scripts or when several statements must succeed or fail together; for a single statement use Run Query. Bind shared dynamic values via numbered `:1`/`:2` placeholders (avoid `?` here). Not idempotent when the batch contains DML/DDL, since those mutate state on each call.',
+ 'Runs an ordered list of SQL statements in one session, optionally inside one transaction that rolls back on failure. Human-only; agents chain the atomic actions instead. Re-running repeats every change.',
idempotent: false,
},
+ outputSchema: multipleQueriesOutputSchema,
auth: snowflakeAuth,
props: {
sqlTexts: Property.Array({
@@ -44,7 +47,7 @@ export const runMultipleQueries = createAction({
timeout: Property.Number({
displayName: 'Query Timeout (ms)',
description:
- 'Maximum time in milliseconds to wait for each query to complete before cancelling it. Defaults to 30 000 ms (30 seconds).',
+ 'Maximum time in milliseconds each query may run before Snowflake cancels it (applied as STATEMENT_TIMEOUT_IN_SECONDS, capped at 540 seconds). Defaults to 30 000 ms (30 seconds).',
required: false,
defaultValue: DEFAULT_QUERY_TIMEOUT,
}),
@@ -56,107 +59,35 @@ export const runMultipleQueries = createAction({
defaultValue: DEFAULT_APPLICATION_NAME,
}),
},
-
async run(context) {
- const connection = configureConnection(
- context.auth as SnowflakeAuthValue,
- context.propsValue.application,
- context.propsValue.timeout
- );
-
- return new Promise<QueryResults>((resolve, reject) => {
- connection.connect(async function (err: SnowflakeError | undefined) {
- if (err) {
- reject(err);
- return;
- }
-
- const { sqlTexts, binds, useTransaction } = context.propsValue;
- const queryResults: QueryResults = [];
-
- function handleError(err: SnowflakeError) {
- if (useTransaction) {
- connection.execute({
- sqlText: 'ROLLBACK',
- complete: () => {
- connection.destroy(() => {
- reject(err);
- });
- },
- });
- } else {
- connection.destroy(() => {
- reject(err);
+ const { sqlTexts, binds, useTransaction, timeout, application } =
+ context.propsValue;
+ const bindValues = (binds ?? []).map(toBind);
+ return withSnowflake({
+ auth: toAuthValue(context.auth),
+ application: application || DEFAULT_APPLICATION_NAME,
+ statementTimeoutSeconds: (timeout ?? DEFAULT_QUERY_TIMEOUT) / 1000,
+ fn: async (session) => {
+ const results: { query: string; result: unknown[] }[] = [];
+ if (useTransaction) await session.query({ sql: 'BEGIN' });
+ try {
+ for (const sqlText of sqlTexts) {
+ const query = String(sqlText);
+ const result = await session.query({
+ sql: query,
+ binds: bindValues,
});
+ results.push({ query, result: result.rows });
}
- }
-
- async function executeQueriesSequentially() {
- try {
- if (useTransaction) {
- await new Promise<void>((resolveBegin, rejectBegin) => {
- connection.execute({
- sqlText: 'BEGIN',
- complete: (err: SnowflakeError | undefined) => {
- if (err) rejectBegin(err);
- else resolveBegin();
- },
- });
- });
- }
- for (const sqlText of sqlTexts) {
- const result = await new Promise<QueryResult>(
- (resolveQuery, rejectQuery) => {
- connection.execute({
- sqlText: sqlText as string,
- binds: binds as snowflake.Binds,
- complete: (
- err: SnowflakeError | undefined,
- stmt: RowStatement,
- rows: QueryResult
- ) => {
- if (err) {
- rejectQuery(err);
- return;
- }
- resolveQuery(rows);
- },
- });
- }
- );
-
- queryResults.push({
- query: sqlText as string,
- result,
- });
- }
-
- if (useTransaction) {
- await new Promise<void>((resolveCommit, rejectCommit) => {
- connection.execute({
- sqlText: 'COMMIT',
- complete: (err: SnowflakeError | undefined) => {
- if (err) rejectCommit(err);
- else resolveCommit();
- },
- });
- });
- }
-
- connection.destroy((err: SnowflakeError | undefined) => {
- if (err) {
- reject(err);
- return;
- }
- resolve(queryResults);
- });
- } catch (err) {
- handleError(err as SnowflakeError); // Reject with the original error!
+ if (useTransaction) await session.query({ sql: 'COMMIT' });
+ } catch (error) {
+ if (useTransaction) {
+ await session.query({ sql: 'ROLLBACK' }).catch(() => undefined);
}
+ throw error;
}
-
- executeQueriesSequentially();
- });
+ return results;
+ },
});
},
});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/run-query.ts b/packages/pieces/community/snowflake/src/lib/actions/run-query.ts
index ce3b29ab769..df13288b7ff 100644
--- a/packages/pieces/community/snowflake/src/lib/actions/run-query.ts
+++ b/packages/pieces/community/snowflake/src/lib/actions/run-query.ts
@@ -1,28 +1,28 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import snowflake from 'snowflake-sdk';
import { snowflakeAuth } from '../auth';
import {
- configureConnection,
- connect,
- execute,
- destroy,
- SnowflakeAuthValue,
+ DEFAULT_APPLICATION_NAME,
+ toAuthValue,
+ withSnowflake,
} from '../common';
+import { rawRowsOutputSchema } from '../common/output-schemas';
+import { toBind } from '../common/sql';
-const DEFAULT_APPLICATION_NAME = 'ActivePieces';
const DEFAULT_QUERY_TIMEOUT = 30000;
export const runQuery = createAction({
name: 'runQuery',
+ classification: 'WRITE',
displayName: 'Run Query',
description:
'Execute a SQL query against your Snowflake database and return the results as rows.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
- 'Runs an arbitrary SQL statement against Snowflake (SELECT, DML, or DDL). Use this for any query the dedicated row/table actions do not cover, or when you need full SQL control. Pass dynamic values via the parameters array bound to `:1`/`?` placeholders rather than concatenating into the SQL. Idempotency depends on the statement: a SELECT is safe to repeat, but an INSERT/UPDATE/DELETE mutates state on each call.',
+ 'Runs one arbitrary SQL statement (SELECT, DML or DDL) and returns all result rows. Human-only escape hatch; agents should use Run Select Query for reads and the dedicated row actions for writes. Re-running repeats any change the statement makes.',
idempotent: false,
},
+ outputSchema: rawRowsOutputSchema,
auth: snowflakeAuth,
props: {
sqlText: Property.LongText({
@@ -40,7 +40,7 @@ export const runQuery = createAction({
timeout: Property.Number({
displayName: 'Query Timeout (ms)',
description:
- 'Maximum time in milliseconds to wait for the query to complete before cancelling it. Defaults to 30 000 ms (30 seconds).',
+ 'Maximum time in milliseconds the query may run before Snowflake cancels it (applied as STATEMENT_TIMEOUT_IN_SECONDS, capped at 540 seconds). Defaults to 30 000 ms (30 seconds).',
required: false,
defaultValue: DEFAULT_QUERY_TIMEOUT,
}),
@@ -53,19 +53,14 @@ export const runQuery = createAction({
}),
},
async run(context) {
- const connection = configureConnection(
- context.auth as SnowflakeAuthValue,
- context.propsValue.application,
- context.propsValue.timeout
- );
-
- const { sqlText, binds } = context.propsValue;
-
- await connect(connection);
- try {
- return await execute(connection, sqlText, binds as snowflake.Binds);
- } finally {
- await destroy(connection);
- }
+ const { sqlText, binds, timeout, application } = context.propsValue;
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ application: application || DEFAULT_APPLICATION_NAME,
+ statementTimeoutSeconds: (timeout ?? DEFAULT_QUERY_TIMEOUT) / 1000,
+ fn: (session) =>
+ session.query({ sql: sqlText, binds: (binds ?? []).map(toBind) }),
+ });
+ return result.rows;
},
});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/search-rows.ts b/packages/pieces/community/snowflake/src/lib/actions/search-rows.ts
index 1fefb8607ec..53aeecf02ed 100644
--- a/packages/pieces/community/snowflake/src/lib/actions/search-rows.ts
+++ b/packages/pieces/community/snowflake/src/lib/actions/search-rows.ts
@@ -1,25 +1,22 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { snowflakeAuth } from '../auth';
-import {
- configureConnection,
- connect,
- destroy,
- execute,
- snowflakeCommonProps,
- SnowflakeAuthValue,
-} from '../common';
+import { snowflakeCommonProps, toAuthValue, withSnowflake } from '../common';
+import { rawRowsOutputSchema } from '../common/output-schemas';
+import { boundedInteger, qualifiedName } from '../common/sql';
export const searchRowsAction = createAction({
name: 'search_rows',
+ classification: 'SEARCH',
displayName: 'Search Rows',
description:
'Search for rows in a Snowflake table using an optional WHERE condition, ordering, and row limit.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
- 'Returns rows from a Snowflake table with an optional WHERE filter, ORDER BY sort, and row limit (default 100); leaving the filter empty returns all rows up to the limit. Use to retrieve a filtered or sorted set of records; for a single row by key use Get Row by ID. The filter and sort clauses are embedded directly into SQL, so pass only trusted values. Read-only and idempotent.',
+ 'Returns rows matching a hand-written WHERE and ORDER BY on a table picked from dropdowns. Human-only; agents use Find Rows with structured filters. Read-only.',
idempotent: true,
},
+ outputSchema: rawRowsOutputSchema,
auth: snowflakeAuth,
props: {
database: snowflakeCommonProps.database,
@@ -42,26 +39,34 @@ export const searchRowsAction = createAction({
}),
limit: Property.Number({
displayName: 'Row Limit',
- description: 'Maximum number of rows to return. Defaults to 100.',
+ description:
+ 'Maximum number of rows to return (1–10 000). Defaults to 100.',
required: false,
defaultValue: 100,
}),
},
async run(context) {
const { table, where_clause, order_by, limit } = context.propsValue;
-
- let sql = `SELECT * FROM ${table}`;
- if (where_clause) sql += ` WHERE ${where_clause}`;
- if (order_by) sql += ` ORDER BY ${order_by}`;
- sql += ` LIMIT ${Math.trunc(limit ?? 100)}`;
-
- const connection = configureConnection(context.auth as SnowflakeAuthValue);
- await connect(connection);
- try {
- const result = await execute(connection, sql, []);
- return result ?? [];
- } finally {
- await destroy(connection);
- }
+ const rowLimit = boundedInteger({
+ value:
+ limit === undefined || limit === null ? undefined : Math.trunc(limit),
+ defaultValue: 100,
+ min: 1,
+ max: 10000,
+ label: 'Row Limit',
+ });
+ let sql = `SELECT * FROM ${qualifiedName({
+ value: table,
+ label: 'Table',
+ })}`;
+ if (where_clause && where_clause.trim() !== '')
+ sql += ` WHERE ${where_clause}`;
+ if (order_by && order_by.trim() !== '') sql += ` ORDER BY ${order_by}`;
+ sql += ` LIMIT ${rowLimit}`;
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql, maxRows: rowLimit }),
+ });
+ return result.rows;
},
});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/update-row.ts b/packages/pieces/community/snowflake/src/lib/actions/update-row.ts
index e44ab0cd35b..0a55a962a4d 100644
--- a/packages/pieces/community/snowflake/src/lib/actions/update-row.ts
+++ b/packages/pieces/community/snowflake/src/lib/actions/update-row.ts
@@ -1,25 +1,23 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { snowflakeAuth } from '../auth';
-import {
- configureConnection,
- connect,
- destroy,
- execute,
- snowflakeCommonProps,
- SnowflakeAuthValue,
-} from '../common';
+import { snowflakeCommonProps, toAuthValue, withSnowflake } from '../common';
+import { buildSetClause, dmlCount } from '../common/operations';
+import { legacyUpdateOutputSchema } from '../common/output-schemas';
+import { qualifiedName } from '../common/sql';
export const updateRowAction = createAction({
name: 'update_row',
+ classification: 'WRITE',
displayName: 'Update Row',
description:
'Update one or more rows in a Snowflake table that match a WHERE condition.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
- 'Runs an UPDATE on a Snowflake table, setting the provided column values on every row matching the given WHERE condition; leaving the condition empty updates ALL rows. Use to modify existing records in place. Repeating the same call generally yields the same final state (it sets values rather than incrementing), but it is a mutating write and the WHERE clause is embedded directly into SQL, so supply only trusted values there.',
- idempotent: false,
+ 'Runs an UPDATE with a hand-written WHERE condition on a table picked from dropdowns. Human-only; agents use Update Row by Key or Update Rows by Filter. Setting the same values again leaves the rows unchanged.',
+ idempotent: true,
},
+ outputSchema: legacyUpdateOutputSchema,
auth: snowflakeAuth,
props: {
database: snowflakeCommonProps.database,
@@ -30,43 +28,48 @@ export const updateRowAction = createAction({
displayName: 'WHERE Condition',
description:
"A SQL condition to filter which rows to update (e.g. `id = 42` or `status = 'active'`). " +
- 'Leave empty to update ALL rows in the table (use with caution). ' +
+ 'To update every row, leave this empty and turn on **Update All Rows**. ' +
'**Security note:** this value is embedded directly in SQL. Only use static values or data from trusted, internal steps — never pass unvalidated end-user input here.',
required: false,
}),
+ update_all_rows: Property.Checkbox({
+ displayName: 'Update All Rows',
+ description:
+ 'Confirm that an empty WHERE condition should update every row in the table.',
+ required: false,
+ defaultValue: false,
+ }),
},
async run(context) {
- const {
- table,
- table_update_values: columnValues,
- where_clause,
- } = context.propsValue;
-
- const setEntries = Object.entries(columnValues).filter(
- ([, v]) => v !== null && v !== undefined && v !== ''
+ const { table, table_update_values, where_clause, update_all_rows } =
+ context.propsValue;
+ const values = Object.fromEntries(
+ Object.entries(table_update_values).filter(
+ ([, value]) => value !== null && value !== undefined && value !== ''
+ )
);
-
- if (setEntries.length === 0) {
+ if (Object.keys(values).length === 0) {
throw new Error('At least one column value must be provided to update.');
}
-
- const setClauses = setEntries.map(([col]) => `${col} = ?`).join(', ');
- const binds = setEntries.map(([, v]) => v) as string[];
-
- const sql = where_clause
- ? `UPDATE ${table} SET ${setClauses} WHERE ${where_clause}`
- : `UPDATE ${table} SET ${setClauses}`;
-
- const connection = configureConnection(context.auth as SnowflakeAuthValue);
- await connect(connection);
- try {
- const result = await execute(connection, sql, binds);
- return {
- success: true,
- rows_updated: result?.[0]?.['number of rows updated'] ?? null,
- };
- } finally {
- await destroy(connection);
+ const where = (where_clause ?? '').trim();
+ if (where === '' && !update_all_rows) {
+ throw new Error(
+ 'The WHERE condition is empty, which would update every row. Add a condition, or turn on "Update All Rows" if that is intended.'
+ );
}
+ const set = buildSetClause(values);
+ const target = qualifiedName({ value: table, label: 'Table' });
+ const sql =
+ where === ''
+ ? `UPDATE ${target} SET ${set.clause}`
+ : `UPDATE ${target} SET ${set.clause} WHERE ${where}`;
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql, binds: set.binds }),
+ });
+ return {
+ success: true,
+ rows_updated: dmlCount({ result, key: 'number of rows updated' }),
+ };
},
});
diff --git a/packages/pieces/community/snowflake/src/lib/actions/upsert-row.ts b/packages/pieces/community/snowflake/src/lib/actions/upsert-row.ts
index 901c383bca3..e371c8a081b 100644
--- a/packages/pieces/community/snowflake/src/lib/actions/upsert-row.ts
+++ b/packages/pieces/community/snowflake/src/lib/actions/upsert-row.ts
@@ -1,26 +1,28 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { snowflakeAuth } from '../auth';
import {
- configureConnection,
- connect,
- destroy,
- execute,
getTableColumnOptions,
snowflakeCommonProps,
- SnowflakeAuthValue,
+ toAuthValue,
+ withSnowflake,
} from '../common';
+import { buildMerge } from '../common/merge';
+import { dmlCount } from '../common/operations';
+import { legacyUpsertOutputSchema } from '../common/output-schemas';
export const upsertRowAction = createAction({
name: 'upsert_row',
+ classification: 'WRITE',
displayName: 'Upsert Row',
description:
'Insert a new row or update an existing one if a row with the same match column value already exists (MERGE INTO).',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
- 'Inserts a row into a Snowflake table, or updates the existing row when one already matches on the chosen match column, via MERGE INTO. Use when you want create-or-update semantics keyed on a stable identifier instead of separate insert/update logic. The match column must be among the supplied column values, and at least one other column is required. Idempotent when the match column is a stable unique key: repeating the call converges to the same row state.',
+ 'MERGE-based create-or-update on a table and match column picked from dropdowns. Human-only; agents use Upsert Row by Key. Repeating the call with the same values converges to the same row.',
idempotent: true,
},
+ outputSchema: legacyUpsertOutputSchema,
auth: snowflakeAuth,
props: {
database: snowflakeCommonProps.database,
@@ -48,71 +50,39 @@ export const upsertRowAction = createAction({
placeholder: 'Please select a table first',
};
}
- return getTableColumnOptions(
- auth as SnowflakeAuthValue,
- table as string
- );
+ return getTableColumnOptions({
+ auth: toAuthValue(auth),
+ table: String(table),
+ });
},
}),
table_column_values: snowflakeCommonProps.table_column_values,
},
async run(context) {
- const {
- table,
- match_column,
- table_column_values: columnValues,
- } = context.propsValue;
-
- const columns = Object.keys(columnValues);
- if (columns.length === 0) {
+ const { table, match_column, table_column_values } = context.propsValue;
+ const values = Object.fromEntries(Object.entries(table_column_values));
+ if (Object.keys(values).length === 0) {
throw new Error('At least one column value must be provided.');
}
-
- if (!columns.includes(match_column)) {
+ if (!(match_column in values)) {
throw new Error(
`Match column "${match_column}" must be included in the column values. ` +
`Please add a value for "${match_column}" in the columns to upsert.`
);
}
-
- // Build MERGE INTO statement
- // source: SELECT ? AS col1, ? AS col2, ...
- const sourceSelects = columns.map((col) => `? AS ${col}`).join(', ');
- const updateEntries = columns.filter((col) => col !== match_column);
- if (updateEntries.length === 0) {
- throw new Error(
- 'At least one column other than the match column must be provided to update.'
- );
- }
- const updateSets = updateEntries
- .map((col) => `target.${col} = source.${col}`)
- .join(', ');
- const insertCols = columns.join(', ');
- const insertVals = columns.map((col) => `source.${col}`).join(', ');
-
- const sql = `
-MERGE INTO ${table} AS target
-USING (SELECT ${sourceSelects}) AS source
-ON target.${match_column} = source.${match_column}
-WHEN MATCHED THEN
- UPDATE SET ${updateSets}
-WHEN NOT MATCHED THEN
- INSERT (${insertCols}) VALUES (${insertVals})
- `.trim();
-
- const binds = Object.values(columnValues) as string[];
-
- const connection = configureConnection(context.auth as SnowflakeAuthValue);
- await connect(connection);
- try {
- const result = await execute(connection, sql, binds);
- return {
- success: true,
- rows_inserted: result?.[0]?.['number of rows inserted'] ?? null,
- rows_updated: result?.[0]?.['number of rows updated'] ?? null,
- };
- } finally {
- await destroy(connection);
- }
+ const { sql, binds } = buildMerge({
+ table,
+ keyColumns: [match_column],
+ values,
+ });
+ const result = await withSnowflake({
+ auth: toAuthValue(context.auth),
+ fn: (session) => session.query({ sql, binds }),
+ });
+ return {
+ success: true,
+ rows_inserted: dmlCount({ result, key: 'number of rows inserted' }),
+ rows_updated: dmlCount({ result, key: 'number of rows updated' }),
+ };
},
});
diff --git a/packages/pieces/community/snowflake/src/lib/auth.ts b/packages/pieces/community/snowflake/src/lib/auth.ts
index f541125f8ff..a047770407f 100644
--- a/packages/pieces/community/snowflake/src/lib/auth.ts
+++ b/packages/pieces/community/snowflake/src/lib/auth.ts
@@ -2,37 +2,16 @@ import {
PieceAuth,
Property,
OAuth2AuthorizationMethod,
+ AppConnectionType,
} from '@activepieces/pieces-framework';
-import snowflake from 'snowflake-sdk';
-
-// Suppress the SDK's verbose INFO/DEBUG logs so they don't corrupt stdout IPC
-snowflake.configure({ logLevel: 'ERROR' } as Parameters<
- typeof snowflake.configure
->[0]);
-
-function formatPrivateKey(privateKey: string): string {
- const lines = privateKey
- .replace('-----BEGIN PRIVATE KEY-----', '')
- .replace('-----END PRIVATE KEY-----', '')
- .trim()
- .split(' ');
- return [
- '-----BEGIN PRIVATE KEY-----',
- ...lines,
- '-----END PRIVATE KEY-----',
- ].join('\n');
-}
-
-function connectAsync(conn: snowflake.Connection): Promise<void> {
- return new Promise((resolve, reject) =>
- conn.connect((err) => (err ? reject(err) : resolve()))
- );
-}
+import {
+ buildConnectionOptions,
+ buildCustomAuthOptions,
+ withConnectionOptions,
+} from './common/client';
-function destroyAsync(conn: snowflake.Connection): Promise<void> {
- return new Promise((resolve, reject) =>
- conn.destroy((err) => (err ? reject(err) : resolve()))
- );
+function optionalString(value: unknown): string | undefined {
+ return typeof value === 'string' && value.trim() !== '' ? value : undefined;
}
export const snowflakeOAuth2Auth = PieceAuth.OAuth2({
@@ -120,17 +99,22 @@ Enter the **Client ID** and **Client Secret** in the Activepieces OAuth2 setting
},
validate: async ({ auth }) => {
try {
- const conn = snowflake.createConnection({
- account: auth.props!['account'] as string,
- authenticator: 'OAUTH',
- token: auth.access_token,
- database: auth.props!['database'] as string | undefined,
- warehouse: auth.props!['warehouse'] as string | undefined,
- role: auth.props!['role'] as string | undefined,
- application: 'ActivePieces',
+ await withConnectionOptions({
+ options: buildConnectionOptions({
+ auth: {
+ type: AppConnectionType.OAUTH2,
+ access_token: auth.access_token,
+ props: {
+ account: String(auth.props?.['account'] ?? ''),
+ database: optionalString(auth.props?.['database']),
+ warehouse: optionalString(auth.props?.['warehouse']),
+ role: optionalString(auth.props?.['role']),
+ },
+ },
+ }),
+ statementTimeoutSeconds: 60,
+ fn: (session) => session.query({ sql: 'SELECT CURRENT_USER()' }),
});
- await connectAsync(conn);
- await destroyAsync(conn);
return { valid: true };
} catch (e) {
return { valid: false, error: (e as Error).message };
@@ -177,7 +161,7 @@ ALTER USER <your_username>
SET RSA_PUBLIC_KEY='<contents of rsa_key.pub, excluding the BEGIN/END lines>';
\`\`\`
-**3. Paste the private key** — copy the full contents of \`rsa_key.p8\` (including the \`-----BEGIN PRIVATE KEY-----\` header and footer) into the **Private Key** field below.`,
+**3. Paste the private key** — copy the full contents of \`rsa_key.p8\` (including the \`-----BEGIN PRIVATE KEY-----\` or \`-----BEGIN ENCRYPTED PRIVATE KEY-----\` header and footer) into the **Private Key** field below. Line breaks may be pasted as spaces.`,
props: {
account: Property.ShortText({
displayName: 'Account Identifier',
@@ -237,26 +221,11 @@ ALTER USER <your_username>
};
}
try {
- const connectionOptions: snowflake.ConnectionOptions = {
- account: auth.account,
- username: auth.username,
- database: auth.database,
- warehouse: auth.warehouse,
- role: auth.role,
- application: 'ActivePieces',
- };
- if (auth.privateKey) {
- connectionOptions.authenticator = 'SNOWFLAKE_JWT';
- connectionOptions.privateKey = formatPrivateKey(auth.privateKey);
- if (auth.privateKeyPassphrase) {
- connectionOptions.privateKeyPass = auth.privateKeyPassphrase;
- }
- } else {
- connectionOptions.password = auth.password;
- }
- const conn = snowflake.createConnection(connectionOptions);
- await connectAsync(conn);
- await destroyAsync(conn);
+ await withConnectionOptions({
+ options: buildCustomAuthOptions({ props: auth }),
+ statementTimeoutSeconds: 60,
+ fn: (session) => session.query({ sql: 'SELECT CURRENT_USER()' }),
+ });
return { valid: true };
} catch (e) {
return { valid: false, error: (e as Error).message };
diff --git a/packages/pieces/community/snowflake/src/lib/common/ai-props.ts b/packages/pieces/community/snowflake/src/lib/common/ai-props.ts
new file mode 100644
index 00000000000..98388cf186e
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/common/ai-props.ts
@@ -0,0 +1,78 @@
+import { Property } from '@activepieces/pieces-framework';
+import { FILTER_OPERATORS } from './sql';
+
+export const aiProps = {
+ table: (description?: string) =>
+ Property.ShortText({
+ displayName: 'Table',
+ description:
+ description ??
+ 'Table name, optionally qualified as DATABASE.SCHEMA.TABLE (e.g. `ANALYTICS.PUBLIC.ORDERS`). An unqualified name uses the connection default database and schema. Unquoted names are case-insensitive; wrap a name in double quotes for exact case.',
+ required: true,
+ }),
+ database: (required: boolean) =>
+ Property.ShortText({
+ displayName: 'Database',
+ description: required
+ ? 'Database name, as returned by List Databases.'
+ : 'Database name, as returned by List Databases. Leave empty to use the connection default.',
+ required,
+ }),
+ schema: (required: boolean) =>
+ Property.ShortText({
+ displayName: 'Schema',
+ description: required
+ ? 'Schema name, optionally qualified as DATABASE.SCHEMA (e.g. `ANALYTICS.PUBLIC`).'
+ : 'Schema name, optionally qualified as DATABASE.SCHEMA (e.g. `ANALYTICS.PUBLIC`). Leave empty to use the connection default.',
+ required,
+ }),
+ namePattern: Property.ShortText({
+ displayName: 'Name Pattern',
+ description:
+ 'Optional case-insensitive SQL LIKE pattern on the name, e.g. `%ORDER%`. Leave empty to list all.',
+ required: false,
+ }),
+ limit: (defaultValue: number, max: number) =>
+ Property.Number({
+ displayName: 'Limit',
+ description: `Maximum number of items to return (1–${max}). Defaults to ${defaultValue}.`,
+ required: false,
+ defaultValue,
+ }),
+ filters: (required: boolean) =>
+ Property.Array({
+ displayName: 'Filters',
+ description: `Conditions combined with AND. Each has a column, an operator (${FILTER_OPERATORS.join(
+ ', '
+ )}) and a value. For IN / NOT IN pass a list or comma-separated values; IS NULL / IS NOT NULL take no value.${
+ required ? ' At least one filter is required.' : ''
+ }`,
+ required,
+ properties: {
+ column: Property.ShortText({ displayName: 'Column', required: true }),
+ operator: Property.StaticDropdown({
+ displayName: 'Operator',
+ required: true,
+ defaultValue: '=',
+ options: {
+ options: FILTER_OPERATORS.map((operator) => ({
+ label: operator,
+ value: operator,
+ })),
+ },
+ }),
+ value: Property.ShortText({ displayName: 'Value', required: false }),
+ },
+ }),
+ values: (displayName: string, description: string) =>
+ Property.Json({
+ displayName,
+ description,
+ required: true,
+ }),
+};
+
+export const READ_DEFAULT_LIMIT = 100;
+export const READ_MAX_LIMIT = 1000;
+export const WRITE_GUARD_DEFAULT = 100;
+export const WRITE_GUARD_MAX = 10000;
diff --git a/packages/pieces/community/snowflake/src/lib/common/client.ts b/packages/pieces/community/snowflake/src/lib/common/client.ts
new file mode 100644
index 00000000000..e5d62768caa
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/common/client.ts
@@ -0,0 +1,302 @@
+import type {
+ Bind,
+ Connection,
+ ConnectionOptions,
+ RowStatement,
+ FileAndStageBindStatement,
+ SnowflakeError,
+} from 'snowflake-sdk';
+import { AppConnectionType } from '@activepieces/pieces-framework';
+import { loadSnowflakeSdk } from './sdk';
+import { normalizePrivateKey } from './private-key';
+
+export function buildConnectionOptions({
+ auth,
+ application = DEFAULT_APPLICATION_NAME,
+}: {
+ auth: SnowflakeAuthValue;
+ application?: string;
+}): ConnectionOptions {
+ if (auth.type === AppConnectionType.OAUTH2) {
+ return {
+ account: auth.props.account.trim(),
+ authenticator: 'OAUTH',
+ token: auth.access_token,
+ database: emptyToUndefined(auth.props.database),
+ warehouse: emptyToUndefined(auth.props.warehouse),
+ role: emptyToUndefined(auth.props.role),
+ application,
+ };
+ }
+ return buildCustomAuthOptions({ props: auth.props, application });
+}
+
+export function buildCustomAuthOptions({
+ props,
+ application = DEFAULT_APPLICATION_NAME,
+}: {
+ props: CustomAuthProps;
+ application?: string;
+}): ConnectionOptions {
+ const options: ConnectionOptions = {
+ account: props.account.trim(),
+ username: props.username.trim(),
+ database: emptyToUndefined(props.database),
+ warehouse: emptyToUndefined(props.warehouse),
+ role: emptyToUndefined(props.role),
+ application,
+ };
+ if (props.privateKey && props.privateKey.trim() !== '') {
+ options.authenticator = 'SNOWFLAKE_JWT';
+ options.privateKey = normalizePrivateKey(props.privateKey);
+ if (props.privateKeyPassphrase) {
+ options.privateKeyPass = props.privateKeyPassphrase;
+ }
+ } else {
+ options.password = props.password;
+ }
+ return options;
+}
+
+export async function withSnowflake<T>({
+ auth,
+ application,
+ statementTimeoutSeconds = MAX_STATEMENT_TIMEOUT_SECONDS,
+ fn,
+}: {
+ auth: SnowflakeAuthValue;
+ application?: string;
+ statementTimeoutSeconds?: number;
+ fn: (session: SnowflakeSession) => Promise<T>;
+}): Promise<T> {
+ return withConnectionOptions({
+ options: buildConnectionOptions({ auth, application }),
+ statementTimeoutSeconds,
+ fn,
+ });
+}
+
+export async function withConnectionOptions<T>({
+ options,
+ statementTimeoutSeconds = MAX_STATEMENT_TIMEOUT_SECONDS,
+ fn,
+}: {
+ options: ConnectionOptions;
+ statementTimeoutSeconds?: number;
+ fn: (session: SnowflakeSession) => Promise<T>;
+}): Promise<T> {
+ const sdk = await loadSnowflakeSdk();
+ const connection = sdk.createConnection(options);
+ try {
+ await connectAsync(connection);
+ } catch (error) {
+ throw friendlyConnectionError(error);
+ }
+ try {
+ const session = createSession(connection);
+ const timeout = clampTimeout(statementTimeoutSeconds);
+ await session.query({
+ sql: `ALTER SESSION SET STATEMENT_TIMEOUT_IN_SECONDS = ${timeout}`,
+ });
+ return await fn(session);
+ } finally {
+ await destroyAsync(connection).catch(() => undefined);
+ }
+}
+
+export function clampTimeout(seconds: number | undefined | null): number {
+ const value = Number(seconds);
+ if (!Number.isFinite(value) || value <= 0) {
+ return MAX_STATEMENT_TIMEOUT_SECONDS;
+ }
+ return Math.min(Math.ceil(value), MAX_STATEMENT_TIMEOUT_SECONDS);
+}
+
+export function friendlyConnectionError(error: unknown): Error {
+ const code = errorCode(error);
+ const original = error instanceof Error ? error.message : String(error);
+ const hint = code ? CONNECTION_ERROR_HINTS[code] : undefined;
+ if (hint) {
+ return new Error(`${hint} (Snowflake: ${original})`);
+ }
+ return error instanceof Error ? error : new Error(original);
+}
+
+function createSession(connection: Connection): SnowflakeSession {
+ return {
+ query: ({ sql, binds, maxRows }) =>
+ runStatement({ connection, sql, binds, maxRows }),
+ getQueryStatus: (queryId) => connection.getQueryStatus(queryId),
+ };
+}
+
+function runStatement({
+ connection,
+ sql,
+ binds,
+ maxRows,
+}: {
+ connection: Connection;
+ sql: string;
+ binds?: Bind[];
+ maxRows?: number;
+}): Promise<QueryResult> {
+ return new Promise<QueryResult>((resolve, reject) => {
+ connection.execute({
+ sqlText: sql,
+ binds: binds && binds.length > 0 ? binds : undefined,
+ streamResult: true,
+ complete: (
+ error: SnowflakeError | undefined,
+ statement: RowStatement | FileAndStageBindStatement
+ ) => {
+ if (error) {
+ reject(error);
+ return;
+ }
+ const total = statement.getNumRows() ?? 0;
+ const queryId = readQueryId(statement);
+ const columns = (statement.getColumns() ?? []).map((column) =>
+ column.getName()
+ );
+ const limit =
+ maxRows === undefined ? total : Math.min(total, Math.max(0, maxRows));
+ if (limit === 0) {
+ resolve({
+ rows: [],
+ columns,
+ totalRows: total,
+ truncated: total > 0,
+ queryId,
+ });
+ return;
+ }
+ const rows: Record<string, unknown>[] = [];
+ statement
+ .streamRows({ start: 0, end: limit - 1 })
+ .on('error', reject)
+ .on('data', (row: Record<string, unknown>) => {
+ rows.push(row);
+ })
+ .on('end', () =>
+ resolve({
+ rows,
+ columns,
+ totalRows: total,
+ truncated: total > rows.length,
+ queryId,
+ })
+ );
+ },
+ });
+ });
+}
+
+function readQueryId(
+ statement: RowStatement | FileAndStageBindStatement
+): string | null {
+ try {
+ return statement.getQueryId() ?? null;
+ } catch {
+ return null;
+ }
+}
+
+function connectAsync(connection: Connection): Promise<void> {
+ return new Promise((resolve, reject) =>
+ connection.connect((error) => (error ? reject(error) : resolve()))
+ );
+}
+
+function destroyAsync(connection: Connection): Promise<void> {
+ return new Promise((resolve, reject) =>
+ connection.destroy((error) => (error ? reject(error) : resolve()))
+ );
+}
+
+function errorCode(error: unknown): string | undefined {
+ if (typeof error === 'object' && error !== null && 'code' in error) {
+ const code = error.code;
+ if (typeof code === 'string' || typeof code === 'number') {
+ return String(code);
+ }
+ }
+ return undefined;
+}
+
+function emptyToUndefined(value: string | undefined): string | undefined {
+ if (value === undefined || value === null) return undefined;
+ const trimmed = value.trim();
+ return trimmed === '' ? undefined : trimmed;
+}
+
+export const DEFAULT_APPLICATION_NAME = 'ActivePieces';
+export const MAX_STATEMENT_TIMEOUT_SECONDS = 540;
+
+const ACCOUNT_IDENTIFIER_HINT =
+ 'Could not reach the Snowflake account. The Account Identifier looks wrong: use the orgname-accountname form (Snowflake console > your profile > Account > View account details), or a legacy locator with its region such as xy12345.us-east-2.aws.';
+
+const CONNECTION_ERROR_HINTS: Record<string, string> = {
+ '390100':
+ 'Snowflake rejected the username or password. Check the credentials in your connection.',
+ '390144':
+ 'Snowflake rejected the key-pair login. Check that the private key matches the public key registered on the user (ALTER USER ... SET RSA_PUBLIC_KEY) and that the passphrase is correct.',
+ '390318':
+ 'The Snowflake OAuth access token has expired. Reconnect the OAuth connection.',
+ '390303':
+ 'The Snowflake OAuth access token is invalid. Reconnect the OAuth connection.',
+ '390422':
+ 'Snowflake blocked this login because of a network policy on the account or user. Allow Activepieces IP addresses in the network policy.',
+ '250001':
+ 'Could not connect to Snowflake. Check the Account Identifier (for example orgname-accountname) in your connection.',
+ '401001': ACCOUNT_IDENTIFIER_HINT,
+ '401002': ACCOUNT_IDENTIFIER_HINT,
+ '390189':
+ 'The role in your connection is not granted to this user. Leave Default Role empty or pick a granted role.',
+ '390201':
+ 'The default database or warehouse in your connection does not exist or is not authorized for this role.',
+};
+
+export type CustomAuthProps = {
+ account: string;
+ username: string;
+ password?: string;
+ privateKey?: string;
+ privateKeyPassphrase?: string;
+ database?: string;
+ role?: string;
+ warehouse?: string;
+};
+
+export type SnowflakeAuthValue =
+ | {
+ type: AppConnectionType.OAUTH2;
+ access_token: string;
+ props: {
+ account: string;
+ database?: string;
+ warehouse?: string;
+ role?: string;
+ };
+ }
+ | {
+ type: AppConnectionType.CUSTOM_AUTH;
+ props: CustomAuthProps;
+ };
+
+export type QueryResult = {
+ rows: Record<string, unknown>[];
+ columns: string[];
+ totalRows: number;
+ truncated: boolean;
+ queryId: string | null;
+};
+
+export type SnowflakeSession = {
+ query: (params: {
+ sql: string;
+ binds?: Bind[];
+ maxRows?: number;
+ }) => Promise<QueryResult>;
+ getQueryStatus: (queryId: string) => Promise<string>;
+};
diff --git a/packages/pieces/community/snowflake/src/lib/common/columns.ts b/packages/pieces/community/snowflake/src/lib/common/columns.ts
new file mode 100644
index 00000000000..a1f2ce4da72
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/common/columns.ts
@@ -0,0 +1,19 @@
+export function columnsQueryResult({
+ rows,
+ max,
+}: {
+ rows: Record<string, unknown>[];
+ max: number;
+}) {
+ const items = rows.slice(0, max).map((row) => ({
+ table_schema: row['TABLE_SCHEMA'] ?? null,
+ table_name: row['TABLE_NAME'] ?? null,
+ column_name: row['COLUMN_NAME'] ?? null,
+ ordinal_position: row['ORDINAL_POSITION'] ?? null,
+ data_type: row['DATA_TYPE'] ?? null,
+ is_nullable: row['IS_NULLABLE'] ?? null,
+ column_default: row['COLUMN_DEFAULT'] ?? null,
+ comment: row['COMMENT'] ?? null,
+ }));
+ return { items, count: items.length, truncated: rows.length > max };
+}
diff --git a/packages/pieces/community/snowflake/src/lib/common/index.ts b/packages/pieces/community/snowflake/src/lib/common/index.ts
index 928f5ec3440..02534d18d48 100644
--- a/packages/pieces/community/snowflake/src/lib/common/index.ts
+++ b/packages/pieces/community/snowflake/src/lib/common/index.ts
@@ -1,150 +1,113 @@
import {
- DynamicPropsValue,
DropdownState,
+ DynamicPropsValue,
Property,
} from '@activepieces/pieces-framework';
-import { AppConnectionType } from '@activepieces/pieces-framework';
import { snowflakeAuth } from '../auth';
-import snowflake from 'snowflake-sdk';
+import { SnowflakeAuthValue, withSnowflake } from './client';
+import { qualifiedName } from './sql';
-const DEFAULT_APPLICATION_NAME = 'ActivePieces';
-const DEFAULT_QUERY_TIMEOUT = 30000;
-
-export type SnowflakeAuthValue =
- | {
- type: AppConnectionType.OAUTH2;
- access_token: string;
- props: {
- account: string;
- database?: string;
- warehouse?: string;
- role?: string;
- };
- }
- | {
- type: AppConnectionType.CUSTOM_AUTH;
- props: {
- account: string;
- username: string;
- password?: string;
- privateKey?: string;
- privateKeyPassphrase?: string;
- database?: string;
- role?: string;
- warehouse?: string;
- };
- };
+export * from './client';
-function formatPrivateKey(privateKey: string): string {
- const privateKeyLines = privateKey
- .replace('-----BEGIN PRIVATE KEY-----', '')
- .replace('-----END PRIVATE KEY-----', '')
- .trim()
- .split(' ');
+export function toAuthValue(auth: unknown): SnowflakeAuthValue {
+ if (isSnowflakeAuthValue(auth)) {
+ return auth;
+ }
+ throw new Error('Connect a Snowflake account to this step first.');
+}
- return [
- '-----BEGIN PRIVATE KEY-----',
- ...privateKeyLines,
- '-----END PRIVATE KEY-----',
- ].join('\n');
+function isSnowflakeAuthValue(auth: unknown): auth is SnowflakeAuthValue {
+ if (typeof auth !== 'object' || auth === null) return false;
+ if (!('type' in auth) || !('props' in auth)) return false;
+ const props = auth.props;
+ return (
+ typeof props === 'object' &&
+ props !== null &&
+ 'account' in props &&
+ typeof props.account === 'string'
+ );
}
-export function configureConnection(
- auth: SnowflakeAuthValue,
- application = DEFAULT_APPLICATION_NAME,
- timeout = DEFAULT_QUERY_TIMEOUT
-) {
- if (auth.type === AppConnectionType.OAUTH2) {
- return snowflake.createConnection({
- account: auth.props.account,
- authenticator: 'OAUTH',
- token: auth.access_token,
- database: auth.props.database,
- warehouse: auth.props.warehouse,
- role: auth.props.role,
- application,
- timeout,
+async function loadDropdown({
+ auth,
+ sql,
+ toOption,
+}: {
+ auth: unknown;
+ sql: string;
+ toOption: (row: Record<string, unknown>) => { label: string; value: string };
+}): Promise<DropdownState<string>> {
+ try {
+ const result = await withSnowflake({
+ auth: toAuthValue(auth),
+ statementTimeoutSeconds: 60,
+ fn: (session) => session.query({ sql, maxRows: 5000 }),
});
+ return { disabled: false, options: result.rows.map(toOption) };
+ } catch (error) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: `Could not load options: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ };
}
-
- const {
- account,
- username,
- password,
- privateKey,
- privateKeyPassphrase,
- database,
- role,
- warehouse,
- } = auth.props;
-
- const connectionOptions: snowflake.ConnectionOptions = {
- account,
- username,
- role,
- database,
- warehouse,
- application,
- timeout,
- };
-
- if (privateKey) {
- connectionOptions.privateKey = formatPrivateKey(privateKey);
- connectionOptions.authenticator = 'SNOWFLAKE_JWT';
- if (privateKeyPassphrase) {
- connectionOptions.privateKeyPass = privateKeyPassphrase;
- }
- } else {
- connectionOptions.password = password;
- }
-
- return snowflake.createConnection(connectionOptions);
}
-export async function connect(conn: snowflake.Connection) {
- return await new Promise<void>((resolve, reject) => {
- conn.connect((error) => {
- if (error) {
- reject(error);
- } else {
- resolve();
- }
- });
- });
+function nameOption(row: Record<string, unknown>) {
+ const name = String(row['name'] ?? '');
+ return { label: name, value: name };
}
-export async function destroy(conn: snowflake.Connection) {
- return await new Promise<void>((resolve, reject) => {
- conn.destroy((error) => {
- if (error) {
- reject(error);
- } else {
- resolve();
- }
- });
+export async function getTableColumnOptions({
+ auth,
+ table,
+}: {
+ auth: SnowflakeAuthValue;
+ table: string;
+}): Promise<DropdownState<string>> {
+ return loadDropdown({
+ auth,
+ sql: `DESCRIBE TABLE ${qualifiedName({ value: table, label: 'Table' })}`,
+ toOption: nameOption,
});
}
-export async function execute(
- conn: snowflake.Connection,
- sqlText: string,
- binds: snowflake.Binds
-) {
- return await new Promise<any[] | undefined>((resolve, reject) => {
- conn.execute({
- sqlText,
- binds,
- complete: (error, _, result) => {
- if (error) {
- reject(error);
- } else {
- resolve(result);
- }
- },
- });
+async function describeColumns({
+ auth,
+ table,
+}: {
+ auth: unknown;
+ table: unknown;
+}): Promise<DynamicPropsValue> {
+ if (!auth || typeof table !== 'string' || table === '') return {};
+ const result = await withSnowflake({
+ auth: toAuthValue(auth),
+ statementTimeoutSeconds: 60,
+ fn: (session) =>
+ session.query({
+ sql: `DESCRIBE TABLE ${qualifiedName({
+ value: table,
+ label: 'Table',
+ })}`,
+ }),
});
+ const fields: DynamicPropsValue = {};
+ for (const column of result.rows) {
+ const name = String(column['name'] ?? '');
+ if (name === '') continue;
+ fields[name] = Property.ShortText({ displayName: name, required: false });
+ }
+ return fields;
}
+const notConnected = {
+ disabled: true,
+ options: [],
+ placeholder: 'Please connect your account first',
+};
+
export const snowflakeCommonProps = {
database: Property.Dropdown({
auth: snowflakeAuth,
@@ -154,28 +117,12 @@ export const snowflakeCommonProps = {
refreshers: [],
required: true,
options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Please connect your account first',
- };
- }
-
- const connection = configureConnection(auth as SnowflakeAuthValue);
- await connect(connection);
- const response = await execute(connection, 'SHOW DATABASES', []);
- await destroy(connection);
-
- return {
- disabled: false,
- options: response
- ? response.map((db: Record<string, unknown>) => ({
- label: db['name'] as string,
- value: db['name'] as string,
- }))
- : [],
- };
+ if (!auth) return notConnected;
+ return loadDropdown({
+ auth,
+ sql: 'SHOW DATABASES',
+ toOption: nameOption,
+ });
},
}),
schema: Property.Dropdown({
@@ -186,13 +133,7 @@ export const snowflakeCommonProps = {
refreshers: ['database'],
required: true,
options: async ({ auth, database }) => {
- if (!auth) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Please connect your account first',
- };
- }
+ if (!auth) return notConnected;
if (!database) {
return {
disabled: true,
@@ -200,25 +141,15 @@ export const snowflakeCommonProps = {
placeholder: 'Please select a database first',
};
}
-
- const connection = configureConnection(auth as SnowflakeAuthValue);
- await connect(connection);
- const response = await execute(
- connection,
- `SHOW SCHEMAS IN DATABASE ${database}`,
- []
- );
- await destroy(connection);
-
- return {
- disabled: false,
- options: response
- ? response.map((schema: Record<string, unknown>) => ({
- label: schema['name'] as string,
- value: schema['name'] as string,
- }))
- : [],
- };
+ return loadDropdown({
+ auth,
+ sql: `SHOW SCHEMAS IN DATABASE ${qualifiedName({
+ value: String(database),
+ maxParts: 1,
+ label: 'Database',
+ })}`,
+ toOption: nameOption,
+ });
},
}),
table: Property.Dropdown({
@@ -228,13 +159,7 @@ export const snowflakeCommonProps = {
refreshers: ['database', 'schema'],
required: true,
options: async ({ auth, database, schema }) => {
- if (!auth) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Please connect your account first',
- };
- }
+ if (!auth) return notConnected;
if (!database) {
return {
disabled: true,
@@ -249,25 +174,18 @@ export const snowflakeCommonProps = {
placeholder: 'Please select a schema first',
};
}
-
- const connection = configureConnection(auth as SnowflakeAuthValue);
- await connect(connection);
- const response = await execute(
- connection,
- `SHOW TABLES IN SCHEMA ${database}.${schema}`,
- []
- );
- await destroy(connection);
-
- return {
- disabled: false,
- options: response
- ? response.map((table: Record<string, unknown>) => ({
- label: table['name'] as string,
- value: `${database}.${schema}.${table['name']}`,
- }))
- : [],
- };
+ return loadDropdown({
+ auth,
+ sql: `SHOW TABLES IN SCHEMA ${qualifiedName({
+ value: `${database}.${schema}`,
+ maxParts: 2,
+ label: 'Schema',
+ })}`,
+ toOption: (row) => {
+ const name = String(row['name'] ?? '');
+ return { label: name, value: `${database}.${schema}.${name}` };
+ },
+ });
},
}),
warehouse: Property.Dropdown({
@@ -278,28 +196,12 @@ export const snowflakeCommonProps = {
refreshers: [],
required: false,
options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Please connect your account first',
- };
- }
-
- const connection = configureConnection(auth as SnowflakeAuthValue);
- await connect(connection);
- const response = await execute(connection, 'SHOW WAREHOUSES', []);
- await destroy(connection);
-
- return {
- disabled: false,
- options: response
- ? response.map((wh: Record<string, unknown>) => ({
- label: wh['name'] as string,
- value: wh['name'] as string,
- }))
- : [],
- };
+ if (!auth) return notConnected;
+ return loadDropdown({
+ auth,
+ sql: 'SHOW WAREHOUSES',
+ toOption: nameOption,
+ });
},
}),
table_column_values: Property.DynamicProperties({
@@ -308,28 +210,7 @@ export const snowflakeCommonProps = {
description: 'Enter the value for each column in the new row.',
required: true,
refreshers: ['database', 'schema', 'table'],
- props: async ({ auth, table }) => {
- if (!auth) return {};
- if (!table) return {};
-
- const connection = configureConnection(auth as SnowflakeAuthValue);
- await connect(connection);
- const response = await execute(connection, `DESCRIBE TABLE ${table}`, []);
- await destroy(connection);
-
- const fields: DynamicPropsValue = {};
-
- if (response) {
- for (const column of response) {
- fields[column.name] = Property.ShortText({
- displayName: column.name,
- required: false,
- });
- }
- }
-
- return fields;
- },
+ props: async ({ auth, table }) => describeColumns({ auth, table }),
}),
table_update_values: Property.DynamicProperties({
auth: snowflakeAuth,
@@ -338,46 +219,6 @@ export const snowflakeCommonProps = {
'Only filled columns will be updated. Leave a column empty to keep its existing value.',
required: true,
refreshers: ['database', 'schema', 'table'],
- props: async ({ auth, table }) => {
- if (!auth) return {};
- if (!table) return {};
-
- const connection = configureConnection(auth as SnowflakeAuthValue);
- await connect(connection);
- const response = await execute(connection, `DESCRIBE TABLE ${table}`, []);
- await destroy(connection);
-
- const fields: DynamicPropsValue = {};
-
- if (response) {
- for (const column of response) {
- fields[column.name] = Property.ShortText({
- displayName: column.name,
- required: false,
- });
- }
- }
-
- return fields;
- },
+ props: async ({ auth, table }) => describeColumns({ auth, table }),
}),
};
-
-export async function getTableColumnOptions(
- auth: SnowflakeAuthValue,
- table: string
-): Promise<DropdownState<string>> {
- const connection = configureConnection(auth);
- await connect(connection);
- const response = await execute(connection, `DESCRIBE TABLE ${table}`, []);
- await destroy(connection);
- return {
- disabled: false,
- options: response
- ? (response as { name: string }[]).map((col) => ({
- label: col.name,
- value: col.name,
- }))
- : [],
- };
-}
diff --git a/packages/pieces/community/snowflake/src/lib/common/mappers.ts b/packages/pieces/community/snowflake/src/lib/common/mappers.ts
new file mode 100644
index 00000000000..6551e84f357
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/common/mappers.ts
@@ -0,0 +1,41 @@
+import { normaliseTimestamp } from './operations';
+
+export function mapTable(row: Record<string, unknown>) {
+ return {
+ table_name: row['name'] ?? null,
+ database_name: row['database_name'] ?? null,
+ schema_name: row['schema_name'] ?? null,
+ kind: row['kind'] ?? null,
+ rows: row['rows'] ?? null,
+ bytes: row['bytes'] ?? null,
+ owner: row['owner'] ?? null,
+ comment: row['comment'] ?? null,
+ created_on: normaliseTimestamp(row['created_on']),
+ };
+}
+
+export function mapView(row: Record<string, unknown>) {
+ return {
+ view_name: row['name'] ?? null,
+ database_name: row['database_name'] ?? null,
+ schema_name: row['schema_name'] ?? null,
+ owner: row['owner'] ?? null,
+ comment: row['comment'] ?? null,
+ text: row['text'] ?? null,
+ is_secure: row['is_secure'] ?? null,
+ is_materialized: row['is_materialized'] ?? null,
+ created_on: normaliseTimestamp(row['created_on']),
+ };
+}
+
+export function mapCopyFile(row: Record<string, unknown>) {
+ return {
+ file: row['file'] ?? null,
+ status: row['status'] ?? null,
+ rows_parsed: row['rows_parsed'] ?? null,
+ rows_loaded: row['rows_loaded'] ?? null,
+ error_limit: row['error_limit'] ?? null,
+ errors_seen: row['errors_seen'] ?? null,
+ first_error: row['first_error'] ?? null,
+ };
+}
diff --git a/packages/pieces/community/snowflake/src/lib/common/merge.ts b/packages/pieces/community/snowflake/src/lib/common/merge.ts
new file mode 100644
index 00000000000..a76651de326
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/common/merge.ts
@@ -0,0 +1,72 @@
+import type { Bind } from 'snowflake-sdk';
+import { identifier, qualifiedName, toBind, valuePlaceholder } from './sql';
+
+export function buildMerge({
+ table,
+ keyColumns,
+ values,
+}: {
+ table: string;
+ keyColumns: string[];
+ values: Record<string, unknown>;
+}): { sql: string; binds: Bind[] } {
+ const columns = Object.keys(values);
+ if (keyColumns.length === 0) {
+ throw new Error('Provide at least one key column.');
+ }
+ const missing = keyColumns.filter((key) => !(key in values));
+ if (missing.length > 0) {
+ throw new Error(
+ `Key column(s) ${missing.join(
+ ', '
+ )} must also be included in the row values.`
+ );
+ }
+ const nullKeys = keyColumns.filter(
+ (key) => values[key] === null || values[key] === undefined
+ );
+ if (nullKeys.length > 0) {
+ throw new Error(
+ `Key column(s) ${nullKeys.join(
+ ', '
+ )} must have a value; a NULL key never matches an existing row, so the upsert would insert a duplicate.`
+ );
+ }
+ const updateColumns = columns.filter(
+ (column) => !keyColumns.includes(column)
+ );
+ if (updateColumns.length === 0) {
+ throw new Error(
+ 'At least one column other than the key column(s) must be provided to update.'
+ );
+ }
+ const binds: Bind[] = [];
+ const aliases = new Map<string, string>();
+ const sourceSelects = columns.map((column, index) => {
+ const alias = `C${index}`;
+ aliases.set(column, alias);
+ binds.push(toBind(values[column]));
+ return `${valuePlaceholder(values[column])} AS ${alias}`;
+ });
+ const ref = (column: string) => `source.${aliases.get(column)}`;
+ const target = (column: string) =>
+ `target.${identifier({ name: column, label: 'Column' })}`;
+ const on = keyColumns
+ .map((key) => `${target(key)} = ${ref(key)}`)
+ .join(' AND ');
+ const updates = updateColumns
+ .map((column) => `${target(column)} = ${ref(column)}`)
+ .join(', ');
+ const insertColumns = columns
+ .map((column) => identifier({ name: column, label: 'Column' }))
+ .join(', ');
+ const insertValues = columns.map(ref).join(', ');
+ const sql = [
+ `MERGE INTO ${qualifiedName({ value: table, label: 'Table' })} AS target`,
+ `USING (SELECT ${sourceSelects.join(', ')}) AS source`,
+ `ON ${on}`,
+ `WHEN MATCHED THEN UPDATE SET ${updates}`,
+ `WHEN NOT MATCHED THEN INSERT (${insertColumns}) VALUES (${insertValues})`,
+ ].join('\n');
+ return { sql, binds };
+}
diff --git a/packages/pieces/community/snowflake/src/lib/common/operations.ts b/packages/pieces/community/snowflake/src/lib/common/operations.ts
new file mode 100644
index 00000000000..3a634c3fbb6
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/common/operations.ts
@@ -0,0 +1,234 @@
+import type { Bind } from 'snowflake-sdk';
+import { QueryResult, SnowflakeSession } from './client';
+import {
+ identifier,
+ qualifiedName,
+ quoteIdentifier,
+ sqlString,
+ toBind,
+ valuePlaceholder,
+} from './sql';
+
+export function dmlCount({
+ result,
+ key,
+}: {
+ result: QueryResult;
+ key: string;
+}): number {
+ const row = result.rows[0];
+ if (!row) return 0;
+ const value = row[key];
+ const num = Number(value);
+ return Number.isFinite(num) ? num : 0;
+}
+
+export function buildInsert({
+ table,
+ rows,
+ exactColumnNames = false,
+}: {
+ table: string;
+ rows: Record<string, unknown>[];
+ exactColumnNames?: boolean;
+}): { sql: string; binds: Bind[] } {
+ if (rows.length === 0) {
+ throw new Error('Provide at least one row to insert.');
+ }
+ const columns = Object.keys(rows[0]);
+ if (columns.length === 0) {
+ throw new Error('Each row needs at least one column.');
+ }
+ const columnSet = new Set(columns);
+ rows.forEach((row, index) => {
+ const keys = Object.keys(row);
+ const missing = columns.filter((column) => !(column in row));
+ const extra = keys.filter((key) => !columnSet.has(key));
+ if (missing.length > 0 || extra.length > 0) {
+ throw new Error(
+ `Row ${index + 1} has a different set of columns than the first row.` +
+ (missing.length > 0 ? ` Missing: ${missing.join(', ')}.` : '') +
+ (extra.length > 0 ? ` Extra: ${extra.join(', ')}.` : '')
+ );
+ }
+ });
+ const target = qualifiedName({ value: table, label: 'Table' });
+ const columnList = columns
+ .map((column) =>
+ exactColumnNames
+ ? quoteIdentifier(column)
+ : identifier({ name: column, label: 'Column' })
+ )
+ .join(', ');
+ const binds: Bind[] = [];
+ const hasJson = rows.some((row) =>
+ columns.some((column) => valuePlaceholder(row[column]) !== '?')
+ );
+ if (!hasJson) {
+ const tuples = rows
+ .map(() => `(${columns.map(() => '?').join(', ')})`)
+ .join(', ');
+ rows.forEach((row) =>
+ columns.forEach((column) => binds.push(toBind(row[column])))
+ );
+ return {
+ sql: `INSERT INTO ${target} (${columnList}) VALUES ${tuples}`,
+ binds,
+ };
+ }
+ const selects = rows.map((row) => {
+ const expressions = columns.map((column) => {
+ binds.push(toBind(row[column]));
+ return valuePlaceholder(row[column]);
+ });
+ return `SELECT ${expressions.join(', ')}`;
+ });
+ return {
+ sql: `INSERT INTO ${target} (${columnList}) ${selects.join(' UNION ALL ')}`,
+ binds,
+ };
+}
+
+export function buildSetClause(values: Record<string, unknown>): {
+ clause: string;
+ binds: Bind[];
+} {
+ const entries = Object.entries(values);
+ if (entries.length === 0) {
+ throw new Error('Provide at least one column value to set.');
+ }
+ const binds: Bind[] = [];
+ const parts = entries.map(([column, value]) => {
+ binds.push(toBind(value));
+ return `${identifier({
+ name: column,
+ label: 'Column',
+ })} = ${valuePlaceholder(value)}`;
+ });
+ return { clause: parts.join(', '), binds };
+}
+
+export async function guardedWrite({
+ session,
+ sql,
+ binds,
+ countKey,
+ maxRows,
+ tooManyMessage,
+}: {
+ session: SnowflakeSession;
+ sql: string;
+ binds: Bind[];
+ countKey: string;
+ maxRows: number;
+ tooManyMessage: (count: number) => string;
+}): Promise<number> {
+ await session.query({ sql: 'BEGIN' });
+ let committed = false;
+ try {
+ const result = await session.query({ sql, binds });
+ const count = dmlCount({ result, key: countKey });
+ if (count > maxRows) {
+ throw new Error(tooManyMessage(count));
+ }
+ await session.query({ sql: 'COMMIT' });
+ committed = true;
+ return count;
+ } finally {
+ if (!committed) {
+ await session.query({ sql: 'ROLLBACK' }).catch(() => undefined);
+ }
+ }
+}
+
+export function scopeClause({
+ database,
+ schema,
+}: {
+ database?: string | null;
+ schema?: string | null;
+}): string {
+ if (schema && schema.trim() !== '') {
+ const parts =
+ schema.includes('.') || !database ? schema : `${database}.${schema}`;
+ return ` IN SCHEMA ${qualifiedName({
+ value: parts,
+ maxParts: 2,
+ label: 'Schema',
+ })}`;
+ }
+ if (database && database.trim() !== '') {
+ return ` IN DATABASE ${qualifiedName({
+ value: database,
+ maxParts: 1,
+ label: 'Database',
+ })}`;
+ }
+ return '';
+}
+
+export function likeClause(pattern: string | null | undefined): string {
+ if (!pattern || pattern.trim() === '') return '';
+ return ` LIKE ${sqlString(pattern.trim())}`;
+}
+
+export async function listShow<T>({
+ session,
+ sql,
+ limit,
+ map,
+ include,
+}: {
+ session: SnowflakeSession;
+ sql: string;
+ limit: number;
+ map: (row: Record<string, unknown>) => T;
+ include?: (row: Record<string, unknown>) => boolean;
+}): Promise<{ items: T[]; count: number; truncated: boolean }> {
+ if (!include) {
+ const result = await session.query({ sql, maxRows: limit });
+ const items = result.rows.map(map);
+ return { items, count: items.length, truncated: result.truncated };
+ }
+ const result = await session.query({ sql, maxRows: LIST_SCAN_MAX_ROWS });
+ const kept = result.rows.filter(include);
+ const items = kept.slice(0, limit).map(map);
+ return {
+ items,
+ count: items.length,
+ truncated: kept.length > limit || result.truncated,
+ };
+}
+
+const LIST_SCAN_MAX_ROWS = 5000;
+
+export function isUserDefined(row: Record<string, unknown>): boolean {
+ return String(row['is_builtin'] ?? 'N').toUpperCase() !== 'Y';
+}
+
+export function pick({
+ row,
+ keys,
+}: {
+ row: Record<string, unknown>;
+ keys: string[];
+}): Record<string, unknown> {
+ const out: Record<string, unknown> = {};
+ for (const key of keys) {
+ out[key] = row[key] ?? null;
+ }
+ return out;
+}
+
+export function normaliseTimestamp(value: unknown): unknown {
+ if (value instanceof Date) return value.toISOString();
+ if (
+ value &&
+ typeof value === 'object' &&
+ 'toJSON' in value &&
+ typeof value.toJSON === 'function'
+ ) {
+ return value.toJSON();
+ }
+ return value ?? null;
+}
diff --git a/packages/pieces/community/snowflake/src/lib/common/output-schemas.ts b/packages/pieces/community/snowflake/src/lib/common/output-schemas.ts
new file mode 100644
index 00000000000..2ed2244e6e7
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/common/output-schemas.ts
@@ -0,0 +1,513 @@
+import {
+ OutputSchema,
+ OutputSchemaField,
+} from '@activepieces/pieces-framework';
+
+const rowColumnsField: OutputSchemaField = {
+ key: 'columns',
+ label: 'Row Columns',
+ value: '',
+ dynamicKey: true,
+};
+
+const rowsField: OutputSchemaField = {
+ key: 'rows',
+ label: 'Rows',
+ description:
+ 'Each row is an object keyed by column name (Snowflake upper-cases unquoted names).',
+ listItems: [rowColumnsField],
+};
+
+const queryIdField: OutputSchemaField = { key: 'queryId', label: 'Query ID' };
+
+const columnFields: OutputSchemaField[] = [
+ { key: 'column_name', label: 'Column Name' },
+ { key: 'data_type', label: 'Data Type' },
+ { key: 'nullable', label: 'Nullable (Y/N)' },
+ { key: 'default_value', label: 'Default Value' },
+ { key: 'primary_key', label: 'Primary Key (Y/N)' },
+ { key: 'unique_key', label: 'Unique Key (Y/N)' },
+ { key: 'check', label: 'Check' },
+ { key: 'expression', label: 'Expression' },
+ { key: 'comment', label: 'Comment' },
+];
+
+const tableFields: OutputSchemaField[] = [
+ { key: 'table_name', label: 'Table Name' },
+ { key: 'database_name', label: 'Database' },
+ { key: 'schema_name', label: 'Schema' },
+ { key: 'kind', label: 'Kind' },
+ { key: 'rows', label: 'Row Count', format: 'number' },
+ { key: 'bytes', label: 'Size', format: 'filesize' },
+ { key: 'owner', label: 'Owner' },
+ { key: 'comment', label: 'Comment' },
+ { key: 'created_on', label: 'Created On', format: 'datetime' },
+];
+
+const viewFields: OutputSchemaField[] = [
+ { key: 'view_name', label: 'View Name' },
+ { key: 'database_name', label: 'Database' },
+ { key: 'schema_name', label: 'Schema' },
+ { key: 'owner', label: 'Owner' },
+ { key: 'comment', label: 'Comment' },
+ { key: 'text', label: 'Definition' },
+ { key: 'is_secure', label: 'Secure' },
+ { key: 'is_materialized', label: 'Materialized' },
+ { key: 'created_on', label: 'Created On', format: 'datetime' },
+];
+
+const listMeta: OutputSchemaField[] = [
+ { key: 'count', label: 'Count', format: 'number' },
+ {
+ key: 'truncated',
+ label: 'Truncated',
+ format: 'boolean',
+ description:
+ 'True when more items exist than were returned; narrow the pattern or raise the limit.',
+ },
+];
+
+function listSchema({
+ fields,
+ labelKey,
+}: {
+ fields: OutputSchemaField[];
+ labelKey: string;
+}): OutputSchema {
+ return {
+ fields: [
+ { key: 'items', label: 'Items', labelKey, listItems: fields },
+ ...listMeta,
+ ],
+ };
+}
+
+export const rawRowsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'rows', label: 'Rows', value: '', listItems: [rowColumnsField] },
+ ],
+ itemLabel: 'Row',
+};
+
+export const queryResultOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'columns', label: 'Columns' },
+ rowsField,
+ { key: 'rowCount', label: 'Rows Returned', format: 'number' },
+ { key: 'totalRows', label: 'Total Rows in Result', format: 'number' },
+ { key: 'truncated', label: 'Truncated', format: 'boolean' },
+ queryIdField,
+ ],
+};
+
+export const multipleQueriesOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'query', label: 'Query' },
+ { key: 'result', label: 'Result Rows' },
+ ],
+ itemLabel: '{query}',
+};
+
+export const findRowsOutputSchema: OutputSchema = {
+ fields: [
+ rowsField,
+ { key: 'rowCount', label: 'Rows Returned', format: 'number' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+ { key: 'nextOffset', label: 'Next Offset', format: 'number' },
+ ],
+};
+
+export const countRowsOutputSchema: OutputSchema = {
+ fields: [{ key: 'count', label: 'Count', format: 'number' }],
+};
+
+export const getRowOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'row', label: 'Row', dynamicKey: true },
+ ],
+};
+
+export const getRowByIdOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ rowColumnsField,
+ ],
+};
+
+export const insertResultOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'rowsInserted', label: 'Rows Inserted', format: 'number' },
+ queryIdField,
+ ],
+};
+
+export const legacyInsertOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'number of rows inserted',
+ label: 'Rows Inserted',
+ format: 'number',
+ },
+ ],
+ itemLabel: 'Result',
+};
+
+export const legacyInsertManyOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'rows_inserted', label: 'Rows Inserted', format: 'number' },
+ ],
+};
+
+export const legacyUpdateOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'rows_updated', label: 'Rows Updated', format: 'number' },
+ ],
+};
+
+export const legacyDeleteOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'rows_deleted', label: 'Rows Deleted', format: 'number' },
+ ],
+};
+
+export const legacyUpsertOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'rows_inserted', label: 'Rows Inserted', format: 'number' },
+ { key: 'rows_updated', label: 'Rows Updated', format: 'number' },
+ ],
+};
+
+export const upsertOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'rowsInserted', label: 'Rows Inserted', format: 'number' },
+ { key: 'rowsUpdated', label: 'Rows Updated', format: 'number' },
+ queryIdField,
+ ],
+};
+
+export const updateByKeyOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'rowsAffected', label: 'Rows Updated', format: 'number' },
+ ],
+};
+
+export const updateByFilterOutputSchema: OutputSchema = {
+ fields: [{ key: 'rowsAffected', label: 'Rows Updated', format: 'number' }],
+};
+
+export const deleteByKeyOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'alreadyDeleted', label: 'Already Deleted', format: 'boolean' },
+ ],
+};
+
+export const deleteByFilterOutputSchema: OutputSchema = {
+ fields: [{ key: 'rowsDeleted', label: 'Rows Deleted', format: 'number' }],
+};
+
+export const tableSchemaOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'table', label: 'Table' },
+ {
+ key: 'columns',
+ label: 'Columns',
+ labelKey: 'column_name',
+ listItems: columnFields,
+ },
+ ],
+};
+
+export const listTablesOutputSchema: OutputSchema = {
+ fields: tableFields,
+ itemLabel: '{table_name}',
+};
+
+export const listTablesAiOutputSchema = listSchema({
+ fields: tableFields,
+ labelKey: 'table_name',
+});
+export const listViewsOutputSchema = listSchema({
+ fields: viewFields,
+ labelKey: 'view_name',
+});
+
+export const listDatabasesOutputSchema = listSchema({
+ fields: [
+ { key: 'name', label: 'Name' },
+ { key: 'owner', label: 'Owner' },
+ { key: 'kind', label: 'Kind' },
+ { key: 'comment', label: 'Comment' },
+ { key: 'created_on', label: 'Created On', format: 'datetime' },
+ ],
+ labelKey: 'name',
+});
+
+export const listSchemasOutputSchema = listSchema({
+ fields: [
+ { key: 'name', label: 'Name' },
+ { key: 'database_name', label: 'Database' },
+ { key: 'owner', label: 'Owner' },
+ { key: 'comment', label: 'Comment' },
+ { key: 'created_on', label: 'Created On', format: 'datetime' },
+ ],
+ labelKey: 'name',
+});
+
+export const listWarehousesOutputSchema = listSchema({
+ fields: [
+ { key: 'name', label: 'Name' },
+ { key: 'state', label: 'State' },
+ { key: 'type', label: 'Type' },
+ { key: 'size', label: 'Size' },
+ { key: 'auto_suspend', label: 'Auto Suspend (s)', format: 'number' },
+ { key: 'auto_resume', label: 'Auto Resume' },
+ { key: 'is_current', label: 'Is Current' },
+ { key: 'owner', label: 'Owner' },
+ { key: 'comment', label: 'Comment' },
+ { key: 'created_on', label: 'Created On', format: 'datetime' },
+ ],
+ labelKey: 'name',
+});
+
+export const listStagesOutputSchema = listSchema({
+ fields: [
+ { key: 'name', label: 'Name' },
+ { key: 'database_name', label: 'Database' },
+ { key: 'schema_name', label: 'Schema' },
+ { key: 'type', label: 'Type' },
+ { key: 'url', label: 'URL' },
+ { key: 'owner', label: 'Owner' },
+ { key: 'comment', label: 'Comment' },
+ { key: 'created_on', label: 'Created On', format: 'datetime' },
+ ],
+ labelKey: 'name',
+});
+
+export const listStageFilesOutputSchema = listSchema({
+ fields: [
+ { key: 'name', label: 'File Name' },
+ { key: 'size', label: 'Size', format: 'filesize' },
+ { key: 'md5', label: 'MD5' },
+ { key: 'last_modified', label: 'Last Modified' },
+ ],
+ labelKey: 'name',
+});
+
+export const listProceduresOutputSchema = listSchema({
+ fields: [
+ { key: 'name', label: 'Name' },
+ { key: 'schema_name', label: 'Schema' },
+ { key: 'database_name', label: 'Database' },
+ { key: 'arguments', label: 'Signature' },
+ { key: 'description', label: 'Description' },
+ { key: 'created_on', label: 'Created On', format: 'datetime' },
+ ],
+ labelKey: 'name',
+});
+
+export const listRolesOutputSchema = listSchema({
+ fields: [
+ { key: 'name', label: 'Name' },
+ { key: 'is_current', label: 'Is Current' },
+ { key: 'is_default', label: 'Is Default' },
+ { key: 'granted_to_roles', label: 'Granted to Roles', format: 'number' },
+ { key: 'granted_roles', label: 'Granted Roles', format: 'number' },
+ { key: 'owner', label: 'Owner' },
+ { key: 'comment', label: 'Comment' },
+ { key: 'created_on', label: 'Created On', format: 'datetime' },
+ ],
+ labelKey: 'name',
+});
+
+export const listColumnsOutputSchema = listSchema({
+ fields: [
+ { key: 'table_schema', label: 'Schema' },
+ { key: 'table_name', label: 'Table' },
+ { key: 'column_name', label: 'Column' },
+ { key: 'ordinal_position', label: 'Position', format: 'number' },
+ { key: 'data_type', label: 'Data Type' },
+ { key: 'is_nullable', label: 'Nullable' },
+ { key: 'column_default', label: 'Default' },
+ { key: 'comment', label: 'Comment' },
+ ],
+ labelKey: 'column_name',
+});
+
+export const queryHistoryOutputSchema = listSchema({
+ fields: [
+ { key: 'query_id', label: 'Query ID' },
+ { key: 'query_text', label: 'Query Text' },
+ { key: 'execution_status', label: 'Status' },
+ { key: 'user_name', label: 'User' },
+ { key: 'role_name', label: 'Role' },
+ { key: 'warehouse_name', label: 'Warehouse' },
+ { key: 'start_time', label: 'Start Time', format: 'datetime' },
+ { key: 'end_time', label: 'End Time', format: 'datetime' },
+ { key: 'total_elapsed_time', label: 'Elapsed (ms)', format: 'number' },
+ { key: 'rows_produced', label: 'Rows Produced', format: 'number' },
+ { key: 'error_message', label: 'Error Message' },
+ ],
+ labelKey: 'query_id',
+});
+
+export const describeTableOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'table', label: 'Table' },
+ {
+ key: 'columns',
+ label: 'Columns',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Name' },
+ { key: 'type', label: 'Data Type' },
+ { key: 'nullable', label: 'Nullable', format: 'boolean' },
+ { key: 'default', label: 'Default' },
+ { key: 'primaryKey', label: 'Primary Key', format: 'boolean' },
+ { key: 'uniqueKey', label: 'Unique Key', format: 'boolean' },
+ { key: 'comment', label: 'Comment' },
+ ],
+ },
+ ],
+};
+
+export const viewDefinitionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'view', label: 'View' },
+ { key: 'ddl', label: 'DDL' },
+ ],
+};
+
+export const explainOutputSchema: OutputSchema = {
+ fields: [{ key: 'plan', label: 'Plan', dynamicKey: true }],
+};
+
+export const queryStatusOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'queryId', label: 'Query ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'isRunning', label: 'Is Running', format: 'boolean' },
+ { key: 'isError', label: 'Is Error', format: 'boolean' },
+ rowsField,
+ { key: 'rowCount', label: 'Rows Returned', format: 'number' },
+ { key: 'truncated', label: 'Truncated', format: 'boolean' },
+ ],
+};
+
+export const cancelQueryOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'queryId', label: 'Query ID' },
+ { key: 'message', label: 'Message' },
+ ],
+};
+
+export const copyIntoOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'filesProcessed', label: 'Files Processed', format: 'number' },
+ { key: 'rowsLoaded', label: 'Rows Loaded', format: 'number' },
+ {
+ key: 'files',
+ label: 'Files',
+ labelKey: 'file',
+ listItems: [
+ { key: 'file', label: 'File' },
+ { key: 'status', label: 'Status' },
+ { key: 'rows_parsed', label: 'Rows Parsed', format: 'number' },
+ { key: 'rows_loaded', label: 'Rows Loaded', format: 'number' },
+ { key: 'error_limit', label: 'Error Limit', format: 'number' },
+ { key: 'errors_seen', label: 'Errors Seen', format: 'number' },
+ { key: 'first_error', label: 'First Error' },
+ ],
+ },
+ ],
+};
+
+export const legacyLoadOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'files_processed', label: 'Files Processed', format: 'number' },
+ { key: 'rows_loaded', label: 'Rows Loaded', format: 'number' },
+ {
+ key: 'files',
+ label: 'Files',
+ labelKey: 'file',
+ listItems: [
+ { key: 'file', label: 'File' },
+ { key: 'status', label: 'Status' },
+ { key: 'rows_parsed', label: 'Rows Parsed', format: 'number' },
+ { key: 'rows_loaded', label: 'Rows Loaded', format: 'number' },
+ { key: 'error_limit', label: 'Error Limit', format: 'number' },
+ { key: 'errors_seen', label: 'Errors Seen', format: 'number' },
+ { key: 'first_error', label: 'First Error' },
+ ],
+ },
+ ],
+};
+
+export const callProcedureOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'result',
+ label: 'Result',
+ description:
+ 'The value returned by the procedure (first column of the first row).',
+ },
+ rowsField,
+ { key: 'rowCount', label: 'Rows Returned', format: 'number' },
+ { key: 'truncated', label: 'Truncated', format: 'boolean' },
+ queryIdField,
+ ],
+};
+
+export const legacyProcedureOutputSchema: OutputSchema = {
+ fields: [{ key: 'result', label: 'Result Rows' }],
+};
+
+export const dynamicTableOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'table', label: 'Table' },
+ { key: 'target_lag', label: 'Target Lag' },
+ { key: 'warehouse', label: 'Warehouse' },
+ ],
+};
+
+export const sessionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'user', label: 'User' },
+ { key: 'role', label: 'Role' },
+ { key: 'warehouse', label: 'Warehouse' },
+ { key: 'database', label: 'Database' },
+ { key: 'schema', label: 'Schema' },
+ { key: 'account', label: 'Account' },
+ { key: 'region', label: 'Region' },
+ { key: 'version', label: 'Snowflake Version' },
+ ],
+};
+
+export const rowTriggerOutputSchema: OutputSchema = {
+ fields: [rowColumnsField],
+};
+
+export const newColumnOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'column_name', label: 'Column Name' },
+ { key: 'data_type', label: 'Data Type' },
+ { key: 'nullable', label: 'Nullable (Y/N)' },
+ { key: 'default_value', label: 'Default Value' },
+ { key: 'primary_key', label: 'Primary Key (Y/N)' },
+ { key: 'unique_key', label: 'Unique Key (Y/N)' },
+ { key: 'comment', label: 'Comment' },
+ { key: 'position', label: 'Position', format: 'number' },
+ { key: 'table', label: 'Table' },
+ ],
+};
+
+export const newTableOutputSchema: OutputSchema = { fields: tableFields };
+export const newViewOutputSchema: OutputSchema = { fields: viewFields };
diff --git a/packages/pieces/community/snowflake/src/lib/common/private-key.ts b/packages/pieces/community/snowflake/src/lib/common/private-key.ts
new file mode 100644
index 00000000000..f86317d3aa9
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/common/private-key.ts
@@ -0,0 +1,17 @@
+const PEM_BLOCK = /-----BEGIN ([A-Z0-9 ]+)-----([\s\S]*?)-----END \1-----/;
+
+export function normalizePrivateKey(privateKey: string): string {
+ const trimmed = privateKey.trim().replace(/\\n/g, '\n');
+ const match = PEM_BLOCK.exec(trimmed);
+ const label = match ? match[1].trim() : 'PRIVATE KEY';
+ const body = (match ? match[2] : trimmed).replace(/\s+/g, '');
+ if (body.length === 0 || !/^[A-Za-z0-9+/=]+$/.test(body)) {
+ throw new Error(
+ 'The private key is not valid PEM. Paste the full contents of your .p8 file, including the -----BEGIN ... PRIVATE KEY----- and -----END ... PRIVATE KEY----- lines.'
+ );
+ }
+ const lines = body.match(/.{1,64}/g) ?? [];
+ return [`-----BEGIN ${label}-----`, ...lines, `-----END ${label}-----`].join(
+ '\n'
+ );
+}
diff --git a/packages/pieces/community/snowflake/src/lib/common/procedures.ts b/packages/pieces/community/snowflake/src/lib/common/procedures.ts
new file mode 100644
index 00000000000..08035e347f4
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/common/procedures.ts
@@ -0,0 +1,54 @@
+import type { Bind } from 'snowflake-sdk';
+import { qualifiedName, toBind, valuePlaceholder } from './sql';
+
+const JSON_TYPES = new Set(['VARIANT', 'OBJECT', 'ARRAY']);
+
+export function buildCall({
+ procedure,
+ args,
+ preQualified = false,
+ argTypes = [],
+}: {
+ procedure: string;
+ args: unknown[];
+ preQualified?: boolean;
+ argTypes?: string[];
+}): { sql: string; binds: Bind[] } {
+ const name = preQualified
+ ? procedure
+ : qualifiedName({ value: procedure, label: 'Procedure' });
+ const binds: Bind[] = [];
+ const placeholders: string[] = [];
+ args.forEach((arg, index) => {
+ const type = (argTypes[index] ?? '').toUpperCase();
+ if (typeof arg === 'string' && JSON_TYPES.has(type)) {
+ binds.push(isJsonText(arg) ? arg : JSON.stringify(arg));
+ placeholders.push('PARSE_JSON(?)');
+ return;
+ }
+ binds.push(toBind(arg));
+ placeholders.push(valuePlaceholder(arg));
+ });
+ return { sql: `CALL ${name}(${placeholders.join(', ')})`, binds };
+}
+
+export function parseSignatureArgTypes(signature: string): string[] {
+ const open = signature.indexOf('(');
+ const close = signature.indexOf(')', open + 1);
+ if (open === -1 || close === -1) return [];
+ const inner = signature.substring(open + 1, close).trim();
+ if (inner === '') return [];
+ return inner.split(',').map((part) => {
+ const words = part.trim().split(/\s+/);
+ return words[words.length - 1] ?? '';
+ });
+}
+
+function isJsonText(value: string): boolean {
+ try {
+ JSON.parse(value);
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/packages/pieces/community/snowflake/src/lib/common/query-id.ts b/packages/pieces/community/snowflake/src/lib/common/query-id.ts
new file mode 100644
index 00000000000..66ec513c6f6
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/common/query-id.ts
@@ -0,0 +1,2 @@
+export const QUERY_ID =
+ /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
diff --git a/packages/pieces/community/snowflake/src/lib/common/row-poll.ts b/packages/pieces/community/snowflake/src/lib/common/row-poll.ts
new file mode 100644
index 00000000000..75b9bb0e74b
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/common/row-poll.ts
@@ -0,0 +1,117 @@
+import { SnowflakeAuthValue, withSnowflake } from './client';
+import { identifier, qualifiedName } from './sql';
+
+const CURSOR = '__AP_CURSOR';
+const PAGE_SIZE = 1000;
+const GROUP_LIMIT = 10000;
+
+export async function fetchBaseline({
+ auth,
+ table,
+ column,
+}: {
+ auth: SnowflakeAuthValue;
+ table: string;
+ column: string;
+}): Promise<string | null> {
+ const col = identifier({ name: column, label: 'Timestamp column' });
+ const sql = `SELECT MAX(DATE_PART(EPOCH_MICROSECOND, ${col})) AS "${CURSOR}" FROM ${qualifiedName(
+ { value: table, label: 'Table' }
+ )}`;
+ const result = await withSnowflake({
+ auth,
+ fn: (session) => session.query({ sql, maxRows: 1 }),
+ });
+ return cursorString(result.rows[0]?.[CURSOR]);
+}
+
+export async function fetchNewRows({
+ auth,
+ table,
+ column,
+ after,
+}: {
+ auth: SnowflakeAuthValue;
+ table: string;
+ column: string;
+ after: string | null;
+}): Promise<{ rows: Record<string, unknown>[]; cursor: string | null }> {
+ const col = identifier({ name: column, label: 'Timestamp column' });
+ const cursorExpr = `DATE_PART(EPOCH_MICROSECOND, ${col})`;
+ const from = `SELECT t.*, ${cursorExpr} AS "${CURSOR}" FROM ${qualifiedName({
+ value: table,
+ label: 'Table',
+ })} t`;
+ const where = after === null ? `${col} IS NOT NULL` : `${cursorExpr} > ?`;
+ const page = await withSnowflake({
+ auth,
+ fn: (session) =>
+ session.query({
+ sql: `${from} WHERE ${where} ORDER BY ${cursorExpr} ASC LIMIT ${PAGE_SIZE}`,
+ binds: after === null ? [] : [after],
+ maxRows: PAGE_SIZE,
+ }),
+ });
+ let rows = page.rows;
+ if (rows.length === PAGE_SIZE) {
+ const lastCursor = cursorString(rows[rows.length - 1][CURSOR]);
+ const trimmed = rows.filter(
+ (row) => cursorString(row[CURSOR]) !== lastCursor
+ );
+ if (trimmed.length > 0) {
+ rows = trimmed;
+ } else if (lastCursor !== null) {
+ const group = await withSnowflake({
+ auth,
+ fn: (session) =>
+ session.query({
+ sql: `${from} WHERE ${cursorExpr} = ? LIMIT ${GROUP_LIMIT}`,
+ binds: [lastCursor],
+ maxRows: GROUP_LIMIT,
+ }),
+ });
+ rows = group.rows;
+ }
+ }
+ if (rows.length === 0) {
+ return { rows: [], cursor: after };
+ }
+ const cursor = cursorString(rows[rows.length - 1][CURSOR]);
+ return { rows: rows.map(stripCursor), cursor: cursor ?? after };
+}
+
+export async function fetchLatestRows({
+ auth,
+ table,
+ column,
+ limit,
+}: {
+ auth: SnowflakeAuthValue;
+ table: string;
+ column: string;
+ limit: number;
+}): Promise<Record<string, unknown>[]> {
+ const col = identifier({ name: column, label: 'Timestamp column' });
+ const sql = `SELECT * FROM ${qualifiedName({
+ value: table,
+ label: 'Table',
+ })} WHERE ${col} IS NOT NULL ORDER BY ${col} DESC LIMIT ${limit}`;
+ const result = await withSnowflake({
+ auth,
+ fn: (session) => session.query({ sql, maxRows: limit }),
+ });
+ return result.rows;
+}
+
+function stripCursor(row: Record<string, unknown>): Record<string, unknown> {
+ const copy = { ...row };
+ delete copy[CURSOR];
+ return copy;
+}
+
+function cursorString(value: unknown): string | null {
+ if (value === null || value === undefined || value === '') return null;
+ return String(value);
+}
+
+export const ROW_CURSOR_STORE_KEY = 'snowflake_row_cursor';
diff --git a/packages/pieces/community/snowflake/src/lib/common/sdk.ts b/packages/pieces/community/snowflake/src/lib/common/sdk.ts
new file mode 100644
index 00000000000..a88d7c033e0
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/common/sdk.ts
@@ -0,0 +1,35 @@
+import type * as SnowflakeSdk from 'snowflake-sdk';
+
+let sdkPromise: Promise<SnowflakeModule> | undefined;
+
+export function loadSnowflakeSdk(): Promise<SnowflakeModule> {
+ if (!sdkPromise) {
+ sdkPromise = import('snowflake-sdk')
+ .then((mod) => {
+ const sdk = pickSdk(mod);
+ sdk.configure({ logLevel: 'ERROR' });
+ return sdk;
+ })
+ .catch((error: unknown) => {
+ sdkPromise = undefined;
+ throw error;
+ });
+ }
+ return sdkPromise;
+}
+
+function pickSdk(
+ mod: SnowflakeModule | { default: SnowflakeModule }
+): SnowflakeModule {
+ return isWrapped(mod) ? mod.default : mod;
+}
+
+function isWrapped(
+ mod: SnowflakeModule | { default: SnowflakeModule }
+): mod is { default: SnowflakeModule } {
+ return (
+ !('createConnection' in mod) || typeof mod.createConnection !== 'function'
+ );
+}
+
+export type SnowflakeModule = typeof SnowflakeSdk;
diff --git a/packages/pieces/community/snowflake/src/lib/common/sql.ts b/packages/pieces/community/snowflake/src/lib/common/sql.ts
new file mode 100644
index 00000000000..e808122b7c3
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/common/sql.ts
@@ -0,0 +1,523 @@
+import type { Bind } from 'snowflake-sdk';
+
+const SIMPLE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;
+const QUOTED_IDENTIFIER = /^"(?:[^"]|"")+"$/;
+const MAX_IDENTIFIER_LENGTH = 255;
+
+export function identifier({
+ name: raw,
+ label = 'Identifier',
+}: {
+ name: string;
+ label?: string;
+}): string {
+ const name = String(raw ?? '').trim();
+ if (name === '') {
+ throw new Error(`${label} is empty.`);
+ }
+ if (name.length > MAX_IDENTIFIER_LENGTH + 2) {
+ throw new Error(
+ `${label} is longer than ${MAX_IDENTIFIER_LENGTH} characters.`
+ );
+ }
+ if (SIMPLE_IDENTIFIER.test(name) || QUOTED_IDENTIFIER.test(name)) {
+ return name;
+ }
+ return quoteIdentifier(name);
+}
+
+export function quoteIdentifier(name: string): string {
+ return `"${name.replace(/"/g, '""')}"`;
+}
+
+export function identifierValue(raw: string): string {
+ const name = String(raw ?? '').trim();
+ if (QUOTED_IDENTIFIER.test(name)) {
+ return name.slice(1, -1).replace(/""/g, '"');
+ }
+ if (SIMPLE_IDENTIFIER.test(name)) {
+ return name.toUpperCase();
+ }
+ return name;
+}
+
+export function splitQualifiedName(value: string): string[] {
+ const parts: string[] = [];
+ let current = '';
+ let inQuotes = false;
+ for (let i = 0; i < value.length; i++) {
+ const char = value[i];
+ if (char === '"') {
+ if (inQuotes && value[i + 1] === '"') {
+ current += '""';
+ i++;
+ continue;
+ }
+ inQuotes = !inQuotes;
+ current += char;
+ continue;
+ }
+ if (char === '.' && !inQuotes) {
+ parts.push(current.trim());
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ if (inQuotes) {
+ throw new Error(`Name ${value} has an unclosed double quote.`);
+ }
+ parts.push(current.trim());
+ return parts;
+}
+
+export function qualifiedName({
+ value,
+ maxParts = 3,
+ label = 'Name',
+}: {
+ value: string;
+ maxParts?: number;
+ label?: string;
+}): string {
+ const raw = String(value ?? '').trim();
+ if (raw === '') {
+ throw new Error(`${label} is empty.`);
+ }
+ const parts = splitQualifiedName(raw);
+ if (parts.length > maxParts || parts.some((part) => part === '')) {
+ throw new Error(
+ `${label} "${raw}" is not valid. Use up to ${maxParts} dot-separated parts, for example ${
+ maxParts === 3 ? 'MY_DB.PUBLIC.ORDERS' : 'MY_DB.PUBLIC'
+ }.`
+ );
+ }
+ return parts.map((part) => identifier({ name: part, label })).join('.');
+}
+
+export function sqlString(value: string): string {
+ return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "''")}'`;
+}
+
+export function toBind(value: unknown): Bind {
+ if (value === undefined || value === null) return null;
+ if (typeof value === 'string' || typeof value === 'boolean') return value;
+ if (typeof value === 'number') {
+ if (!Number.isFinite(value)) {
+ throw new Error(`Value ${value} is not a finite number.`);
+ }
+ return value;
+ }
+ if (typeof value === 'bigint') return value.toString();
+ if (value instanceof Date) return value.toISOString();
+ return JSON.stringify(value);
+}
+
+export function isJsonValue(value: unknown): boolean {
+ return (
+ value !== null && typeof value === 'object' && !(value instanceof Date)
+ );
+}
+
+export function valuePlaceholder(value: unknown): string {
+ return isJsonValue(value) ? 'PARSE_JSON(?)' : '?';
+}
+
+export function parseObject({
+ value,
+ label,
+}: {
+ value: unknown;
+ label: string;
+}): Record<string, unknown> {
+ let parsed = value;
+ if (typeof value === 'string') {
+ try {
+ parsed = JSON.parse(value);
+ } catch {
+ throw new Error(`${label} must be a JSON object like {"NAME": "Alice"}.`);
+ }
+ }
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ throw new Error(`${label} must be a JSON object like {"NAME": "Alice"}.`);
+ }
+ return Object.fromEntries(Object.entries(parsed));
+}
+
+export function parseRowArray({
+ value,
+ label,
+}: {
+ value: unknown;
+ label: string;
+}): Record<string, unknown>[] {
+ let parsed = value;
+ if (typeof value === 'string') {
+ try {
+ parsed = JSON.parse(value);
+ } catch {
+ throw new Error(`${label} must be a JSON array of objects.`);
+ }
+ }
+ if (!Array.isArray(parsed)) {
+ throw new Error(`${label} must be a JSON array of objects.`);
+ }
+ return parsed.map((item, index) =>
+ parseObject({ value: item, label: `${label} item ${index + 1}` })
+ );
+}
+
+export function parseStringList({
+ value,
+ label,
+}: {
+ value: unknown;
+ label: string;
+}): string[] {
+ let list: unknown[];
+ if (Array.isArray(value)) {
+ list = value;
+ } else if (typeof value === 'string') {
+ const trimmed = value.trim();
+ if (trimmed.startsWith('[')) {
+ try {
+ const parsed: unknown = JSON.parse(trimmed);
+ list = Array.isArray(parsed) ? parsed : [parsed];
+ } catch {
+ throw new Error(`${label} must be a list of names.`);
+ }
+ } else {
+ list = trimmed === '' ? [] : trimmed.split(',');
+ }
+ } else {
+ list = [];
+ }
+ return list.map((item) => String(item).trim()).filter((item) => item !== '');
+}
+
+export function boundedInteger({
+ value,
+ defaultValue,
+ min,
+ max,
+ label,
+}: {
+ value: unknown;
+ defaultValue: number;
+ min: number;
+ max: number;
+ label: string;
+}): number {
+ if (value === undefined || value === null || value === '')
+ return defaultValue;
+ const num = Number(value);
+ if (!Number.isInteger(num) || num < min || num > max) {
+ throw new Error(
+ `${label} must be a whole number between ${min} and ${max}.`
+ );
+ }
+ return num;
+}
+
+export function buildWhere(filtersInput: unknown): {
+ clause: string;
+ binds: Bind[];
+} {
+ const filters = parseFilters(filtersInput);
+ if (filters.length === 0) {
+ return { clause: '', binds: [] };
+ }
+ const binds: Bind[] = [];
+ const conditions = filters.map((filter) => {
+ const column = identifier({ name: filter.column, label: 'Filter column' });
+ switch (filter.operator) {
+ case 'IS NULL':
+ case 'IS NOT NULL':
+ return `${column} ${filter.operator}`;
+ case 'IN':
+ case 'NOT IN': {
+ const values = filterValueList(filter.value);
+ if (values.length === 0) {
+ throw new Error(
+ `Filter on ${filter.column} with ${filter.operator} needs at least one value.`
+ );
+ }
+ values.forEach((item) => binds.push(toBind(item)));
+ return `${column} ${filter.operator} (${values
+ .map(() => '?')
+ .join(', ')})`;
+ }
+ default: {
+ if (filter.value === undefined || filter.value === null) {
+ throw new Error(
+ `Filter on ${filter.column} with ${filter.operator} needs a value. Use IS NULL to match empty values.`
+ );
+ }
+ binds.push(toBind(filter.value));
+ return `${column} ${filter.operator} ?`;
+ }
+ }
+ });
+ return { clause: ` WHERE ${conditions.join(' AND ')}`, binds };
+}
+
+export function parseFilters(input: unknown): Filter[] {
+ let list: unknown = input;
+ if (typeof input === 'string') {
+ if (input.trim() === '') return [];
+ try {
+ list = JSON.parse(input);
+ } catch {
+ throw new Error(
+ 'Filters must be a list of {column, operator, value} objects.'
+ );
+ }
+ }
+ if (list === undefined || list === null) return [];
+ if (!Array.isArray(list)) {
+ throw new Error(
+ 'Filters must be a list of {column, operator, value} objects.'
+ );
+ }
+ return list.map((item, index) => {
+ const entry = parseObject({ value: item, label: `Filter ${index + 1}` });
+ const column = entry['column'];
+ if (typeof column !== 'string' || column.trim() === '') {
+ throw new Error(`Filter ${index + 1} needs a column name.`);
+ }
+ const operator = String(entry['operator'] ?? '=')
+ .trim()
+ .toUpperCase();
+ if (!isFilterOperator(operator)) {
+ throw new Error(
+ `Filter ${
+ index + 1
+ } operator "${operator}" is not supported. Use one of: ${FILTER_OPERATORS.join(
+ ', '
+ )}.`
+ );
+ }
+ return { column, operator, value: entry['value'] };
+ });
+}
+
+export function buildOrderBy(input: unknown): string {
+ let list: unknown = input;
+ if (typeof input === 'string') {
+ if (input.trim() === '') return '';
+ try {
+ list = JSON.parse(input);
+ } catch {
+ throw new Error('Sort must be a list of {column, direction} objects.');
+ }
+ }
+ if (list === undefined || list === null) return '';
+ if (!Array.isArray(list)) {
+ throw new Error('Sort must be a list of {column, direction} objects.');
+ }
+ const parts = list.map((item, index) => {
+ const entry = parseObject({ value: item, label: `Sort ${index + 1}` });
+ const column = entry['column'];
+ if (typeof column !== 'string' || column.trim() === '') {
+ throw new Error(`Sort ${index + 1} needs a column name.`);
+ }
+ const direction = String(entry['direction'] ?? 'ASC')
+ .trim()
+ .toUpperCase();
+ if (direction !== 'ASC' && direction !== 'DESC') {
+ throw new Error(`Sort ${index + 1} direction must be ASC or DESC.`);
+ }
+ return `${identifier({ name: column, label: 'Sort column' })} ${direction}`;
+ });
+ return parts.length > 0 ? ` ORDER BY ${parts.join(', ')}` : '';
+}
+
+export function assertReadOnlyStatement(sql: string): string {
+ const { code, body } = stripSql(sql);
+ const words = code.toUpperCase().match(/[A-Z_][A-Z0-9_$]*/g) ?? [];
+ const firstWord = words[0];
+ if (firstWord === undefined) {
+ throw new Error('The query is empty.');
+ }
+ if (!READ_ONLY_FIRST_WORDS.includes(firstWord)) {
+ throw new Error(
+ `Only read-only statements are allowed here (SELECT, WITH, SHOW, DESCRIBE, EXPLAIN); the query starts with ${firstWord}. Use the dedicated insert, update or delete actions to change data.`
+ );
+ }
+ const blocked = words.find(
+ (word) => BLOCKED_WORDS.has(word) || word.startsWith('SYSTEM$')
+ );
+ if (blocked) {
+ throw new Error(
+ `The query contains ${blocked}, which is not allowed in a read-only query.`
+ );
+ }
+ return body;
+}
+
+export function firstKeyword(sql: string): string | undefined {
+ const { code } = stripSql(sql);
+ return code.toUpperCase().match(/[A-Z_][A-Z0-9_$]*/)?.[0];
+}
+
+function stripSql(sql: string): { code: string; body: string } {
+ let code = '';
+ let i = 0;
+ let lastSignificant = -1;
+ const text = sql;
+ while (i < text.length) {
+ const char = text.charAt(i);
+ const next = text.charAt(i + 1);
+ if ((char === '-' && next === '-') || (char === '/' && next === '/')) {
+ while (i < text.length && text[i] !== '\n') i++;
+ code += ' ';
+ continue;
+ }
+ if (char === '/' && next === '*') {
+ const end = text.indexOf('*/', i + 2);
+ if (end === -1) throw new Error('The query has an unclosed /* comment.');
+ i = end + 2;
+ code += ' ';
+ continue;
+ }
+ if (char === "'") {
+ i++;
+ while (i < text.length) {
+ if (text[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ if (text[i] === "'") {
+ if (text[i + 1] === "'") {
+ i += 2;
+ continue;
+ }
+ break;
+ }
+ i++;
+ }
+ if (i >= text.length)
+ throw new Error('The query has an unclosed string literal.');
+ i++;
+ code += ' ? ';
+ lastSignificant = i - 1;
+ continue;
+ }
+ if (char === '"') {
+ const end = text.indexOf('"', i + 1);
+ if (end === -1)
+ throw new Error('The query has an unclosed quoted identifier.');
+ i = end + 1;
+ code += ' x ';
+ lastSignificant = i - 1;
+ continue;
+ }
+ if (char === '$' && next === '$') {
+ const end = text.indexOf('$$', i + 2);
+ if (end === -1) throw new Error('The query has an unclosed $$ string.');
+ i = end + 2;
+ code += ' ? ';
+ lastSignificant = i - 1;
+ continue;
+ }
+ if (char === ';') {
+ const rest = stripSqlTail(text.slice(i + 1));
+ if (rest !== '') {
+ throw new Error(
+ 'Only one statement is allowed; remove the extra statements after ";".'
+ );
+ }
+ return { code, body: text.slice(0, lastSignificant + 1).trim() };
+ }
+ if (!/\s/.test(char)) lastSignificant = i;
+ code += char;
+ i++;
+ }
+ return { code, body: text.slice(0, lastSignificant + 1).trim() };
+}
+
+function stripSqlTail(rest: string): string {
+ return rest
+ .replace(/--[^\n]*/g, '')
+ .replace(/\/\/[^\n]*/g, '')
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .replace(/[\s;]/g, '');
+}
+
+function filterValueList(value: unknown): unknown[] {
+ if (Array.isArray(value)) return value;
+ if (typeof value === 'string') {
+ const trimmed = value.trim();
+ if (trimmed.startsWith('[')) {
+ try {
+ const parsed: unknown = JSON.parse(trimmed);
+ if (Array.isArray(parsed)) return parsed;
+ } catch {
+ return trimmed.split(',').map((item) => item.trim());
+ }
+ }
+ return trimmed === '' ? [] : trimmed.split(',').map((item) => item.trim());
+ }
+ if (value === undefined || value === null) return [];
+ return [value];
+}
+
+function isFilterOperator(value: string): value is FilterOperator {
+ return FILTER_OPERATORS.some((operator) => operator === value);
+}
+
+const READ_ONLY_FIRST_WORDS = [
+ 'SELECT',
+ 'WITH',
+ 'SHOW',
+ 'DESCRIBE',
+ 'DESC',
+ 'EXPLAIN',
+];
+
+const BLOCKED_WORDS = new Set([
+ 'INSERT',
+ 'UPDATE',
+ 'DELETE',
+ 'MERGE',
+ 'CREATE',
+ 'DROP',
+ 'ALTER',
+ 'TRUNCATE',
+ 'GRANT',
+ 'REVOKE',
+ 'CALL',
+ 'COPY',
+ 'PUT',
+ 'REMOVE',
+ 'UNDROP',
+ 'USE',
+ 'EXECUTE',
+ 'BEGIN',
+ 'COMMIT',
+ 'ROLLBACK',
+ 'UNSET',
+]);
+
+export const FILTER_OPERATORS = [
+ '=',
+ '!=',
+ '<',
+ '<=',
+ '>',
+ '>=',
+ 'IN',
+ 'NOT IN',
+ 'LIKE',
+ 'ILIKE',
+ 'IS NULL',
+ 'IS NOT NULL',
+] as const;
+
+export type FilterOperator = (typeof FILTER_OPERATORS)[number];
+
+export type Filter = {
+ column: string;
+ operator: FilterOperator;
+ value: unknown;
+};
diff --git a/packages/pieces/community/snowflake/src/lib/common/stage.ts b/packages/pieces/community/snowflake/src/lib/common/stage.ts
new file mode 100644
index 00000000000..dfacdfca20d
--- /dev/null
+++ b/packages/pieces/community/snowflake/src/lib/common/stage.ts
@@ -0,0 +1,124 @@
+import { qualifiedName, sqlString } from './sql';
+
+export function stageReference({
+ stage: rawStage,
+ path: rawPath,
+}: {
+ stage: string;
+ path?: string | null;
+}): string {
+ let stage = String(rawStage ?? '').trim();
+ if (stage.startsWith('@')) stage = stage.slice(1);
+ let path = (rawPath ?? '').trim();
+ const slash = findPathStart(stage);
+ if (slash !== -1) {
+ const inlinePath = stage.slice(slash + 1);
+ stage = stage.slice(0, slash);
+ path =
+ path === ''
+ ? inlinePath
+ : `${inlinePath.replace(/\/+$/, '')}/${path.replace(/^\/+/, '')}`;
+ }
+ if (stage === '~' || stage.startsWith('%')) {
+ throw new Error(
+ 'User (@~) and table (@%) stages are not supported here; use a named stage.'
+ );
+ }
+ const name = qualifiedName({ value: stage, label: 'Stage' });
+ if (path === '') return `@${name}`;
+ if (!STAGE_PATH_CHARS.test(path) || path.includes('..')) {
+ throw new Error(
+ `Stage path "${path}" contains characters that are not allowed. Use letters, digits and - _ . / = + % ~ only.`
+ );
+ }
+ const reference = `@${name}/${path.replace(/^\/+/, '')}`;
+ return path.includes(' ') ? sqlString(reference) : reference;
+}
+
+function findPathStart(stage: string): number {
+ let inQuotes = false;
+ for (let i = 0; i < stage.length; i++) {
+ if (stage[i] === '"') inQuotes = !inQuotes;
+ if (stage[i] === '/' && !inQuotes) return i;
+ }
+ return -1;
+}
+
+export function buildCopyInto({
+ table,
+ stage,
+ fileFormat,
+ pattern,
+ skipHeader,
+ errorOnColumnCountMismatch,
+ onError,
+}: {
+ table: string;
+ stage: string;
+ fileFormat: string;
+ pattern?: string | null;
+ skipHeader?: number | null;
+ errorOnColumnCountMismatch?: boolean | null;
+ onError?: string | null;
+}): string {
+ const format = String(fileFormat ?? 'CSV').toUpperCase();
+ if (!FILE_FORMAT_TYPES.some((value) => value === format)) {
+ throw new Error(
+ `File format must be one of ${FILE_FORMAT_TYPES.join(', ')}.`
+ );
+ }
+ const errorMode = String(onError || 'ABORT_STATEMENT').toUpperCase();
+ if (!ON_ERROR_VALUES.some((value) => value === errorMode)) {
+ throw new Error(`On Error must be one of ${ON_ERROR_VALUES.join(', ')}.`);
+ }
+ let formatClause = `TYPE = '${format}'`;
+ if (
+ skipHeader !== undefined &&
+ skipHeader !== null &&
+ Number(skipHeader) !== 0
+ ) {
+ const rows = Number(skipHeader);
+ if (!Number.isInteger(rows) || rows < 0 || rows > 1000) {
+ throw new Error(
+ 'Skip Header Rows must be a whole number between 0 and 1000.'
+ );
+ }
+ if (format !== 'CSV') {
+ throw new Error('Skip Header Rows only applies to CSV files.');
+ }
+ formatClause += ` SKIP_HEADER = ${rows}`;
+ }
+ if (
+ errorOnColumnCountMismatch !== undefined &&
+ errorOnColumnCountMismatch !== null &&
+ format === 'CSV'
+ ) {
+ formatClause += ` ERROR_ON_COLUMN_COUNT_MISMATCH = ${
+ errorOnColumnCountMismatch ? 'TRUE' : 'FALSE'
+ }`;
+ }
+ let sql = `COPY INTO ${qualifiedName({
+ value: table,
+ label: 'Table',
+ })} FROM ${stage} FILE_FORMAT = (${formatClause})`;
+ if (pattern && pattern.trim() !== '')
+ sql += ` PATTERN = ${sqlString(pattern.trim())}`;
+ sql += ` ON_ERROR = '${errorMode}'`;
+ return sql;
+}
+
+export const FILE_FORMAT_TYPES = [
+ 'CSV',
+ 'JSON',
+ 'PARQUET',
+ 'AVRO',
+ 'ORC',
+ 'XML',
+] as const;
+export const ON_ERROR_VALUES = [
+ 'ABORT_STATEMENT',
+ 'CONTINUE',
+ 'SKIP_FILE',
+] as const;
+
+const STAGE_PATH_CHARS = /^[A-Za-z0-9_\-./=+%~ ]*$/;
diff --git a/packages/pieces/community/snowflake/src/lib/triggers/new-column.ts b/packages/pieces/community/snowflake/src/lib/triggers/new-column.ts
index 57848a6f454..0d435e8eee1 100644
--- a/packages/pieces/community/snowflake/src/lib/triggers/new-column.ts
+++ b/packages/pieces/community/snowflake/src/lib/triggers/new-column.ts
@@ -9,14 +9,9 @@ import {
pollingHelper,
} from '@activepieces/pieces-common';
import { snowflakeAuth } from '../auth';
-import {
- configureConnection,
- connect,
- destroy,
- execute,
- snowflakeCommonProps,
- SnowflakeAuthValue,
-} from '../common';
+import { snowflakeCommonProps, toAuthValue, withSnowflake } from '../common';
+import { newColumnOutputSchema } from '../common/output-schemas';
+import { qualifiedName } from '../common/sql';
type NewColumnProps = {
database: string;
@@ -39,18 +34,25 @@ const polling: Polling<
const { table } = propsValue;
if (!table) return [];
- const connection = configureConnection(auth as SnowflakeAuthValue);
- await connect(connection);
- try {
- const result = await execute(connection, `DESCRIBE TABLE ${table}`, []);
-
- if (!result) return [];
+ {
+ const result = (
+ await withSnowflake({
+ auth: toAuthValue(auth),
+ fn: (session) =>
+ session.query({
+ sql: `DESCRIBE TABLE ${qualifiedName({
+ value: table,
+ label: 'Table',
+ })}`,
+ }),
+ })
+ ).rows;
// Columns are returned in ordinal-position order (lowest first).
// New columns are always appended at the end → highest index = newest.
// Reverse so that LAST_ITEM deduplication stores the newest column's id
// and emits only columns added after that position on subsequent polls.
- return (result as Record<string, unknown>[])
+ return result
.map((col, index) => ({
id: index + 1,
data: {
@@ -66,8 +68,6 @@ const polling: Polling<
},
}))
.reverse();
- } finally {
- await destroy(connection);
}
},
};
@@ -78,6 +78,8 @@ export const newColumnTrigger = createTrigger({
displayName: 'New Column',
description:
'Triggers when a new column is added to the selected table. Checked by polling every few minutes.',
+ classification: 'READ',
+ outputSchema: newColumnOutputSchema,
aiMetadata: {
description:
"Fires when a new column is added to the selected Snowflake table, detected by polling the table's column list and emitting columns appended since the last check. Each newly added column produces one event with its name, data type, and constraints.",
diff --git a/packages/pieces/community/snowflake/src/lib/triggers/new-or-updated-row.ts b/packages/pieces/community/snowflake/src/lib/triggers/new-or-updated-row.ts
index da951fa0f23..a1eef281da8 100644
--- a/packages/pieces/community/snowflake/src/lib/triggers/new-or-updated-row.ts
+++ b/packages/pieces/community/snowflake/src/lib/triggers/new-or-updated-row.ts
@@ -2,30 +2,20 @@ import {
createTrigger,
TriggerStrategy,
Property,
- AppConnectionValueForAuthProperty,
} from '@activepieces/pieces-framework';
-import {
- DedupeStrategy,
- Polling,
- pollingHelper,
-} from '@activepieces/pieces-common';
import { snowflakeAuth } from '../auth';
import {
- configureConnection,
- connect,
- destroy,
- execute,
getTableColumnOptions,
snowflakeCommonProps,
- SnowflakeAuthValue,
+ toAuthValue,
} from '../common';
-
-type NewOrUpdatedRowProps = {
- database: string;
- schema: string;
- table: string;
- updated_at_column: string;
-};
+import { rowTriggerOutputSchema } from '../common/output-schemas';
+import {
+ fetchBaseline,
+ fetchLatestRows,
+ fetchNewRows,
+ ROW_CURSOR_STORE_KEY,
+} from '../common/row-poll';
const props = {
database: snowflakeCommonProps.database,
@@ -35,9 +25,7 @@ const props = {
auth: snowflakeAuth,
displayName: 'Updated At Column',
description:
- 'Select the column that stores when each row was last modified (e.g. `UPDATED_AT`, `LAST_MODIFIED_TIME`). ' +
- 'Both new rows and rows updated after the last check will fire the trigger. ' +
- 'The column must be updated by your application or a DEFAULT clause every time a row changes.',
+ 'Select the column that stores when each row was last modified (e.g. `UPDATED_AT`, `LAST_MODIFIED_TIME`). Both new rows and rows updated after the last check will fire the trigger. The column must be updated by your application or a DEFAULT clause every time a row changes.',
refreshers: ['table'],
required: true,
options: async ({ auth, table }) => {
@@ -55,60 +43,28 @@ const props = {
placeholder: 'Please select a table first',
};
}
- return getTableColumnOptions(auth as SnowflakeAuthValue, table as string);
+ return getTableColumnOptions({
+ auth: toAuthValue(auth),
+ table: String(table),
+ });
},
}),
};
-function toEpochMs(value: unknown): number {
- if (value instanceof Date) return value.getTime();
- if (typeof value === 'string') return new Date(value).getTime();
- return 0;
-}
-
-const polling: Polling<
- AppConnectionValueForAuthProperty<typeof snowflakeAuth>,
- NewOrUpdatedRowProps
-> = {
- strategy: DedupeStrategy.TIMEBASED,
- items: async ({ auth, propsValue }) => {
- const { table, updated_at_column } = propsValue;
- if (!table || !updated_at_column) return [];
-
- const connection = configureConnection(auth as SnowflakeAuthValue);
- await connect(connection);
- try {
- // Fetch the 100 most-recently modified rows. pollingHelper keeps only
- // rows whose timestamp exceeds the last stored watermark.
- const result = await execute(
- connection,
- `SELECT * FROM ${table} ORDER BY ${updated_at_column} DESC LIMIT 100`,
- []
- );
-
- if (!result) return [];
-
- return (result as Record<string, unknown>[]).map((row) => ({
- epochMilliSeconds: toEpochMs(row[updated_at_column]),
- data: row,
- }));
- } finally {
- await destroy(connection);
- }
- },
-};
-
export const newOrUpdatedRowTrigger = createTrigger({
auth: snowflakeAuth,
name: 'new_or_updated_row',
+ classification: 'READ',
displayName: 'New or Updated Row',
description:
'Triggers when a row is inserted or updated in the selected table. Uses an "updated at" timestamp column you choose — any row whose timestamp is newer than the last check will fire the trigger.',
aiMetadata: {
description:
- 'Fires for each row that is inserted or modified in the selected Snowflake table, detected by polling a chosen "updated at" timestamp column against the last-seen watermark. Relies on that column being refreshed on every change (by the application or a DEFAULT clause); a row whose timestamp does not advance on update will not fire.',
+ 'Fires once per row whose chosen "updated at" timestamp moved past the newest one already seen (inserts and updates alike), oldest first, up to 1000 rows per poll (all rows sharing one exact timestamp are sent together, up to 10,000). The column must be refreshed on every change; a row updated without advancing it does not fire.',
},
+ outputSchema: rowTriggerOutputSchema,
props,
+
sampleData: {
ID: 1001,
NAME: 'Jane Doe',
@@ -117,15 +73,56 @@ export const newOrUpdatedRowTrigger = createTrigger({
},
type: TriggerStrategy.POLLING,
async test(context) {
- return await pollingHelper.test(polling, context);
+ const { table, updated_at_column } = context.propsValue;
+ return fetchLatestRows({
+ auth: toAuthValue(context.auth),
+ table,
+ column: updated_at_column,
+ limit: 5,
+ });
},
async onEnable(context) {
- await pollingHelper.onEnable(polling, context);
+ if (
+ context.isRepublish &&
+ (await context.store.get(ROW_CURSOR_STORE_KEY))
+ ) {
+ return;
+ }
+ const { table, updated_at_column } = context.propsValue;
+ const cursor = await fetchBaseline({
+ auth: toAuthValue(context.auth),
+ table,
+ column: updated_at_column,
+ });
+ await context.store.put(ROW_CURSOR_STORE_KEY, { cursor });
},
- async onDisable(context) {
- await pollingHelper.onDisable(polling, context);
+ async onDisable() {
+ return;
},
async run(context) {
- return await pollingHelper.poll(polling, context);
+ const { table, updated_at_column } = context.propsValue;
+ const auth = toAuthValue(context.auth);
+ const stored = await context.store.get<{ cursor: string | null }>(
+ ROW_CURSOR_STORE_KEY
+ );
+ if (!stored) {
+ const cursor = await fetchBaseline({
+ auth,
+ table,
+ column: updated_at_column,
+ });
+ await context.store.put(ROW_CURSOR_STORE_KEY, { cursor });
+ return [];
+ }
+ const page = await fetchNewRows({
+ auth,
+ table,
+ column: updated_at_column,
+ after: stored.cursor,
+ });
+ if (page.rows.length > 0) {
+ await context.store.put(ROW_CURSOR_STORE_KEY, { cursor: page.cursor });
+ }
+ return page.rows;
},
});
diff --git a/packages/pieces/community/snowflake/src/lib/triggers/new-row.ts b/packages/pieces/community/snowflake/src/lib/triggers/new-row.ts
index eaa837fe62f..3dcf761c924 100644
--- a/packages/pieces/community/snowflake/src/lib/triggers/new-row.ts
+++ b/packages/pieces/community/snowflake/src/lib/triggers/new-row.ts
@@ -2,30 +2,20 @@ import {
createTrigger,
TriggerStrategy,
Property,
- AppConnectionValueForAuthProperty,
} from '@activepieces/pieces-framework';
-import {
- DedupeStrategy,
- Polling,
- pollingHelper,
-} from '@activepieces/pieces-common';
import { snowflakeAuth } from '../auth';
import {
- configureConnection,
- connect,
- destroy,
- execute,
getTableColumnOptions,
snowflakeCommonProps,
- SnowflakeAuthValue,
+ toAuthValue,
} from '../common';
-
-type NewRowProps = {
- database: string;
- schema: string;
- table: string;
- created_at_column: string;
-};
+import { rowTriggerOutputSchema } from '../common/output-schemas';
+import {
+ fetchBaseline,
+ fetchLatestRows,
+ fetchNewRows,
+ ROW_CURSOR_STORE_KEY,
+} from '../common/row-poll';
const props = {
database: snowflakeCommonProps.database,
@@ -35,8 +25,7 @@ const props = {
auth: snowflakeAuth,
displayName: 'Created At Column',
description:
- 'Select the column that stores when each row was inserted (e.g. `CREATED_AT`, `INSERT_TIME`). ' +
- 'Only rows with a timestamp in this column newer than the last check will fire the trigger.',
+ 'Select the column that stores when each row was inserted (e.g. `CREATED_AT`, `INSERT_TIME`). Only rows with a timestamp in this column newer than the last check will fire the trigger.',
refreshers: ['table'],
required: true,
options: async ({ auth, table }) => {
@@ -54,60 +43,28 @@ const props = {
placeholder: 'Please select a table first',
};
}
- return getTableColumnOptions(auth as SnowflakeAuthValue, table as string);
+ return getTableColumnOptions({
+ auth: toAuthValue(auth),
+ table: String(table),
+ });
},
}),
};
-function toEpochMs(value: unknown): number {
- if (value instanceof Date) return value.getTime();
- if (typeof value === 'string') return new Date(value).getTime();
- return 0;
-}
-
-const polling: Polling<
- AppConnectionValueForAuthProperty<typeof snowflakeAuth>,
- NewRowProps
-> = {
- strategy: DedupeStrategy.TIMEBASED,
- items: async ({ auth, propsValue }) => {
- const { table, created_at_column } = propsValue;
- if (!table || !created_at_column) return [];
-
- const connection = configureConnection(auth as SnowflakeAuthValue);
- await connect(connection);
- try {
- // Fetch the 100 most-recently inserted rows. pollingHelper keeps only
- // rows whose timestamp exceeds the last stored watermark.
- const result = await execute(
- connection,
- `SELECT * FROM ${table} ORDER BY ${created_at_column} DESC LIMIT 100`,
- []
- );
-
- if (!result) return [];
-
- return (result as Record<string, unknown>[]).map((row) => ({
- epochMilliSeconds: toEpochMs(row[created_at_column]),
- data: row,
- }));
- } finally {
- await destroy(connection);
- }
- },
-};
-
export const newRowTrigger = createTrigger({
auth: snowflakeAuth,
name: 'new_row',
+ classification: 'READ',
displayName: 'New Row',
description:
'Triggers when a new row is inserted into the selected table. Uses a timestamp column you choose to detect rows added since the last check.',
aiMetadata: {
description:
- 'Fires for each newly inserted row in the selected Snowflake table, detected by polling and comparing a chosen "created at" timestamp column against the last-seen watermark. Each new row whose timestamp is later than the previous poll produces one event.',
+ 'Fires once per row whose chosen "created at" timestamp is later than the newest one already seen, oldest first, up to 1000 rows per poll (all rows sharing one exact timestamp are sent together, up to 10,000) (the rest follow on the next poll). Rows with an empty timestamp, or inserted with a timestamp older than the last seen one, never fire.',
},
+ outputSchema: rowTriggerOutputSchema,
props,
+
sampleData: {
ID: 1001,
NAME: 'Jane Doe',
@@ -116,15 +73,56 @@ export const newRowTrigger = createTrigger({
},
type: TriggerStrategy.POLLING,
async test(context) {
- return await pollingHelper.test(polling, context);
+ const { table, created_at_column } = context.propsValue;
+ return fetchLatestRows({
+ auth: toAuthValue(context.auth),
+ table,
+ column: created_at_column,
+ limit: 5,
+ });
},
async onEnable(context) {
- await pollingHelper.onEnable(polling, context);
+ if (
+ context.isRepublish &&
+ (await context.store.get(ROW_CURSOR_STORE_KEY))
+ ) {
+ return;
+ }
+ const { table, created_at_column } = context.propsValue;
+ const cursor = await fetchBaseline({
+ auth: toAuthValue(context.auth),
+ table,
+ column: created_at_column,
+ });
+ await context.store.put(ROW_CURSOR_STORE_KEY, { cursor });
},
- async onDisable(context) {
- await pollingHelper.onDisable(polling, context);
+ async onDisable() {
+ return;
},
async run(context) {
- return await pollingHelper.poll(polling, context);
+ const { table, created_at_column } = context.propsValue;
+ const auth = toAuthValue(context.auth);
+ const stored = await context.store.get<{ cursor: string | null }>(
+ ROW_CURSOR_STORE_KEY
+ );
+ if (!stored) {
+ const cursor = await fetchBaseline({
+ auth,
+ table,
+ column: created_at_column,
+ });
+ await context.store.put(ROW_CURSOR_STORE_KEY, { cursor });
+ return [];
+ }
+ const page = await fetchNewRows({
+ auth,
+ table,
+ column: created_at_column,
+ after: stored.cursor,
+ });
+ if (page.rows.length > 0) {
+ await context.store.put(ROW_CURSOR_STORE_KEY, { cursor: page.cursor });
+ }
+ return page.rows;
},
});
diff --git a/packages/pieces/community/snowflake/src/lib/triggers/new-table.ts b/packages/pieces/community/snowflake/src/lib/triggers/new-table.ts
index 9e90f6973fa..64448a62b93 100644
--- a/packages/pieces/community/snowflake/src/lib/triggers/new-table.ts
+++ b/packages/pieces/community/snowflake/src/lib/triggers/new-table.ts
@@ -9,14 +9,10 @@ import {
pollingHelper,
} from '@activepieces/pieces-common';
import { snowflakeAuth } from '../auth';
-import {
- configureConnection,
- connect,
- destroy,
- execute,
- snowflakeCommonProps,
- SnowflakeAuthValue,
-} from '../common';
+import { snowflakeCommonProps, toAuthValue, withSnowflake } from '../common';
+import { newTableOutputSchema } from '../common/output-schemas';
+import { qualifiedName } from '../common/sql';
+import { mapTable } from '../common/mappers';
type NewTableProps = {
database: string;
@@ -43,33 +39,25 @@ const polling: Polling<
const { database, schema } = propsValue;
if (!database || !schema) return [];
- const connection = configureConnection(auth as SnowflakeAuthValue);
- await connect(connection);
- try {
- const result = await execute(
- connection,
- `SHOW TABLES IN SCHEMA ${database}.${schema}`,
- []
- );
-
- if (!result) return [];
+ {
+ const result = (
+ await withSnowflake({
+ auth: toAuthValue(auth),
+ fn: (session) =>
+ session.query({
+ sql: `SHOW TABLES IN SCHEMA ${qualifiedName({
+ value: `${database}.${schema}`,
+ maxParts: 2,
+ label: 'Schema',
+ })}`,
+ }),
+ })
+ ).rows;
- return (result as Record<string, unknown>[]).map((table) => ({
+ return result.map((table) => ({
epochMilliSeconds: toEpochMs(table['created_on']),
- data: {
- table_name: table['name'],
- database_name: table['database_name'],
- schema_name: table['schema_name'],
- kind: table['kind'],
- rows: table['rows'],
- bytes: table['bytes'],
- owner: table['owner'],
- comment: table['comment'],
- created_on: table['created_on'],
- },
+ data: mapTable(table),
}));
- } finally {
- await destroy(connection);
}
},
};
@@ -80,6 +68,8 @@ export const newTableTrigger = createTrigger({
displayName: 'New Table',
description:
'Triggers when a new table is created in the selected schema. Checked by polling every few minutes.',
+ classification: 'READ',
+ outputSchema: newTableOutputSchema,
aiMetadata: {
description:
"Fires when a new table is created in the selected Snowflake database and schema, detected by polling and comparing each table's creation time against the last-seen watermark. Each newly created table produces one event with its name, kind, owner, and metadata.",
diff --git a/packages/pieces/community/snowflake/src/lib/triggers/new-view.ts b/packages/pieces/community/snowflake/src/lib/triggers/new-view.ts
index e9d0b09b398..cf8e4aa1dcd 100644
--- a/packages/pieces/community/snowflake/src/lib/triggers/new-view.ts
+++ b/packages/pieces/community/snowflake/src/lib/triggers/new-view.ts
@@ -9,14 +9,10 @@ import {
pollingHelper,
} from '@activepieces/pieces-common';
import { snowflakeAuth } from '../auth';
-import {
- configureConnection,
- connect,
- destroy,
- execute,
- snowflakeCommonProps,
- SnowflakeAuthValue,
-} from '../common';
+import { snowflakeCommonProps, toAuthValue, withSnowflake } from '../common';
+import { newViewOutputSchema } from '../common/output-schemas';
+import { qualifiedName } from '../common/sql';
+import { mapView } from '../common/mappers';
type NewViewProps = {
database: string;
@@ -43,33 +39,25 @@ const polling: Polling<
const { database, schema } = propsValue;
if (!database || !schema) return [];
- const connection = configureConnection(auth as SnowflakeAuthValue);
- await connect(connection);
- try {
- const result = await execute(
- connection,
- `SHOW VIEWS IN SCHEMA ${database}.${schema}`,
- []
- );
-
- if (!result) return [];
+ {
+ const result = (
+ await withSnowflake({
+ auth: toAuthValue(auth),
+ fn: (session) =>
+ session.query({
+ sql: `SHOW VIEWS IN SCHEMA ${qualifiedName({
+ value: `${database}.${schema}`,
+ maxParts: 2,
+ label: 'Schema',
+ })}`,
+ }),
+ })
+ ).rows;
- return (result as Record<string, unknown>[]).map((view) => ({
+ return result.map((view) => ({
epochMilliSeconds: toEpochMs(view['created_on']),
- data: {
- view_name: view['name'],
- database_name: view['database_name'],
- schema_name: view['schema_name'],
- owner: view['owner'],
- comment: view['comment'],
- text: view['text'],
- is_secure: view['is_secure'],
- is_materialized: view['is_materialized'],
- created_on: view['created_on'],
- },
+ data: mapView(view),
}));
- } finally {
- await destroy(connection);
}
},
};
@@ -80,6 +68,8 @@ export const newViewTrigger = createTrigger({
displayName: 'New View',
description:
'Triggers when a new view is created in the selected schema. Checked by polling every few minutes.',
+ classification: 'READ',
+ outputSchema: newViewOutputSchema,
aiMetadata: {
description:
"Fires when a new view is created in the selected Snowflake database and schema, detected by polling and comparing each view's creation time against the last-seen watermark. Each newly created view produces one event with its name, owner, definition text, and metadata.",
diff --git a/packages/pieces/community/snowflake/test/actions-ai.test.ts b/packages/pieces/community/snowflake/test/actions-ai.test.ts
new file mode 100644
index 00000000000..3f6f057ed58
--- /dev/null
+++ b/packages/pieces/community/snowflake/test/actions-ai.test.ts
@@ -0,0 +1,284 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { lastCall, resetSnowflake, respond, runAction, state, userCalls } from './helpers';
+
+vi.mock('snowflake-sdk', async () => (await import('./helpers')).fakeSdk);
+
+import { runSelectQueryAction } from '../src/lib/actions/ai/run-select-query';
+import { explainQueryAction } from '../src/lib/actions/ai/explain-query';
+import { getQueryStatusAction } from '../src/lib/actions/ai/get-query-status';
+import { cancelQueryAction } from '../src/lib/actions/ai/cancel-query';
+import { listQueryHistoryAction } from '../src/lib/actions/ai/list-query-history';
+import { findRowsAction } from '../src/lib/actions/ai/find-rows';
+import { countRowsAction } from '../src/lib/actions/ai/count-rows';
+import { getRowByKeyAction } from '../src/lib/actions/ai/get-row-by-key';
+import { insertRowJsonAction } from '../src/lib/actions/ai/insert-row-json';
+import { insertRowsJsonAction } from '../src/lib/actions/ai/insert-rows-json';
+import { upsertRowByKeyAction } from '../src/lib/actions/ai/upsert-row-by-key';
+import { updateRowByKeyAction } from '../src/lib/actions/ai/update-row-by-key';
+import { updateRowsByFilterAction } from '../src/lib/actions/ai/update-rows-by-filter';
+import { deleteRowByKeyAction } from '../src/lib/actions/ai/delete-row-by-key';
+import { deleteRowsByFilterAction } from '../src/lib/actions/ai/delete-rows-by-filter';
+import { listDatabasesAction } from '../src/lib/actions/ai/list-databases';
+import { listSchemasAction } from '../src/lib/actions/ai/list-schemas';
+import { listTablesAiAction } from '../src/lib/actions/ai/list-tables-ai';
+import { listViewsAction } from '../src/lib/actions/ai/list-views';
+import { getViewDefinitionAction } from '../src/lib/actions/ai/get-view-definition';
+import { describeTableAction } from '../src/lib/actions/ai/describe-table';
+import { listColumnsAction } from '../src/lib/actions/ai/list-columns';
+import { listWarehousesAction } from '../src/lib/actions/ai/list-warehouses';
+import { listStagesAction } from '../src/lib/actions/ai/list-stages';
+import { listStageFilesAction } from '../src/lib/actions/ai/list-stage-files';
+import { copyStageIntoTableAction } from '../src/lib/actions/ai/copy-stage-into-table';
+import { listProceduresAction } from '../src/lib/actions/ai/list-procedures';
+import { callProcedureAction } from '../src/lib/actions/ai/call-procedure';
+import { getCurrentSessionAction } from '../src/lib/actions/ai/get-current-session';
+import { listRolesAction } from '../src/lib/actions/ai/list-roles';
+
+const QID = '01b2c3d4-0000-1234-0000-0001a2b3c4d5';
+
+beforeEach(() => resetSnowflake());
+
+describe('query actions', () => {
+ it('run_select_query runs one read-only statement with a row cap', async () => {
+ respond({ match: /SELECT/, rows: [{ A: 1 }, { A: 2 }, { A: 3 }] });
+ const out = await runAction({ action: runSelectQueryAction, propsValue: { sql: 'SELECT A FROM T WHERE B = ?;', parameters: ['x'], limit: 2 } });
+ expect(lastCall()).toEqual({ sql: 'SELECT A FROM T WHERE B = ?', binds: ['x'] });
+ expect(out).toMatchObject({ rows: [{ A: 1 }, { A: 2 }], rowCount: 2, totalRows: 3, truncated: true, queryId: QID, columns: ['A'] });
+ await expect(runAction({ action: runSelectQueryAction, propsValue: { sql: 'DROP TABLE T' } })).rejects.toThrow('read-only');
+ await expect(runAction({ action: runSelectQueryAction, propsValue: { sql: 'SELECT 1', limit: 5000 } })).rejects.toThrow('Limit');
+ });
+
+ it('explain_query parses the JSON plan', async () => {
+ respond({ match: /EXPLAIN/, rows: [{ content: '{"GlobalStats":{"partitionsTotal":3}}' }] });
+ const out = await runAction({ action: explainQueryAction, propsValue: { sql: 'SELECT * FROM T' } });
+ expect(lastCall().sql).toBe('EXPLAIN USING JSON SELECT * FROM T');
+ expect(out).toEqual({ plan: { GlobalStats: { partitionsTotal: 3 } } });
+ await expect(runAction({ action: explainQueryAction, propsValue: { sql: 'SHOW TABLES' } })).rejects.toThrow('SELECT or WITH');
+ });
+
+ it('explain_query accepts queries with leading comments', async () => {
+ respond({ match: /EXPLAIN/, rows: [{ content: '{}' }] });
+ await runAction({ action: explainQueryAction, propsValue: { sql: '-- daily report\n/* v2 */ SELECT 1' } });
+ expect(lastCall().sql).toBe('EXPLAIN USING JSON -- daily report\n/* v2 */ SELECT 1');
+ });
+
+ it('get_query_status returns status and optional rows', async () => {
+ respond({ match: /RESULT_SCAN/, rows: [{ A: 1 }] });
+ const out = await runAction({ action: getQueryStatusAction, propsValue: { queryId: QID, includeResults: true } });
+ expect(out).toMatchObject({ queryId: QID, status: 'SUCCESS', isRunning: false, isError: false, rows: [{ A: 1 }], rowCount: 1 });
+ expect(lastCall()).toEqual({ sql: 'SELECT * FROM TABLE(RESULT_SCAN(?))', binds: [QID] });
+ state.queryStatus = 'RUNNING';
+ resetSnowflake();
+ state.queryStatus = 'RUNNING';
+ expect(await runAction({ action: getQueryStatusAction, propsValue: { queryId: QID, includeResults: true } })).toMatchObject({ isRunning: true, rows: [] });
+ await expect(runAction({ action: getQueryStatusAction, propsValue: { queryId: "x'; --" } })).rejects.toThrow('UUID');
+ });
+
+ it('cancel_query binds the query id', async () => {
+ respond({ match: /CANCEL/, rows: [{ message: 'query [x] terminated.' }] });
+ expect(await runAction({ action: cancelQueryAction, propsValue: { queryId: QID } })).toEqual({ queryId: QID, message: 'query [x] terminated.' });
+ expect(lastCall()).toEqual({ sql: 'SELECT SYSTEM$CANCEL_QUERY(?) AS "message"', binds: [QID] });
+ });
+
+ it('list_query_history filters by status', async () => {
+ respond({ match: /QUERY_HISTORY/, rows: [{ QUERY_ID: QID, EXECUTION_STATUS: 'FAILED_WITH_ERROR' }] });
+ const out = await runAction({ action: listQueryHistoryAction, propsValue: { database: 'DB', status: 'FAILED_WITH_ERROR', limit: 10 } });
+ expect(lastCall().sql).toContain('FROM TABLE(DB.INFORMATION_SCHEMA.QUERY_HISTORY(RESULT_LIMIT => ?)) WHERE EXECUTION_STATUS = ? ORDER BY START_TIME DESC LIMIT 10');
+ expect(lastCall().binds).toEqual([10000, 'FAILED_WITH_ERROR']);
+ expect(out).toMatchObject({ items: [{ query_id: QID, execution_status: 'FAILED_WITH_ERROR' }], count: 1 });
+ await expect(runAction({ action: listQueryHistoryAction, propsValue: { status: 'X' } })).rejects.toThrow('Status');
+ });
+});
+
+describe('row actions', () => {
+ it('find_rows uses bound filters, sort and paging', async () => {
+ respond({ match: /SELECT/, rows: [{ ID: 1 }, { ID: 2 }, { ID: 3 }] });
+ const out = await runAction({ action: findRowsAction, propsValue: {
+ table: 'DB.PUBLIC.ORDERS',
+ filters: [{ column: 'STATUS', operator: '=', value: 'open' }],
+ columns: ['ID'],
+ sort: [{ column: 'ID', direction: 'DESC' }],
+ limit: 2,
+ offset: 4,
+ } });
+ expect(lastCall()).toEqual({ sql: 'SELECT ID FROM DB.PUBLIC.ORDERS WHERE STATUS = ? ORDER BY ID DESC LIMIT 3 OFFSET 4', binds: ['open'] });
+ expect(out).toEqual({ rows: [{ ID: 1 }, { ID: 2 }], rowCount: 2, hasMore: true, nextOffset: 6 });
+ });
+
+ it('count_rows counts with filters', async () => {
+ respond({ match: /COUNT/, rows: [{ count: 42 }] });
+ expect(await runAction({ action: countRowsAction, propsValue: { table: 'T', filters: [{ column: 'A', operator: '>', value: '1' }] } })).toEqual({ count: 42 });
+ expect(lastCall()).toEqual({ sql: 'SELECT COUNT(*) AS "count" FROM T WHERE A > ?', binds: ['1'] });
+ });
+
+ it('get_row_by_key returns found/row and refuses non-unique keys', async () => {
+ respond({ match: /SELECT/, rows: [{ ID: 1 }] });
+ expect(await runAction({ action: getRowByKeyAction, propsValue: { table: 'T', keyColumn: 'ID', keyValue: '1' } })).toEqual({ found: true, row: { ID: 1 } });
+ resetSnowflake();
+ expect(await runAction({ action: getRowByKeyAction, propsValue: { table: 'T', keyColumn: 'ID', keyValue: '1' } })).toEqual({ found: false, row: null });
+ respond({ match: /SELECT/, rows: [{ ID: 1 }, { ID: 1 }] });
+ await expect(runAction({ action: getRowByKeyAction, propsValue: { table: 'T', keyColumn: 'ID', keyValue: '1' } })).rejects.toThrow('not a unique key');
+ });
+
+ it('insert_row_json inserts one row with JSON values', async () => {
+ respond({ match: /INSERT/, rows: [{ 'number of rows inserted': 1 }] });
+ const out = await runAction({ action: insertRowJsonAction, propsValue: { table: 'T', row: { ID: 1, TAGS: ['a'] } } });
+ expect(lastCall()).toEqual({ sql: 'INSERT INTO T (ID, TAGS) SELECT ?, PARSE_JSON(?)', binds: [1, '["a"]'] });
+ expect(out).toEqual({ rowsInserted: 1, queryId: QID });
+ await expect(runAction({ action: insertRowJsonAction, propsValue: { table: 'T', row: '[1]' } })).rejects.toThrow('JSON object');
+ });
+
+ it('insert_rows_json enforces the batch size', async () => {
+ respond({ match: /INSERT/, rows: [{ 'number of rows inserted': 2 }] });
+ expect(await runAction({ action: insertRowsJsonAction, propsValue: { table: 'T', rows: [{ A: 1 }, { A: 2 }] } })).toMatchObject({ rowsInserted: 2 });
+ expect(lastCall()).toEqual({ sql: 'INSERT INTO T (A) VALUES (?), (?)', binds: [1, 2] });
+ await expect(runAction({ action: insertRowsJsonAction, propsValue: { table: 'T', rows: [] } })).rejects.toThrow('between 1 and 500');
+ });
+
+ it('upsert_row_by_key merges on key columns', async () => {
+ respond({ match: /MERGE/, rows: [{ 'number of rows inserted': 1, 'number of rows updated': 0 }] });
+ const out = await runAction({ action: upsertRowByKeyAction, propsValue: { table: 'T', keyColumns: ['ID'], row: { ID: 1, NAME: 'x' } } });
+ expect(lastCall().sql).toContain('ON target.ID = source.C0');
+ expect(out).toEqual({ rowsInserted: 1, rowsUpdated: 0, queryId: QID });
+ });
+
+ it('upsert_row_by_key rejects null key values so retries cannot duplicate', async () => {
+ await expect(runAction({ action: upsertRowByKeyAction, propsValue: { table: 'T', keyColumns: ['ID'], row: { ID: null, NAME: 'Alice' } } })).rejects.toThrow('must have a value');
+ expect(userCalls().some((call) => call.sql.includes('MERGE'))).toBe(false);
+ });
+
+ it('update_row_by_key runs in a transaction and rolls back on duplicates', async () => {
+ respond({ match: /UPDATE/, rows: [{ 'number of rows updated': 1 }] });
+ expect(await runAction({ action: updateRowByKeyAction, propsValue: { table: 'T', keyColumn: 'ID', keyValue: '1', values: { S: 'x' } } })).toEqual({ found: true, rowsAffected: 1 });
+ expect(userCalls().map((c) => c.sql)).toEqual(['BEGIN', 'UPDATE T SET S = ? WHERE ID = ?', 'COMMIT']);
+ expect(userCalls()[1].binds).toEqual(['x', '1']);
+ resetSnowflake();
+ respond({ match: /UPDATE/, rows: [{ 'number of rows updated': 2 }] });
+ await expect(runAction({ action: updateRowByKeyAction, propsValue: { table: 'T', keyColumn: 'ID', keyValue: '1', values: { S: 'x' } } })).rejects.toThrow('not a unique key');
+ expect(userCalls().map((c) => c.sql)).toEqual(['BEGIN', 'UPDATE T SET S = ? WHERE ID = ?', 'ROLLBACK']);
+ });
+
+ it('update_rows_by_filter requires a filter and respects Max Rows', async () => {
+ await expect(runAction({ action: updateRowsByFilterAction, propsValue: { table: 'T', filters: [], values: { S: 1 } } })).rejects.toThrow('at least one filter');
+ respond({ match: /UPDATE/, rows: [{ 'number of rows updated': 5 }] });
+ await expect(
+ runAction({ action: updateRowsByFilterAction, propsValue: { table: 'T', filters: [{ column: 'A', operator: '=', value: '1' }], values: { S: 1 }, maxRows: 4 } })
+ ).rejects.toThrow('more than Max Rows (4)');
+ expect(userCalls().at(-1)?.sql).toBe('ROLLBACK');
+ resetSnowflake();
+ respond({ match: /UPDATE/, rows: [{ 'number of rows updated': 5 }] });
+ expect(await runAction({ action: updateRowsByFilterAction, propsValue: { table: 'T', filters: [{ column: 'A', operator: '=', value: '1' }], values: { S: 1 } } })).toEqual({ rowsAffected: 5 });
+ expect(userCalls()[1]).toEqual({ sql: 'UPDATE T SET S = ? WHERE A = ?', binds: [1, '1'] });
+ });
+
+ it('delete_row_by_key reports alreadyDeleted', async () => {
+ respond({ match: /DELETE/, rows: [{ 'number of rows deleted': 0 }] });
+ expect(await runAction({ action: deleteRowByKeyAction, propsValue: { table: 'T', keyColumn: 'ID', keyValue: '9' } })).toEqual({ deleted: false, alreadyDeleted: true });
+ expect(userCalls()[1]).toEqual({ sql: 'DELETE FROM T WHERE ID = ?', binds: ['9'] });
+ });
+
+ it('delete_rows_by_filter guards row count', async () => {
+ await expect(runAction({ action: deleteRowsByFilterAction, propsValue: { table: 'T' } })).rejects.toThrow('at least one filter');
+ respond({ match: /DELETE/, rows: [{ 'number of rows deleted': 3 }] });
+ expect(await runAction({ action: deleteRowsByFilterAction, propsValue: { table: 'T', filters: [{ column: 'A', operator: 'IS NULL' }] } })).toEqual({ rowsDeleted: 3 });
+ expect(userCalls().map((c) => c.sql)).toEqual(['BEGIN', 'DELETE FROM T WHERE A IS NULL', 'COMMIT']);
+ });
+});
+
+describe('catalog actions', () => {
+ it('list_databases applies LIKE and the limit', async () => {
+ respond({ match: /SHOW DATABASES/, rows: [{ name: 'A' }, { name: 'B' }] });
+ const out = await runAction({ action: listDatabasesAction, propsValue: { namePattern: "%it's%", limit: 1 } });
+ expect(lastCall().sql).toBe("SHOW DATABASES LIKE '%it''s%'");
+ expect(out).toMatchObject({ items: [{ name: 'A' }], count: 1, truncated: true });
+ });
+
+ it('list_schemas scopes to a database', async () => {
+ await runAction({ action: listSchemasAction, propsValue: { database: 'DB' } });
+ expect(lastCall().sql).toBe('SHOW SCHEMAS IN DATABASE DB');
+ });
+
+ it('list_tables_ai scopes to a schema', async () => {
+ respond({ match: /SHOW TABLES/, rows: [{ name: 'ORDERS' }] });
+ const out = await runAction({ action: listTablesAiAction, propsValue: { database: 'DB', schema: 'PUBLIC' } });
+ expect(lastCall().sql).toBe('SHOW TABLES IN SCHEMA DB.PUBLIC');
+ expect(out).toMatchObject({ items: [{ table_name: 'ORDERS' }] });
+ });
+
+ it('list_views accepts a qualified schema', async () => {
+ respond({ match: /SHOW VIEWS/, rows: [{ name: 'V' }] });
+ expect(await runAction({ action: listViewsAction, propsValue: { schema: 'DB.PUBLIC' } })).toMatchObject({ items: [{ view_name: 'V' }] });
+ expect(lastCall().sql).toBe('SHOW VIEWS IN SCHEMA DB.PUBLIC');
+ });
+
+ it('get_view_definition binds the view name', async () => {
+ respond({ match: /GET_DDL/, rows: [{ ddl: 'create view V as select 1;' }] });
+ expect(await runAction({ action: getViewDefinitionAction, propsValue: { view: 'db.public.v' } })).toEqual({ view: 'db.public.v', ddl: 'create view V as select 1;' });
+ expect(lastCall().binds).toEqual(['db.public.v']);
+ });
+
+ it('describe_table_ai maps flags to booleans', async () => {
+ respond({ match: /DESCRIBE/, rows: [{ name: 'ID', type: 'NUMBER', 'null?': 'N', 'primary key': 'Y', 'unique key': 'N' }] });
+ const out = await runAction({ action: describeTableAction, propsValue: { table: 'T' } });
+ expect(out).toEqual({ table: 'T', columns: [{ name: 'ID', type: 'NUMBER', nullable: false, default: null, primaryKey: true, uniqueKey: false, comment: null }] });
+ });
+
+ it('list_columns filters with binds', async () => {
+ respond({ match: /INFORMATION_SCHEMA.COLUMNS/, rows: [{ TABLE_NAME: 'T', COLUMN_NAME: 'EMAIL' }] });
+ const out = await runAction({ action: listColumnsAction, propsValue: { database: 'DB', schema: 'public', table: '"t"', columnPattern: '%mail%' } });
+ expect(lastCall().sql).toContain('FROM DB.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA <> \'INFORMATION_SCHEMA\' AND TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME ILIKE ?');
+ expect(lastCall().binds).toEqual(['PUBLIC', 't', '%mail%']);
+ expect(out).toMatchObject({ items: [{ table_name: 'T', column_name: 'EMAIL' }], truncated: false });
+ });
+
+ it('list_warehouses, list_stages, list_procedures and list_roles run SHOW', async () => {
+ await runAction({ action: listWarehousesAction, propsValue: {} });
+ expect(lastCall().sql).toBe('SHOW WAREHOUSES');
+ await runAction({ action: listStagesAction, propsValue: { database: 'DB' } });
+ expect(lastCall().sql).toBe('SHOW STAGES IN DATABASE DB');
+ respond({ match: /SHOW PROCEDURES/, rows: [{ name: 'P', catalog_name: 'DB', arguments: 'P(NUMBER) RETURN VARCHAR' }] });
+ expect(await runAction({ action: listProceduresAction, propsValue: { schema: 'PUBLIC', namePattern: 'P%' } })).toMatchObject({ items: [{ name: 'P', database_name: 'DB' }] });
+ expect(lastCall().sql).toBe("SHOW PROCEDURES LIKE 'P%' IN SCHEMA PUBLIC");
+ await runAction({ action: listRolesAction, propsValue: {} });
+ expect(lastCall().sql).toBe('SHOW ROLES');
+ });
+
+ it('list_procedures skips built-in system procedures before applying the limit', async () => {
+ respond({ match: /SHOW PROCEDURES/, rows: [
+ { name: 'SYS1', is_builtin: 'Y', schema_name: '' },
+ { name: 'SYS2', is_builtin: 'Y', schema_name: '' },
+ { name: 'MINE', is_builtin: 'N', schema_name: 'S', catalog_name: 'DB' },
+ { name: 'MINE2', is_builtin: 'N', schema_name: 'S', catalog_name: 'DB' },
+ ] });
+ const out = await runAction({ action: listProceduresAction, propsValue: { database: 'DB', schema: 'S', limit: 1 } });
+ expect(out).toMatchObject({ items: [{ name: 'MINE' }], count: 1, truncated: true });
+ });
+
+ it('list_stage_files lists a path with a pattern', async () => {
+ respond({ match: /^LIST/, rows: [{ name: 's3://b/a.csv', size: 10, md5: 'x', last_modified: 'Mon' }] });
+ const out = await runAction({ action: listStageFilesAction, propsValue: { stage: '@DB.PUBLIC.S', path: 'in/', pattern: '.*csv' } });
+ expect(lastCall().sql).toBe("LIST @DB.PUBLIC.S/in/ PATTERN = '.*csv'");
+ expect(out).toMatchObject({ items: [{ name: 's3://b/a.csv', size: 10 }], count: 1 });
+ });
+
+ it('copy_stage_into_table returns per-file results', async () => {
+ respond({ match: /COPY/, rows: [{ file: 'a.csv', status: 'LOADED', rows_loaded: 4 }] });
+ const out = await runAction({ action: copyStageIntoTableAction, propsValue: { table: 'T', stage: 'S', path: 'in', fileFormat: 'JSON' } });
+ expect(lastCall().sql).toBe("COPY INTO T FROM @S/in FILE_FORMAT = (TYPE = 'JSON') ON_ERROR = 'ABORT_STATEMENT'");
+ expect(out).toMatchObject({ filesProcessed: 1, rowsLoaded: 4 });
+ });
+
+ it('call_procedure returns the first value', async () => {
+ respond({ match: /CALL/, rows: [{ P: 'done' }] });
+ const out = await runAction({ action: callProcedureAction, propsValue: { procedure: 'DB.PUBLIC.P', arguments: ['a', 2] } });
+ expect(lastCall()).toEqual({ sql: 'CALL DB.PUBLIC.P(?, ?)', binds: ['a', 2] });
+ expect(out).toMatchObject({ result: 'done', rowCount: 1 });
+ await expect(runAction({ action: callProcedureAction, propsValue: { procedure: 'P()' } })).resolves.toBeDefined();
+ expect(lastCall().sql).toBe('CALL "P()"()');
+ });
+
+ it('get_current_session returns the session context', async () => {
+ respond({ match: /CURRENT_USER/, rows: [{ user: 'AP_TEST', role: 'R', warehouse: 'W', database: 'D', schema: 'S', account: 'A', region: 'AWS_US_EAST_1', version: '9.1' }] });
+ expect(await runAction({ action: getCurrentSessionAction, propsValue: {} })).toMatchObject({ user: 'AP_TEST', region: 'AWS_US_EAST_1' });
+ });
+});
diff --git a/packages/pieces/community/snowflake/test/actions-human.test.ts b/packages/pieces/community/snowflake/test/actions-human.test.ts
new file mode 100644
index 00000000000..422c6d096fe
--- /dev/null
+++ b/packages/pieces/community/snowflake/test/actions-human.test.ts
@@ -0,0 +1,166 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { lastCall, resetSnowflake, respond, runAction, state, userCalls } from './helpers';
+
+vi.mock('snowflake-sdk', async () => (await import('./helpers')).fakeSdk);
+
+import { runQuery } from '../src/lib/actions/run-query';
+import { runMultipleQueries } from '../src/lib/actions/run-multiple-queries';
+import { insertRowAction } from '../src/lib/actions/insert-row';
+import { insertMultipleRowsAction } from '../src/lib/actions/insert-multiple-rows';
+import { updateRowAction } from '../src/lib/actions/update-row';
+import { deleteRowAction } from '../src/lib/actions/delete-row';
+import { upsertRowAction } from '../src/lib/actions/upsert-row';
+import { getRowByIdAction } from '../src/lib/actions/get-row-by-id';
+import { searchRowsAction } from '../src/lib/actions/search-rows';
+import { getTableSchemaAction } from '../src/lib/actions/get-table-schema';
+import { listTablesAction } from '../src/lib/actions/list-tables';
+import { executeStoredProcedureAction } from '../src/lib/actions/execute-stored-procedure';
+import { createDynamicTableAction } from '../src/lib/actions/create-dynamic-table';
+import { loadDataFromStageAction } from '../src/lib/actions/load-data-from-stage';
+
+const table = { database: 'DB', schema: 'PUBLIC', table: 'DB.PUBLIC.ORDERS' };
+
+beforeEach(() => resetSnowflake());
+
+describe('human actions', () => {
+ it('runQuery binds parameters and applies the timeout as statement timeout', async () => {
+ respond({ match: /SELECT/, rows: [{ ID: 1 }] });
+ const rows = await runAction({ action: runQuery, propsValue: { sqlText: 'SELECT * FROM T WHERE ID = ?', binds: [1], timeout: 45000 } });
+ expect(rows).toEqual([{ ID: 1 }]);
+ expect(state.calls[0].sql).toBe('ALTER SESSION SET STATEMENT_TIMEOUT_IN_SECONDS = 45');
+ expect(lastCall()).toEqual({ sql: 'SELECT * FROM T WHERE ID = ?', binds: [1] });
+ });
+
+ it('runMultipleQueries rolls back the transaction on failure', async () => {
+ respond({ match: /BAD/, rows: new Error('boom') });
+ await expect(
+ runAction({ action: runMultipleQueries, propsValue: { sqlTexts: ['INSERT 1', 'BAD'], useTransaction: true } })
+ ).rejects.toThrow('boom');
+ expect(userCalls().map((c) => c.sql)).toEqual(['BEGIN', 'INSERT 1', 'BAD', 'ROLLBACK']);
+ });
+
+ it('runMultipleQueries returns per-query results and commits', async () => {
+ respond({ match: /SELECT/, rows: [{ A: 1 }] });
+ const out = await runAction({ action: runMultipleQueries, propsValue: { sqlTexts: ['SELECT 1'], useTransaction: true } });
+ expect(out).toEqual([{ query: 'SELECT 1', result: [{ A: 1 }] }]);
+ expect(userCalls().map((c) => c.sql)).toEqual(['BEGIN', 'SELECT 1', 'COMMIT']);
+ });
+
+ it('insert-row quotes odd column names and binds values', async () => {
+ respond({ match: /INSERT/, rows: [{ 'number of rows inserted': 1 }] });
+ const out = await runAction({ action: insertRowAction, propsValue: { ...table, table_column_values: { NAME: 'Jo', 'first name': 'J' } } });
+ expect(lastCall()).toEqual({ sql: 'INSERT INTO DB.PUBLIC.ORDERS (NAME, "first name") VALUES (?, ?)', binds: ['Jo', 'J'] });
+ expect(out).toEqual([{ 'number of rows inserted': 1 }]);
+ });
+
+ it('insert_multiple_rows stores objects as JSON', async () => {
+ respond({ match: /INSERT/, rows: [{ 'number of rows inserted': 2 }] });
+ const out = await runAction({ action: insertMultipleRowsAction, propsValue: { ...table, rows: [{ A: 1, J: { x: 1 } }, '{"A": 2, "J": null}'] } });
+ expect(lastCall().sql).toBe('INSERT INTO DB.PUBLIC.ORDERS ("A", "J") SELECT ?, PARSE_JSON(?) UNION ALL SELECT ?, ?');
+ expect(out).toEqual({ success: true, rows_inserted: 2 });
+ });
+
+ it('insert_multiple_rows keeps the exact case of column names', async () => {
+ respond({ match: /INSERT/, rows: [{ 'number of rows inserted': 1 }] });
+ await runAction({ action: insertMultipleRowsAction, propsValue: { ...table, rows: [{ name: 'Alice' }] } });
+ expect(lastCall().sql).toBe('INSERT INTO DB.PUBLIC.ORDERS ("name") VALUES (?)');
+ });
+
+ it('update_row refuses an empty WHERE unless confirmed', async () => {
+ await expect(runAction({ action: updateRowAction, propsValue: { ...table, table_update_values: { STATUS: 'x' }, where_clause: '' } })).rejects.toThrow('every row');
+ respond({ match: /UPDATE/, rows: [{ 'number of rows updated': 3 }] });
+ const out = await runAction({ action: updateRowAction, propsValue: { ...table, table_update_values: { STATUS: 'x', EMPTY: '' }, where_clause: 'ID > 1' } });
+ expect(lastCall()).toEqual({ sql: 'UPDATE DB.PUBLIC.ORDERS SET STATUS = ? WHERE ID > 1', binds: ['x'] });
+ expect(out).toEqual({ success: true, rows_updated: 3 });
+ await runAction({ action: updateRowAction, propsValue: { ...table, table_update_values: { STATUS: 'x' }, update_all_rows: true } });
+ expect(lastCall().sql).toBe('UPDATE DB.PUBLIC.ORDERS SET STATUS = ?');
+ });
+
+ it('delete_row requires a condition', async () => {
+ await expect(runAction({ action: deleteRowAction, propsValue: { ...table, where_clause: ' ' } })).rejects.toThrow('required');
+ respond({ match: /DELETE/, rows: [{ 'number of rows deleted': 2 }] });
+ expect(await runAction({ action: deleteRowAction, propsValue: { ...table, where_clause: 'ID = 1' } })).toEqual({ success: true, rows_deleted: 2 });
+ expect(lastCall().sql).toBe('DELETE FROM DB.PUBLIC.ORDERS WHERE ID = 1');
+ });
+
+ it('upsert_row merges on the match column', async () => {
+ respond({ match: /MERGE/, rows: [{ 'number of rows inserted': 0, 'number of rows updated': 1 }] });
+ const out = await runAction({ action: upsertRowAction, propsValue: { ...table, match_column: 'ID', table_column_values: { ID: '7', NAME: 'Jo' } } });
+ expect(lastCall().sql).toContain('MERGE INTO DB.PUBLIC.ORDERS AS target');
+ expect(lastCall().binds).toEqual(['7', 'Jo']);
+ expect(out).toEqual({ success: true, rows_inserted: 0, rows_updated: 1 });
+ await expect(runAction({ action: upsertRowAction, propsValue: { ...table, match_column: 'ID', table_column_values: { NAME: 'Jo' } } })).rejects.toThrow('must be included');
+ });
+
+ it('get_row_by_id spreads the row', async () => {
+ respond({ match: /SELECT/, rows: [{ ID: 7, NAME: 'Jo' }] });
+ expect(await runAction({ action: getRowByIdAction, propsValue: { ...table, id_column: 'ID', id_value: '7' } })).toEqual({ found: true, ID: 7, NAME: 'Jo' });
+ expect(lastCall()).toEqual({ sql: 'SELECT * FROM DB.PUBLIC.ORDERS WHERE ID = ? LIMIT 1', binds: ['7'] });
+ resetSnowflake();
+ expect(await runAction({ action: getRowByIdAction, propsValue: { ...table, id_column: 'ID', id_value: '8' } })).toEqual({ found: false });
+ });
+
+ it('search_rows bounds the limit', async () => {
+ respond({ match: /SELECT/, rows: [{ ID: 1 }] });
+ await runAction({ action: searchRowsAction, propsValue: { ...table, where_clause: "S = 'a'", order_by: 'ID DESC', limit: 5 } });
+ expect(lastCall().sql).toBe("SELECT * FROM DB.PUBLIC.ORDERS WHERE S = 'a' ORDER BY ID DESC LIMIT 5");
+ await expect(runAction({ action: searchRowsAction, propsValue: { ...table, limit: 50000 } })).rejects.toThrow('between 1 and 10000');
+ });
+
+ it('get_table_schema maps DESCRIBE output', async () => {
+ respond({ match: /DESCRIBE/, rows: [{ name: 'ID', type: 'NUMBER(38,0)', 'null?': 'N', 'primary key': 'Y' }] });
+ const out = await runAction({ action: getTableSchemaAction, propsValue: table });
+ expect(lastCall().sql).toBe('DESCRIBE TABLE DB.PUBLIC.ORDERS');
+ expect(out).toMatchObject({ table: 'DB.PUBLIC.ORDERS', columns: [{ column_name: 'ID', data_type: 'NUMBER(38,0)', nullable: 'N', primary_key: 'Y' }] });
+ });
+
+ it('list_tables maps SHOW TABLES', async () => {
+ respond({ match: /SHOW TABLES/, rows: [{ name: 'ORDERS', database_name: 'DB', schema_name: 'PUBLIC', created_on: new Date('2026-01-01T00:00:00Z') }] });
+ const out = await runAction({ action: listTablesAction, propsValue: { database: 'DB', schema: 'PUBLIC' } });
+ expect(lastCall().sql).toBe('SHOW TABLES IN SCHEMA DB.PUBLIC');
+ expect(out).toEqual([expect.objectContaining({ table_name: 'ORDERS', created_on: '2026-01-01T00:00:00.000Z' })]);
+ });
+
+ it('execute_stored_procedure strips the signature and binds args', async () => {
+ respond({ match: /CALL/, rows: [{ MY_PROC: 'ok' }] });
+ const out = await runAction({ action: executeStoredProcedureAction, propsValue: { database: 'DB', schema: 'PUBLIC', procedure_name: 'MY_PROC(NUMBER) RETURN VARCHAR', arguments: [1, { a: 1 }] } });
+ expect(lastCall()).toEqual({ sql: 'CALL DB.PUBLIC.MY_PROC(?, PARSE_JSON(?))', binds: [1, '{"a":1}'] });
+ expect(out).toEqual({ result: [{ MY_PROC: 'ok' }] });
+ });
+
+ it('execute_stored_procedure sends text args for VARIANT params through PARSE_JSON', async () => {
+ respond({ match: /CALL/, rows: [{ P1: 'ok' }] });
+ await runAction({ action: executeStoredProcedureAction, propsValue: { database: 'DB', schema: 'PUBLIC', procedure_name: 'P1(NUMBER, VARIANT, OBJECT, VARCHAR) RETURN VARCHAR', arguments: [8, '{"b":2}', 'plain', '{"c":3}'] } });
+ expect(lastCall()).toEqual({ sql: 'CALL DB.PUBLIC.P1(?, PARSE_JSON(?), PARSE_JSON(?), ?)', binds: [8, '{"b":2}', '"plain"', '{"c":3}'] });
+ });
+
+ it('create_dynamic_table validates the target lag', async () => {
+ await expect(
+ runAction({ action: createDynamicTableAction, propsValue: { database: 'DB', schema: 'PUBLIC', table_name: 'D', target_lag: "1 hour'", warehouse: 'WH', query: 'SELECT 1' } })
+ ).rejects.toThrow('Refresh Interval');
+ const out = await runAction({ action: createDynamicTableAction, propsValue: { database: 'DB', schema: 'PUBLIC', table_name: 'D', target_lag: 'downstream', query: 'SELECT 1' } });
+ expect(lastCall().sql).toContain('TARGET_LAG = DOWNSTREAM');
+ expect(lastCall().sql).toContain('WAREHOUSE = AP_TEST_WH');
+ expect(out).toMatchObject({ success: true, table: 'DB.PUBLIC.D' });
+ });
+
+ it('load_data_from_stage reports zero files when Snowflake returns only a status row', async () => {
+ respond({ match: /COPY/, rows: [{ status: 'Copy executed with 0 files processed.' }] });
+ const out = await runAction({ action: loadDataFromStageAction, propsValue: { ...table, stage_path: '@s/', file_format_type: 'CSV' } });
+ expect(out).toEqual({ success: true, files_processed: 0, rows_loaded: 0, files: [] });
+ });
+
+ it('load_data_from_stage builds a safe COPY INTO and sums rows', async () => {
+ respond({ match: /COPY/, rows: [
+ { file: 'a.csv', status: 'LOADED', rows_loaded: 2 },
+ { file: 'b.csv', status: 'LOADED', rows_loaded: 3 },
+ ] });
+ const out = await runAction({ action: loadDataFromStageAction, propsValue: { ...table, stage_path: '@my_stage/data/', file_format_type: 'CSV', skip_header: 1, on_error: 'CONTINUE' } });
+ expect(lastCall().sql).toBe(
+ "COPY INTO DB.PUBLIC.ORDERS FROM @my_stage/data/ FILE_FORMAT = (TYPE = 'CSV' SKIP_HEADER = 1) ON_ERROR = 'CONTINUE'"
+ );
+ expect(out).toMatchObject({ success: true, files_processed: 2, rows_loaded: 5 });
+ await runAction({ action: loadDataFromStageAction, propsValue: { ...table, stage_path: "@s'; DROP", file_format_type: 'CSV' } });
+ expect(lastCall().sql).toContain(`FROM @"s'; DROP" FILE_FORMAT`);
+ });
+});
diff --git a/packages/pieces/community/snowflake/test/client.test.ts b/packages/pieces/community/snowflake/test/client.test.ts
new file mode 100644
index 00000000000..02fa18b8d64
--- /dev/null
+++ b/packages/pieces/community/snowflake/test/client.test.ts
@@ -0,0 +1,80 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { fakeSdk, oauthAuth, customAuth, resetSnowflake, respond, state } from './helpers';
+
+vi.mock('snowflake-sdk', async () => (await import('./helpers')).fakeSdk);
+
+import { withSnowflake, clampTimeout } from '../src/lib/common/client';
+import { snowflakeCustomAuth, snowflakeOAuth2Auth } from '../src/lib/auth';
+
+beforeEach(() => resetSnowflake());
+
+describe('client', () => {
+ it('loading the piece does not create connections', async () => {
+ await import('../src');
+ expect(fakeSdk.createConnection).not.toHaveBeenCalled();
+ });
+
+ it('sets a statement timeout and caps rows', async () => {
+ respond({ match: /SELECT/, rows: [{ A: 1 }, { A: 2 }, { A: 3 }] });
+ const result = await withSnowflake({
+ auth: customAuth,
+ statementTimeoutSeconds: 30,
+ fn: (session) => session.query({ sql: 'SELECT A FROM T', maxRows: 2 }),
+ });
+ expect(state.calls[0].sql).toBe('ALTER SESSION SET STATEMENT_TIMEOUT_IN_SECONDS = 30');
+ expect(result).toMatchObject({ rows: [{ A: 1 }, { A: 2 }], totalRows: 3, truncated: true, columns: ['A'] });
+ expect(fakeSdk.configure).toHaveBeenCalledWith({ logLevel: 'ERROR' });
+ });
+
+ it('clamps timeouts to the step limit', () => {
+ expect(clampTimeout(9999)).toBe(540);
+ expect(clampTimeout(0.2)).toBe(1);
+ expect(clampTimeout(undefined)).toBe(540);
+ });
+
+ it('builds OAuth options from the connection', async () => {
+ await withSnowflake({ auth: oauthAuth, fn: async () => null });
+ expect(state.lastOptions).toMatchObject({ account: 'org-acct', authenticator: 'OAUTH', token: 'token-123', role: 'AP_ROLE' });
+ });
+
+ it('uses key-pair auth when a private key is set', async () => {
+ await withSnowflake({
+ auth: { ...customAuth, props: { ...customAuth.props, privateKey: 'A'.repeat(70), privateKeyPassphrase: 'pp' } },
+ fn: async () => null,
+ });
+ expect(state.lastOptions).toMatchObject({ authenticator: 'SNOWFLAKE_JWT', privateKeyPass: 'pp' });
+ expect(String(state.lastOptions?.['privateKey'])).toContain('-----BEGIN PRIVATE KEY-----\n');
+ expect(state.lastOptions?.['password']).toBeUndefined();
+ });
+
+ it('maps known login error codes to a clear message', async () => {
+ state.connectError = Object.assign(new Error('Incorrect username or password was specified.'), { code: '390100' });
+ await expect(withSnowflake({ auth: customAuth, fn: async () => null })).rejects.toThrow('rejected the username or password');
+ });
+
+ it('points to the account identifier when the host cannot be reached', async () => {
+ state.connectError = Object.assign(new Error('Request to Snowflake failed.'), { code: 401002 });
+ await expect(withSnowflake({ auth: customAuth, fn: async () => null })).rejects.toThrow('orgname-accountname');
+ state.connectError = Object.assign(new Error('Network error. Could not reach Snowflake.'), { code: 401001 });
+ await expect(withSnowflake({ auth: customAuth, fn: async () => null })).rejects.toThrow('Account Identifier looks wrong');
+ });
+
+ it('validates custom auth and reports missing credentials', async () => {
+ const validate = snowflakeCustomAuth.validate;
+ if (!validate) throw new Error('no validate');
+ await expect(Reflect.apply(validate, undefined, [{ auth: { account: 'a', username: 'u' }, server: {} }])).resolves.toMatchObject({ valid: false });
+ await expect(Reflect.apply(validate, undefined, [{ auth: { account: 'a', username: 'u', password: 'p' }, server: {} }])).resolves.toEqual({ valid: true });
+ state.connectError = Object.assign(new Error('JWT token is invalid.'), { code: '390144' });
+ await expect(Reflect.apply(validate, undefined, [{ auth: { account: 'a', username: 'u', privateKey: 'A'.repeat(64) }, server: {} }])).resolves.toMatchObject({
+ valid: false,
+ error: expect.stringContaining('key-pair'),
+ });
+ });
+
+ it('validates OAuth auth', async () => {
+ const validate = snowflakeOAuth2Auth.validate;
+ if (!validate) throw new Error('no validate');
+ await expect(Reflect.apply(validate, undefined, [{ auth: { access_token: 't', props: { account: 'a' } }, server: {} }])).resolves.toEqual({ valid: true });
+ expect(state.lastOptions).toMatchObject({ authenticator: 'OAUTH', token: 't' });
+ });
+});
diff --git a/packages/pieces/community/snowflake/test/helpers.ts b/packages/pieces/community/snowflake/test/helpers.ts
new file mode 100644
index 00000000000..ee951eb685c
--- /dev/null
+++ b/packages/pieces/community/snowflake/test/helpers.ts
@@ -0,0 +1,149 @@
+import { Readable } from 'stream';
+import { vi } from 'vitest';
+import { AppConnectionType } from '@activepieces/pieces-framework';
+
+export type Call = { sql: string; binds: unknown[] | undefined };
+type Responder = { match: RegExp; rows: Record<string, unknown>[] | Error };
+
+export const state: State = {
+ calls: [],
+ responders: [],
+ connectError: undefined,
+ lastOptions: undefined,
+ queryStatus: 'SUCCESS',
+};
+
+export function resetSnowflake() {
+ state.calls = [];
+ state.responders = [];
+ state.connectError = undefined;
+ state.lastOptions = undefined;
+ state.queryStatus = 'SUCCESS';
+ fakeSdk.createConnection.mockClear();
+ fakeSdk.configure.mockClear();
+}
+
+export function respond({ match, rows }: { match: RegExp; rows: Record<string, unknown>[] | Error }) {
+ state.responders.push({ match, rows });
+}
+
+export function userCalls(): Call[] {
+ return state.calls.filter((call) => !call.sql.startsWith('ALTER SESSION SET STATEMENT_TIMEOUT'));
+}
+
+export function lastCall(): Call {
+ const calls = userCalls();
+ const call = calls[calls.length - 1];
+ if (!call) throw new Error('no call');
+ return call;
+}
+
+function statement(rows: Record<string, unknown>[]) {
+ return {
+ getNumRows: () => rows.length,
+ getQueryId: () => '01b2c3d4-0000-1234-0000-0001a2b3c4d5',
+ getColumns: () => Object.keys(rows[0] ?? {}).map((name) => ({ getName: () => name })),
+ streamRows: ({ start = 0, end }: { start?: number; end?: number }) =>
+ Readable.from(rows.slice(start, (end ?? rows.length - 1) + 1)),
+ };
+}
+
+const connection = {
+ connect: (cb: (error?: Error) => void) => cb(state.connectError),
+ destroy: (cb: (error?: Error) => void) => cb(undefined),
+ getQueryStatus: async () => state.queryStatus,
+ execute: ({
+ sqlText,
+ binds,
+ complete,
+ }: {
+ sqlText: string;
+ binds?: unknown[];
+ complete: (error: Error | undefined, stmt: unknown) => void;
+ }) => {
+ state.calls.push({ sql: sqlText, binds });
+ const responder = state.responders.find((r) => r.match.test(sqlText));
+ const rows = responder ? responder.rows : [];
+ if (rows instanceof Error) {
+ complete(rows, statement([]));
+ return;
+ }
+ complete(undefined, statement(rows));
+ },
+};
+
+export const fakeSdk = {
+ configure: vi.fn(),
+ createConnection: vi.fn((options: Record<string, unknown>) => {
+ state.lastOptions = options;
+ return connection;
+ }),
+};
+
+export const customAuth = {
+ type: AppConnectionType.CUSTOM_AUTH,
+ props: {
+ account: 'org-acct',
+ username: 'AP_TEST',
+ password: 'secret',
+ database: 'AP_TEST_DB',
+ warehouse: 'AP_TEST_WH',
+ },
+};
+
+export const oauthAuth = {
+ type: AppConnectionType.OAUTH2,
+ access_token: 'token-123',
+ props: { account: 'org-acct', role: 'AP_ROLE' },
+};
+
+export function runAction({
+ action,
+ propsValue,
+ auth = customAuth,
+}: {
+ action: { run: (...args: never[]) => Promise<unknown> };
+ propsValue: Record<string, unknown>;
+ auth?: unknown;
+}): Promise<unknown> {
+ return Reflect.apply(action.run, action, [{ auth, propsValue }]);
+}
+
+export function callHook({
+ trigger,
+ hook,
+ context,
+}: {
+ trigger: object;
+ hook: 'onEnable' | 'onDisable' | 'run' | 'test';
+ context: unknown;
+}): Promise<unknown> {
+ const fn: unknown = Reflect.get(trigger, hook);
+ if (typeof fn !== 'function') throw new Error(`missing ${hook}`);
+ return Reflect.apply(fn, trigger, [context]);
+}
+
+type State = {
+ calls: Call[];
+ responders: Responder[];
+ connectError: Error | undefined;
+ lastOptions: Record<string, unknown> | undefined;
+ queryStatus: string;
+};
+
+export function memoryStore() {
+ const data = new Map<string, unknown>();
+ return {
+ data,
+ store: {
+ get: async (key: string) => (data.has(key) ? data.get(key) : null),
+ put: async (key: string, value: unknown) => {
+ data.set(key, value);
+ return value;
+ },
+ delete: async (key: string) => {
+ data.delete(key);
+ },
+ },
+ };
+}
diff --git a/packages/pieces/community/snowflake/test/metadata.test.ts b/packages/pieces/community/snowflake/test/metadata.test.ts
new file mode 100644
index 00000000000..da2f3c1b0af
--- /dev/null
+++ b/packages/pieces/community/snowflake/test/metadata.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('snowflake-sdk', async () => (await import('./helpers')).fakeSdk);
+
+import { snowflake } from '../src';
+
+const actions = Object.values(snowflake.actions());
+const triggers = Object.values(snowflake.triggers());
+
+describe('piece metadata', () => {
+ it('has 14 existing + 30 ai actions and 5 triggers', () => {
+ expect(actions).toHaveLength(44);
+ expect(actions.filter((a) => a.audience === 'ai')).toHaveLength(30);
+ expect(actions.filter((a) => a.audience === 'human')).toHaveLength(11);
+ expect(actions.filter((a) => a.audience === 'both')).toHaveLength(3);
+ expect(triggers).toHaveLength(5);
+ });
+
+ it.each(actions.map((a) => [a.name, a]))('%s declares classification, aiMetadata and outputSchema', (_name, action) => {
+ expect(['READ', 'SEARCH', 'WRITE', 'DESTRUCTIVE']).toContain(action.classification);
+ expect(action.aiMetadata?.description?.length).toBeGreaterThan(40);
+ expect(typeof action.aiMetadata?.idempotent).toBe('boolean');
+ expect(action.outputSchema).toBeDefined();
+ });
+
+ it.each(actions.filter((a) => a.audience === 'ai').map((a) => [a.name, a]))('%s has no dynamic or dropdown props', (_name, action) => {
+ for (const prop of Object.values(action.props)) {
+ expect(['DROPDOWN', 'MULTI_SELECT_DROPDOWN', 'DYNAMIC']).not.toContain(prop.type);
+ }
+ });
+
+ it.each(triggers.map((t) => [t.name, t]))('%s is READ with outputSchema', (_name, trigger) => {
+ expect(trigger.classification).toBe('READ');
+ expect(trigger.outputSchema).toBeDefined();
+ expect(trigger.aiMetadata?.description).toBeTruthy();
+ });
+});
diff --git a/packages/pieces/community/snowflake/test/sql.test.ts b/packages/pieces/community/snowflake/test/sql.test.ts
new file mode 100644
index 00000000000..44294c60e71
--- /dev/null
+++ b/packages/pieces/community/snowflake/test/sql.test.ts
@@ -0,0 +1,131 @@
+import { describe, expect, it } from 'vitest';
+import {
+ assertReadOnlyStatement,
+ buildOrderBy,
+ buildWhere,
+ identifier,
+ identifierValue,
+ qualifiedName,
+ sqlString,
+} from '../src/lib/common/sql';
+import { normalizePrivateKey } from '../src/lib/common/private-key';
+import { buildCopyInto, stageReference } from '../src/lib/common/stage';
+import { buildInsert } from '../src/lib/common/operations';
+import { buildMerge } from '../src/lib/common/merge';
+
+describe('identifiers', () => {
+ it('keeps plain and quoted identifiers, quotes everything else', () => {
+ expect(identifier({ name: 'orders' })).toBe('orders');
+ expect(identifier({ name: '"My Table"' })).toBe('"My Table"');
+ expect(identifier({ name: 'my table' })).toBe('"my table"');
+ expect(identifier({ name: 'x"; DROP TABLE y; --' })).toBe('"x""; DROP TABLE y; --"');
+ expect(() => identifier({ name: ' ' })).toThrow('empty');
+ });
+ it('splits qualified names outside quotes', () => {
+ expect(qualifiedName({ value: 'DB.PUBLIC.ORDERS' })).toBe('DB.PUBLIC.ORDERS');
+ expect(qualifiedName({ value: 'DB."a.b".T' })).toBe('DB."a.b".T');
+ expect(qualifiedName({ value: 'db.my schema.t' })).toBe('db."my schema".t');
+ expect(() => qualifiedName({ value: 'a.b.c.d' })).toThrow('not valid');
+ expect(() => qualifiedName({ value: 'a..b' })).toThrow('not valid');
+ expect(() => qualifiedName({ value: '"open' })).toThrow('unclosed');
+ });
+ it('resolves stored identifier values', () => {
+ expect(identifierValue('orders')).toBe('ORDERS');
+ expect(identifierValue('"orders"')).toBe('orders');
+ });
+ it('escapes string literals', () => {
+ expect(sqlString("it's \\ ok")).toBe("'it''s \\\\ ok'");
+ });
+});
+
+describe('read-only guard', () => {
+ it('accepts read statements and strips one trailing semicolon', () => {
+ expect(assertReadOnlyStatement('SELECT 1;')).toBe('SELECT 1');
+ expect(assertReadOnlyStatement('-- c\nWITH a AS (SELECT 1) SELECT * FROM a')).toContain('WITH');
+ expect(assertReadOnlyStatement("SELECT 'DELETE FROM x' AS s")).toContain('DELETE');
+ expect(assertReadOnlyStatement('SHOW TABLES')).toBe('SHOW TABLES');
+ expect(assertReadOnlyStatement('SELECT "update" FROM t')).toContain('"update"');
+ });
+ it('rejects writes, multiple statements and SYSTEM$ calls', () => {
+ expect(() => assertReadOnlyStatement('DELETE FROM t')).toThrow('read-only');
+ expect(() => assertReadOnlyStatement('SELECT 1; DROP TABLE t')).toThrow('Only one statement');
+ expect(() => assertReadOnlyStatement('WITH a AS (SELECT 1) DELETE FROM t')).toThrow('DELETE');
+ expect(() => assertReadOnlyStatement('/* x */ INSERT INTO t VALUES (1)')).toThrow('INSERT');
+ expect(() => assertReadOnlyStatement("SELECT SYSTEM$CANCEL_QUERY('x')")).toThrow('SYSTEM$');
+ expect(() => assertReadOnlyStatement('SELECT 1 /* open')).toThrow('unclosed');
+ expect(() => assertReadOnlyStatement(' ')).toThrow('empty');
+ });
+});
+
+describe('filters and sort', () => {
+ it('turns filters into bound conditions', () => {
+ const where = buildWhere([
+ { column: 'status', operator: '=', value: 'open' },
+ { column: 'id', operator: 'in', value: '1, 2' },
+ { column: 'deleted_at', operator: 'IS NULL' },
+ ]);
+ expect(where.clause).toBe(' WHERE status = ? AND id IN (?, ?) AND deleted_at IS NULL');
+ expect(where.binds).toEqual(['open', '1', '2']);
+ });
+ it('rejects unknown operators and missing values', () => {
+ expect(() => buildWhere([{ column: 'a', operator: '; DROP' }])).toThrow('not supported');
+ expect(() => buildWhere([{ column: 'a', operator: '=' }])).toThrow('needs a value');
+ expect(buildWhere(undefined).clause).toBe('');
+ });
+ it('builds a validated ORDER BY', () => {
+ expect(buildOrderBy([{ column: 'created_at', direction: 'desc' }])).toBe(' ORDER BY created_at DESC');
+ expect(() => buildOrderBy([{ column: 'a', direction: 'sideways' }])).toThrow('ASC or DESC');
+ });
+});
+
+describe('private key normalisation', () => {
+ const body = 'A'.repeat(100);
+ it('rebuilds PEM lines from a key pasted with spaces', () => {
+ const pem = normalizePrivateKey(`-----BEGIN PRIVATE KEY----- ${body.slice(0, 50)} ${body.slice(50)} -----END PRIVATE KEY-----`);
+ expect(pem.split('\n')).toEqual(['-----BEGIN PRIVATE KEY-----', 'A'.repeat(64), 'A'.repeat(36), '-----END PRIVATE KEY-----']);
+ });
+ it('keeps the ENCRYPTED header', () => {
+ const pem = normalizePrivateKey(`-----BEGIN ENCRYPTED PRIVATE KEY-----\n${body}\n-----END ENCRYPTED PRIVATE KEY-----\n`);
+ expect(pem.startsWith('-----BEGIN ENCRYPTED PRIVATE KEY-----\n')).toBe(true);
+ expect(pem.endsWith('-----END ENCRYPTED PRIVATE KEY-----')).toBe(true);
+ });
+ it('accepts a bare body and rejects garbage', () => {
+ expect(normalizePrivateKey(body)).toContain('-----BEGIN PRIVATE KEY-----');
+ expect(() => normalizePrivateKey('not a key!')).toThrow('not valid PEM');
+ });
+});
+
+describe('stages and COPY', () => {
+ it('builds stage references safely', () => {
+ expect(stageReference({ stage: '@db.public.my_stage', path: 'data/' })).toBe('@db.public.my_stage/data/');
+ expect(stageReference({ stage: 'my_stage/data' })).toBe('@my_stage/data');
+ expect(() => stageReference({ stage: 's', path: "x'; DROP" })).toThrow('not allowed');
+ expect(() => stageReference({ stage: 's', path: '../x' })).toThrow('not allowed');
+ expect(() => stageReference({ stage: '~' })).toThrow('not supported');
+ });
+ it('validates enums in COPY INTO', () => {
+ expect(buildCopyInto({ table: 'T', stage: '@S', fileFormat: 'CSV', skipHeader: 1, onError: 'CONTINUE', pattern: ".*'x" })).toBe(
+ "COPY INTO T FROM @S FILE_FORMAT = (TYPE = 'CSV' SKIP_HEADER = 1) PATTERN = '.*''x' ON_ERROR = 'CONTINUE'"
+ );
+ expect(() => buildCopyInto({ table: 'T', stage: '@S', fileFormat: "CSV' x" })).toThrow('File format');
+ expect(() => buildCopyInto({ table: 'T', stage: '@S', fileFormat: 'CSV', onError: 'NOPE' })).toThrow('On Error');
+ });
+});
+
+describe('insert and merge builders', () => {
+ it('uses VALUES for scalars and PARSE_JSON for objects', () => {
+ expect(buildInsert({ table: 'T', rows: [{ a: 1, b: 'x' }] })).toEqual({ sql: 'INSERT INTO T (a, b) VALUES (?, ?)', binds: [1, 'x'] });
+ expect(buildInsert({ table: 'T', rows: [{ a: 1, tags: ['x'] }] })).toEqual({
+ sql: 'INSERT INTO T (a, tags) SELECT ?, PARSE_JSON(?)',
+ binds: [1, '["x"]'],
+ });
+ expect(() => buildInsert({ table: 'T', rows: [{ a: 1 }, { b: 2 }] })).toThrow('different set of columns');
+ });
+ it('quotes merge columns and binds through aliases', () => {
+ const merge = buildMerge({ table: 'T', keyColumns: ['id'], values: { id: 1, 'first name': 'Jo' } });
+ expect(merge.sql).toContain('ON target.id = source.C0');
+ expect(merge.sql).toContain('target."first name" = source.C1');
+ expect(merge.binds).toEqual([1, 'Jo']);
+ expect(() => buildMerge({ table: 'T', keyColumns: ['id'], values: { id: 1 } })).toThrow('other than the key');
+ });
+});
diff --git a/packages/pieces/community/snowflake/test/triggers.test.ts b/packages/pieces/community/snowflake/test/triggers.test.ts
new file mode 100644
index 00000000000..918419af344
--- /dev/null
+++ b/packages/pieces/community/snowflake/test/triggers.test.ts
@@ -0,0 +1,149 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { callHook, lastCall, memoryStore, customAuth, resetSnowflake, respond, userCalls } from './helpers';
+
+vi.mock('snowflake-sdk', async () => (await import('./helpers')).fakeSdk);
+
+import { newRowTrigger } from '../src/lib/triggers/new-row';
+import { newOrUpdatedRowTrigger } from '../src/lib/triggers/new-or-updated-row';
+import { newTableTrigger } from '../src/lib/triggers/new-table';
+import { newViewTrigger } from '../src/lib/triggers/new-view';
+import { newColumnTrigger } from '../src/lib/triggers/new-column';
+
+function context({ propsValue, store = memoryStore().store }: { propsValue: Record<string, unknown>; store?: ReturnType<typeof memoryStore>['store'] }) {
+ return { auth: customAuth, propsValue, store, setSchedule: () => undefined };
+}
+
+function rowsWithCursor(cursors: number[]) {
+ return cursors.map((c, i) => ({ ID: i, __AP_CURSOR: c }));
+}
+
+function hookOf({ trigger, hook }: { trigger: object; hook: 'onEnable' | 'onDisable' | 'run' | 'test' }) {
+ return (ctx: unknown) => callHook({ trigger, hook, context: ctx });
+}
+
+beforeEach(() => resetSnowflake());
+
+describe.each([
+ ['new_row', newRowTrigger, 'created_at_column'],
+ ['new_or_updated_row', newOrUpdatedRowTrigger, 'updated_at_column'],
+])('%s', (_name, trigger, columnProp) => {
+ const props = { database: 'DB', schema: 'PUBLIC', table: 'DB.PUBLIC.T', [columnProp]: 'TS' };
+
+ it('stores a baseline on enable and emits nothing old', async () => {
+ const mem = memoryStore();
+ respond({ match: /MAX\(/, rows: [{ __AP_CURSOR: 1700000000000000 }] });
+ await hookOf({ trigger: trigger, hook: 'onEnable' })(context({ propsValue: props, store: mem.store }));
+ expect(lastCall().sql).toBe('SELECT MAX(DATE_PART(EPOCH_MICROSECOND, TS)) AS "__AP_CURSOR" FROM DB.PUBLIC.T');
+ expect(mem.data.get('snowflake_row_cursor')).toEqual({ cursor: '1700000000000000' });
+ });
+
+ it('pages forward from the stored cursor in ascending order', async () => {
+ const mem = memoryStore();
+ mem.data.set('snowflake_row_cursor', { cursor: '100' });
+ respond({ match: /WHERE DATE_PART/, rows: rowsWithCursor([101, 102]) });
+ const out = await hookOf({ trigger: trigger, hook: 'run' })(context({ propsValue: props, store: mem.store }));
+ expect(lastCall()).toEqual({
+ sql: 'SELECT t.*, DATE_PART(EPOCH_MICROSECOND, TS) AS "__AP_CURSOR" FROM DB.PUBLIC.T t WHERE DATE_PART(EPOCH_MICROSECOND, TS) > ? ORDER BY DATE_PART(EPOCH_MICROSECOND, TS) ASC LIMIT 1000',
+ binds: ['100'],
+ });
+ expect(out).toEqual([{ ID: 0 }, { ID: 1 }]);
+ expect(mem.data.get('snowflake_row_cursor')).toEqual({ cursor: '102' });
+ });
+
+ it('holds back trailing ties on a full page so none are lost', async () => {
+ const mem = memoryStore();
+ mem.data.set('snowflake_row_cursor', { cursor: '1' });
+ const cursors = Array.from({ length: 1000 }, (_, i) => (i < 998 ? 10 + i : 5000));
+ respond({ match: /> \? ORDER/, rows: rowsWithCursor(cursors) });
+ const out = await hookOf({ trigger: trigger, hook: 'run' })(context({ propsValue: props, store: mem.store }));
+ expect(out).toHaveLength(998);
+ expect(mem.data.get('snowflake_row_cursor')).toEqual({ cursor: String(10 + 997) });
+ });
+
+ it('fetches the whole group when a full page shares one timestamp', async () => {
+ const mem = memoryStore();
+ mem.data.set('snowflake_row_cursor', { cursor: '1' });
+ respond({ match: /> \? ORDER/, rows: rowsWithCursor(Array.from({ length: 1000 }, () => 50)) });
+ respond({ match: /= \? LIMIT/, rows: rowsWithCursor(Array.from({ length: 1500 }, () => 50)) });
+ const out = await hookOf({ trigger: trigger, hook: 'run' })(context({ propsValue: props, store: mem.store }));
+ expect(lastCall()).toEqual({
+ sql: 'SELECT t.*, DATE_PART(EPOCH_MICROSECOND, TS) AS "__AP_CURSOR" FROM DB.PUBLIC.T t WHERE DATE_PART(EPOCH_MICROSECOND, TS) = ? LIMIT 10000',
+ binds: ['50'],
+ });
+ expect(out).toHaveLength(1500);
+ expect(mem.data.get('snowflake_row_cursor')).toEqual({ cursor: '50' });
+ });
+
+ it('never re-reads rows at the saved timestamp, so edits to emitted rows do not re-fire', async () => {
+ const mem = memoryStore();
+ mem.data.set('snowflake_row_cursor', { cursor: '10' });
+ respond({ match: /> \? ORDER/, rows: [{ ID: 1, __AP_CURSOR: 20 }] });
+ const out = await hookOf({ trigger: trigger, hook: 'run' })(context({ propsValue: props, store: mem.store }));
+ expect(out).toEqual([{ ID: 1 }]);
+ expect(lastCall().sql).toContain('TS) > ? ORDER BY');
+ expect(lastCall().sql).not.toContain('HASH');
+ });
+
+ it('keeps the saved cursor on republish', async () => {
+ const mem = memoryStore();
+ mem.data.set('snowflake_row_cursor', { cursor: '7' });
+ await hookOf({ trigger: trigger, hook: 'onEnable' })({ ...context({ propsValue: props, store: mem.store }), isRepublish: true });
+ expect(userCalls()).toHaveLength(0);
+ expect(mem.data.get('snowflake_row_cursor')).toEqual({ cursor: '7' });
+ });
+
+ it('keeps the cursor when nothing is new', async () => {
+ const mem = memoryStore();
+ mem.data.set('snowflake_row_cursor', { cursor: '5' });
+ expect(await hookOf({ trigger: trigger, hook: 'run' })(context({ propsValue: props, store: mem.store }))).toEqual([]);
+ expect(mem.data.get('snowflake_row_cursor')).toEqual({ cursor: '5' });
+ });
+
+ it('first run without state stores a baseline and emits nothing', async () => {
+ const mem = memoryStore();
+ respond({ match: /MAX\(/, rows: [{ __AP_CURSOR: null }] });
+ expect(await hookOf({ trigger: trigger, hook: 'run' })(context({ propsValue: props, store: mem.store }))).toEqual([]);
+ expect(mem.data.get('snowflake_row_cursor')).toEqual({ cursor: null });
+ respond({ match: /IS NOT NULL ORDER BY DATE_PART/, rows: rowsWithCursor([3]) });
+ expect(await hookOf({ trigger: trigger, hook: 'run' })(context({ propsValue: props, store: mem.store }))).toEqual([{ ID: 0 }]);
+ expect(lastCall().sql).toContain('WHERE TS IS NOT NULL ORDER BY');
+ });
+
+ it('test returns the latest rows', async () => {
+ respond({ match: /DESC LIMIT 5/, rows: [{ ID: 9 }] });
+ expect(await hookOf({ trigger: trigger, hook: 'test' })(context({ propsValue: props }))).toEqual([{ ID: 9 }]);
+ expect(lastCall().sql).toBe('SELECT * FROM DB.PUBLIC.T WHERE TS IS NOT NULL ORDER BY TS DESC LIMIT 5');
+ });
+
+ it('keeps the cursor across disable then republish enable', async () => {
+ const mem = memoryStore();
+ mem.data.set('snowflake_row_cursor', { cursor: '5' });
+ await hookOf({ trigger: trigger, hook: 'onDisable' })(context({ propsValue: props, store: mem.store }));
+ await hookOf({ trigger: trigger, hook: 'onEnable' })({ ...context({ propsValue: props, store: mem.store }), isRepublish: true });
+ expect(userCalls()).toHaveLength(0);
+ expect(mem.data.get('snowflake_row_cursor')).toEqual({ cursor: '5' });
+ });
+});
+
+describe('catalog triggers', () => {
+ it('new_table polls SHOW TABLES with a quoted scope', async () => {
+ respond({ match: /SHOW TABLES/, rows: [{ name: 'ORDERS', created_on: '2026-01-01T00:00:00Z' }] });
+ const out = await hookOf({ trigger: newTableTrigger, hook: 'test' })(context({ propsValue: { database: 'DB', schema: 'my schema' } }));
+ expect(lastCall().sql).toBe('SHOW TABLES IN SCHEMA DB."my schema"');
+ expect(out).toEqual([expect.objectContaining({ table_name: 'ORDERS' })]);
+ });
+
+ it('new_view polls SHOW VIEWS', async () => {
+ respond({ match: /SHOW VIEWS/, rows: [{ name: 'V', created_on: '2026-01-01T00:00:00Z' }] });
+ const out = await hookOf({ trigger: newViewTrigger, hook: 'test' })(context({ propsValue: { database: 'DB', schema: 'PUBLIC' } }));
+ expect(out).toEqual([expect.objectContaining({ view_name: 'V' })]);
+ });
+
+ it('new_column describes the table', async () => {
+ respond({ match: /DESCRIBE/, rows: [{ name: 'ID', type: 'NUMBER' }, { name: 'EMAIL', type: 'VARCHAR' }] });
+ const out = await hookOf({ trigger: newColumnTrigger, hook: 'test' })(context({ propsValue: { database: 'DB', schema: 'PUBLIC', table: 'DB.PUBLIC.T' } }));
+ expect(lastCall().sql).toBe('DESCRIBE TABLE DB.PUBLIC.T');
+ expect(out).toMatchObject([{ column_name: 'EMAIL' }, { column_name: 'ID' }]);
+ expect(userCalls()).toHaveLength(1);
+ });
+});
diff --git a/packages/pieces/community/snowflake/vitest.config.ts b/packages/pieces/community/snowflake/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/snowflake/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})