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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(surrealdb): let AI agents explore, query, write and link SurrealDB records (#17076)
Kishan Parmar8e387d6e4ef7
diff --git a/bun.lock b/bun.lockindex 630e1e3568e..8bf08eb7478 100644--- a/bun.lock+++ b/bun.lock@@ -9001,7 +9001,7 @@},"packages/pieces/community/surrealdb": {"name": "@activepieces/piece-surrealdb",- "version": "0.1.8",+ "version": "0.2.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",diff --git a/packages/pieces/community/surrealdb/package.json b/packages/pieces/community/surrealdb/package.jsonindex f75280b6000..ba85d9dbaee 100644--- a/packages/pieces/community/surrealdb/package.json+++ b/packages/pieces/community/surrealdb/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-surrealdb",- "version": "0.1.8",+ "version": "0.2.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {diff --git a/packages/pieces/community/surrealdb/src/index.ts b/packages/pieces/community/surrealdb/src/index.tsindex a6e19f8fc0d..8e5bb603bef 100644--- a/packages/pieces/community/surrealdb/src/index.ts+++ b/packages/pieces/community/surrealdb/src/index.ts@@ -1,69 +1,31 @@-import {- PieceAuth,- Property,- createPiece,-} from '@activepieces/pieces-framework';-import { PieceCategory } from '@activepieces/pieces-framework';-import { runQuery } from './lib/actions/run-query';-import { newRow } from './lib/triggers/new-row';-import surrealClient from './lib/common';--export const surrealdbAuth = PieceAuth.CustomAuth({- props: {- url: Property.ShortText({- displayName: 'Connection URL',- required: true,- description: 'Connection string, e.g. http://1.2.3.5:8000.',- }),- database: Property.ShortText({- displayName: 'Database',- description:- 'A string indicating the name of the database to connect to.',- required: true,- }),- namespace: Property.ShortText({- displayName: 'Namespace',- required: true,- description:- 'As string indicating the namespace of the database to connect to.',- }),- username: Property.ShortText({- displayName: 'Username',- required: true,- description:- 'As string indicating the username of the database to connect to.',- }),- password: Property.ShortText({- displayName: 'Password',- required: true,- description:- 'As string indicating the password of the database to connect to.',- }),- },- required: true,- validate: async ({ auth }) => {- try {- surrealClient.query(auth, 'INFO for db');- } catch (e) {- return {- valid: false,- error: JSON.stringify(e),- };- }- return {- valid: true,- };- },-});+import { createCustomApiCallAction } from '@activepieces/pieces-common';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';+import { surrealdbAiActions } from './lib/actions/ai';+import { runQueryAction } from './lib/actions/run-query';+import { surrealdbAuth } from './lib/auth';+import { surrealdbClient } from './lib/common/client';+import { newRowTrigger } from './lib/triggers/new-row';export const surrealdb = createPiece({displayName: 'SurrealDB',description: "Multi Model Database",- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',categories: [PieceCategory.DEVELOPER_TOOLS],logoUrl: 'https://cdn.activepieces.com/pieces/surrealdb.jpg',authors: ['maarteNNNN'],auth: surrealdbAuth,- actions: [runQuery],- triggers: [newRow],+ actions: [+ runQueryAction,+ ...surrealdbAiActions,+ createCustomApiCallAction({+ auth: surrealdbAuth,+ baseUrl: (auth) => (auth ? surrealdbClient.baseUrl({ auth }) : ''),+ authMapping: async (auth) => ({+ Authorization: `Basic ${Buffer.from(`${auth.props.username}:${auth.props.password}`).toString('base64')}`,+ 'surreal-ns': auth.props.namespace,+ 'surreal-db': auth.props.database,+ }),+ }),+ ],+ triggers: [newRowTrigger],});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/count-records.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/count-records.tsnew file mode 100644index 00000000000..d54c48a7331--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/count-records.ts@@ -0,0 +1,34 @@+import { createAction } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbAiProps } from '../../common/ai-props';+import { surrealdbApi } from '../../common/api';+import { surrealdbUtils } from '../../common/utils';+import { surrealdbCountRecordsOutputSchema } from '../../output-schemas';++export const countRecordsAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_count_records',+ outputSchema: surrealdbCountRecordsOutputSchema,+ displayName: 'Count Records',+ description: 'Counts the records in a table that match filters.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description: 'Returns how many records of a table match all the filters (or the whole table without filters). Use Find Records to read them. Fails when the table does not exist. Read-only.',+ idempotent: true,+ },+ props: {+ table: surrealdbAiProps.table({ required: true }),+ filters: surrealdbAiProps.filters({ required: false }),+ },+ async run(context) {+ const { table, filters } = context.propsValue;+ const where = surrealdbUtils.buildWhere({ filters });+ const rows = await surrealdbApi.rpcQuery<{ count: number }[]>({+ auth: context.auth,+ sql: `SELECT count() FROM type::table($table)${where.clause} GROUP ALL;`,+ vars: { ...where.vars, table },+ });+ return { count: rows[0]?.count ?? 0 };+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/create-record.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/create-record.tsnew file mode 100644index 00000000000..76a550b61ea--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/create-record.ts@@ -0,0 +1,39 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbAiProps } from '../../common/ai-props';+import { surrealdbApi } from '../../common/api';+import { surrealdbUtils } from '../../common/utils';+import { surrealdbRecordOutputSchema } from '../../output-schemas';++export const createRecordAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_create_record',+ outputSchema: surrealdbRecordOutputSchema,+ displayName: 'Create Record',+ description: 'Creates a record in a table.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Creates one record in a table, with a generated id or the given one, and returns it with its full "table:id" id. Fails if a record with that id already exists; use Upsert Record to create-or-update. Creates the table if it does not exist (unless the database is strict). Repeating it without an id creates duplicates.',+ idempotent: false,+ },+ props: {+ table: surrealdbAiProps.table({ required: true }),+ id: Property.ShortText({+ displayName: 'ID',+ description: 'The id part only, without the table, e.g. "tobie" for "person:tobie". Leave empty to generate one.',+ required: false,+ }),+ data: surrealdbAiProps.data({ required: true }),+ },+ async run(context) {+ const { table, id, data } = context.propsValue;+ const content = surrealdbUtils.toObject({ value: data, label: 'Data' });+ const records = await surrealdbApi.rpcQuery<Record<string, unknown>[]>({+ auth: context.auth,+ sql: id ? 'CREATE type::record($table, $id) CONTENT $data;' : 'CREATE type::table($table) CONTENT $data;',+ vars: { table, id, data: content },+ });+ return surrealdbUtils.singleRecord({ records, recordId: id ? `${table}:${id}` : table });+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/delete-record.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/delete-record.tsnew file mode 100644index 00000000000..5b4a9109648--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/delete-record.ts@@ -0,0 +1,32 @@+import { createAction } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbAiProps } from '../../common/ai-props';+import { surrealdbApi } from '../../common/api';+import { surrealdbUtils } from '../../common/utils';+import { surrealdbRecordOutputSchema } from '../../output-schemas';++export const deleteRecordAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_delete_record',+ outputSchema: surrealdbRecordOutputSchema,+ displayName: 'Delete Record',+ description: 'Permanently deletes one record by its id.',+ audience: 'ai',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description: 'Permanently deletes one record by its full "table:id" id and returns the record as it was before deletion. Fails when the record does not exist. There is no trash; use Delete Records to delete by filter.',+ idempotent: false,+ },+ props: {+ recordId: surrealdbAiProps.recordId({ required: true }),+ },+ async run(context) {+ const { recordId } = context.propsValue;+ const records = await surrealdbApi.rpcQuery<Record<string, unknown>[]>({+ auth: context.auth,+ sql: 'DELETE type::record($recordId) RETURN BEFORE;',+ vars: { recordId },+ });+ return surrealdbUtils.singleRecord({ records, recordId });+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/delete-records.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/delete-records.tsnew file mode 100644index 00000000000..478c46aec13--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/delete-records.ts@@ -0,0 +1,39 @@+import { createAction } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbAiProps } from '../../common/ai-props';+import { surrealdbApi } from '../../common/api';+import { surrealdbUtils } from '../../common/utils';+import { surrealdbRecordsOutputSchema } from '../../output-schemas';++export const deleteRecordsAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_delete_records',+ outputSchema: surrealdbRecordsOutputSchema,+ displayName: 'Delete Records',+ description: 'Permanently deletes every record that matches filters.',+ audience: 'ai',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description: 'Permanently deletes every record of a table that matches all the filters, in one transaction, and returns the deleted records. Fails without deleting anything when more records match than Max Rows (default 100). Filters are required; use Delete Record for one id. There is no trash.',+ idempotent: false,+ },+ props: {+ table: surrealdbAiProps.table({ required: true }),+ filters: surrealdbAiProps.filters({ required: true }),+ maxRows: surrealdbAiProps.maxRows({ required: false }),+ },+ async run(context) {+ const { table, filters, maxRows } = context.propsValue;+ const where = surrealdbUtils.buildWhere({ filters });+ if (where.clause === '') {+ throw new Error('Filters must have at least one condition. Use Find Records to check which records match.');+ }+ const maxRowsValue = surrealdbUtils.boundedInteger({ value: maxRows, defaultValue: surrealdbAiProps.DEFAULT_MAX_ROWS, min: 1, max: Number.MAX_SAFE_INTEGER, label: 'Max Rows' });+ const records = await surrealdbApi.rpcQuery<Record<string, unknown>[]>({+ auth: context.auth,+ sql: `BEGIN; LET $matched = (SELECT count() FROM type::table($table)${where.clause} GROUP ALL)[0].count ?? 0; IF $matched > $max_rows { THROW "The filters match " + <string>$matched + " records, more than Max Rows (" + <string>$max_rows + "). Nothing was deleted; narrow the filters or raise Max Rows."; }; LET $changed = (DELETE type::table($table)${where.clause} RETURN BEFORE); COMMIT; RETURN $changed;`,+ vars: { ...where.vars, table, max_rows: maxRowsValue },+ });+ return { records, count: records.length };+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/describe-table.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/describe-table.tsnew file mode 100644index 00000000000..d66eab5fd7d--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/describe-table.ts@@ -0,0 +1,29 @@+import { createAction } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbAiProps } from '../../common/ai-props';+import { surrealdbApi } from '../../common/api';+import { surrealdbDescribeTableOutputSchema } from '../../output-schemas';++export const describeTableAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_describe_table',+ outputSchema: surrealdbDescribeTableOutputSchema,+ displayName: 'Describe Table',+ description: 'Gets a table\'s fields, indexes, events and views.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description: 'Returns the defined fields (name, type, readonly, permissions), indexes, events, live queries and views of one table. Schemaless tables may hold fields that are not defined here; Find Records shows real data. Fails when the table does not exist; table names come from List Tables. Read-only.',+ idempotent: true,+ },+ props: {+ table: surrealdbAiProps.table({ required: true }),+ },+ async run(context) {+ return await surrealdbApi.rpcQuery<Record<string, unknown>>({+ auth: context.auth,+ sql: 'IF $table NOTINSIDE (INFO FOR DB STRUCTURE).tables.name { THROW "Table \'" + $table + "\' does not exist. Use List Tables to see the tables."; }; INFO FOR TABLE $table STRUCTURE;',+ vars: { table: context.propsValue.table },+ });+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/export-database.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/export-database.tsnew file mode 100644index 00000000000..73a55bbb399--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/export-database.ts@@ -0,0 +1,53 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbClient } from '../../common/client';+import { surrealdbExportDatabaseOutputSchema } from '../../output-schemas';++export const exportDatabaseAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_export_database',+ outputSchema: surrealdbExportDatabaseOutputSchema,+ displayName: 'Export Database',+ description: 'Exports the database as a SurrealQL file.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description: 'Exports the connection\'s database (definitions and, by default, records) as a SurrealQL file and returns a link to it, which Import Data accepts. Limit it to some tables, or to definitions only. Needs the VIEWER role or above. Read-only.',+ idempotent: true,+ },+ props: {+ tables: Property.Array({+ displayName: 'Tables',+ description: 'Only export these tables, e.g. ["person", "knows"]. Leave empty for all tables.',+ required: false,+ }),+ includeRecords: Property.StaticDropdown({+ displayName: 'Include Records',+ description: 'true to export the records as well as the definitions, false for definitions only. Defaults to true.',+ required: false,+ options: { options: [{ label: 'Yes', value: 'true' }, { label: 'No', value: 'false' }] },+ }),+ },+ async run(context) {+ const { tables, includeRecords } = context.propsValue;+ if (includeRecords !== undefined && includeRecords !== 'true' && includeRecords !== 'false') {+ throw new Error('Include Records must be "true" or "false".');+ }+ const selected = (tables ?? []).map(String);+ const dump = await surrealdbClient.request<string>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: '/export',+ headers: { 'Content-Type': 'application/json' },+ body: {+ ...(selected.length > 0 ? { tables: selected } : {}),+ ...(includeRecords !== undefined ? { records: includeRecords === 'true' } : {}),+ },+ responseType: 'text',+ });+ const fileName = `${context.auth.props.namespace}-${context.auth.props.database}.surql`;+ const file = await context.files.write({ fileName, data: Buffer.from(dump, 'utf8') });+ return { file, file_name: fileName, size_bytes: Buffer.byteLength(dump, 'utf8') };+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/find-records.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/find-records.tsnew file mode 100644index 00000000000..f2348b3c495--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/find-records.ts@@ -0,0 +1,66 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbAiProps } from '../../common/ai-props';+import { surrealdbApi } from '../../common/api';+import { surrealdbUtils } from '../../common/utils';+import { surrealdbFindRecordsOutputSchema } from '../../output-schemas';++export const findRecordsAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_find_records',+ outputSchema: surrealdbFindRecordsOutputSchema,+ displayName: 'Find Records',+ description: 'Finds records in a table using filters, sorting and paging.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Returns records of a table matching all the filters, optionally only some fields, sorted by one field, with paging (has_more, next_start). Values are sent as typed variables, never spliced into the query. Use Count Records for totals and Get Record for one id; table names come from List Tables. Read-only.',+ idempotent: true,+ },+ props: {+ table: surrealdbAiProps.table({ required: true }),+ filters: surrealdbAiProps.filters({ required: false }),+ fields: Property.Array({+ displayName: 'Fields',+ description: 'Fields to return, e.g. ["id", "name", "address.city"]. Leave empty for all fields.',+ required: false,+ }),+ orderBy: Property.ShortText({+ displayName: 'Order By',+ description: 'Field to sort by, e.g. "created_at" or "address.city". Leave empty for no particular order.',+ required: false,+ }),+ orderDirection: Property.StaticDropdown({+ displayName: 'Order Direction',+ description: 'ASC or DESC. Defaults to ASC.',+ required: false,+ options: { options: [{ label: 'Ascending', value: 'ASC' }, { label: 'Descending', value: 'DESC' }] },+ }),+ limit: surrealdbAiProps.limit({ required: false }),+ start: Property.Number({+ displayName: 'Start',+ description: 'Number of records to skip, for paging. Use next_start from the previous call with the same filters and order.',+ required: false,+ }),+ },+ async run(context) {+ const { table, filters, fields, orderBy, orderDirection, limit, start } = context.propsValue;+ const max = surrealdbUtils.boundedInteger({ value: limit, defaultValue: surrealdbAiProps.DEFAULT_LIMIT, min: 1, max: surrealdbAiProps.MAX_LIMIT, label: 'Limit' });+ const skip = surrealdbUtils.boundedInteger({ value: start, defaultValue: 0, min: 0, max: Number.MAX_SAFE_INTEGER, label: 'Start' });+ if (orderDirection !== undefined && orderDirection !== 'ASC' && orderDirection !== 'DESC') {+ throw new Error('Order Direction must be ASC or DESC.');+ }+ const where = surrealdbUtils.buildWhere({ filters });+ const selected = (fields ?? []).map(String);+ const projection = selected.length > 0 ? 'type::fields($fields)' : '*';+ const order = orderBy ? ` ORDER BY ${surrealdbUtils.fieldPath({ field: orderBy, label: 'Order By' })} ${orderDirection ?? 'ASC'}` : '';+ const found = await surrealdbApi.rpcQuery<Record<string, unknown>[]>({+ auth: context.auth,+ sql: `SELECT ${projection} FROM type::table($table)${where.clause}${order} LIMIT $limit START $start;`,+ vars: { ...where.vars, table, fields: selected, limit: max + 1, start: skip },+ });+ const hasMore = found.length > max;+ const records = found.slice(0, max);+ return { records, count: records.length, has_more: hasMore, next_start: hasMore ? skip + max : null };+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/find-related-records.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/find-related-records.tsnew file mode 100644index 00000000000..b385c741e4e--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/find-related-records.ts@@ -0,0 +1,69 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbAiProps } from '../../common/ai-props';+import { surrealdbApi } from '../../common/api';+import { surrealdbUtils } from '../../common/utils';+import { surrealdbFindRelatedRecordsOutputSchema } from '../../output-schemas';++export const findRelatedRecordsAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_find_related_records',+ outputSchema: surrealdbFindRelatedRecordsOutputSchema,+ displayName: 'Find Related Records',+ description: 'Finds the records linked to a record through an edge table.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Returns the edges of one edge table that start at (outgoing), end at (incoming) or touch (both) a record, each with the record on the other side in "related", with paging (has_more, next_start). Edges are created by Relate Records; edge table names come from List Tables. Read-only.',+ idempotent: true,+ },+ props: {+ recordId: surrealdbAiProps.recordId({ required: true }),+ edge: Property.ShortText({+ displayName: 'Edge Table',+ description: 'Name of the edge table, e.g. "knows".',+ required: true,+ }),+ direction: Property.StaticDropdown({+ displayName: 'Direction',+ description: 'outgoing: edges from this record; incoming: edges to it; both. Defaults to outgoing.',+ required: false,+ options: {+ options: [+ { label: 'Outgoing', value: 'outgoing' },+ { label: 'Incoming', value: 'incoming' },+ { label: 'Both', value: 'both' },+ ],+ },+ }),+ limit: surrealdbAiProps.limit({ required: false }),+ start: Property.Number({+ displayName: 'Start',+ description: 'Number of edges to skip, for paging. Use next_start from the previous call.',+ required: false,+ }),+ },+ async run(context) {+ const { recordId, edge, direction, limit, start } = context.propsValue;+ const match = MATCH_BY_DIRECTION[direction ?? 'outgoing'];+ if (match === undefined) {+ throw new Error('Direction must be outgoing, incoming or both.');+ }+ const max = surrealdbUtils.boundedInteger({ value: limit, defaultValue: surrealdbAiProps.DEFAULT_LIMIT, min: 1, max: surrealdbAiProps.MAX_LIMIT, label: 'Limit' });+ const skip = surrealdbUtils.boundedInteger({ value: start, defaultValue: 0, min: 0, max: Number.MAX_SAFE_INTEGER, label: 'Start' });+ const found = await surrealdbApi.rpcQuery<Record<string, unknown>[]>({+ auth: context.auth,+ sql: `LET $record = type::record($record_id); SELECT *, (IF in = $record { out } ELSE { in }).* AS related FROM type::table($edge) WHERE ${match} LIMIT $limit START $start;`,+ vars: { record_id: recordId, edge, limit: max + 1, start: skip },+ });+ const hasMore = found.length > max;+ const edges = found.slice(0, max);+ return { edges, count: edges.length, has_more: hasMore, next_start: hasMore ? skip + max : null };+ },+});++const MATCH_BY_DIRECTION: Record<string, string | undefined> = {+ outgoing: 'in = $record',+ incoming: 'out = $record',+ both: 'in = $record OR out = $record',+};diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/get-database-info.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/get-database-info.tsnew file mode 100644index 00000000000..3f826d60c6d--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/get-database-info.ts@@ -0,0 +1,22 @@+import { createAction } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbApi } from '../../common/api';+import { surrealdbGetDatabaseInfoOutputSchema } from '../../output-schemas';++export const getDatabaseInfoAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_get_database_info',+ outputSchema: surrealdbGetDatabaseInfoOutputSchema,+ displayName: 'Get Database Info',+ description: 'Gets everything defined in the connected database.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description: 'Returns the definitions in the connection\'s database: tables, functions (with arguments and body), params, accesses, analyzers, users, sequences, APIs and configs. Use List Tables when only the tables are needed, and Describe Table for one table\'s fields. Read-only.',+ idempotent: true,+ },+ props: {},+ async run(context) {+ return await surrealdbApi.rpcQuery<Record<string, unknown>>({ auth: context.auth, sql: 'INFO FOR DB STRUCTURE;', vars: {} });+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/get-record.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/get-record.tsnew file mode 100644index 00000000000..f83454e635b--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/get-record.ts@@ -0,0 +1,32 @@+import { createAction } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbAiProps } from '../../common/ai-props';+import { surrealdbApi } from '../../common/api';+import { surrealdbUtils } from '../../common/utils';+import { surrealdbRecordOutputSchema } from '../../output-schemas';++export const getRecordAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_get_record',+ outputSchema: surrealdbRecordOutputSchema,+ displayName: 'Get Record',+ description: 'Gets one record by its id.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description: 'Returns one record by its full "table:id" id. Fails when the record does not exist. Use Find Records to search by field values. Read-only.',+ idempotent: true,+ },+ props: {+ recordId: surrealdbAiProps.recordId({ required: true }),+ },+ async run(context) {+ const { recordId } = context.propsValue;+ const records = await surrealdbApi.rpcQuery<Record<string, unknown>[]>({+ auth: context.auth,+ sql: 'SELECT * FROM type::record($recordId);',+ vars: { recordId },+ });+ return surrealdbUtils.singleRecord({ records, recordId });+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/import-data.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/import-data.tsnew file mode 100644index 00000000000..68e9be59393--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/import-data.ts@@ -0,0 +1,49 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbClient } from '../../common/client';+import { surrealdbImportDataOutputSchema } from '../../output-schemas';++export const importDataAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_import_data',+ outputSchema: surrealdbImportDataOutputSchema,+ displayName: 'Import Data',+ description: 'Imports a SurrealQL script or export file into the database.',+ audience: 'ai',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description: 'Runs a SurrealQL script (such as a file from Export Database) against the connection\'s database in import mode: events and field processing are skipped. Pass the script as text or as a file, not both. Statements that fail are reported with HTTP 422, but earlier statements stay applied (no rollback), and DEFINE ... OVERWRITE or DELETE statements in the script replace data. Not idempotent.',+ idempotent: false,+ },+ props: {+ script: Property.LongText({+ displayName: 'Script',+ description: 'SurrealQL statements to import, e.g. CREATE person:tobie SET name = "Tobie";. Leave empty when using File.',+ required: false,+ }),+ file: Property.File({+ displayName: 'File',+ description: 'A .surql file to import, such as one from Export Database. Leave empty when using Script.',+ required: false,+ }),+ },+ async run(context) {+ const { script, file } = context.propsValue;+ if ((script === undefined || script === '') === (file === undefined || file === null)) {+ throw new Error('Provide exactly one of Script or File.');+ }+ const text = file ? file.data.toString('utf8') : script ?? '';+ const body = IMPORT_OPTION.test(text) ? text : `OPTION IMPORT;\n${text}`;+ await surrealdbClient.request<unknown>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: '/import',+ headers: { 'Content-Type': 'text/plain' },+ body,+ });+ return { success: true, size_bytes: Buffer.byteLength(body, 'utf8') };+ },+});++const IMPORT_OPTION = /^\s*(--[^\n]*\n\s*)*OPTION\s+IMPORT\s*;/i;diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/index.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/index.tsnew file mode 100644index 00000000000..54a48c1cdf4--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/index.ts@@ -0,0 +1,51 @@+import { countRecordsAction } from './count-records';+import { createRecordAction } from './create-record';+import { deleteRecordAction } from './delete-record';+import { deleteRecordsAction } from './delete-records';+import { describeTableAction } from './describe-table';+import { exportDatabaseAction } from './export-database';+import { findRecordsAction } from './find-records';+import { findRelatedRecordsAction } from './find-related-records';+import { getDatabaseInfoAction } from './get-database-info';+import { getRecordAction } from './get-record';+import { importDataAction } from './import-data';+import { insertRecordsAction } from './insert-records';+import { listDatabasesAction } from './list-databases';+import { listNamespacesAction } from './list-namespaces';+import { listTablesAction } from './list-tables';+import { mergeRecordAction } from './merge-record';+import { patchRecordAction } from './patch-record';+import { relateRecordsAction } from './relate-records';+import { replaceRecordAction } from './replace-record';+import { runFunctionAction } from './run-function';+import { runGqlQueryAction } from './run-gql-query';+import { runGraphqlQueryAction } from './run-graphql-query';+import { updateRecordsAction } from './update-records';+import { upsertRecordAction } from './upsert-record';++export const surrealdbAiActions = [+ listNamespacesAction,+ listDatabasesAction,+ listTablesAction,+ getDatabaseInfoAction,+ describeTableAction,+ findRecordsAction,+ getRecordAction,+ countRecordsAction,+ createRecordAction,+ insertRecordsAction,+ replaceRecordAction,+ mergeRecordAction,+ patchRecordAction,+ upsertRecordAction,+ deleteRecordAction,+ updateRecordsAction,+ deleteRecordsAction,+ relateRecordsAction,+ findRelatedRecordsAction,+ runFunctionAction,+ runGqlQueryAction,+ runGraphqlQueryAction,+ exportDatabaseAction,+ importDataAction,+];diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/insert-records.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/insert-records.tsnew file mode 100644index 00000000000..97f3e73c1c1--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/insert-records.ts@@ -0,0 +1,40 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbAiProps } from '../../common/ai-props';+import { surrealdbApi } from '../../common/api';+import { surrealdbUtils } from '../../common/utils';+import { surrealdbRecordsOutputSchema } from '../../output-schemas';++export const insertRecordsAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_insert_records',+ outputSchema: surrealdbRecordsOutputSchema,+ displayName: 'Insert Records',+ description: 'Inserts several records into a table in one statement.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Inserts an array of records into a table in one statement and returns them with their ids. A record may set "id" to the id part only (e.g. "tobie"); others get generated ids. The whole insert fails if any id already exists. Repeating it without ids creates duplicates.',+ idempotent: false,+ },+ props: {+ table: surrealdbAiProps.table({ required: true }),+ records: Property.Json({+ displayName: 'Records',+ description: 'JSON array of record objects, e.g. [{"name": "Ada"}, {"id": "alan", "name": "Alan"}]. An "id" is the id part only, without the table.',+ required: true,+ }),+ },+ async run(context) {+ const { table, records } = context.propsValue;+ if (!Array.isArray(records) || records.length === 0) {+ throw new Error('Records must be a non-empty JSON array of objects.');+ }+ const inserted = await surrealdbApi.rpcQuery<Record<string, unknown>[]>({+ auth: context.auth,+ sql: 'INSERT INTO $table $records;',+ vars: { table, records: records.map((record, index) => surrealdbUtils.toObject({ value: record, label: `Record ${index + 1}` })) },+ });+ return { records: inserted, count: inserted.length };+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/list-databases.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/list-databases.tsnew file mode 100644index 00000000000..5965cf5b8bf--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/list-databases.ts@@ -0,0 +1,25 @@+import { createAction } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbApi } from '../../common/api';+import type { SurrealdbNamespaceStructure } from '../../common/types';+import { surrealdbListDatabasesOutputSchema } from '../../output-schemas';++export const listDatabasesAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_list_databases',+ outputSchema: surrealdbListDatabasesOutputSchema,+ displayName: 'List Databases',+ description: 'Lists the databases in the connection\'s namespace.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Returns every database defined in the connection\'s namespace. Needs a namespace-level or root user; database users get a permission error. Read-only.',+ idempotent: true,+ },+ props: {},+ async run(context) {+ const info = await surrealdbApi.rpcQuery<SurrealdbNamespaceStructure>({ auth: context.auth, sql: 'INFO FOR NS STRUCTURE;', vars: {} });+ const databases = info.databases ?? [];+ return { databases, count: databases.length };+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/list-namespaces.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/list-namespaces.tsnew file mode 100644index 00000000000..31e6c10a708--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/list-namespaces.ts@@ -0,0 +1,25 @@+import { createAction } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbApi } from '../../common/api';+import type { SurrealdbRootStructure } from '../../common/types';+import { surrealdbListNamespacesOutputSchema } from '../../output-schemas';++export const listNamespacesAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_list_namespaces',+ outputSchema: surrealdbListNamespacesOutputSchema,+ displayName: 'List Namespaces',+ description: 'Lists the namespaces on the SurrealDB server.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Returns every namespace defined on the server. Needs a root-level user; namespace and database users get a permission error. Use List Databases for the databases inside the connection\'s namespace. Read-only.',+ idempotent: true,+ },+ props: {},+ async run(context) {+ const info = await surrealdbApi.rpcQuery<SurrealdbRootStructure>({ auth: context.auth, sql: 'INFO FOR ROOT STRUCTURE;', vars: {} });+ const namespaces = info.namespaces ?? [];+ return { namespaces, count: namespaces.length };+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/list-tables.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/list-tables.tsnew file mode 100644index 00000000000..b3f2813777e--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/list-tables.ts@@ -0,0 +1,25 @@+import { createAction } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbApi } from '../../common/api';+import type { SurrealdbDbStructure } from '../../common/types';+import { surrealdbListTablesOutputSchema } from '../../output-schemas';++export const listTablesAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_list_tables',+ outputSchema: surrealdbListTablesOutputSchema,+ displayName: 'List Tables',+ description: 'Lists the tables defined in the connected database.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Returns every table defined in the connection\'s database with its kind (normal or relation), whether it is schemafull, and its permissions. Use Describe Table for a table\'s fields and indexes. Read-only.',+ idempotent: true,+ },+ props: {},+ async run(context) {+ const info = await surrealdbApi.rpcQuery<SurrealdbDbStructure>({ auth: context.auth, sql: 'INFO FOR DB STRUCTURE;', vars: {} });+ const tables = info.tables ?? [];+ return { tables, count: tables.length };+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/merge-record.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/merge-record.tsnew file mode 100644index 00000000000..e114562b22c--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/merge-record.ts@@ -0,0 +1,33 @@+import { createAction } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbAiProps } from '../../common/ai-props';+import { surrealdbApi } from '../../common/api';+import { surrealdbUtils } from '../../common/utils';+import { surrealdbRecordOutputSchema } from '../../output-schemas';++export const mergeRecordAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_merge_record',+ outputSchema: surrealdbRecordOutputSchema,+ displayName: 'Merge Record',+ description: 'Updates some fields of an existing record.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Merges the given fields into an existing record, leaving other fields as they are; nested objects are merged too. Fails when the record does not exist. Use Patch Record to remove fields or edit arrays, Replace Record to overwrite everything.',+ idempotent: true,+ },+ props: {+ recordId: surrealdbAiProps.recordId({ required: true }),+ data: surrealdbAiProps.data({ required: true }),+ },+ async run(context) {+ const { recordId, data } = context.propsValue;+ const records = await surrealdbApi.rpcQuery<Record<string, unknown>[]>({+ auth: context.auth,+ sql: 'UPDATE type::record($recordId) MERGE $data;',+ vars: { recordId, data: surrealdbUtils.toObject({ value: data, label: 'Data' }) },+ });+ return surrealdbUtils.singleRecord({ records, recordId });+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/patch-record.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/patch-record.tsnew file mode 100644index 00000000000..9ad9cf566fb--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/patch-record.ts@@ -0,0 +1,40 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbAiProps } from '../../common/ai-props';+import { surrealdbApi } from '../../common/api';+import { surrealdbUtils } from '../../common/utils';+import { surrealdbRecordOutputSchema } from '../../output-schemas';++export const patchRecordAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_patch_record',+ outputSchema: surrealdbRecordOutputSchema,+ displayName: 'Patch Record',+ description: 'Applies JSON Patch operations to an existing record.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Applies a JSON Patch (RFC 6902) array to an existing record: add, remove, replace, move, copy or test, with paths like "/tags/0". Use it to remove fields or edit arrays; Merge Record is simpler for setting fields. Fails when the record does not exist. Not idempotent for array appends.',+ idempotent: false,+ },+ props: {+ recordId: surrealdbAiProps.recordId({ required: true }),+ patches: Property.Json({+ displayName: 'Patches',+ description: 'JSON Patch array, e.g. [{"op": "replace", "path": "/age", "value": 34}, {"op": "remove", "path": "/nickname"}, {"op": "add", "path": "/tags/-", "value": "new"}].',+ required: true,+ }),+ },+ async run(context) {+ const { recordId, patches } = context.propsValue;+ if (!Array.isArray(patches) || patches.length === 0) {+ throw new Error('Patches must be a non-empty JSON array of patch operations.');+ }+ const records = await surrealdbApi.rpcQuery<Record<string, unknown>[]>({+ auth: context.auth,+ sql: 'UPDATE type::record($recordId) PATCH $patches;',+ vars: { recordId, patches },+ });+ return surrealdbUtils.singleRecord({ records, recordId });+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/relate-records.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/relate-records.tsnew file mode 100644index 00000000000..f8994c3f9c2--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/relate-records.ts@@ -0,0 +1,40 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbAiProps } from '../../common/ai-props';+import { surrealdbApi } from '../../common/api';+import { surrealdbUtils } from '../../common/utils';+import { surrealdbRelateRecordsOutputSchema } from '../../output-schemas';++export const relateRecordsAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_relate_records',+ outputSchema: surrealdbRelateRecordsOutputSchema,+ displayName: 'Relate Records',+ description: 'Creates a graph edge from one record to another.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Creates an edge record in an edge table linking one record (in) to another (out), e.g. person:tobie -> knows -> person:jaime, with optional fields on the edge, and returns the edge. Each call adds a new edge unless the edge table has a unique index. Read edges back with Find Related Records.',+ idempotent: false,+ },+ props: {+ fromRecordId: surrealdbAiProps.recordId({ required: true, displayName: 'From Record ID', description: 'Record the edge starts at, in "table:id" form, e.g. "person:tobie".' }),+ edge: Property.ShortText({+ displayName: 'Edge Table',+ description: 'Name of the edge table, e.g. "knows" or "purchased". Created if it does not exist.',+ required: true,+ }),+ toRecordId: surrealdbAiProps.recordId({ required: true, displayName: 'To Record ID', description: 'Record the edge points to, in "table:id" form, e.g. "person:jaime".' }),+ data: surrealdbAiProps.data({ required: false, description: 'Optional JSON object of fields stored on the edge, e.g. {"since": 2020}.' }),+ },+ async run(context) {+ const { fromRecordId, edge, toRecordId, data } = context.propsValue;+ const content = data === undefined ? {} : surrealdbUtils.toObject({ value: data, label: 'Data' });+ const edges = await surrealdbApi.rpcQuery<Record<string, unknown>[]>({+ auth: context.auth,+ sql: 'RELATE (type::record($from))->(type::table($edge))->(type::record($to)) CONTENT $data;',+ vars: { from: fromRecordId, edge, to: toRecordId, data: content },+ });+ return surrealdbUtils.singleRecord({ records: edges, recordId: `${fromRecordId} -> ${edge} -> ${toRecordId}` });+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/replace-record.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/replace-record.tsnew file mode 100644index 00000000000..c86da51c13d--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/replace-record.ts@@ -0,0 +1,33 @@+import { createAction } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbAiProps } from '../../common/ai-props';+import { surrealdbApi } from '../../common/api';+import { surrealdbUtils } from '../../common/utils';+import { surrealdbRecordOutputSchema } from '../../output-schemas';++export const replaceRecordAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_replace_record',+ outputSchema: surrealdbRecordOutputSchema,+ displayName: 'Replace Record',+ description: 'Replaces all fields of an existing record.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Replaces the whole content of an existing record with the given data; fields not in the data are removed (the id is kept). Fails when the record does not exist. Use Merge Record to change only some fields, or Upsert Record to create it when missing.',+ idempotent: true,+ },+ props: {+ recordId: surrealdbAiProps.recordId({ required: true }),+ data: surrealdbAiProps.data({ required: true }),+ },+ async run(context) {+ const { recordId, data } = context.propsValue;+ const records = await surrealdbApi.rpcQuery<Record<string, unknown>[]>({+ auth: context.auth,+ sql: 'UPDATE type::record($recordId) CONTENT $data;',+ vars: { recordId, data: surrealdbUtils.toObject({ value: data, label: 'Data' }) },+ });+ return surrealdbUtils.singleRecord({ records, recordId });+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/run-function.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/run-function.tsnew file mode 100644index 00000000000..f106320db0d--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/run-function.ts@@ -0,0 +1,38 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbApi } from '../../common/api';+import { surrealdbRunFunctionOutputSchema } from '../../output-schemas';++export const runFunctionAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_run_function',+ outputSchema: surrealdbRunFunctionOutputSchema,+ displayName: 'Run Function',+ description: 'Runs a custom or built-in SurrealDB function with arguments.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Calls a function by name with positional arguments and returns its result: a custom function defined in the database ("fn::name"; Get Database Info lists them with their arguments) or a built-in one such as "string::uppercase" or "time::now". Arguments keep their JSON types. Not idempotent in general: a custom function may write data.',+ idempotent: false,+ },+ props: {+ name: Property.ShortText({+ displayName: 'Function',+ description: 'Function name, e.g. "fn::greet" or "math::sum".',+ required: true,+ }),+ args: Property.Json({+ displayName: 'Arguments',+ description: 'JSON array of positional arguments, e.g. ["Tobie", 33]. Leave empty for none.',+ required: false,+ }),+ },+ async run(context) {+ const { name, args } = context.propsValue;+ if (args !== undefined && !Array.isArray(args)) {+ throw new Error('Arguments must be a JSON array, e.g. ["Tobie", 33].');+ }+ const result = await surrealdbApi.rpc<unknown>({ auth: context.auth, method: 'run', params: [name, null, args ?? []] });+ return { result };+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/run-gql-query.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/run-gql-query.tsnew file mode 100644index 00000000000..8e1bc559318--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/run-gql-query.ts@@ -0,0 +1,38 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbClient } from '../../common/client';+import type { SurrealdbStatementResult } from '../../common/types';+import { surrealdbUtils } from '../../common/utils';+import { surrealdbRunGqlQueryOutputSchema } from '../../output-schemas';++export const runGqlQueryAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_run_gql_query',+ outputSchema: surrealdbRunGqlQueryOutputSchema,+ displayName: 'Run GQL Query',+ description: 'Runs an ISO GQL graph query, e.g. MATCH (p:person) RETURN p.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Runs a GQL (ISO graph query language) statement such as MATCH (p:person)-[:knows]->(f) RETURN p, f and returns its result. Needs SurrealDB 3.3 or later (3.2 with the experimental flag). Use Find Related Records for simple edge lookups and Run Query for SurrealQL. Not idempotent when the statement writes.',+ idempotent: false,+ },+ props: {+ query: Property.LongText({+ displayName: 'GQL Query',+ description: 'GQL statement, e.g. MATCH (p:person) RETURN p.',+ required: true,+ }),+ },+ async run(context) {+ const statements = await surrealdbClient.request<SurrealdbStatementResult<unknown>[]>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: '/gql',+ headers: { 'Content-Type': 'text/plain' },+ body: context.propsValue.query,+ });+ return { result: surrealdbUtils.lastStatementResult({ statements }) };+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/run-graphql-query.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/run-graphql-query.tsnew file mode 100644index 00000000000..8c0e0cc3740--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/run-graphql-query.ts@@ -0,0 +1,46 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbClient } from '../../common/client';+import type { SurrealdbGraphqlResponse } from '../../common/types';+import { surrealdbRunGraphqlQueryOutputSchema } from '../../output-schemas';++export const runGraphqlQueryAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_run_graphql_query',+ outputSchema: surrealdbRunGraphqlQueryOutputSchema,+ displayName: 'Run GraphQL Query',+ description: 'Runs a GraphQL query against the database.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Runs a GraphQL query and returns its data. Works only when the database has GraphQL enabled (DEFINE CONFIG GRAPHQL); table names become camelCase types (table "p3_person" is queried as p3Person / p3Persons). Fails with the GraphQL errors when the query is invalid. Read-only: SurrealDB GraphQL has no mutations.',+ idempotent: true,+ },+ props: {+ query: Property.LongText({+ displayName: 'GraphQL Query',+ description: 'GraphQL query, e.g. { person(limit: 10) { id name } }.',+ required: true,+ }),+ variables: Property.Json({+ displayName: 'Variables',+ description: 'Optional JSON object of GraphQL variables.',+ required: false,+ }),+ },+ async run(context) {+ const { query, variables } = context.propsValue;+ const response = await surrealdbClient.request<SurrealdbGraphqlResponse>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: '/graphql',+ headers: { 'Content-Type': 'application/json' },+ body: { query, variables },+ });+ if (response.errors && response.errors.length > 0) {+ throw new Error(`GraphQL error: ${response.errors.map((error) => error.message).join('; ')}`);+ }+ return { data: response.data ?? null };+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/update-records.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/update-records.tsnew file mode 100644index 00000000000..4902a98b40c--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/update-records.ts@@ -0,0 +1,40 @@+import { createAction } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbAiProps } from '../../common/ai-props';+import { surrealdbApi } from '../../common/api';+import { surrealdbUtils } from '../../common/utils';+import { surrealdbRecordsOutputSchema } from '../../output-schemas';++export const updateRecordsAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_update_records',+ outputSchema: surrealdbRecordsOutputSchema,+ displayName: 'Update Records',+ description: 'Merges fields into every record that matches filters.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Merges the given fields into every record of a table that matches all the filters, in one transaction, and returns the updated records. Fails without changing anything when more records match than Max Rows (default 100). Filters are required; use Merge Record for one id.',+ idempotent: true,+ },+ props: {+ table: surrealdbAiProps.table({ required: true }),+ filters: surrealdbAiProps.filters({ required: true }),+ data: surrealdbAiProps.data({ required: true }),+ maxRows: surrealdbAiProps.maxRows({ required: false }),+ },+ async run(context) {+ const { table, filters, data, maxRows } = context.propsValue;+ const where = surrealdbUtils.buildWhere({ filters });+ if (where.clause === '') {+ throw new Error('Filters must have at least one condition. Use Find Records to check which records match.');+ }+ const maxRowsValue = surrealdbUtils.boundedInteger({ value: maxRows, defaultValue: surrealdbAiProps.DEFAULT_MAX_ROWS, min: 1, max: Number.MAX_SAFE_INTEGER, label: 'Max Rows' });+ const records = await surrealdbApi.rpcQuery<Record<string, unknown>[]>({+ auth: context.auth,+ sql: `BEGIN; LET $matched = (SELECT count() FROM type::table($table)${where.clause} GROUP ALL)[0].count ?? 0; IF $matched > $max_rows { THROW "The filters match " + <string>$matched + " records, more than Max Rows (" + <string>$max_rows + "). Nothing was updated; narrow the filters or raise Max Rows."; }; LET $changed = (UPDATE type::table($table) MERGE $data${where.clause} RETURN AFTER); COMMIT; RETURN $changed;`,+ vars: { ...where.vars, table, data: surrealdbUtils.toObject({ value: data, label: 'Data' }), max_rows: maxRowsValue },+ });+ return { records, count: records.length };+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/ai/upsert-record.ts b/packages/pieces/community/surrealdb/src/lib/actions/ai/upsert-record.tsnew file mode 100644index 00000000000..dbc4f8a6e35--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/actions/ai/upsert-record.ts@@ -0,0 +1,33 @@+import { createAction } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../../auth';+import { surrealdbAiProps } from '../../common/ai-props';+import { surrealdbApi } from '../../common/api';+import { surrealdbUtils } from '../../common/utils';+import { surrealdbRecordOutputSchema } from '../../output-schemas';++export const upsertRecordAction = createAction({+ auth: surrealdbAuth,+ name: 'surrealdb_upsert_record',+ outputSchema: surrealdbRecordOutputSchema,+ displayName: 'Upsert Record',+ description: 'Creates a record or merges fields into it if it exists.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Creates the record with the given "table:id" id when it does not exist, otherwise merges the given fields into it, and returns the record. Repeating it with the same data gives the same result. Use Create Record when the id should be generated.',+ idempotent: true,+ },+ props: {+ recordId: surrealdbAiProps.recordId({ required: true }),+ data: surrealdbAiProps.data({ required: true }),+ },+ async run(context) {+ const { recordId, data } = context.propsValue;+ const records = await surrealdbApi.rpcQuery<Record<string, unknown>[]>({+ auth: context.auth,+ sql: 'UPSERT type::record($recordId) MERGE $data;',+ vars: { recordId, data: surrealdbUtils.toObject({ value: data, label: 'Data' }) },+ });+ return surrealdbUtils.singleRecord({ records, recordId });+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/actions/run-query.ts b/packages/pieces/community/surrealdb/src/lib/actions/run-query.tsindex 4a798d10bd6..84ad6e9ffcf 100644--- a/packages/pieces/community/surrealdb/src/lib/actions/run-query.ts+++ b/packages/pieces/community/surrealdb/src/lib/actions/run-query.ts@@ -1,10 +1,12 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { surrealdbAuth } from '../..';-import surrealClient from '../common';+import { surrealdbAuth } from '../auth';+import { surrealdbApi } from '../common/api';+import { runQueryOutputSchema } from '../output-schemas';-export const runQuery = createAction({+export const runQueryAction = createAction({auth: surrealdbAuth,name: 'run-query',+ outputSchema: runQueryOutputSchema,classification: 'WRITE',displayName: 'Run Query',description: 'Run a query in SurrealDB.',@@ -49,14 +51,15 @@ export const runQuery = createAction({async run(context) {try {const { query, args } = context.propsValue;- const response = await surrealClient.query(- context.auth.props,- query,- args as Record<string, string>- );- return response.body;+ return await surrealdbApi.query({+ auth: context.auth,+ sql: query,+ args: args+ ? Object.fromEntries(Object.entries(args).map(([key, value]) => [key, String(value)]))+ : undefined,+ });} catch (error) {- throw new Error(`Query execution failed: ${(error as Error).message}`);+ throw new Error(`Query execution failed: ${error instanceof Error ? error.message : undefined}`);}},});diff --git a/packages/pieces/community/surrealdb/src/lib/auth.ts b/packages/pieces/community/surrealdb/src/lib/auth.tsnew file mode 100644index 00000000000..7348d997c34--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/auth.ts@@ -0,0 +1,56 @@+import { HttpError } from '@activepieces/pieces-common';+import { AppConnectionType, PieceAuth, Property } from '@activepieces/pieces-framework';+import { surrealdbApi } from './common/api';+import { surrealdbUtils } from './common/utils';++export const surrealdbAuth = PieceAuth.CustomAuth({+ props: {+ url: Property.ShortText({+ displayName: 'Connection URL',+ required: true,+ description: 'Connection string, e.g. http://1.2.3.5:8000.',+ }),+ database: Property.ShortText({+ displayName: 'Database',+ description:+ 'A string indicating the name of the database to connect to.',+ required: true,+ }),+ namespace: Property.ShortText({+ displayName: 'Namespace',+ required: true,+ description:+ 'As string indicating the namespace of the database to connect to.',+ }),+ username: Property.ShortText({+ displayName: 'Username',+ required: true,+ description:+ 'As string indicating the username of the database to connect to.',+ }),+ password: Property.ShortText({+ displayName: 'Password',+ required: true,+ description:+ 'As string indicating the password of the database to connect to.',+ }),+ },+ required: true,+ validate: async ({ auth }) => {+ try {+ const statements = await surrealdbApi.query({+ auth: { type: AppConnectionType.CUSTOM_AUTH, props: auth },+ sql: 'INFO for db',+ });+ surrealdbUtils.lastStatementResult({ statements });+ } catch (e) {+ return {+ valid: false,+ error: e instanceof Error && !(e instanceof HttpError) ? e.message : JSON.stringify(e),+ };+ }+ return {+ valid: true,+ };+ },+});diff --git a/packages/pieces/community/surrealdb/src/lib/common.ts b/packages/pieces/community/surrealdb/src/lib/common.tsdeleted file mode 100644index 89960013244..00000000000--- a/packages/pieces/community/surrealdb/src/lib/common.ts+++ /dev/null@@ -1,40 +0,0 @@-import {- HttpMethod,- HttpRequest,- httpClient,-} from '@activepieces/pieces-common';-import { PiecePropValueSchema } from '@activepieces/pieces-framework';-import { surrealdbAuth } from '..';--const query = async (- auth: PiecePropValueSchema<typeof surrealdbAuth>,- query: string,- args?: Record<string, string>-) => {- const { url, username, password, namespace, database } = auth;-- const sqlUrl = new URL('/sql', url);- const request: HttpRequest = {- method: HttpMethod.POST,- url: sqlUrl.toString(),- headers: {- 'Content-Type': 'text/plain',- Accept: 'application/json',- Authorization: `Basic ${Buffer.from(`${username}:${password}`).toString(- 'base64'- )}`,- 'surreal-ns': namespace,- 'surreal-db': database,- },- queryParams: args,- body: query,- };-- const response = await httpClient.sendRequest(request);-- return response;-};--export default {- query,-};diff --git a/packages/pieces/community/surrealdb/src/lib/common/ai-props.ts b/packages/pieces/community/surrealdb/src/lib/common/ai-props.tsnew file mode 100644index 00000000000..3d65f41f4e3--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/common/ai-props.ts@@ -0,0 +1,36 @@+import { Property } from '@activepieces/pieces-framework';+import type { PropParams } from './props';++const DEFAULT_LIMIT = 100;+const MAX_LIMIT = 1000;+const DEFAULT_MAX_ROWS = 100;++function table<R extends boolean>({ required, displayName = 'Table', description = 'Table name, e.g. "person". Use List Tables to find it.' }: PropParams<R>) {+ return Property.ShortText({ displayName, description, required });+}++function recordId<R extends boolean>({ required, displayName = 'Record ID', description = 'Full record id in "table:id" form, e.g. "person:tobie", as returned in the id field by Find Records, Create Record and the other record actions.' }: PropParams<R>) {+ return Property.ShortText({ displayName, description, required });+}++function filters<R extends boolean>({+ required,+ displayName = 'Filters',+ description = 'JSON object of conditions, all combined with AND. {"field": value} matches equality; {"field": {"$gt": 18}} uses an operator: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin, $contains, $containsNot, $containsAny, $containsAll, $exists (true/false). Nested fields use dots ("address.city"). Wrap a value as {"$record": "user:tobie"}, {"$datetime": "2024-01-01T00:00:00Z"}, {"$decimal": "1.50"}, {"$uuid": "..."} or {"$duration": "1h"} to compare against that SurrealDB type; plain strings stay strings.',+}: PropParams<R>) {+ return Property.Json({ displayName, description, required });+}++function data<R extends boolean>({ required, displayName = 'Data', description = 'JSON object of field values, e.g. {"name": "Tobie", "age": 33}. Strings are stored as strings; use Run Query to store record links or datetimes.' }: PropParams<R>) {+ return Property.Json({ displayName, description, required });+}++function limit<R extends boolean>({ required, displayName = 'Limit', description = `Max records to return (1-${MAX_LIMIT}). Defaults to ${DEFAULT_LIMIT}.` }: PropParams<R>) {+ return Property.Number({ displayName, description, required });+}++function maxRows<R extends boolean>({ required, displayName = 'Max Rows', description = `Safety limit: if the filters match more records than this, nothing is changed and the action fails. Defaults to ${DEFAULT_MAX_ROWS}.` }: PropParams<R>) {+ return Property.Number({ displayName, description, required });+}++export const surrealdbAiProps = { table, recordId, filters, data, limit, maxRows, DEFAULT_LIMIT, MAX_LIMIT, DEFAULT_MAX_ROWS };diff --git a/packages/pieces/community/surrealdb/src/lib/common/api.ts b/packages/pieces/community/surrealdb/src/lib/common/api.tsnew file mode 100644index 00000000000..5342e279228--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/common/api.ts@@ -0,0 +1,39 @@+import { HttpMethod, QueryParams } from '@activepieces/pieces-common';+import { surrealdbClient } from './client';+import { surrealdbUtils } from './utils';+import type { SurrealdbAuthValue, SurrealdbRpcResponse, SurrealdbStatementResult } from './types';++async function query<T>({ auth, sql, args }: { auth: SurrealdbAuthValue; sql: string; args?: QueryParams }): Promise<SurrealdbStatementResult<T>[]> {+ return await surrealdbClient.request<SurrealdbStatementResult<T>[]>({+ auth,+ method: HttpMethod.POST,+ path: '/sql',+ headers: { 'Content-Type': 'text/plain' },+ query: args,+ body: sql,+ });+}++async function rpc<T>({ auth, method, params }: { auth: SurrealdbAuthValue; method: string; params: unknown[] }): Promise<T> {+ const response = await surrealdbClient.request<SurrealdbRpcResponse<T>>({+ auth,+ method: HttpMethod.POST,+ path: '/rpc',+ headers: { 'Content-Type': 'application/json' },+ body: { id: 1, method, params },+ });+ if (response.error) {+ throw new Error(`SurrealDB error: ${response.error.message ?? 'unknown error'}`);+ }+ if (response.result === undefined) {+ throw new Error('SurrealDB returned no result.');+ }+ return response.result;+}++async function rpcQuery<T>({ auth, sql, vars }: { auth: SurrealdbAuthValue; sql: string; vars: Record<string, unknown> }): Promise<T> {+ const statements = await rpc<SurrealdbStatementResult<T>[]>({ auth, method: 'query', params: [sql, vars] });+ return surrealdbUtils.lastStatementResult({ statements });+}++export const surrealdbApi = { query, rpc, rpcQuery };diff --git a/packages/pieces/community/surrealdb/src/lib/common/client.ts b/packages/pieces/community/surrealdb/src/lib/common/client.tsnew file mode 100644index 00000000000..4fc85b1ccc8--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/common/client.ts@@ -0,0 +1,36 @@+import { HttpHeaders, HttpMethod, httpClient, QueryParams } from '@activepieces/pieces-common';+import type { SurrealdbAuthValue } from './types';++function baseUrl({ auth }: { auth: SurrealdbAuthValue }): string {+ return auth.props.url;+}++async function request<T>({ auth, method, path, query, body, headers, responseType }: RequestParams & { auth: SurrealdbAuthValue }): Promise<T> {+ const { username, password, namespace, database } = auth.props;+ const response = await httpClient.sendRequest<T>({+ method,+ url: new URL(path, baseUrl({ auth })).toString(),+ headers: {+ ...headers,+ Accept: 'application/json',+ Authorization: `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`,+ 'surreal-ns': namespace,+ 'surreal-db': database,+ },+ queryParams: query,+ body,+ responseType,+ });+ return response.body;+}++export const surrealdbClient = { baseUrl, request };++type RequestParams = {+ method: HttpMethod;+ path: string;+ query?: QueryParams;+ body?: unknown;+ headers?: HttpHeaders;+ responseType?: 'json' | 'text';+};diff --git a/packages/pieces/community/surrealdb/src/lib/common/props.ts b/packages/pieces/community/surrealdb/src/lib/common/props.tsnew file mode 100644index 00000000000..6e4d2378930--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/common/props.ts@@ -0,0 +1,41 @@+import { DropdownState, Property } from '@activepieces/pieces-framework';+import { surrealdbAuth } from '../auth';+import { surrealdbApi } from './api';+import type { SurrealdbDbInfo } from './types';++function table<R extends boolean>({ required, displayName = 'Table name', description }: PropParams<R>) {+ return Property.Dropdown({+ displayName,+ description,+ required,+ refreshers: ['auth'],+ refreshOnSearch: false,+ auth: surrealdbAuth,+ options: async ({ auth }) => {+ if (!auth) {+ return disabledOptions({ placeholder: 'Please authenticate first' });+ }+ try {+ const result = await surrealdbApi.query<SurrealdbDbInfo>({ auth, sql: 'INFO FOR DB' });+ const options = Object.keys(result[0].result.tables).map((row) => ({+ label: row,+ value: row,+ }));+ return {+ disabled: false,+ options,+ };+ } catch (e) {+ return disabledOptions({ placeholder: JSON.stringify(e) });+ }+ },+ });+}++function disabledOptions({ placeholder }: { placeholder: string }): DropdownState<never> {+ return { disabled: true, options: [], placeholder };+}++export const surrealdbProps = { table };++export type PropParams<R extends boolean> = { required: R; displayName?: string; description?: string };diff --git a/packages/pieces/community/surrealdb/src/lib/common/types.ts b/packages/pieces/community/surrealdb/src/lib/common/types.tsnew file mode 100644index 00000000000..90de093b750--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/common/types.ts@@ -0,0 +1,55 @@+import type { AppConnectionType } from '@activepieces/pieces-framework';+import type { ConfigType } from 'dayjs';++export type SurrealdbAuthValue = {+ type: AppConnectionType.CUSTOM_AUTH;+ props: {+ url: string;+ database: string;+ namespace: string;+ username: string;+ password: string;+ };+};++export type SurrealdbStatementResult<T> = {+ time?: string;+ status?: string;+ kind?: string;+ details?: { kind?: string };+ result: T;+};++export type SurrealdbRpcResponse<T> = {+ id?: number;+ result?: T;+ error?: { code?: number; kind?: string; message?: string };+};++export type SurrealdbRow = Record<string, ConfigType>;++export type SurrealdbDbInfo = {+ tables: Record<string, string>;+};++export type SurrealdbWhere = {+ clause: string;+ vars: Record<string, unknown>;+};++export type SurrealdbDbStructure = {+ tables?: Record<string, unknown>[];+};++export type SurrealdbRootStructure = {+ namespaces?: Record<string, unknown>[];+};++export type SurrealdbNamespaceStructure = {+ databases?: Record<string, unknown>[];+};++export type SurrealdbGraphqlResponse = {+ data?: Record<string, unknown> | null;+ errors?: { message?: string }[];+};diff --git a/packages/pieces/community/surrealdb/src/lib/common/utils.ts b/packages/pieces/community/surrealdb/src/lib/common/utils.tsnew file mode 100644index 00000000000..71076dedf61--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/common/utils.ts@@ -0,0 +1,137 @@+import type { SurrealdbStatementResult, SurrealdbWhere } from './types';++function isObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function toObject({ value, label }: { value: unknown; label: string }): Record<string, unknown> {+ if (!isObject(value)) {+ throw new Error(`${label} must be a JSON object.`);+ }+ return value;+}++function buildWhere({ filters }: { filters: unknown }): SurrealdbWhere {+ if (filters === undefined || filters === null) {+ return { clause: '', vars: {} };+ }+ const conditions = Object.entries(toObject({ value: filters, label: 'Filters' })).flatMap(([field, condition]) =>+ isOperatorObject(condition)+ ? Object.entries(condition).map(([operator, value]) => ({ field, operator, value }))+ : [{ field, operator: '$eq', value: condition }],+ );+ const parts = conditions.map(({ field, operator, value }, index) => conditionToSql({ field, operator, value, index }));+ if (parts.length === 0) {+ return { clause: '', vars: {} };+ }+ return {+ clause: ` WHERE ${parts.map((part) => part.sql).join(' AND ')}`,+ vars: parts.reduce<Record<string, unknown>>((all, part) => ({ ...all, ...part.vars }), {}),+ };+}++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 fieldPath({ field, label }: { field: string; label: string }): string {+ if (!FIELD_PATH.test(field)) {+ throw new Error(`${label} "${field}" is not a valid field path. Use letters, digits and underscores, with dots for nested fields (e.g. "address.city").`);+ }+ return field;+}++function singleRecord({ records, recordId }: { records: Record<string, unknown>[]; recordId: string }): Record<string, unknown> {+ const [record] = records;+ if (record === undefined) {+ throw new Error(`Record "${recordId}" was not found. Record ids look like "table:id"; Find Records returns them.`);+ }+ return record;+}++function lastStatementResult<T>({ statements }: { statements: SurrealdbStatementResult<T>[] }): T {+ const failures = statements.filter((statement) => statement.status === 'ERR');+ if (failures.length > 0) {+ const causes = failures.filter((statement) => !FOLLOW_ON_ERRORS.includes(statement.details?.kind ?? ''));+ throw new Error(`SurrealDB error: ${(causes.length > 0 ? causes : failures).map((statement) => String(statement.result)).join('; ')}`);+ }+ const last = statements[statements.length - 1];+ if (!last) {+ throw new Error('SurrealDB returned no result.');+ }+ return last.result;+}++function isOperatorObject(value: unknown): value is Record<string, unknown> {+ if (!isObject(value)) {+ return false;+ }+ const keys = Object.keys(value);+ const isCast = keys.length === 1 && Object.keys(CASTS).includes(keys[0]);+ return !isCast && keys.some((key) => key.startsWith('$'));+}++function conditionToSql({ field, operator, value, index }: { field: string; operator: string; value: unknown; index: number }): { sql: string; vars: Record<string, unknown> } {+ const fieldVar = `ap_f${index}`;+ const valueVar = `ap_v${index}`;+ const target = `type::field($${fieldVar})`;+ if (operator === '$exists') {+ if (typeof value !== 'boolean') {+ throw new Error(`Filter on "${field}": $exists takes true or false.`);+ }+ return { sql: `${target} ${value ? '!=' : '='} NONE`, vars: { [fieldVar]: field } };+ }+ const sqlOperator = Object.keys(OPERATORS).includes(operator) ? OPERATORS[operator] : undefined;+ if (sqlOperator === undefined) {+ throw new Error(`Filter on "${field}": operator "${operator}" is not supported. Use one of: ${Object.keys(OPERATORS).join(', ')}.`);+ }+ const typed = typedValue({ value });+ return {+ sql: `${target} ${sqlOperator} ${typed.cast}$${valueVar}`,+ vars: { [fieldVar]: field, [valueVar]: typed.value },+ };+}++function typedValue({ value }: { value: unknown }): { cast: string; value: unknown } {+ if (isObject(value) && Object.keys(value).length === 1) {+ const [key] = Object.keys(value);+ if (Object.keys(CASTS).includes(key)) {+ return { cast: CASTS[key], value: value[key] };+ }+ }+ return { cast: '', value };+}++export const surrealdbUtils = { toObject, buildWhere, boundedInteger, fieldPath, isObject, singleRecord, lastStatementResult };++const FOLLOW_ON_ERRORS = ['NotExecuted', 'Cancelled'];++const FIELD_PATH = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/;++const OPERATORS: Record<string, string> = {+ $eq: '=',+ $ne: '!=',+ $gt: '>',+ $gte: '>=',+ $lt: '<',+ $lte: '<=',+ $in: 'INSIDE',+ $nin: 'NOTINSIDE',+ $contains: 'CONTAINS',+ $containsNot: 'CONTAINSNOT',+ $containsAny: 'CONTAINSANY',+ $containsAll: 'CONTAINSALL',+ $exists: '',+};++const CASTS: Record<string, string> = {+ $record: '<record>',+ $datetime: '<datetime>',+ $decimal: '<decimal>',+ $uuid: '<uuid>',+ $duration: '<duration>',+};diff --git a/packages/pieces/community/surrealdb/src/lib/output-schemas.ts b/packages/pieces/community/surrealdb/src/lib/output-schemas.tsnew file mode 100644index 00000000000..e58f1085698--- /dev/null+++ b/packages/pieces/community/surrealdb/src/lib/output-schemas.ts@@ -0,0 +1,210 @@+import { OutputSchema } from '@activepieces/pieces-framework';++const recordFields: OutputSchema['fields'] = [{ key: 'id', label: 'Record ID', description: 'Full record id in "table:id" form; the other fields are the record\'s own data.' }];++const permissionFields: OutputSchema['fields'] = [+ { key: 'select', label: 'Select' },+ { key: 'create', label: 'Create' },+ { key: 'update', label: 'Update' },+ { key: 'delete', label: 'Delete' },+];++const tableFields: OutputSchema['fields'] = [+ { key: 'name', label: 'Name' },+ { key: 'id', label: 'Internal ID', format: 'number' },+ { key: 'kind', label: 'Kind', children: [{ key: 'kind', label: 'Kind' }] },+ { key: 'schemafull', label: 'Schemafull', format: 'boolean' },+ { key: 'drop', label: 'Drop', format: 'boolean' },+ { key: 'permissions', label: 'Permissions', children: permissionFields },+];++const pageFields: OutputSchema['fields'] = [+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ { key: 'next_start', label: 'Next Start', format: 'number' },+];++const recordsListFields: OutputSchema['fields'] = [+ { key: 'records', label: 'Records', labelKey: 'id', listItems: recordFields },+ { key: 'count', label: 'Count', format: 'number' },+];++export const runQueryOutputSchema: OutputSchema = {+ itemLabel: 'Statement {status}',+ fields: [+ {+ key: 'statements',+ label: 'Statements',+ value: '',+ listItems: [+ { key: 'status', label: 'Status' },+ { key: 'result', label: 'Result' },+ { key: 'time', label: 'Time' },+ ],+ },+ ],+};++export const surrealdbCountRecordsOutputSchema: OutputSchema = {+ fields: [{ key: 'count', label: 'Count', format: 'number' }],+};++export const surrealdbRecordOutputSchema: OutputSchema = {+ fields: recordFields,+};++export const surrealdbRecordsOutputSchema: OutputSchema = {+ fields: recordsListFields,+};++export const surrealdbDescribeTableOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'fields',+ label: 'Fields',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'kind', label: 'Type' },+ { key: 'readonly', label: 'Read Only', format: 'boolean' },+ { key: 'table', label: 'Table' },+ { key: 'permissions', label: 'Permissions', children: permissionFields.filter((field) => field.key !== 'delete') },+ ],+ },+ {+ key: 'indexes',+ label: 'Indexes',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'cols', label: 'Columns' },+ { key: 'index', label: 'Index Type' },+ { key: 'table', label: 'Table' },+ ],+ },+ { key: 'events', label: 'Events' },+ { key: 'lives', label: 'Live Queries' },+ { key: 'tables', label: 'Views' },+ ],+};++export const surrealdbExportDatabaseOutputSchema: OutputSchema = {+ fields: [+ { key: 'file', label: 'File', format: 'url' },+ { key: 'file_name', label: 'File Name' },+ { key: 'size_bytes', label: 'Size', format: 'filesize' },+ ],+};++export const surrealdbFindRecordsOutputSchema: OutputSchema = {+ fields: [{ key: 'records', label: 'Records', labelKey: 'id', listItems: recordFields }, ...pageFields],+};++export const surrealdbFindRelatedRecordsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'edges',+ label: 'Edges',+ labelKey: 'id',+ listItems: [+ { key: 'id', label: 'Edge ID' },+ { key: 'in', label: 'From Record ID' },+ { key: 'out', label: 'To Record ID' },+ { key: 'related', label: 'Related Record', children: recordFields },+ ],+ },+ ...pageFields,+ ],+};++export const surrealdbGetDatabaseInfoOutputSchema: OutputSchema = {+ fields: [+ { key: 'tables', label: 'Tables', labelKey: 'name', listItems: tableFields },+ {+ key: 'functions',+ label: 'Functions',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'args', label: 'Arguments' },+ { key: 'block', label: 'Body' },+ { key: 'permissions', label: 'Permissions' },+ ],+ },+ { key: 'params', label: 'Params' },+ { key: 'accesses', label: 'Accesses' },+ { key: 'analyzers', label: 'Analyzers' },+ { key: 'users', label: 'Users' },+ { key: 'sequences', label: 'Sequences' },+ { key: 'apis', label: 'APIs' },+ { key: 'buckets', label: 'Buckets' },+ { key: 'configs', label: 'Configs' },+ { key: 'models', label: 'Models' },+ { key: 'modules', label: 'Modules' },+ ],+};++export const surrealdbImportDataOutputSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'size_bytes', label: 'Size', format: 'filesize' },+ ],+};++export const surrealdbListDatabasesOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'databases',+ label: 'Databases',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'id', label: 'Internal ID', format: 'number' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const surrealdbListNamespacesOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'namespaces',+ label: 'Namespaces',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'id', label: 'Internal ID', format: 'number' },+ { key: 'comment', label: 'Comment' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const surrealdbListTablesOutputSchema: OutputSchema = {+ fields: [+ { key: 'tables', label: 'Tables', labelKey: 'name', listItems: tableFields },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const surrealdbRelateRecordsOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Edge ID' },+ { key: 'in', label: 'From Record ID' },+ { key: 'out', label: 'To Record ID' },+ ],+};++export const surrealdbRunFunctionOutputSchema: OutputSchema = {+ fields: [{ key: 'result', label: 'Result' }],+};++export const surrealdbRunGqlQueryOutputSchema: OutputSchema = {+ fields: [{ key: 'result', label: 'Result' }],+};++export const surrealdbRunGraphqlQueryOutputSchema: OutputSchema = {+ fields: [{ key: 'data', label: 'Data', dynamicKey: true }],+};diff --git a/packages/pieces/community/surrealdb/src/lib/triggers/new-row.ts b/packages/pieces/community/surrealdb/src/lib/triggers/new-row.tsindex f5d062a9642..c973d2d126a 100644--- a/packages/pieces/community/surrealdb/src/lib/triggers/new-row.ts+++ b/packages/pieces/community/surrealdb/src/lib/triggers/new-row.ts@@ -1,7 +1,6 @@import {createTrigger,TriggerStrategy,- PiecePropValueSchema,Property,AppConnectionValueForAuthProperty,} from '@activepieces/pieces-framework';@@ -11,11 +10,12 @@ import {pollingHelper,} from '@activepieces/pieces-common';import dayjs from 'dayjs';-import { surrealdbAuth } from '../..';-import client from '../common';import crypto from 'crypto';+import { surrealdbAuth } from '../auth';+import { surrealdbApi } from '../common/api';+import { surrealdbProps } from '../common/props';+import type { SurrealdbRow } from '../common/types';-// replace auth with piece auth variableconst polling: Polling<AppConnectionValueForAuthProperty<typeof surrealdbAuth>,{@@ -26,21 +26,22 @@ const polling: Polling<> = {strategy: DedupeStrategy.LAST_ITEM,items: async ({ auth, propsValue, lastItemId }) => {- const lastItem = lastItemId as string;+ const lastItem = typeof lastItemId === 'string' ? lastItemId : undefined;const query = constructQuery({order_by: propsValue.order_by,lastItem: lastItem,order_direction: propsValue.order_direction,});- const authProps = auth.props;- const result = await client.query(authProps, query, {- table: propsValue.table,+ const result = await surrealdbApi.query<SurrealdbRow[]>({+ auth,+ sql: query,+ args: {+ table: propsValue.table,+ },});- const items = result.body[0].result.map(function (- row: Record<string, any>- ) {+ const items = result[0].result.map(function (row) {const rowHash = crypto.createHash('md5').update(JSON.stringify(row))@@ -66,7 +67,7 @@ function constructQuery({}: {order_by: string;order_direction: 'ASC' | 'DESC' | undefined;- lastItem: string;+ lastItem: string | undefined;}): string {const lastOrderKey = lastItem ? lastItem.split('|')[0] : null;if (lastOrderKey === null) {@@ -100,7 +101,7 @@ function constructQuery({}}-export const newRow = createTrigger({+export const newRowTrigger = createTrigger({name: 'new-row',classification: 'READ',displayName: 'New Row',@@ -112,42 +113,7 @@ export const newRow = createTrigger({description: Property.MarkDown({value: `**NOTE:** The trigger fetches the latest rows using the provided order by column (newest first), and then will keep polling until the previous last row is reached. It's suggested to add a created_at timestamp. \`DEFINE FIELD OVERWRITE createdAt ON schedule VALUE time::now() READONLY;\``,}),- table: Property.Dropdown({- displayName: 'Table name',- required: true,- refreshers: ['auth'],- refreshOnSearch: false,- auth: surrealdbAuth,- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- options: [],- placeholder: 'Please authenticate first',- };- }- const authProps = auth.props;- try {- const result = await client.query(authProps, 'INFO FOR DB');- const options = Object.keys(result.body[0].result.tables).map(- (row) => ({- label: row,- value: row,- })- );- return {- disabled: false,- options,- };- } catch (e) {- return {- disabled: true,- options: [],- placeholder: JSON.stringify(e),- };- }- },- }),+ table: surrealdbProps.table({ required: true }),order_by: Property.ShortText({displayName: 'Column to order by',description: 'Use something like a created timestamp.',