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(postgres): let AI agents explore schemas, query and safely write rows (#17073)

Kishan Parmar3d37862e1725
diff --git a/bun.lock b/bun.lock
index 578b1954618..f065d651eb2 100644
--- a/bun.lock
+++ b/bun.lock
@@ -7332,7 +7332,7 @@
},
"packages/pieces/community/postgres": {
"name": "@activepieces/piece-postgres",
- "version": "0.5.1",
+ "version": "0.6.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
diff --git a/packages/pieces/community/postgres/package.json b/packages/pieces/community/postgres/package.json
index eef628dc69a..c73f5a9aac8 100644
--- a/packages/pieces/community/postgres/package.json
+++ b/packages/pieces/community/postgres/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-postgres",
- "version": "0.5.1",
+ "version": "0.6.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"dependencies": {
diff --git a/packages/pieces/community/postgres/src/index.ts b/packages/pieces/community/postgres/src/index.ts
index 15dda94279e..8d3e5e2b693 100644
--- a/packages/pieces/community/postgres/src/index.ts
+++ b/packages/pieces/community/postgres/src/index.ts
@@ -1,9 +1,4 @@
-import {
- PieceAuth,
- Property,
- createPiece,
-} from '@activepieces/pieces-framework';
-import { AppConnectionType, PieceCategory } from '@activepieces/pieces-framework';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
import { runQuery } from './lib/actions/run-query';
import { findRows } from './lib/actions/find-rows';
import { insertRow } from './lib/actions/insert-row';
@@ -12,79 +7,10 @@ import { updateRow } from './lib/actions/update-row';
import { deleteRow } from './lib/actions/delete-row';
import { getTables } from './lib/actions/get-tables';
import { newRow } from './lib/triggers/new-row';
-import { pgClient } from './lib/common';
+import { postgresAuth } from './lib/auth';
+import { postgresAiActions } from './lib/actions/ai';
-export const postgresAuth = PieceAuth.CustomAuth({
- props: {
- host: Property.ShortText({
- displayName: 'Host',
- required: true,
- description: "The server's hostname or IP address.",
- placeholder: 'db.example.com',
- }),
- port: Property.Number({
- displayName: 'Port',
- defaultValue: 5432,
- description: 'The port the server listens on, usually 5432.',
- required: true,
- }),
- user: Property.ShortText({
- displayName: 'User',
- required: true,
- description: 'The database user to sign in as.',
- }),
- password: PieceAuth.SecretText({
- displayName: 'Password',
- description: 'The password for that user.',
- required: true,
- }),
- database: Property.ShortText({
- displayName: 'Database',
- description: 'The name of the database to connect to.',
- required: true,
- }),
- enable_ssl: Property.Checkbox({
- displayName: 'Enable SSL',
- description: 'Encrypt the connection. Most hosted databases require it.',
- required: true,
- defaultValue: true,
- }),
- reject_unauthorized: Property.Checkbox({
- displayName: 'Verify Server Certificate',
- description:
- "Check the server's certificate. Self-signed servers need a CA below.",
- required: true,
- defaultValue: false,
- }),
- certificate: Property.LongText({
- displayName: 'Certificate',
- description:
- 'The CA certificate (PEM) to trust when verifying the server.',
- placeholder: '-----BEGIN CERTIFICATE-----',
- defaultValue: '',
- required: false,
- }),
- },
- required: true,
- validate: async ({ auth }) => {
- try {
- const client = await pgClient({
- type: AppConnectionType.CUSTOM_AUTH,
- props: auth,
- });
- await client.end();
- }
- catch (e) {
- return {
- valid: false,
- error: e instanceof Error && e.message ? e.message : JSON.stringify(e)
- };
- }
- return {
- valid: true,
- };
- }
-});
+export { postgresAuth };
export const postgres = createPiece({
displayName: 'Postgres',
@@ -94,6 +20,6 @@ export const postgres = createPiece({
logoUrl: 'https://cdn.activepieces.com/pieces/postgres.png',
authors: ["AbdullahBitar", "Willianwg", "dentych", "kishanprmr", "AbdulTheActivePiecer", "khaledmashaly", "abuaboud"],
auth: postgresAuth,
- actions: [findRows, insertRow, insertRows, updateRow, deleteRow, getTables, runQuery],
+ actions: [findRows, insertRow, insertRows, updateRow, deleteRow, getTables, runQuery, ...postgresAiActions],
triggers: [newRow],
});
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/index.ts b/packages/pieces/community/postgres/src/lib/actions/ai/index.ts
new file mode 100644
index 00000000000..44bae95c94d
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/index.ts
@@ -0,0 +1,39 @@
+import { callRoutine } from './queries/call-routine';
+import { explainQuery } from './queries/explain-query';
+import { runSelectQuery } from './queries/run-select-query';
+import { countRows } from './rows/count-rows';
+import { deleteRowsAi } from './rows/delete-rows';
+import { findRowsAi } from './rows/find-rows';
+import { getRowByKey } from './rows/get-row-by-key';
+import { insertRowsAi } from './rows/insert-rows';
+import { updateRowsAi } from './rows/update-rows';
+import { upsertRow } from './rows/upsert-row';
+import { getServerInfo } from './server/get-server-info';
+import { listActivity } from './server/list-activity';
+import { describeTable } from './schema/describe-table';
+import { getViewDefinition } from './schema/get-view-definition';
+import { listIndexes } from './schema/list-indexes';
+import { listRoutines } from './schema/list-routines';
+import { listSchemas } from './schema/list-schemas';
+import { listViews } from './schema/list-views';
+
+export const postgresAiActions = [
+ listSchemas,
+ describeTable,
+ listIndexes,
+ listViews,
+ getViewDefinition,
+ listRoutines,
+ findRowsAi,
+ getRowByKey,
+ countRows,
+ insertRowsAi,
+ upsertRow,
+ updateRowsAi,
+ deleteRowsAi,
+ runSelectQuery,
+ explainQuery,
+ callRoutine,
+ getServerInfo,
+ listActivity,
+];
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/queries/call-routine.ts b/packages/pieces/community/postgres/src/lib/actions/ai/queries/call-routine.ts
new file mode 100644
index 00000000000..40d5fd4e41b
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/queries/call-routine.ts
@@ -0,0 +1,54 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { postgresAuth } from '../../../auth';
+import { postgresAi, postgresAiProps } from '../../../ai-common';
+import { postgresCallRoutineOutputSchema } from '../../../output-schemas';
+
+export const callRoutine = createAction({
+ auth: postgresAuth,
+ name: 'postgres_call_routine',
+ outputSchema: postgresCallRoutineOutputSchema,
+ displayName: 'Call Routine',
+ description: 'Calls a function or procedure and returns what it produces.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description: 'Calls a user-defined function (SELECT * FROM fn(...)) or procedure (CALL proc(...)) with the given arguments in order and returns the rows it produces: a function\'s result, or a procedure\'s INOUT/OUT values. Routine names and their argument lists come from List Routines. Not idempotent: the routine may change data.',
+ idempotent: false,
+ },
+ props: {
+ routine: Property.ShortText({
+ displayName: 'Routine',
+ description: 'Function or procedure name as returned by List Routines, written schema.name. A bare name is looked up on the search path.',
+ required: true,
+ }),
+ args: Property.Array({
+ displayName: 'Arguments',
+ description: 'Values for the routine\'s arguments, in order. Leave out trailing arguments that have defaults.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { routine } = context.propsValue;
+ const args = context.propsValue.args ?? [];
+ const { schema, name } = postgresAi.splitName({ name: routine });
+ return postgresAi.withClient({
+ auth: context.auth,
+ fn: async (client) => {
+ const kinds = await client.query<{ kind: string }>(
+ `SELECT DISTINCT p.prokind AS kind FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE p.proname = $1 AND p.prokind IN ('f', 'p') AND (n.nspname = $2::text OR ($2::text IS NULL AND n.nspname = ANY(current_schemas(false))))`,
+ [name, schema],
+ );
+ const found = kinds.rows.map((row) => row.kind);
+ if (found.length === 0) {
+ throw new Error(`No function or procedure named "${routine}". Use List Routines to find it, written schema.name.`);
+ }
+ if (found.length > 1) {
+ throw new Error(`"${routine}" names both a function and a procedure; write it as schema.name to pick one.`);
+ }
+ const call = `${postgresAi.quoteName({ name: routine })}(${args.map((_, index) => `$${index + 1}`).join(', ')})`;
+ const result = await client.query(found[0] === 'p' ? `CALL ${call}` : `SELECT * FROM ${call}`, args);
+ return { kind: found[0] === 'p' ? 'procedure' : 'function', rows: result.rows, rowCount: result.rows.length };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/queries/explain-query.ts b/packages/pieces/community/postgres/src/lib/actions/ai/queries/explain-query.ts
new file mode 100644
index 00000000000..8517bd59d22
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/queries/explain-query.ts
@@ -0,0 +1,39 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { postgresAuth } from '../../../auth';
+import { postgresAi, postgresAiProps } from '../../../ai-common';
+import { postgresExplainQueryOutputSchema } from '../../../output-schemas';
+
+export const explainQuery = createAction({
+ auth: postgresAuth,
+ name: 'postgres_explain_query',
+ outputSchema: postgresExplainQueryOutputSchema,
+ displayName: 'Explain Query',
+ description: 'Shows the plan Postgres would use for a query, without running it.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Returns the planner\'s estimated execution plan for one statement as JSON (EXPLAIN, never ANALYZE), so the statement itself is not run, even an INSERT, UPDATE or DELETE. Use to check whether a query uses an index or scans a whole table before running it with Run Select Query or Run Query. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ query: Property.LongText({
+ displayName: 'Query',
+ description: 'The statement to explain. Write $1, $2 where each value goes.',
+ required: true,
+ }),
+ args: postgresAiProps.args,
+ },
+ async run(context) {
+ const { query, args } = context.propsValue;
+ const result = await postgresAi.withClient({
+ auth: context.auth,
+ fn: (client) =>
+ postgresAi.inTransaction({
+ client,
+ readOnly: true,
+ fn: () => client.query<{ 'QUERY PLAN': unknown[] }>(postgresAi.singleStatement({ text: `EXPLAIN (FORMAT JSON) ${query}`, values: args ?? [] })),
+ }),
+ });
+ return { plan: result.rows[0]?.['QUERY PLAN'][0] ?? null };
+ },
+});
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/queries/run-select-query.ts b/packages/pieces/community/postgres/src/lib/actions/ai/queries/run-select-query.ts
new file mode 100644
index 00000000000..5315a9789e0
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/queries/run-select-query.ts
@@ -0,0 +1,46 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { postgresAuth } from '../../../auth';
+import { postgresAi, postgresAiProps } from '../../../ai-common';
+import { postgresRunSelectQueryOutputSchema } from '../../../output-schemas';
+
+export const runSelectQuery = createAction({
+ auth: postgresAuth,
+ name: 'postgres_run_select_query',
+ outputSchema: postgresRunSelectQueryOutputSchema,
+ displayName: 'Run Select Query',
+ description: 'Runs one read-only SELECT query and returns its rows.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description: 'Runs a single SELECT, WITH or VALUES statement inside a read-only transaction and returns up to Limit rows, with hasMore when there were more. Use for joins, aggregates and anything Find Rows cannot express; the database rejects any write, and only one statement is accepted. Pass values as $1, $2 placeholders with Arguments. Use Run Query to change data.',
+ idempotent: true,
+ },
+ props: {
+ query: Property.LongText({
+ displayName: 'Query',
+ description: 'One SELECT, WITH or VALUES statement. Write $1, $2 where each value goes, e.g. SELECT * FROM orders WHERE status = $1',
+ required: true,
+ }),
+ args: postgresAiProps.args,
+ limit: postgresAiProps.limit,
+ },
+ async run(context) {
+ const { query, args, limit } = context.propsValue;
+ const max = postgresAi.boundedInteger({ value: limit, defaultValue: postgresAi.READ_DEFAULT_LIMIT, min: 1, max: postgresAi.READ_MAX_LIMIT, label: 'Limit' });
+ const fetched = await postgresAi.withClient({
+ auth: context.auth,
+ fn: (client) =>
+ postgresAi.inTransaction({
+ client,
+ readOnly: true,
+ fn: async () => {
+ await client.query(postgresAi.singleStatement({ text: `DECLARE ap_select NO SCROLL CURSOR FOR ${query}`, values: args ?? [] }));
+ return client.query(`FETCH FORWARD ${max + 1} FROM ap_select`);
+ },
+ }),
+ });
+ const hasMore = fetched.rows.length > max;
+ const rows = fetched.rows.slice(0, max);
+ return { rows, count: rows.length, hasMore };
+ },
+});
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/rows/count-rows.ts b/packages/pieces/community/postgres/src/lib/actions/ai/rows/count-rows.ts
new file mode 100644
index 00000000000..2908eba64f7
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/rows/count-rows.ts
@@ -0,0 +1,31 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { postgresAuth } from '../../../auth';
+import { postgresAi, postgresAiProps } from '../../../ai-common';
+import { postgresCountRowsOutputSchema } from '../../../output-schemas';
+
+export const countRows = createAction({
+ auth: postgresAuth,
+ name: 'postgres_count_rows',
+ outputSchema: postgresCountRowsOutputSchema,
+ displayName: 'Count Rows',
+ description: 'Counts the rows in a table that match the filters.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Returns the exact number of rows in a table or view matching all given filters, or every row when no filter is given. Use before Update Rows or Delete Rows to check how many rows a filter hits, or to size paging in Find Rows. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ table: postgresAiProps.table,
+ filters: postgresAiProps.filters({ required: false }),
+ },
+ async run(context) {
+ const { table, filters } = context.propsValue;
+ const where = postgresAi.buildWhere({ filters, startAt: 0 });
+ const result = await postgresAi.withClient({
+ auth: context.auth,
+ fn: (client) => client.query<{ count: string }>(`SELECT count(*) AS count FROM ${postgresAi.quoteName({ name: table })}${where.sql}`, where.values),
+ });
+ return { count: Number(result.rows[0]?.count ?? 0) };
+ },
+});
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/rows/delete-rows.ts b/packages/pieces/community/postgres/src/lib/actions/ai/rows/delete-rows.ts
new file mode 100644
index 00000000000..bd56fa15339
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/rows/delete-rows.ts
@@ -0,0 +1,41 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { postgresAuth } from '../../../auth';
+import { postgresAi, postgresAiProps } from '../../../ai-common';
+import { postgresDeleteRowsOutputSchema } from '../../../output-schemas';
+
+export const deleteRowsAi = createAction({
+ auth: postgresAuth,
+ name: 'postgres_delete_rows',
+ outputSchema: postgresDeleteRowsOutputSchema,
+ displayName: 'Delete Rows',
+ description: 'Permanently deletes every row that matches the filters, up to a safety limit.',
+ audience: 'ai',
+ classification: 'DESTRUCTIVE',
+ aiMetadata: {
+ description: 'Permanently deletes all rows matching every filter (at least one filter required) and returns the deleted rows as they were. Runs in a transaction and deletes nothing if more than Max Rows match; check with Count Rows first. Cannot be undone.',
+ idempotent: false,
+ },
+ props: {
+ table: postgresAiProps.table,
+ filters: postgresAiProps.filters({ required: true }),
+ maxRows: postgresAiProps.maxRows({ verb: 'deleted' }),
+ },
+ async run(context) {
+ const { table, filters, maxRows } = context.propsValue;
+ const limit = postgresAi.boundedInteger({ value: maxRows, defaultValue: postgresAi.WRITE_GUARD_DEFAULT, min: 1, max: postgresAi.WRITE_GUARD_MAX, label: 'Max Rows' });
+ const where = postgresAi.buildWhere({ filters, startAt: 0 });
+ const quotedTable = postgresAi.quoteName({ name: table });
+ return postgresAi.withClient({
+ auth: context.auth,
+ fn: (client) =>
+ postgresAi.guardedWrite({
+ client,
+ quotedTable,
+ where,
+ maxRows: limit,
+ verb: 'deleted',
+ write: { sql: `DELETE FROM ${quotedTable}${where.sql} RETURNING *`, values: where.values },
+ }),
+ });
+ },
+});
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/rows/find-rows.ts b/packages/pieces/community/postgres/src/lib/actions/ai/rows/find-rows.ts
new file mode 100644
index 00000000000..ef489998169
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/rows/find-rows.ts
@@ -0,0 +1,65 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import format from 'pg-format';
+import { postgresAuth } from '../../../auth';
+import { postgresAi, postgresAiProps } from '../../../ai-common';
+import { postgresFindRowsOutputSchema } from '../../../output-schemas';
+
+export const findRowsAi = createAction({
+ auth: postgresAuth,
+ name: 'postgres_find_rows',
+ outputSchema: postgresFindRowsOutputSchema,
+ displayName: 'Find Rows',
+ description: 'Finds rows in a table using structured filters, sort and paging.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description: 'Returns rows of a table or view matching all given filters (column, operator, value), optionally limited to chosen columns and sorted, with offset paging (hasMore, nextOffset). Values are sent as bound parameters. Use Count Rows for totals and Get Row by Key for one row by its key. Column names come from Describe Table. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ table: postgresAiProps.table,
+ filters: postgresAiProps.filters({ required: 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: postgresAiProps.limit,
+ offset: Property.Number({
+ displayName: 'Offset',
+ description: 'Number of rows to skip, for paging. Use nextOffset from the previous call with the same filters and sort.',
+ required: false,
+ defaultValue: 0,
+ }),
+ },
+ async run(context) {
+ const { table, filters, columns, sort, limit, offset } = context.propsValue;
+ const max = postgresAi.boundedInteger({ value: limit, defaultValue: postgresAi.READ_DEFAULT_LIMIT, min: 1, max: postgresAi.READ_MAX_LIMIT, label: 'Limit' });
+ const skip = postgresAi.boundedInteger({ value: offset, defaultValue: 0, min: 0, max: Number.MAX_SAFE_INTEGER, label: 'Offset' });
+ const where = postgresAi.buildWhere({ filters, startAt: 0 });
+ const columnList = (columns ?? []).map((column) => format.ident(String(column)));
+ const select = columnList.length > 0 ? columnList.join(', ') : '*';
+ const sql = `SELECT ${select} FROM ${postgresAi.quoteName({ name: table })}${where.sql}${postgresAi.buildOrderBy({ sort })} LIMIT ${max + 1} OFFSET ${skip}`;
+ const result = await postgresAi.withClient({
+ auth: context.auth,
+ fn: (client) => client.query(sql, where.values),
+ });
+ const hasMore = result.rows.length > max;
+ const rows = result.rows.slice(0, max);
+ return { rows, count: rows.length, hasMore, nextOffset: hasMore ? skip + max : null };
+ },
+});
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/rows/get-row-by-key.ts b/packages/pieces/community/postgres/src/lib/actions/ai/rows/get-row-by-key.ts
new file mode 100644
index 00000000000..e39c6ac4661
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/rows/get-row-by-key.ts
@@ -0,0 +1,62 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { Client } from 'pg';
+import format from 'pg-format';
+import { postgresAuth } from '../../../auth';
+import { postgresAi, postgresAiProps } from '../../../ai-common';
+import { postgresGetRowByKeyOutputSchema } from '../../../output-schemas';
+
+export const getRowByKey = createAction({
+ auth: postgresAuth,
+ name: 'postgres_get_row_by_key',
+ outputSchema: postgresGetRowByKeyOutputSchema,
+ displayName: 'Get Row by Key',
+ description: 'Gets one row by its primary key or another unique column.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Returns the single row whose key column equals the given value, and fails if no row or more than one row matches. Key Column defaults to the table\'s single-column primary key; name a unique column to look up by it instead. Key values come from Insert Rows, Upsert Row or Find Rows. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ table: postgresAiProps.table,
+ keyValue: Property.ShortText({
+ displayName: 'Key Value',
+ description: 'The value of the key column, e.g. the id returned by Insert Rows.',
+ required: true,
+ }),
+ keyColumn: Property.ShortText({
+ displayName: 'Key Column',
+ description: 'A unique column to look up by. Leave empty to use the primary key.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { table, keyColumn, keyValue } = context.propsValue;
+ return postgresAi.withClient({
+ auth: context.auth,
+ fn: async (client) => {
+ const relation = await postgresAi.resolveRelation({ client, name: table, label: 'Table' });
+ const column = keyColumn !== undefined && keyColumn !== '' ? keyColumn : await primaryKeyColumn({ client, oid: relation.oid, table });
+ const result = await client.query(
+ `SELECT * FROM ${format('%I.%I', relation.schema, relation.name)} WHERE ${format.ident(column)} = $1 LIMIT 2`,
+ [keyValue],
+ );
+ if (result.rows.length === 0) {
+ throw new Error(`No row in "${table}" where ${column} = ${keyValue}.`);
+ }
+ if (result.rows.length > 1) {
+ throw new Error(`More than one row in "${table}" has ${column} = ${keyValue}; that column is not unique. Use Find Rows instead.`);
+ }
+ return { row: result.rows[0] };
+ },
+ });
+ },
+});
+
+async function primaryKeyColumn({ client, oid, table }: { client: Client; oid: string; table: string }): Promise<string> {
+ const columns = await postgresAi.primaryKeyColumns({ client, oid });
+ if (columns.length !== 1) {
+ throw new Error(`Table "${table}" ${columns.length === 0 ? 'has no primary key' : `has a composite primary key (${columns.join(', ')})`}; set Key Column, or use Find Rows.`);
+ }
+ return columns[0];
+}
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/rows/insert-rows.ts b/packages/pieces/community/postgres/src/lib/actions/ai/rows/insert-rows.ts
new file mode 100644
index 00000000000..69b9a8a4f26
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/rows/insert-rows.ts
@@ -0,0 +1,80 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import format from 'pg-format';
+import { postgresAuth } from '../../../auth';
+import { postgresAi, postgresAiProps } from '../../../ai-common';
+import { postgresInsertRowsOutputSchema } from '../../../output-schemas';
+
+export const insertRowsAi = createAction({
+ auth: postgresAuth,
+ name: 'postgres_insert_rows',
+ outputSchema: postgresInsertRowsOutputSchema,
+ displayName: 'Insert Rows',
+ description: 'Inserts one or more rows into a table and returns them as stored.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description: `Inserts a list of rows (objects of column name to value) in one statement, so either all rows are inserted or none. Columns a row leaves out get their default, and the stored rows come back with generated ids and defaults. Up to ${postgresAi.INSERT_MAX_ROWS} rows per call. Not idempotent: repeating adds duplicates or fails on a unique key; use Upsert Row to insert-or-update by key. Column names come from Describe Table.`,
+ idempotent: false,
+ },
+ props: {
+ table: postgresAiProps.table,
+ rows: Property.Json({
+ displayName: 'Rows',
+ description: 'A list of objects, one per row, e.g. [{"email": "[email protected]", "name": "Ada"}]. For a json or jsonb column holding a list, pass the list as a JSON string.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { table } = context.propsValue;
+ const records = toRecords({ rows: context.propsValue.rows });
+ const columns = [...new Set(records.flatMap((record) => Object.keys(record)))];
+ if (columns.length === 0 && records.length > 1) {
+ throw new Error('Every row is empty; give at least one column per row, or insert one empty row at a time.');
+ }
+ const values: unknown[] = [];
+ const tuples = records.map((record) => `(${columns.map((column) => {
+ if (!(column in record)) {
+ return 'DEFAULT';
+ }
+ values.push(record[column]);
+ return `$${values.length}`;
+ }).join(', ')})`);
+ if (values.length > MAX_PARAMETERS) {
+ throw new Error(`These rows need ${values.length} values, more than Postgres accepts in one statement (${MAX_PARAMETERS}). Split them into smaller calls.`);
+ }
+ const target = columns.length > 0
+ ? ` (${columns.map((column) => format.ident(column)).join(', ')}) VALUES ${tuples.join(', ')}`
+ : ' DEFAULT VALUES';
+ const result = await postgresAi.withClient({
+ auth: context.auth,
+ fn: (client) => client.query(`INSERT INTO ${postgresAi.quoteName({ name: table })}${target} RETURNING *`, values),
+ });
+ return { rows: result.rows, rowCount: result.rowCount ?? 0 };
+ },
+});
+
+function toRecords({ rows }: { rows: unknown }): Record<string, unknown>[] {
+ const list = typeof rows === 'string' ? parseRows({ text: rows }) : rows;
+ if (!Array.isArray(list) || list.length === 0) {
+ throw new Error('Rows must be a non-empty list of objects, e.g. [{"name": "Ada"}].');
+ }
+ if (list.length > postgresAi.INSERT_MAX_ROWS) {
+ throw new Error(`Rows has ${list.length} entries; insert at most ${postgresAi.INSERT_MAX_ROWS} per call.`);
+ }
+ return list.map((row, index) => {
+ if (!postgresAi.isRecord(row)) {
+ throw new Error(`Row ${index + 1} must be an object of column name to value.`);
+ }
+ return row;
+ });
+}
+
+function parseRows({ text }: { text: string }): unknown {
+ try {
+ return JSON.parse(text);
+ } catch {
+ throw new Error('Rows must be valid JSON: a list of objects.');
+ }
+}
+
+const MAX_PARAMETERS = 65535;
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/rows/update-rows.ts b/packages/pieces/community/postgres/src/lib/actions/ai/rows/update-rows.ts
new file mode 100644
index 00000000000..5a5064d0d31
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/rows/update-rows.ts
@@ -0,0 +1,47 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { postgresAuth } from '../../../auth';
+import { postgresAi, postgresAiProps } from '../../../ai-common';
+import { postgresUpdateRowsOutputSchema } from '../../../output-schemas';
+
+export const updateRowsAi = createAction({
+ auth: postgresAuth,
+ name: 'postgres_update_rows',
+ outputSchema: postgresUpdateRowsOutputSchema,
+ displayName: 'Update Rows',
+ description: 'Updates every row that matches the filters, up to a safety limit.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description: 'Sets the given column values on all rows matching every filter (at least one filter required) and returns the updated rows. Runs in a transaction and changes nothing if more than Max Rows match; check with Count Rows first. Setting the same values again leaves the same rows, so it is safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ table: postgresAiProps.table,
+ filters: postgresAiProps.filters({ required: true }),
+ values: Property.Object({
+ displayName: 'Values',
+ description: 'Column names mapped to new values, e.g. {"status": "archived"}. Columns left out keep their value.',
+ required: true,
+ }),
+ maxRows: postgresAiProps.maxRows({ verb: 'updated' }),
+ },
+ async run(context) {
+ const { table, filters, maxRows } = context.propsValue;
+ const limit = postgresAi.boundedInteger({ value: maxRows, defaultValue: postgresAi.WRITE_GUARD_DEFAULT, min: 1, max: postgresAi.WRITE_GUARD_MAX, label: 'Max Rows' });
+ const set = postgresAi.buildSet({ values: postgresAi.parseValues({ value: context.propsValue.values, label: 'Values' }), startAt: 0 });
+ const where = postgresAi.buildWhere({ filters, startAt: set.values.length });
+ const quotedTable = postgresAi.quoteName({ name: table });
+ return postgresAi.withClient({
+ auth: context.auth,
+ fn: (client) =>
+ postgresAi.guardedWrite({
+ client,
+ quotedTable,
+ where: postgresAi.buildWhere({ filters, startAt: 0 }),
+ maxRows: limit,
+ verb: 'updated',
+ write: { sql: `UPDATE ${quotedTable} SET ${set.sql}${where.sql} RETURNING *`, values: [...set.values, ...where.values] },
+ }),
+ });
+ },
+});
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/rows/upsert-row.ts b/packages/pieces/community/postgres/src/lib/actions/ai/rows/upsert-row.ts
new file mode 100644
index 00000000000..767f099f7d7
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/rows/upsert-row.ts
@@ -0,0 +1,62 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import format from 'pg-format';
+import { postgresAuth } from '../../../auth';
+import { postgresAi, postgresAiProps } from '../../../ai-common';
+import { postgresUpsertRowOutputSchema } from '../../../output-schemas';
+
+export const upsertRow = createAction({
+ auth: postgresAuth,
+ name: 'postgres_upsert_row',
+ outputSchema: postgresUpsertRowOutputSchema,
+ displayName: 'Upsert Row',
+ description: 'Inserts a row, or updates it when a row with the same key already exists.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description: 'Inserts a row, or when a row with the same Conflict Columns values exists, updates it instead (INSERT ... ON CONFLICT). Conflict Columns must match a primary key or unique index (List Indexes shows them) and be present in Values. Returns the stored row and whether it was inserted. Repeating with the same values leaves the same row, so it is safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ table: postgresAiProps.table,
+ values: Property.Object({
+ displayName: 'Values',
+ description: 'Column names mapped to values, including the conflict columns, e.g. {"email": "[email protected]", "name": "Ada"}.',
+ required: true,
+ }),
+ conflictColumns: Property.Array({
+ displayName: 'Conflict Columns',
+ description: 'The columns of a primary key or unique index that identify an existing row, e.g. ["email"].',
+ required: true,
+ }),
+ updateColumns: Property.Array({
+ displayName: 'Update Columns',
+ description: 'Columns to overwrite when the row already exists. Leave empty to overwrite every column in Values except the conflict columns.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { table } = context.propsValue;
+ const values = postgresAi.parseValues({ value: context.propsValue.values, label: 'Values' });
+ const columns = Object.keys(values);
+ const conflict = (context.propsValue.conflictColumns ?? []).map((column) => String(column));
+ if (conflict.length === 0) {
+ throw new Error('Conflict Columns needs at least one column.');
+ }
+ const requested = (context.propsValue.updateColumns ?? []).map((column) => String(column));
+ const missing = [...conflict, ...requested].filter((column) => !columns.includes(column));
+ if (missing.length > 0) {
+ throw new Error(`Conflict Columns and Update Columns must also be in Values; missing: ${missing.join(', ')}.`);
+ }
+ const nonKey = columns.filter((column) => !conflict.includes(column));
+ const toUpdate = requested.length > 0 ? requested : nonKey.length > 0 ? nonKey : conflict.slice(0, 1);
+ const sql = `INSERT INTO ${postgresAi.quoteName({ name: table })} (${columns.map((column) => format.ident(column)).join(', ')}) VALUES (${columns.map((_, index) => `$${index + 1}`).join(', ')}) ON CONFLICT (${conflict.map((column) => format.ident(column)).join(', ')}) DO UPDATE SET ${toUpdate.map((column) => `${format.ident(column)} = EXCLUDED.${format.ident(column)}`).join(', ')} RETURNING *, (xmax = 0)`;
+ const result = await postgresAi.withClient({
+ auth: context.auth,
+ fn: (client) => client.query<unknown[]>({ text: sql, values: columns.map((column) => values[column]), rowMode: 'array' }),
+ });
+ const stored = result.rows[0] ?? [];
+ const rowFields = result.fields.slice(0, -1);
+ const row = Object.fromEntries(rowFields.map((field, index) => [field.name, stored[index]]));
+ return { row, inserted: stored[rowFields.length] === true };
+ },
+});
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/schema/describe-table.ts b/packages/pieces/community/postgres/src/lib/actions/ai/schema/describe-table.ts
new file mode 100644
index 00000000000..d9edabee00a
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/schema/describe-table.ts
@@ -0,0 +1,70 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { postgresAuth } from '../../../auth';
+import { postgresAi, postgresAiProps } from '../../../ai-common';
+import { postgresDescribeTableOutputSchema } from '../../../output-schemas';
+
+export const describeTable = createAction({
+ auth: postgresAuth,
+ name: 'postgres_describe_table',
+ outputSchema: postgresDescribeTableOutputSchema,
+ displayName: 'Describe Table',
+ description: 'Lists the columns of a table or view with their types, keys, references and defaults.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Returns every column of a table or view in order: name, type, nullability, default, identity and generated flags, whether it is part of the primary key, and the schema.table.column it references through a foreign key. Use before reading or writing rows to learn column names, required columns, the primary key and how tables join. Table names come from Get Tables or List Views. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ table: postgresAiProps.table,
+ },
+ async run(context) {
+ const { table } = context.propsValue;
+ return postgresAi.withClient({
+ auth: context.auth,
+ fn: async (client) => {
+ const relation = await postgresAi.resolveRelation({ client, name: table, label: 'Table' });
+ const columns = await client.query<ColumnRow>(
+ `SELECT a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type, NOT a.attnotnull AS nullable, pg_get_expr(d.adbin, d.adrelid) AS "defaultValue", a.attidentity <> '' AS "isIdentity", a.attgenerated <> '' AS "isGenerated", col_description(a.attrelid, a.attnum) AS comment FROM pg_attribute a LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum WHERE a.attrelid = $1::oid AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`,
+ [relation.oid],
+ );
+ const references = await client.query<ReferenceRow>(
+ `SELECT a.attname AS column, fn.nspname AS "refSchema", fc.relname AS "refTable", fa.attname AS "refColumn" FROM pg_constraint con JOIN LATERAL unnest(con.conkey, con.confkey) AS k(attnum, fattnum) ON true JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = k.attnum JOIN pg_class fc ON fc.oid = con.confrelid JOIN pg_namespace fn ON fn.oid = fc.relnamespace JOIN pg_attribute fa ON fa.attrelid = con.confrelid AND fa.attnum = k.fattnum WHERE con.conrelid = $1::oid AND con.contype = 'f'`,
+ [relation.oid],
+ );
+ const primaryKey = await postgresAi.primaryKeyColumns({ client, oid: relation.oid });
+ return {
+ schema: relation.schema,
+ table: relation.name,
+ primaryKey,
+ columns: columns.rows.map((column) => {
+ const reference = references.rows.find((row) => row.column === column.name);
+ return {
+ ...column,
+ isPrimaryKey: primaryKey.includes(column.name),
+ references: reference === undefined ? null : `${reference.refSchema}.${reference.refTable}.${reference.refColumn}`,
+ };
+ }),
+ count: columns.rows.length,
+ };
+ },
+ });
+ },
+});
+
+type ColumnRow = {
+ name: string;
+ type: string;
+ nullable: boolean;
+ defaultValue: string | null;
+ isIdentity: boolean;
+ isGenerated: boolean;
+ comment: string | null;
+};
+
+type ReferenceRow = {
+ column: string;
+ refSchema: string;
+ refTable: string;
+ refColumn: string;
+};
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/schema/get-view-definition.ts b/packages/pieces/community/postgres/src/lib/actions/ai/schema/get-view-definition.ts
new file mode 100644
index 00000000000..a21bf8b7065
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/schema/get-view-definition.ts
@@ -0,0 +1,44 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { postgresAuth } from '../../../auth';
+import { postgresAi } from '../../../ai-common';
+import { postgresGetViewDefinitionOutputSchema } from '../../../output-schemas';
+
+export const getViewDefinition = createAction({
+ auth: postgresAuth,
+ name: 'postgres_get_view_definition',
+ outputSchema: postgresGetViewDefinitionOutputSchema,
+ displayName: 'Get View Definition',
+ description: 'Returns the SQL that defines a view or materialized view.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Returns the SELECT statement behind a view or materialized view, to learn what it computes and which tables it reads. View names come from List Views. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ view: Property.ShortText({
+ displayName: 'View',
+ description: 'View name as returned by List Views, written schema.view (e.g. public.active_orders). A bare name is looked up on the search path.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { view } = context.propsValue;
+ return postgresAi.withClient({
+ auth: context.auth,
+ fn: async (client) => {
+ const relation = await postgresAi.resolveRelation({ client, name: view, label: 'View' });
+ if (relation.kind !== 'v' && relation.kind !== 'm') {
+ throw new Error(`"${view}" is a table, not a view. Use Describe Table for its columns.`);
+ }
+ const result = await client.query<{ definition: string }>('SELECT pg_get_viewdef($1::oid, true) AS definition', [relation.oid]);
+ return {
+ schema: relation.schema,
+ name: relation.name,
+ isMaterialized: relation.kind === 'm',
+ definition: result.rows[0]?.definition ?? null,
+ };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/schema/list-indexes.ts b/packages/pieces/community/postgres/src/lib/actions/ai/schema/list-indexes.ts
new file mode 100644
index 00000000000..3155d3f9a85
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/schema/list-indexes.ts
@@ -0,0 +1,35 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { postgresAuth } from '../../../auth';
+import { postgresAi, postgresAiProps } from '../../../ai-common';
+import { postgresListIndexesOutputSchema } from '../../../output-schemas';
+
+export const listIndexes = createAction({
+ auth: postgresAuth,
+ name: 'postgres_list_indexes',
+ outputSchema: postgresListIndexesOutputSchema,
+ displayName: 'List Indexes',
+ description: 'Lists the indexes on a table.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description: 'Lists every index on a table with its key columns, method (btree, gin, ...), whether it is unique or the primary key, and its full CREATE INDEX definition. Use to learn which columns lookups and filters are fast on, and which unique keys Upsert Row can use as conflict columns. Table names come from Get Tables. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ table: postgresAiProps.table,
+ },
+ async run(context) {
+ const { table } = context.propsValue;
+ return postgresAi.withClient({
+ auth: context.auth,
+ fn: async (client) => {
+ const relation = await postgresAi.resolveRelation({ client, name: table, label: 'Table' });
+ const result = await client.query(
+ `SELECT ic.relname AS name, ARRAY(SELECT pg_get_indexdef(ix.indexrelid, n, true) FROM generate_series(1, ix.indnkeyatts) AS n ORDER BY n) AS columns, am.amname AS method, ix.indisunique AS "isUnique", ix.indisprimary AS "isPrimary", pg_get_indexdef(ix.indexrelid) AS definition FROM pg_index ix JOIN pg_class ic ON ic.oid = ix.indexrelid JOIN pg_am am ON am.oid = ic.relam WHERE ix.indrelid = $1::oid ORDER BY ic.relname`,
+ [relation.oid],
+ );
+ return { schema: relation.schema, table: relation.name, indexes: result.rows, count: result.rows.length };
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/schema/list-routines.ts b/packages/pieces/community/postgres/src/lib/actions/ai/schema/list-routines.ts
new file mode 100644
index 00000000000..860dc11ed77
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/schema/list-routines.ts
@@ -0,0 +1,39 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { postgresAuth } from '../../../auth';
+import { postgresAi, postgresAiProps } from '../../../ai-common';
+import { postgresListRoutinesOutputSchema } from '../../../output-schemas';
+
+export const listRoutines = createAction({
+ auth: postgresAuth,
+ name: 'postgres_list_routines',
+ outputSchema: postgresListRoutinesOutputSchema,
+ displayName: 'List Routines',
+ description: 'Lists the user-defined functions and procedures in the database.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description: 'Lists user-defined functions and procedures (not built-ins or extension functions) with their schema, kind, argument list (with each default, marking the arguments Call Routine may leave out), return type and language, optionally in one schema or matching a LIKE name pattern. Use before Call Routine to learn the name and the arguments to pass in order. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ schema: postgresAiProps.schema,
+ namePattern: postgresAiProps.namePattern,
+ },
+ async run(context) {
+ const { schema, namePattern } = context.propsValue;
+ const conditions = [
+ { sql: 'n.nspname = $', value: schema },
+ { sql: 'p.proname LIKE $', value: namePattern },
+ ].filter((condition) => condition.value !== undefined && condition.value !== '');
+ const where = conditions.map((condition, index) => ` AND ${condition.sql}${index + 1}`).join('');
+ const result = await postgresAi.withClient({
+ auth: context.auth,
+ fn: (client) =>
+ client.query(
+ `SELECT n.nspname AS schema, p.proname AS name, CASE p.prokind WHEN 'p' THEN 'procedure' ELSE 'function' END AS kind, pg_get_function_arguments(p.oid) AS arguments, pg_get_function_result(p.oid) AS returns, l.lanname AS language FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace JOIN pg_language l ON l.oid = p.prolang WHERE p.prokind IN ('f', 'p') AND ${postgresAi.notSystemSchema({ column: 'n.nspname' })} AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e')${where} ORDER BY n.nspname, p.proname`,
+ conditions.map((condition) => condition.value),
+ ),
+ });
+ return { routines: result.rows, count: result.rows.length };
+ },
+});
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/schema/list-schemas.ts b/packages/pieces/community/postgres/src/lib/actions/ai/schema/list-schemas.ts
new file mode 100644
index 00000000000..8f8ebbecfcc
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/schema/list-schemas.ts
@@ -0,0 +1,34 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { postgresAuth } from '../../../auth';
+import { postgresAi, postgresAiProps } from '../../../ai-common';
+import { postgresListSchemasOutputSchema } from '../../../output-schemas';
+
+export const listSchemas = createAction({
+ auth: postgresAuth,
+ name: 'postgres_list_schemas',
+ outputSchema: postgresListSchemasOutputSchema,
+ displayName: 'List Schemas',
+ description: 'Lists the schemas in the connected database.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description: 'Lists the non-system schemas of the connected database with their owner, and marks the one tables resolve to by default (current). Use first to learn where tables live; Get Tables, List Views and List Routines take or return these schema names. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ namePattern: postgresAiProps.namePattern,
+ },
+ async run(context) {
+ const { namePattern } = context.propsValue;
+ const hasPattern = namePattern !== undefined && namePattern !== '';
+ const result = await postgresAi.withClient({
+ auth: context.auth,
+ fn: (client) =>
+ client.query(
+ `SELECT nspname AS name, pg_get_userbyid(nspowner) AS owner, nspname = current_schema() AS current FROM pg_namespace WHERE ${postgresAi.notSystemSchema({ column: 'nspname' })}${hasPattern ? ' AND nspname LIKE $1' : ''} ORDER BY nspname`,
+ hasPattern ? [namePattern] : [],
+ ),
+ });
+ return { schemas: result.rows, count: result.rows.length };
+ },
+});
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/schema/list-views.ts b/packages/pieces/community/postgres/src/lib/actions/ai/schema/list-views.ts
new file mode 100644
index 00000000000..0270e67e739
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/schema/list-views.ts
@@ -0,0 +1,39 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { postgresAuth } from '../../../auth';
+import { postgresAi, postgresAiProps } from '../../../ai-common';
+import { postgresListViewsOutputSchema } from '../../../output-schemas';
+
+export const listViews = createAction({
+ auth: postgresAuth,
+ name: 'postgres_list_views',
+ outputSchema: postgresListViewsOutputSchema,
+ displayName: 'List Views',
+ description: 'Lists the views and materialized views in the database.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description: 'Lists views and materialized views with their schema, optionally in one schema or matching a LIKE name pattern. Views are read like tables with Find Rows or Run Select Query; Get View Definition shows the SQL behind one. Schema names come from List Schemas. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ schema: postgresAiProps.schema,
+ namePattern: postgresAiProps.namePattern,
+ },
+ async run(context) {
+ const { schema, namePattern } = context.propsValue;
+ const conditions = [
+ { sql: 'n.nspname = $', value: schema },
+ { sql: 'c.relname LIKE $', value: namePattern },
+ ].filter((condition) => condition.value !== undefined && condition.value !== '');
+ const where = conditions.map((condition, index) => ` AND ${condition.sql}${index + 1}`).join('');
+ const result = await postgresAi.withClient({
+ auth: context.auth,
+ fn: (client) =>
+ client.query(
+ `SELECT n.nspname AS schema, c.relname AS name, c.relkind = 'm' AS "isMaterialized", pg_get_userbyid(c.relowner) AS owner FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('v', 'm') AND ${postgresAi.notSystemSchema({ column: 'n.nspname' })}${where} ORDER BY n.nspname, c.relname`,
+ conditions.map((condition) => condition.value),
+ ),
+ });
+ return { views: result.rows, count: result.rows.length };
+ },
+});
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/server/get-server-info.ts b/packages/pieces/community/postgres/src/lib/actions/ai/server/get-server-info.ts
new file mode 100644
index 00000000000..027fb1c6ba0
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/server/get-server-info.ts
@@ -0,0 +1,29 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { postgresAuth } from '../../../auth';
+import { postgresAi } from '../../../ai-common';
+import { postgresGetServerInfoOutputSchema } from '../../../output-schemas';
+
+export const getServerInfo = createAction({
+ auth: postgresAuth,
+ name: 'postgres_get_server_info',
+ outputSchema: postgresGetServerInfoOutputSchema,
+ displayName: 'Get Server Info',
+ description: 'Returns the server version and the settings of the current session.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Returns the Postgres version, the connected database and user, the session time zone, search path and encoding, and whether the server is a read-only replica. Use to learn which SQL features are available and how unqualified table names resolve. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ async run(context) {
+ const result = await postgresAi.withClient({
+ auth: context.auth,
+ fn: (client) =>
+ client.query(
+ `SELECT version() AS version, current_setting('server_version') AS "serverVersion", current_setting('server_version_num')::int AS "serverVersionNum", current_database() AS database, current_user AS "user", current_setting('TimeZone') AS "timeZone", current_setting('search_path') AS "searchPath", current_setting('server_encoding') AS encoding, pg_is_in_recovery() AS "isReplica"`,
+ ),
+ });
+ return result.rows[0];
+ },
+});
diff --git a/packages/pieces/community/postgres/src/lib/actions/ai/server/list-activity.ts b/packages/pieces/community/postgres/src/lib/actions/ai/server/list-activity.ts
new file mode 100644
index 00000000000..457f7d36aab
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/actions/ai/server/list-activity.ts
@@ -0,0 +1,29 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { postgresAuth } from '../../../auth';
+import { postgresAi } from '../../../ai-common';
+import { postgresListActivityOutputSchema } from '../../../output-schemas';
+
+export const listActivity = createAction({
+ auth: postgresAuth,
+ name: 'postgres_list_activity',
+ outputSchema: postgresListActivityOutputSchema,
+ displayName: 'List Activity',
+ description: 'Lists the sessions connected to the current database and what they are running.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description: 'Lists the sessions connected to the current database: process id, user, application, client address, state, the current or last query, when it started, and what it is waiting on. Use to spot long-running or blocked queries. Query text of other users\' sessions is hidden unless the connection user has the pg_read_all_stats role. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ async run(context) {
+ const result = await postgresAi.withClient({
+ auth: context.auth,
+ fn: (client) =>
+ client.query(
+ `SELECT pid, usename AS "user", application_name AS application, host(client_addr) AS "clientAddress", state, query, backend_start AS "backendStart", xact_start AS "transactionStart", query_start AS "queryStart", state_change AS "stateChange", wait_event_type AS "waitEventType", wait_event AS "waitEvent", pid = pg_backend_pid() AS "isCurrentSession" FROM pg_stat_activity WHERE datname = current_database() ORDER BY backend_start`,
+ ),
+ });
+ return { sessions: result.rows, count: result.rows.length };
+ },
+});
diff --git a/packages/pieces/community/postgres/src/lib/actions/delete-row.ts b/packages/pieces/community/postgres/src/lib/actions/delete-row.ts
index 8867ef52a78..b378827773d 100644
--- a/packages/pieces/community/postgres/src/lib/actions/delete-row.ts
+++ b/packages/pieces/community/postgres/src/lib/actions/delete-row.ts
@@ -1,5 +1,5 @@
import { createAction, MarkdownVariant, Property } from '@activepieces/pieces-framework';
-import { postgresAuth } from '../..';
+import { postgresAuth } from '../auth';
import { pgClient, postgresCommon, postgresUtils } from '../common';
import { deleteRowOutputSchema } from '../output-schemas';
@@ -9,7 +9,7 @@ export const deleteRow = createAction({
classification: 'DESTRUCTIVE',
displayName: 'Delete Row',
description: 'Deletes one or more rows from a table',
- audience: 'both',
+ audience: 'human',
outputSchema: deleteRowOutputSchema,
aiMetadata: {
description: 'Deletes every row in a PostgreSQL table whose search column equals a given value, and returns how many rows were removed. Use to remove records matched by a single column. Enable Return Deleted Rows to also get the deleted rows back, but leave it off when the delete can match many rows. Idempotent: once the matching rows are gone, re-running with the same input deletes nothing further.',
diff --git a/packages/pieces/community/postgres/src/lib/actions/find-rows.ts b/packages/pieces/community/postgres/src/lib/actions/find-rows.ts
index 0e59ab43b5a..27c3fbeb6e0 100644
--- a/packages/pieces/community/postgres/src/lib/actions/find-rows.ts
+++ b/packages/pieces/community/postgres/src/lib/actions/find-rows.ts
@@ -1,5 +1,5 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { postgresAuth } from '../..';
+import { postgresAuth } from '../auth';
import { pgClient, postgresCommon, postgresUtils, warningMarkdown } from '../common';
import { findRowsOutputSchema } from '../output-schemas';
@@ -9,7 +9,7 @@ export const findRows = createAction({
classification: 'SEARCH',
displayName: 'Find Rows',
description: 'Reads rows from a table',
- audience: 'both',
+ audience: 'human',
outputSchema: findRowsOutputSchema,
aiMetadata: {
description: 'Reads rows from a PostgreSQL table, optionally narrowed by a SQL WHERE condition and limited to specific columns. Use to look up or filter records by arbitrary criteria. Returns at most 100 rows unless limit is raised or cleared. The condition is interpolated raw into the query, so pass dynamic values through the args array and reference them as $1, $2 placeholders to avoid SQL injection. Read-only and idempotent.',
diff --git a/packages/pieces/community/postgres/src/lib/actions/get-tables.ts b/packages/pieces/community/postgres/src/lib/actions/get-tables.ts
index 020ea357471..49ea398084c 100644
--- a/packages/pieces/community/postgres/src/lib/actions/get-tables.ts
+++ b/packages/pieces/community/postgres/src/lib/actions/get-tables.ts
@@ -1,5 +1,5 @@
import { createAction } from '@activepieces/pieces-framework';
-import { postgresAuth } from '../..';
+import { postgresAuth } from '../auth';
import { pgClient, postgresUtils } from '../common';
import { getTablesOutputSchema } from '../output-schemas';
diff --git a/packages/pieces/community/postgres/src/lib/actions/insert-row.ts b/packages/pieces/community/postgres/src/lib/actions/insert-row.ts
index 680630dd5da..0fbfaa583cc 100644
--- a/packages/pieces/community/postgres/src/lib/actions/insert-row.ts
+++ b/packages/pieces/community/postgres/src/lib/actions/insert-row.ts
@@ -1,5 +1,5 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { postgresAuth } from '../..';
+import { postgresAuth } from '../auth';
import { pgClient, postgresCommon, postgresUtils } from '../common';
import { insertRowOutputSchema } from '../output-schemas';
diff --git a/packages/pieces/community/postgres/src/lib/actions/insert-rows.ts b/packages/pieces/community/postgres/src/lib/actions/insert-rows.ts
index 4a291f539f8..559e0601c19 100644
--- a/packages/pieces/community/postgres/src/lib/actions/insert-rows.ts
+++ b/packages/pieces/community/postgres/src/lib/actions/insert-rows.ts
@@ -1,6 +1,6 @@
import { createAction, InputPropertyMap, Property } from '@activepieces/pieces-framework';
import { QueryResult } from 'pg';
-import { postgresAuth } from '../..';
+import { postgresAuth } from '../auth';
import { pgClient, PostgresColumn, postgresCommon, postgresUtils } from '../common';
import { insertRowsOutputSchema } from '../output-schemas';
@@ -10,7 +10,7 @@ export const insertRows = createAction({
classification: 'WRITE',
displayName: 'Insert Multiple Rows',
description: 'Inserts many rows into a table in a single transaction',
- audience: 'both',
+ audience: 'human',
outputSchema: insertRowsOutputSchema,
aiMetadata: {
description: 'Inserts an array of rows into a PostgreSQL table, each row a map of column names to values, using multi-row INSERT statements inside one transaction: if any row fails, none are inserted. Columns a row omits get the column default. Returns the inserted count and, when Return Inserted Rows is on, the stored rows including generated ids. Use instead of repeated single inserts for bulk loads. Not idempotent: each call appends new rows, so repeating it adds duplicates or errors on a unique-key collision.',
diff --git a/packages/pieces/community/postgres/src/lib/actions/run-query.ts b/packages/pieces/community/postgres/src/lib/actions/run-query.ts
index a839e4262c7..bd39a256bb8 100644
--- a/packages/pieces/community/postgres/src/lib/actions/run-query.ts
+++ b/packages/pieces/community/postgres/src/lib/actions/run-query.ts
@@ -1,5 +1,5 @@
import { createAction, MarkdownVariant, Property } from '@activepieces/pieces-framework';
-import { postgresAuth } from '../..';
+import { postgresAuth } from '../auth';
import { pgClient } from '../common';
export const runQuery = createAction({
diff --git a/packages/pieces/community/postgres/src/lib/actions/update-row.ts b/packages/pieces/community/postgres/src/lib/actions/update-row.ts
index 4b2337c9f50..608df707638 100644
--- a/packages/pieces/community/postgres/src/lib/actions/update-row.ts
+++ b/packages/pieces/community/postgres/src/lib/actions/update-row.ts
@@ -1,5 +1,5 @@
import { createAction, MarkdownVariant, Property } from '@activepieces/pieces-framework';
-import { postgresAuth } from '../..';
+import { postgresAuth } from '../auth';
import { pgClient, postgresCommon, postgresUtils } from '../common';
import { updateRowOutputSchema } from '../output-schemas';
@@ -9,7 +9,7 @@ export const updateRow = createAction({
classification: 'WRITE',
displayName: 'Update Row',
description: 'Updates one or more rows in a table',
- audience: 'both',
+ audience: 'human',
outputSchema: updateRowOutputSchema,
aiMetadata: {
description: 'Updates every row in a PostgreSQL table whose search column equals a given value, setting the supplied column-to-value pairs, and returns how many rows changed. Use to modify existing records matched by a single column. Enable Return Updated Rows to also get the rows themselves back, but leave it off when the update can match many rows. Idempotent: re-running with the same input writes the same values and has no additional effect.',
diff --git a/packages/pieces/community/postgres/src/lib/ai-common.ts b/packages/pieces/community/postgres/src/lib/ai-common.ts
new file mode 100644
index 00000000000..0784da44d3c
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/ai-common.ts
@@ -0,0 +1,336 @@
+import { randomUUID } from 'crypto';
+import { AppConnectionValueForAuthProperty, Property } from '@activepieces/pieces-framework';
+import { Client, QueryConfig, QueryResultRow } from 'pg';
+import format from 'pg-format';
+import { postgresAuth } from './auth';
+import { pgClient } from './client';
+
+async function withClient<T>({ auth, fn }: { auth: PostgresAuthValue; fn: (client: Client) => Promise<T> }): Promise<T> {
+ const client = await pgClient(auth);
+ client.on('error', () => undefined);
+ try {
+ return await fn(client);
+ } finally {
+ await client.end().catch(() => undefined);
+ }
+}
+
+async function inTransaction<T>({ client, readOnly, fn }: { client: Client; readOnly: boolean; fn: () => Promise<T> }): Promise<T> {
+ await client.query(readOnly ? 'BEGIN READ ONLY' : 'BEGIN');
+ try {
+ const result = await fn();
+ await client.query(readOnly ? 'ROLLBACK' : 'COMMIT');
+ return result;
+ } catch (error) {
+ await client.query('ROLLBACK').catch(() => undefined);
+ throw error;
+ }
+}
+
+function singleStatement({ text, values }: { text: string; values: unknown[] }): QueryConfig<unknown[]> {
+ return { name: `ap_${randomUUID().replace(/-/g, '')}`, text, values };
+}
+
+function splitName({ name }: { name: string }): { schema: string | null; name: string } {
+ const matches = [...name.matchAll(NAME_PART)];
+ const parts = matches.map((match) => (match[1] !== undefined ? match[1].replace(/""/g, '"') : match[2]));
+ const covered = matches.reduce((total, match) => total + match[0].length, 0);
+ if (covered !== name.length || name.startsWith('.') || parts.length === 0 || parts.length > 2 || parts.some((part) => part === '')) {
+ throw new Error(`"${name}" is not a valid name. Write schema.name, and wrap a part that contains a dot in double quotes, e.g. "my.schema".orders.`);
+ }
+ return parts.length === 1 ? { schema: null, name: parts[0] } : { schema: parts[0], name: parts[1] };
+}
+
+function quoteName({ name }: { name: string }): string {
+ const parts = splitName({ name });
+ return parts.schema === null ? format.ident(parts.name) : format('%I.%I', parts.schema, parts.name);
+}
+
+async function resolveRelation({ client, name, label }: { client: Client; name: string; label: string }): Promise<Relation> {
+ const result = await client.query<Relation>(
+ `SELECT c.oid::text AS oid, n.nspname AS schema, c.relname AS name, c.relkind AS kind FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.oid = to_regclass($1)`,
+ [quoteName({ name })],
+ );
+ const relation = result.rows[0];
+ if (relation === undefined) {
+ throw new Error(`${label} "${name}" was not found. Use schema.name, or a name on the search path; Get Tables and List Views list them.`);
+ }
+ return relation;
+}
+
+async function primaryKeyColumns({ client, oid }: { client: Client; oid: string }): Promise<string[]> {
+ const result = await client.query<{ name: string }>(
+ `SELECT a.attname AS name FROM pg_index i JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord) ON true JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum WHERE i.indrelid = $1::oid AND i.indisprimary AND k.ord <= i.indnkeyatts ORDER BY k.ord`,
+ [oid],
+ );
+ return result.rows.map((row) => row.name);
+}
+
+function buildWhere({ filters, startAt }: { filters: unknown; startAt: number }): SqlFragment {
+ const parts = parseFilters({ filters }).reduce<SqlFragment[]>((acc, filter) => {
+ const used = acc.reduce((total, part) => total + part.values.length, 0);
+ return [...acc, filterToSql({ filter, index: startAt + used })];
+ }, []);
+ if (parts.length === 0) {
+ return { sql: '', values: [] };
+ }
+ return {
+ sql: ` WHERE ${parts.map((part) => part.sql).join(' AND ')}`,
+ values: parts.flatMap((part) => part.values),
+ };
+}
+
+function buildOrderBy({ sort }: { sort: unknown }): string {
+ const parts = toList({ value: sort, label: 'Sort' }).map((entry, index) => {
+ if (!isRecord(entry) || typeof entry['column'] !== 'string' || entry['column'] === '') {
+ throw new Error(`Sort ${index + 1} needs a column.`);
+ }
+ const direction = String(entry['direction'] ?? 'ASC').toUpperCase();
+ if (direction !== 'ASC' && direction !== 'DESC') {
+ throw new Error(`Sort ${index + 1} direction must be ASC or DESC.`);
+ }
+ return `${format.ident(entry['column'])} ${direction}`;
+ });
+ return parts.length > 0 ? ` ORDER BY ${parts.join(', ')}` : '';
+}
+
+function buildSet({ values, startAt }: { values: Record<string, unknown>; startAt: number }): SqlFragment {
+ const columns = Object.keys(values);
+ return {
+ sql: columns.map((column, index) => `${format.ident(column)} = $${startAt + index + 1}`).join(', '),
+ values: columns.map((column) => values[column]),
+ };
+}
+
+function boundedInteger({ value, defaultValue, min, max, label }: {
+ value: number | undefined;
+ defaultValue: number;
+ min: number;
+ max: number;
+ label: string;
+}): number {
+ const resolved = value ?? defaultValue;
+ if (!Number.isInteger(resolved) || resolved < min || resolved > max) {
+ throw new Error(`${label} must be a whole number from ${min} to ${max}.`);
+ }
+ return resolved;
+}
+
+function parseValues({ value, label }: { value: unknown; label: string }): Record<string, unknown> {
+ if (!isRecord(value) || Object.keys(value).length === 0) {
+ throw new Error(`${label} must be an object with at least one column name mapped to a value.`);
+ }
+ return value;
+}
+
+async function guardedWrite({ client, quotedTable, where, maxRows, write, verb }: {
+ client: Client;
+ quotedTable: string;
+ where: SqlFragment;
+ maxRows: number;
+ write: SqlFragment;
+ verb: string;
+}): Promise<{ rows: QueryResultRow[]; rowCount: number }> {
+ if (where.sql === '') {
+ throw new Error(`Provide at least one filter; this action never ${verb} a whole table.`);
+ }
+ const refuse = (total: number): Error =>
+ new Error(`The filters match ${total} rows, more than Max Rows (${maxRows}). Nothing was ${verb}; narrow the filters or raise Max Rows.`);
+ return inTransaction({
+ client,
+ readOnly: false,
+ fn: async () => {
+ const counted = await client.query<{ total: string }>(
+ `SELECT count(*) AS total FROM (SELECT 1 FROM ${quotedTable}${where.sql} LIMIT ${maxRows + 1} FOR UPDATE) AS matched`,
+ where.values,
+ );
+ const total = Number(counted.rows[0]?.total ?? 0);
+ if (total > maxRows) {
+ throw refuse(total);
+ }
+ const result = await client.query(write.sql, write.values);
+ const rowCount = result.rowCount ?? 0;
+ if (rowCount > maxRows) {
+ throw refuse(rowCount);
+ }
+ return { rows: result.rows, rowCount };
+ },
+ });
+}
+
+function parseFilters({ filters }: { filters: unknown }): Filter[] {
+ return toList({ value: filters, label: 'Filters' }).map((entry, index) => {
+ if (!isRecord(entry) || typeof entry['column'] !== 'string' || entry['column'] === '') {
+ throw new Error(`Filter ${index + 1} needs a column.`);
+ }
+ const operator = String(entry['operator'] ?? '=').toUpperCase();
+ if (!isFilterOperator(operator)) {
+ throw new Error(`Filter ${index + 1} operator "${operator}" is not supported. Use one of: ${FILTER_OPERATORS.join(', ')}.`);
+ }
+ return { column: entry['column'], operator, value: entry['value'] };
+ });
+}
+
+function filterToSql({ filter, index }: { filter: Filter; index: number }): SqlFragment {
+ const column = format.ident(filter.column);
+ const placeholder = `$${index + 1}`;
+ if (filter.operator === 'IS NULL' || filter.operator === 'IS NOT NULL') {
+ return { sql: `${column} ${filter.operator}`, values: [] };
+ }
+ 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 null values, or Run Select Query (WHERE column = '') to match empty text.`);
+ }
+ if (filter.operator === 'IN') {
+ return { sql: `${column} = ANY(${placeholder})`, values: [toArray({ value: filter.value })] };
+ }
+ if (filter.operator === 'NOT IN') {
+ return { sql: `${column} <> ALL(${placeholder})`, values: [toArray({ value: filter.value })] };
+ }
+ return { sql: `${column} ${filter.operator} ${placeholder}`, values: [filter.value] };
+}
+
+function toArray({ value }: { value: unknown }): unknown[] {
+ if (Array.isArray(value)) {
+ return value;
+ }
+ const text = String(value);
+ const parsed = text.trim().startsWith('[') ? parseJson({ text }) : undefined;
+ return Array.isArray(parsed) ? parsed : text.split(',').map((item) => item.trim());
+}
+
+function parseJson({ text }: { text: string }): unknown {
+ try {
+ return JSON.parse(text);
+ } catch {
+ return undefined;
+ }
+}
+
+function toList({ value, label }: { value: unknown; label: string }): unknown[] {
+ if (value === undefined || value === null || value === '') {
+ return [];
+ }
+ if (!Array.isArray(value)) {
+ throw new Error(`${label} must be a list.`);
+ }
+ return value;
+}
+
+function notSystemSchema({ column }: { column: string }): string {
+ return `${column} NOT LIKE 'pg\\_%' AND ${column} <> 'information_schema'`;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function isFilterOperator(value: string): value is FilterOperator {
+ return FILTER_OPERATORS.some((operator) => operator === value);
+}
+
+const NAME_PART = /(?:^|\.)(?:"((?:[^"]|"")*)"|([^."]+))(?=\.|$)/g;
+
+const FILTER_OPERATORS = ['=', '!=', '<', '<=', '>', '>=', 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE', 'IN', 'NOT IN', 'IS NULL', 'IS NOT NULL'] as const;
+
+const READ_DEFAULT_LIMIT = 100;
+const READ_MAX_LIMIT = 1000;
+const WRITE_GUARD_DEFAULT = 100;
+const WRITE_GUARD_MAX = 10000;
+const INSERT_MAX_ROWS = 1000;
+
+export const postgresAi = {
+ withClient,
+ inTransaction,
+ singleStatement,
+ splitName,
+ quoteName,
+ resolveRelation,
+ primaryKeyColumns,
+ buildWhere,
+ buildOrderBy,
+ buildSet,
+ boundedInteger,
+ parseValues,
+ guardedWrite,
+ isRecord,
+ notSystemSchema,
+ READ_DEFAULT_LIMIT,
+ READ_MAX_LIMIT,
+ WRITE_GUARD_DEFAULT,
+ WRITE_GUARD_MAX,
+ INSERT_MAX_ROWS,
+};
+
+export const postgresAiProps = {
+ table: Property.ShortText({
+ displayName: 'Table',
+ description: 'Table name as returned by Get Tables, written schema.table (e.g. public.orders). A bare name is looked up on the search path.',
+ required: true,
+ }),
+ schema: Property.ShortText({
+ displayName: 'Schema',
+ description: 'Only list objects in this schema, as returned by List Schemas. Leave empty for every non-system schema.',
+ required: false,
+ }),
+ namePattern: Property.ShortText({
+ displayName: 'Name Pattern',
+ description: 'Optional SQL LIKE pattern on the name, e.g. %order%. Leave empty to list all.',
+ required: false,
+ }),
+ args: Property.Array({
+ displayName: 'Arguments',
+ description: 'Values for $1, $2 and so on, in order.',
+ required: false,
+ }),
+ filters: ({ required }: { 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 JSON list such as ["a", "b"] 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 }),
+ },
+ }),
+ limit: Property.Number({
+ displayName: 'Limit',
+ description: `Maximum number of rows to return (1-${READ_MAX_LIMIT}). Defaults to ${READ_DEFAULT_LIMIT}.`,
+ required: false,
+ defaultValue: READ_DEFAULT_LIMIT,
+ }),
+ maxRows: ({ verb }: { verb: string }) =>
+ Property.Number({
+ displayName: 'Max Rows',
+ description: `Refuse, changing nothing, if more rows than this would be ${verb} (1-${WRITE_GUARD_MAX}). Defaults to ${WRITE_GUARD_DEFAULT}.`,
+ required: false,
+ defaultValue: WRITE_GUARD_DEFAULT,
+ }),
+};
+
+type PostgresAuthValue = AppConnectionValueForAuthProperty<typeof postgresAuth>;
+
+type FilterOperator = (typeof FILTER_OPERATORS)[number];
+
+type Filter = {
+ column: string;
+ operator: FilterOperator;
+ value: unknown;
+};
+
+export type SqlFragment = {
+ sql: string;
+ values: unknown[];
+};
+
+export type Relation = {
+ oid: string;
+ schema: string;
+ name: string;
+ kind: string;
+};
diff --git a/packages/pieces/community/postgres/src/lib/auth.ts b/packages/pieces/community/postgres/src/lib/auth.ts
new file mode 100644
index 00000000000..bc3de8e30b6
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/auth.ts
@@ -0,0 +1,74 @@
+import { AppConnectionType, PieceAuth, Property } from '@activepieces/pieces-framework';
+import { pgClient } from './client';
+
+export const postgresAuth = PieceAuth.CustomAuth({
+ props: {
+ host: Property.ShortText({
+ displayName: 'Host',
+ required: true,
+ description: "The server's hostname or IP address.",
+ placeholder: 'db.example.com',
+ }),
+ port: Property.Number({
+ displayName: 'Port',
+ defaultValue: 5432,
+ description: 'The port the server listens on, usually 5432.',
+ required: true,
+ }),
+ user: Property.ShortText({
+ displayName: 'User',
+ required: true,
+ description: 'The database user to sign in as.',
+ }),
+ password: PieceAuth.SecretText({
+ displayName: 'Password',
+ description: 'The password for that user.',
+ required: true,
+ }),
+ database: Property.ShortText({
+ displayName: 'Database',
+ description: 'The name of the database to connect to.',
+ required: true,
+ }),
+ enable_ssl: Property.Checkbox({
+ displayName: 'Enable SSL',
+ description: 'Encrypt the connection. Most hosted databases require it.',
+ required: true,
+ defaultValue: true,
+ }),
+ reject_unauthorized: Property.Checkbox({
+ displayName: 'Verify Server Certificate',
+ description:
+ "Check the server's certificate. Self-signed servers need a CA below.",
+ required: true,
+ defaultValue: false,
+ }),
+ certificate: Property.LongText({
+ displayName: 'Certificate',
+ description:
+ 'The CA certificate (PEM) to trust when verifying the server.',
+ placeholder: '-----BEGIN CERTIFICATE-----',
+ defaultValue: '',
+ required: false,
+ }),
+ },
+ required: true,
+ validate: async ({ auth }) => {
+ try {
+ const client = await pgClient({
+ type: AppConnectionType.CUSTOM_AUTH,
+ props: auth,
+ });
+ await client.end();
+ }
+ catch (e) {
+ return {
+ valid: false,
+ error: e instanceof Error && e.message ? e.message : JSON.stringify(e)
+ };
+ }
+ return {
+ valid: true,
+ };
+ }
+});
diff --git a/packages/pieces/community/postgres/src/lib/client.ts b/packages/pieces/community/postgres/src/lib/client.ts
new file mode 100644
index 00000000000..685c70ad4e8
--- /dev/null
+++ b/packages/pieces/community/postgres/src/lib/client.ts
@@ -0,0 +1,36 @@
+import { AppConnectionValueForAuthProperty } from "@activepieces/pieces-framework";
+import { Client } from "pg";
+import type { postgresAuth } from "./auth";
+
+export const pgClient = async (auth: AppConnectionValueForAuthProperty<typeof postgresAuth>, query_timeout = 30000, application_name: string | undefined = undefined , connectionTimeoutMillis = 30000) => {
+ const {
+ host,
+ user,
+ database,
+ password,
+ port,
+ enable_ssl,
+ reject_unauthorized: rejectUnauthorized,
+ certificate,
+ } = auth.props;
+
+ const sslConf = {
+ rejectUnauthorized: rejectUnauthorized,
+ ca: certificate && certificate.length > 0 ? certificate : undefined,
+ };
+ const client = new Client({
+ host,
+ port: Number(port),
+ user,
+ password,
+ database,
+ ssl: enable_ssl ? sslConf : undefined,
+ query_timeout: Number(query_timeout),
+ statement_timeout: Number(query_timeout),
+ application_name,
+ connectionTimeoutMillis: Number(connectionTimeoutMillis),
+ });
+ await client.connect();
+
+ return client;
+}
diff --git a/packages/pieces/community/postgres/src/lib/common.ts b/packages/pieces/community/postgres/src/lib/common.ts
index 4dbdc4c9ac6..d3d0c87f4df 100644
--- a/packages/pieces/community/postgres/src/lib/common.ts
+++ b/packages/pieces/community/postgres/src/lib/common.ts
@@ -1,40 +1,9 @@
-import { AppConnectionValueForAuthProperty, MarkdownVariant, Property } from "@activepieces/pieces-framework";
-import { postgresAuth } from "..";
+import { MarkdownVariant, Property } from "@activepieces/pieces-framework";
+import { postgresAuth } from "./auth";
import { Client } from "pg";
+import { pgClient } from "./client";
import format from "pg-format";
-export const pgClient = async (auth: AppConnectionValueForAuthProperty<typeof postgresAuth>, query_timeout = 30000, application_name: string | undefined = undefined , connectionTimeoutMillis = 30000) => {
- const {
- host,
- user,
- database,
- password,
- port,
- enable_ssl,
- reject_unauthorized: rejectUnauthorized,
- certificate,
- } = auth.props;
-
- const sslConf = {
- rejectUnauthorized: rejectUnauthorized,
- ca: certificate && certificate.length > 0 ? certificate : undefined,
- };
- const client = new Client({
- host,
- port: Number(port),
- user,
- password,
- database,
- ssl: enable_ssl ? sslConf : undefined,
- query_timeout: Number(query_timeout),
- statement_timeout: Number(query_timeout),
- application_name,
- connectionTimeoutMillis: Number(connectionTimeoutMillis),
- });
- await client.connect();
-
- return client;
-}
const listTables = async (client: Client): Promise<PostgresTable[]> => {
const result = await client.query<PostgresTable>(
@@ -71,6 +40,8 @@ const qualifiedName = (table: PostgresTable): string => format('%I.%I', table.ta
const quoteIdentifier = (name: string): string => name === '*' ? name : format.ident(name);
+export { pgClient };
+
export const warningMarkdown = Property.MarkDown({
value: 'Never type dynamic values into the condition. Write $1, $2 and put the values in Arguments to prevent SQL injection.',
variant: MarkdownVariant.WARNING,
diff --git a/packages/pieces/community/postgres/src/lib/output-schemas.ts b/packages/pieces/community/postgres/src/lib/output-schemas.ts
index 580f46257be..b993937b91b 100644
--- a/packages/pieces/community/postgres/src/lib/output-schemas.ts
+++ b/packages/pieces/community/postgres/src/lib/output-schemas.ts
@@ -69,3 +69,256 @@ export const findRowsOutputSchema: OutputSchema = {
{ key: 'rowCount', label: 'Row Count', format: 'number' },
],
};
+
+export const postgresListSchemasOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'schemas',
+ label: 'Schemas',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Schema' },
+ { key: 'owner', label: 'Owner' },
+ { key: 'current', label: 'Default Schema', format: 'boolean', description: 'True for the schema unqualified table names resolve to.' },
+ ],
+ },
+ { key: 'count', label: 'Schema Count', format: 'number' },
+ ],
+};
+
+export const postgresDescribeTableOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'schema', label: 'Schema' },
+ { key: 'table', label: 'Table' },
+ { key: 'primaryKey', label: 'Primary Key Columns' },
+ {
+ key: 'columns',
+ label: 'Columns',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Column' },
+ { key: 'type', label: 'Type' },
+ { key: 'nullable', label: 'Nullable', format: 'boolean' },
+ { key: 'defaultValue', label: 'Default' },
+ { key: 'isIdentity', label: 'Identity', format: 'boolean' },
+ { key: 'isGenerated', label: 'Generated', format: 'boolean' },
+ { key: 'comment', label: 'Comment' },
+ { key: 'isPrimaryKey', label: 'Primary Key', format: 'boolean' },
+ { key: 'references', label: 'References', description: 'The schema.table.column this column points to through a foreign key, or null.' },
+ ],
+ },
+ { key: 'count', label: 'Column Count', format: 'number' },
+ ],
+};
+
+export const postgresListIndexesOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'schema', label: 'Schema' },
+ { key: 'table', label: 'Table' },
+ {
+ key: 'indexes',
+ label: 'Indexes',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Index' },
+ { key: 'columns', label: 'Key Columns' },
+ { key: 'method', label: 'Method' },
+ { key: 'isUnique', label: 'Unique', format: 'boolean' },
+ { key: 'isPrimary', label: 'Primary Key', format: 'boolean' },
+ { key: 'definition', label: 'Definition' },
+ ],
+ },
+ { key: 'count', label: 'Index Count', format: 'number' },
+ ],
+};
+
+export const postgresListViewsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'views',
+ label: 'Views',
+ labelKey: 'name',
+ listItems: [
+ { key: 'schema', label: 'Schema' },
+ { key: 'name', label: 'View' },
+ { key: 'isMaterialized', label: 'Materialized', format: 'boolean' },
+ { key: 'owner', label: 'Owner' },
+ ],
+ },
+ { key: 'count', label: 'View Count', format: 'number' },
+ ],
+};
+
+export const postgresGetViewDefinitionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'schema', label: 'Schema' },
+ { key: 'name', label: 'View' },
+ { key: 'isMaterialized', label: 'Materialized', format: 'boolean' },
+ { key: 'definition', label: 'Definition', description: 'The SELECT statement behind the view.' },
+ ],
+};
+
+export const postgresListRoutinesOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'routines',
+ label: 'Routines',
+ labelKey: 'name',
+ listItems: [
+ { key: 'schema', label: 'Schema' },
+ { key: 'name', label: 'Routine' },
+ { key: 'kind', label: 'Kind', description: 'function or procedure.' },
+ { key: 'arguments', label: 'Arguments' },
+ { key: 'returns', label: 'Returns', description: 'The return type; null for a procedure.' },
+ { key: 'language', label: 'Language' },
+ ],
+ },
+ { key: 'count', label: 'Routine Count', format: 'number' },
+ ],
+};
+
+export const postgresFindRowsOutputSchema: OutputSchema = {
+ fields: [
+ tableRows({ description: 'Rows matching the filters; each row\'s fields are the columns of the queried table.' }),
+ { key: 'count', label: 'Row Count', format: 'number' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+ { key: 'nextOffset', label: 'Next Offset', format: 'number', description: 'Offset for the next page; null when there are no more rows.' },
+ ],
+};
+
+export const postgresGetRowByKeyOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'row', label: 'Row', description: 'The matching row; its fields are the columns of the table.' },
+ ],
+};
+
+export const postgresCountRowsOutputSchema: OutputSchema = {
+ fields: [{ key: 'count', label: 'Row Count', format: 'number' }],
+};
+
+export const postgresInsertRowsOutputSchema: OutputSchema = {
+ fields: [
+ tableRows({ description: 'The inserted rows as stored, with generated ids and defaults; each row\'s fields are the columns of the table.' }),
+ { key: 'rowCount', label: 'Inserted Row Count', format: 'number' },
+ ],
+};
+
+export const postgresUpsertRowOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'row', label: 'Row', description: 'The row as stored after the insert or update; its fields are the columns of the table.' },
+ { key: 'inserted', label: 'Inserted', format: 'boolean', description: 'True when a new row was inserted, false when an existing row was updated.' },
+ ],
+};
+
+export const postgresUpdateRowsOutputSchema: OutputSchema = {
+ fields: [
+ tableRows({ description: 'The rows after the update; each row\'s fields are the columns of the table.' }),
+ { key: 'rowCount', label: 'Updated Row Count', format: 'number' },
+ ],
+};
+
+export const postgresDeleteRowsOutputSchema: OutputSchema = {
+ fields: [
+ tableRows({ description: 'The rows as they were just before deletion; each row\'s fields are the columns of the table.' }),
+ { key: 'rowCount', label: 'Deleted Row Count', format: 'number' },
+ ],
+};
+
+export const postgresRunSelectQueryOutputSchema: OutputSchema = {
+ fields: [
+ tableRows({ description: 'Rows returned by the query; each row\'s fields are the columns it selects.' }),
+ { key: 'count', label: 'Row Count', format: 'number' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean', description: 'True when the query returned more rows than Limit.' },
+ ],
+};
+
+export const postgresExplainQueryOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'plan',
+ label: 'Plan',
+ children: [
+ {
+ key: 'Plan',
+ label: 'Root Node',
+ children: [
+ { key: 'Node Type', label: 'Node Type' },
+ { key: 'Relation Name', label: 'Table' },
+ { key: 'Startup Cost', label: 'Startup Cost', format: 'number' },
+ { key: 'Total Cost', label: 'Total Cost', format: 'number' },
+ { key: 'Plan Rows', label: 'Estimated Rows', format: 'number' },
+ { key: 'Plan Width', label: 'Estimated Row Width', format: 'number' },
+ {
+ key: 'Plans',
+ label: 'Child Nodes',
+ description: 'Nested plan nodes, each shaped like the root node.',
+ listItems: [
+ { key: 'Node Type', label: 'Node Type' },
+ { key: 'Index Name', label: 'Index' },
+ { key: 'Relation Name', label: 'Table' },
+ { key: 'Total Cost', label: 'Total Cost', format: 'number' },
+ { key: 'Plan Rows', label: 'Estimated Rows', format: 'number' },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+};
+
+export const postgresCallRoutineOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'kind', label: 'Kind', description: 'function or procedure.' },
+ {
+ key: 'rows',
+ label: 'Result Rows',
+ description: 'A function\'s result rows, or one row of a procedure\'s INOUT and OUT values; field names come from the routine.',
+ },
+ { key: 'rowCount', label: 'Row Count', format: 'number' },
+ ],
+};
+
+export const postgresGetServerInfoOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'version', label: 'Version' },
+ { key: 'serverVersion', label: 'Server Version' },
+ { key: 'serverVersionNum', label: 'Server Version Number', format: 'number' },
+ { key: 'database', label: 'Database' },
+ { key: 'user', label: 'User' },
+ { key: 'timeZone', label: 'Time Zone' },
+ { key: 'searchPath', label: 'Search Path' },
+ { key: 'encoding', label: 'Encoding' },
+ { key: 'isReplica', label: 'Read Replica', format: 'boolean' },
+ ],
+};
+
+export const postgresListActivityOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'sessions',
+ label: 'Sessions',
+ labelKey: 'pid',
+ listItems: [
+ { key: 'pid', label: 'Process ID', format: 'number' },
+ { key: 'user', label: 'User' },
+ { key: 'application', label: 'Application' },
+ { key: 'clientAddress', label: 'Client Address' },
+ { key: 'state', label: 'State' },
+ { key: 'query', label: 'Query' },
+ { key: 'backendStart', label: 'Connected At', format: 'datetime' },
+ { key: 'transactionStart', label: 'Transaction Started At', format: 'datetime' },
+ { key: 'queryStart', label: 'Query Started At', format: 'datetime' },
+ { key: 'stateChange', label: 'State Changed At', format: 'datetime' },
+ { key: 'waitEventType', label: 'Wait Event Type' },
+ { key: 'waitEvent', label: 'Wait Event' },
+ { key: 'isCurrentSession', label: 'This Session', format: 'boolean' },
+ ],
+ },
+ { key: 'count', label: 'Session Count', format: 'number' },
+ ],
+};
+
+function tableRows({ description }: { description: string }): OutputSchema['fields'][number] {
+ return { key: 'rows', label: 'Rows', description };
+}
diff --git a/packages/pieces/community/postgres/src/lib/triggers/new-row.ts b/packages/pieces/community/postgres/src/lib/triggers/new-row.ts
index fc74dc41c04..3e32f8718b3 100644
--- a/packages/pieces/community/postgres/src/lib/triggers/new-row.ts
+++ b/packages/pieces/community/postgres/src/lib/triggers/new-row.ts
@@ -2,7 +2,7 @@
import { createTrigger, TriggerStrategy, Property, AppConnectionValueForAuthProperty, MarkdownVariant } from '@activepieces/pieces-framework';
import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
import crypto from 'crypto';
-import { postgresAuth } from '../..';
+import { postgresAuth } from '../auth';
import { pgClient, postgresCommon } from '../common';
import format from 'pg-format';
import dayjs from 'dayjs';