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(microsoft-sql-server): let AI agents explore schemas, query and safely write rows (#17075)
Kishan Parmar209255bda908
diff --git a/bun.lock b/bun.lockindex f065d651eb2..44d12afa603 100644--- a/bun.lock+++ b/bun.lock@@ -6088,7 +6088,7 @@},"packages/pieces/community/microsoft-sql-server": {"name": "@activepieces/piece-microsoft-sql-server",- "version": "0.1.1",+ "version": "0.2.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",diff --git a/packages/pieces/community/microsoft-sql-server/package.json b/packages/pieces/community/microsoft-sql-server/package.jsonindex 504669fd1d6..56103f1cf8b 100644--- a/packages/pieces/community/microsoft-sql-server/package.json+++ b/packages/pieces/community/microsoft-sql-server/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-microsoft-sql-server",- "version": "0.1.1",+ "version": "0.2.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {diff --git a/packages/pieces/community/microsoft-sql-server/src/index.ts b/packages/pieces/community/microsoft-sql-server/src/index.tsindex d88019ec8fa..ed86eb0e32c 100644--- a/packages/pieces/community/microsoft-sql-server/src/index.ts+++ b/packages/pieces/community/microsoft-sql-server/src/index.ts@@ -8,12 +8,13 @@ import { deleteRowsAction } from './lib/actions/delete-rows';import { getTablesAction } from './lib/actions/get-tables';import { runQueryAction } from './lib/actions/run-query';import { newOrUpdatedRowTrigger } from './lib/triggers/new-or-updated-row';+import { microsoftSqlServerAiActions } from './lib/actions/ai';export const mssql = createPiece({displayName: 'Microsoft SQL Server',description:"Microsoft's relational database engine, on-premise or as Azure SQL",- minimumSupportedRelease: '0.36.1',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/microsoft-sql-server.png',categories: [PieceCategory.DEVELOPER_TOOLS],authors: ['OdaiAhmed99'],@@ -26,6 +27,7 @@ export const mssql = createPiece({deleteRowsAction,getTablesAction,runQueryAction,+ ...microsoftSqlServerAiActions,],triggers: [newOrUpdatedRowTrigger],});diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/index.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/index.tsnew file mode 100644index 00000000000..228744c68bc--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/index.ts@@ -0,0 +1,41 @@+import { describeTable } from './schema/describe-table';+import { getViewDefinition } from './schema/get-view-definition';+import { listDatabases } from './schema/list-databases';+import { listIndexes } from './schema/list-indexes';+import { listRoutines } from './schema/list-routines';+import { listSchemas } from './schema/list-schemas';+import { listViews } from './schema/list-views';+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 { callProcedure } from './queries/call-procedure';+import { explainQuery } from './queries/explain-query';+import { runSelectQuery } from './queries/run-select-query';+import { getServerInfo } from './server/get-server-info';+import { listSessions } from './server/list-sessions';++export const microsoftSqlServerAiActions = [+ listDatabases,+ listSchemas,+ describeTable,+ listIndexes,+ listViews,+ getViewDefinition,+ listRoutines,+ findRowsAi,+ getRowByKey,+ countRows,+ insertRowsAi,+ upsertRow,+ updateRowsAi,+ deleteRowsAi,+ runSelectQuery,+ explainQuery,+ callProcedure,+ getServerInfo,+ listSessions,+];diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/queries/call-procedure.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/queries/call-procedure.tsnew file mode 100644index 00000000000..12bf1936519--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/queries/call-procedure.ts@@ -0,0 +1,133 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import sql from 'mssql';+import { mssqlAuth } from '../../../auth';+import { MssqlTable, mssqlCommon } from '../../../common';+import { mssqlAi, mssqlAiProps } from '../../../common/ai';+import { microsoftSqlServerCallProcedureOutputSchema } from '../../../output-schemas';++export const callProcedure = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_call_procedure',+ outputSchema: microsoftSqlServerCallProcedureOutputSchema,+ displayName: 'Call Procedure',+ description: 'Runs a stored procedure and returns its result sets, OUTPUT parameters and return value.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Executes a stored procedure with named parameters and returns every result set it selects, the final values of its OUTPUT parameters by name, its return value and the rows it affected. Input parameters left out take their declared default, or fail if they have none; OUTPUT parameters are always passed, starting as NULL unless given a value, so pass one where the procedure relies on the default of an OUTPUT parameter. Procedure and parameter names come from List Routines. Not idempotent: the effect depends on the procedure.',+ idempotent: false,+ },+ props: {+ schema: mssqlAiProps.schema,+ procedure: Property.ShortText({+ displayName: 'Procedure',+ description: 'Procedure name without the schema, as returned by List Routines.',+ required: true,+ }),+ parameters: Property.Object({+ displayName: 'Parameters',+ description: 'Parameter names mapped to values, with or without the @, e.g. {"customer_id": 42}. An OUTPUT parameter left out starts as NULL, not its declared default.',+ required: false,+ }),+ },+ async run(context) {+ const { schema, procedure } = context.propsValue;+ const given = Object.fromEntries(+ Object.entries(context.propsValue.parameters ?? {}).map(([name, value]) => [`@${name.replace(/^@/, '')}`.toLowerCase(), value]),+ );+ return mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const target = await mssqlAi.resolveObject({ pool, schema, name: procedure, kinds: ['P', 'PC'], label: 'Procedure' });+ const declared = await loadParameters({ pool, target });+ const unknown = Object.keys(given).filter((name) => !declared.some((parameter) => parameter.name.toLowerCase() === name));+ if (unknown.length > 0) {+ const known = declared.map((parameter) => parameter.name).join(', ') || 'none';+ throw new Error(`Procedure "${target.table_schema}.${target.table_name}" has no parameter ${unknown.join(', ')}. Its parameters: ${known}.`);+ }+ const plan = buildCall({ target, declared, given });+ const result = await mssqlAi.bind({ request: pool.request(), params: plan.params }).query<Record<string, unknown>>(plan.sql);+ const sets = result.recordsets.map((set) => [...set]);+ const status = sets[sets.length - 1]?.[0] ?? {};+ const counts = result.rowsAffected ?? [];+ return {+ result_sets: sets.slice(0, -1),+ output_parameters: Object.fromEntries(plan.outputs.map((name, index) => [name, status[`o${index}`]])),+ return_value: status['return_value'] ?? null,+ rows_affected: counts.reduce((a, b) => a + b, 0),+ };+ },+ });+ },+});++async function loadParameters({ pool, target }: { pool: sql.ConnectionPool; target: MssqlTable }): Promise<Parameter[]> {+ const result = await pool+ .request()+ .input('name', mssqlCommon.quoteTable(target))+ .query<Record<string, unknown>>(+ `SELECT p.name, t.name AS type, SCHEMA_NAME(t.schema_id) AS type_schema, t.is_user_defined,+ p.max_length, p.precision, p.scale, p.is_output+ FROM sys.parameters p+ JOIN sys.types t ON t.user_type_id = p.user_type_id+ WHERE p.object_id = OBJECT_ID(@name) AND p.parameter_id > 0 ORDER BY p.parameter_id`+ );+ return result.recordset.map((row) => ({+ name: String(row['name']),+ dataType: row['is_user_defined']+ ? `${mssqlCommon.quoteId(String(row['type_schema']))}.${mssqlCommon.quoteId(String(row['type']))}`+ : mssqlAi.typeLabel({+ type: String(row['type']),+ maxLength: Number(row['max_length']),+ precision: Number(row['precision']),+ scale: Number(row['scale']),+ }),+ isOutput: Boolean(row['is_output']),+ }));+}++function buildCall({ target, declared, given }: { target: MssqlTable; declared: Parameter[]; given: Record<string, unknown> }): CallPlan {+ const outputs = declared.filter((parameter) => parameter.isOutput);+ const inputs = declared.filter((parameter) => !parameter.isOutput && parameter.name.toLowerCase() in given);+ const declarations = outputs.map((parameter, index) => {+ const initial = parameter.name.toLowerCase() in given ? `@oi${index}` : 'NULL';+ return `DECLARE @o${index} ${parameter.dataType} = ${initial};`;+ });+ const args = [+ ...inputs.map((parameter, index) => `${parameter.name} = @i${index}`),+ ...outputs.map((parameter, index) => `${parameter.name} = @o${index} OUTPUT`),+ ];+ const selects = ['@ap_return AS return_value', ...outputs.map((_, index) => `@o${index} AS o${index}`)];+ return {+ sql: [+ 'SET NOCOUNT ON;',+ 'DECLARE @ap_return int;',+ ...declarations,+ 'SET NOCOUNT OFF;',+ `EXEC @ap_return = ${mssqlCommon.quoteTable(target)}${args.length > 0 ? ` ${args.join(', ')}` : ''};`,+ 'SET NOCOUNT ON;',+ `SELECT ${selects.join(', ')};`,+ ].join('\n'),+ params: {+ ...Object.fromEntries(inputs.map((parameter, index) => [`i${index}`, given[parameter.name.toLowerCase()]])),+ ...Object.fromEntries(+ outputs+ .map((parameter, index) => [`oi${index}`, given[parameter.name.toLowerCase()]] as const)+ .filter(([, value]) => value !== undefined),+ ),+ },+ outputs: outputs.map((parameter) => parameter.name.replace(/^@/, '')),+ };+}++type Parameter = {+ name: string;+ dataType: string;+ isOutput: boolean;+};++type CallPlan = {+ sql: string;+ params: Record<string, unknown>;+ outputs: string[];+};diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/queries/explain-query.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/queries/explain-query.tsnew file mode 100644index 00000000000..0a9cad5ef7a--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/queries/explain-query.ts@@ -0,0 +1,51 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import sql from 'mssql';+import { mssqlAuth } from '../../../auth';+import { mssqlAi } from '../../../common/ai';+import { microsoftSqlServerExplainQueryOutputSchema } from '../../../output-schemas';++export const explainQuery = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_explain_query',+ outputSchema: microsoftSqlServerExplainQueryOutputSchema,+ displayName: 'Explain Query',+ description: 'Returns the estimated execution plan of a query without running it.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description: 'Returns the estimated execution plan (showplan XML) of a T-SQL statement without executing it, one plan per statement, to check index use and costs before running a slow query. Write literal values: @placeholders are not supported unless the query DECLAREs them. Needs the SHOWPLAN permission. Read-only.',+ idempotent: true,+ },+ props: {+ query: Property.LongText({+ displayName: 'Query',+ description: 'The T-SQL statement to explain, with literal values, e.g. SELECT * FROM dbo.orders WHERE status = \'open\'',+ required: true,+ }),+ },+ async run(context) {+ const { query } = context.propsValue;+ if (/\bSHOWPLAN/i.test(query) || /^\s*GO\s*$/im.test(query)) {+ throw new Error('The query must not contain SHOWPLAN settings or GO separators.');+ }+ const plans = await mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const transaction = new sql.Transaction(pool);+ await transaction.begin();+ try {+ await transaction.request().batch('SET SHOWPLAN_XML ON');+ try {+ const result = await transaction.request().batch<Record<string, unknown>>(query);+ return result.recordsets.flatMap((set) => [...set].map((row) => String(Object.values(row)[0])));+ } finally {+ await transaction.request().batch('SET SHOWPLAN_XML OFF');+ }+ } finally {+ await transaction.rollback().catch(() => undefined);+ }+ },+ });+ return { plans, count: plans.length };+ },+});diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/queries/run-select-query.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/queries/run-select-query.tsnew file mode 100644index 00000000000..65b00c37219--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/queries/run-select-query.ts@@ -0,0 +1,56 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import sql from 'mssql';+import { mssqlAuth } from '../../../auth';+import { mssqlAi, mssqlAiProps } from '../../../common/ai';+import { microsoftSqlServerRunSelectQueryOutputSchema } from '../../../output-schemas';++export const runSelectQuery = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_run_select_query',+ outputSchema: microsoftSqlServerRunSelectQueryOutputSchema,+ displayName: 'Run Select Query',+ description: 'Runs a read-only SELECT query and returns up to a limit of rows.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Runs one SELECT query (optionally starting with WITH) inside a transaction that is always rolled back, and returns up to Limit rows of its first result set, with has_more when it produced more. Statements that write, execute procedures or change settings are rejected. Pass dynamic values as @name placeholders in Parameters. Use for joins and aggregates Find Rows cannot express; use Run Query to change data. Read-only.',+ idempotent: true,+ },+ props: {+ query: Property.LongText({+ displayName: 'Query',+ description: 'One SELECT query. Write @name where each value goes, e.g. SELECT * FROM dbo.orders WHERE status = @status',+ required: true,+ }),+ parameters: Property.Object({+ displayName: 'Parameters',+ description: 'Values for the @placeholders in the query, keyed by name without the @, e.g. {"status": "open"}.',+ required: false,+ }),+ limit: mssqlAiProps.limit,+ },+ async run(context) {+ const { query, parameters, limit } = context.propsValue;+ mssqlAi.assertReadOnlyQuery({ query });+ const max = mssqlAi.boundedInteger({ value: limit, defaultValue: mssqlAi.READ_DEFAULT_LIMIT, min: 1, max: mssqlAi.READ_MAX_LIMIT, label: 'Limit' });+ const params = Object.fromEntries(Object.entries(parameters ?? {}).map(([name, value]) => [name.replace(/^@/, ''), value]));+ const found = await mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const transaction = new sql.Transaction(pool);+ await transaction.begin();+ try {+ const result = await mssqlAi+ .bind({ request: transaction.request(), params })+ .query<Record<string, unknown>>(`SET ROWCOUNT ${max + 1};\n${query}`);+ return result.recordsets.length > 0 ? [...result.recordsets[0]] : [];+ } finally {+ await transaction.rollback().catch(() => undefined);+ }+ },+ });+ const hasMore = found.length > max;+ const rows = found.slice(0, max);+ return { rows, count: rows.length, has_more: hasMore };+ },+});diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/count-rows.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/count-rows.tsnew file mode 100644index 00000000000..9965e5555c6--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/count-rows.ts@@ -0,0 +1,39 @@+import { createAction } from '@activepieces/pieces-framework';+import { mssqlAuth } from '../../../auth';+import { mssqlCommon } from '../../../common';+import { mssqlAi, mssqlAiProps } from '../../../common/ai';+import { microsoftSqlServerCountRowsOutputSchema } from '../../../output-schemas';++export const countRows = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_count_rows',+ outputSchema: microsoftSqlServerCountRowsOutputSchema,+ displayName: 'Count Rows',+ description: 'Counts the rows of a table that match the filters.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description: 'Counts the rows of a table or view matching all given filters, or every row when none are given. Use before Update Rows or Delete Rows to check how many rows a filter hits, or to plan paging with Find Rows. Read-only.',+ idempotent: true,+ },+ props: {+ schema: mssqlAiProps.schema,+ table: mssqlAiProps.table,+ filters: mssqlAiProps.filters({ required: false }),+ },+ async run(context) {+ const { schema, table, filters } = context.propsValue;+ const where = mssqlAi.buildWhere({ filters });+ const count = await mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const target = await mssqlAi.resolveObject({ pool, schema, name: table, kinds: mssqlAi.TABLE_KINDS, label: 'Table' });+ const result = await mssqlAi+ .bind({ request: pool.request(), params: where.params })+ .query<Record<string, unknown>>(`SELECT COUNT_BIG(*) AS total FROM ${mssqlCommon.quoteTable(target)}${where.sql}`);+ return Number(result.recordset[0]?.['total'] ?? 0);+ },+ });+ return { count };+ },+});diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/delete-rows.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/delete-rows.tsnew file mode 100644index 00000000000..9492bb33acb--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/delete-rows.ts@@ -0,0 +1,48 @@+import { createAction } from '@activepieces/pieces-framework';+import { mssqlAuth } from '../../../auth';+import { mssqlCommon } from '../../../common';+import { mssqlAi, mssqlAiProps } from '../../../common/ai';+import { writeRowsActionOutputSchema } from '../../../output-schemas';++export const deleteRowsAi = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_delete_rows',+ outputSchema: writeRowsActionOutputSchema,+ 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. Runs in a transaction and deletes nothing if more than Max Rows match; check with Count Rows first. Rows come back empty on tables with triggers; rows_affected is always set. There is no undo.',+ idempotent: false,+ },+ props: {+ schema: mssqlAiProps.schema,+ table: mssqlAiProps.table,+ filters: mssqlAiProps.filters({ required: true }),+ maxRows: mssqlAiProps.maxRows({ verb: 'deleted' }),+ },+ async run(context) {+ const { schema, table, filters, maxRows } = context.propsValue;+ const limit = mssqlAi.boundedInteger({ value: maxRows, defaultValue: mssqlAi.WRITE_GUARD_DEFAULT, min: 1, max: mssqlAi.WRITE_GUARD_MAX, label: 'Max Rows' });+ const where = mssqlAi.buildWhere({ filters });+ return mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const target = await mssqlAi.resolveObject({ pool, schema, name: table, kinds: mssqlAi.TABLE_KINDS, label: 'Table' });+ const meta = await mssqlCommon.getTableMeta({ pool, table: target });+ const quoted = mssqlCommon.quoteTable(target);+ return mssqlAi.guardedWrite({+ pool,+ target: quoted,+ where,+ maxRows: limit,+ verb: 'deleted',+ withOutput: `DELETE FROM ${quoted} OUTPUT ${mssqlAi.projection({ columns: meta.columns, prefix: 'DELETED' })}${where.sql}`,+ withoutOutput: `DELETE FROM ${quoted}${where.sql}`,+ params: where.params,+ });+ },+ });+ },+});diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/find-rows.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/find-rows.tsnew file mode 100644index 00000000000..70d23eb2bd9--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/find-rows.ts@@ -0,0 +1,76 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { mssqlAuth } from '../../../auth';+import { mssqlCommon } from '../../../common';+import { mssqlAi, mssqlAiProps } from '../../../common/ai';+import { microsoftSqlServerFindRowsOutputSchema } from '../../../output-schemas';++export const findRowsAi = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_find_rows',+ outputSchema: microsoftSqlServerFindRowsOutputSchema,+ 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 (has_more, next_offset). Values are sent as bound parameters; decimal, money and date/time values come back as exact strings. Without a sort, rows are ordered by the primary key. Use Count Rows for totals and Get Row by Key for one row. Column names come from Describe Table. Read-only.',+ idempotent: true,+ },+ props: {+ schema: mssqlAiProps.schema,+ table: mssqlAiProps.table,+ filters: mssqlAiProps.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). Leave empty to sort by the primary key.',+ 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: mssqlAiProps.limit,+ offset: Property.Number({+ displayName: 'Offset',+ description: 'Number of rows to skip, for paging. Use next_offset from the previous call with the same filters and sort.',+ required: false,+ defaultValue: 0,+ }),+ },+ async run(context) {+ const { schema, table, filters, columns, sort, limit, offset } = context.propsValue;+ const max = mssqlAi.boundedInteger({ value: limit, defaultValue: mssqlAi.READ_DEFAULT_LIMIT, min: 1, max: mssqlAi.READ_MAX_LIMIT, label: 'Limit' });+ const skip = mssqlAi.boundedInteger({ value: offset, defaultValue: 0, min: 0, max: Number.MAX_SAFE_INTEGER, label: 'Offset' });+ const where = mssqlAi.buildWhere({ filters });+ const sortBy = mssqlAi.buildOrderBy({ sort });+ const found = await mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const target = await mssqlAi.resolveObject({ pool, schema, name: table, kinds: mssqlAi.TABLE_KINDS, label: 'Table' });+ const meta = await mssqlCommon.getTableMeta({ pool, table: target });+ const select = mssqlAi.projection({ columns: meta.columns, selected: (columns ?? []).map(String) });+ const keyOrder = meta.keyColumns.map((column) => `${mssqlCommon.quoteId(column)} ASC`).join(', ');+ const orderBy = sortBy || keyOrder || '(SELECT NULL)';+ const result = await mssqlAi+ .bind({ request: pool.request(), params: { ...where.params, ap_offset: skip, ap_fetch: max + 1 } })+ .query<Record<string, unknown>>(+ `SELECT ${select} FROM ${mssqlCommon.quoteTable(target)}${where.sql} ORDER BY ${orderBy} OFFSET @ap_offset ROWS FETCH NEXT @ap_fetch ROWS ONLY`+ );+ return result.recordset;+ },+ });+ const hasMore = found.length > max;+ const rows = found.slice(0, max);+ return { rows, count: rows.length, has_more: hasMore, next_offset: hasMore ? skip + max : null };+ },+});diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/get-row-by-key.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/get-row-by-key.tsnew file mode 100644index 00000000000..924bf34a4ed--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/get-row-by-key.ts@@ -0,0 +1,56 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { mssqlAuth } from '../../../auth';+import { mssqlCommon } from '../../../common';+import { mssqlAi, mssqlAiProps } from '../../../common/ai';+import { microsoftSqlServerGetRowByKeyOutputSchema } from '../../../output-schemas';++export const getRowByKey = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_get_row_by_key',+ outputSchema: microsoftSqlServerGetRowByKeyOutputSchema,+ displayName: 'Get Row by Key',+ description: 'Returns the one row whose key columns equal the given values.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description: 'Returns the single row whose key columns equal the given values, e.g. {"id": 42}, or found false with row null when none matches. Fails when the values match more than one row, so give every column of the primary or a unique key (see Describe Table or List Indexes). Use Find Rows to search by other columns. Read-only.',+ idempotent: true,+ },+ props: {+ schema: mssqlAiProps.schema,+ table: mssqlAiProps.table,+ key: Property.Object({+ displayName: 'Key',+ description: 'Key column names mapped to their values, e.g. {"id": 42} or {"order_id": 7, "line": 1}.',+ required: true,+ }),+ },+ async run(context) {+ const { schema, table } = context.propsValue;+ const key = mssqlAi.parseValues({ value: context.propsValue.key, label: 'Key' });+ const columns = Object.keys(key);+ return mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const target = await mssqlAi.resolveObject({ pool, schema, name: table, kinds: mssqlAi.TABLE_KINDS, label: 'Table' });+ const meta = await mssqlCommon.getTableMeta({ pool, table: target });+ const where = columns+ .map((column, index) =>+ key[column] === null ? `${mssqlCommon.quoteId(column)} IS NULL` : `${mssqlCommon.quoteId(column)} = @k${index}`,+ )+ .join(' AND ');+ const params = Object.fromEntries(columns.map((column, index) => [`k${index}`, key[column]]));+ const result = await mssqlAi+ .bind({ request: pool.request(), params })+ .query<Record<string, unknown>>(+ `SELECT TOP (2) ${mssqlAi.projection({ columns: meta.columns })} FROM ${mssqlCommon.quoteTable(target)} WHERE ${where}`+ );+ if (result.recordset.length > 1) {+ throw new Error(`More than one row matches ${JSON.stringify(key)}. Give every column of the primary or a unique key; List Indexes shows them.`);+ }+ const row = result.recordset[0] ?? null;+ return { found: row !== null, row };+ },+ });+ },+});diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/insert-rows.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/insert-rows.tsnew file mode 100644index 00000000000..7ae69d20ecb--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/insert-rows.ts@@ -0,0 +1,77 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import sql from 'mssql';+import { mssqlAuth } from '../../../auth';+import { mssqlCommon } from '../../../common';+import { mssqlAi, mssqlAiProps } from '../../../common/ai';+import { insertRowsUtils } from '../../insert-rows';+import { writeRowsActionOutputSchema } from '../../../output-schemas';++export const insertRowsAi = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_insert_rows',+ outputSchema: writeRowsActionOutputSchema,+ displayName: 'Insert Rows',+ description: 'Inserts a list of rows into a table in one transaction and returns them.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Inserts a list of rows, each an object of column names to values, in one transaction: if any row fails, none are inserted. Columns a row omits get the column default; objects and arrays are stored as JSON text. Returns the inserted rows as stored, with IDENTITY ids and defaults (empty when the table has triggers; rows_affected is always set). Use Upsert Row to insert-or-update by key. Not idempotent: repeating it inserts the rows again.',+ idempotent: false,+ },+ props: {+ schema: mssqlAiProps.schema,+ table: mssqlAiProps.table,+ rows: Property.Json({+ displayName: 'Rows',+ description: 'A list of objects, one per row, e.g. [{"name": "Ada", "age": 36}]. Column names come from Describe Table.',+ required: true,+ }),+ },+ async run(context) {+ const { schema, table, rows } = context.propsValue;+ const records = insertRowsUtils.toRecords({ rows, keepEmptyStrings: true });+ const columns = insertRowsUtils.collectColumns({ records });+ return mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const target = await mssqlAi.resolveObject({ pool, schema, name: table, kinds: mssqlAi.TABLE_KINDS, label: 'Table' });+ const meta = await mssqlCommon.getTableMeta({ pool, table: target });+ const quotedTable = mssqlCommon.quoteTable(target);+ const insert = (output: string) =>+ insertAll({ pool, statements: insertRowsUtils.buildStatements({ quotedTable, columns, records, output }) });+ const results = await insert(`OUTPUT ${mssqlAi.projection({ columns: meta.columns, prefix: 'INSERTED' })}`).catch(+ (error: unknown) => {+ if (!mssqlCommon.isOutputBlockedByTrigger(error)) {+ throw error;+ }+ return insert('');+ },+ );+ return {+ rows: results.flatMap((result) => result.recordset ?? []),+ rows_affected: results.reduce((total, result) => total + (result.rowsAffected ?? []).reduce((a, b) => a + b, 0), 0),+ };+ },+ });+ },+});++function insertAll({+ pool,+ statements,+}: {+ pool: sql.ConnectionPool;+ statements: { text: string; values: unknown[] }[];+}): Promise<sql.IResult<Record<string, unknown>>[]> {+ return mssqlAi.withTransaction({+ pool,+ fn: async (transaction) => {+ const results: sql.IResult<Record<string, unknown>>[] = [];+ for (const statement of statements) {+ const params = Object.fromEntries(statement.values.map((value, index) => [`p${index}`, value]));+ results.push(await mssqlAi.bind({ request: transaction.request(), params }).query<Record<string, unknown>>(statement.text));+ }+ return results;+ },+ });+}diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/update-rows.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/update-rows.tsnew file mode 100644index 00000000000..2f3a35a6246--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/update-rows.ts@@ -0,0 +1,54 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { mssqlAuth } from '../../../auth';+import { mssqlCommon } from '../../../common';+import { mssqlAi, mssqlAiProps } from '../../../common/ai';+import { writeRowsActionOutputSchema } from '../../../output-schemas';++export const updateRowsAi = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_update_rows',+ outputSchema: writeRowsActionOutputSchema,+ 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. Rows come back empty on tables with triggers; rows_affected is always set. Setting the same values again changes nothing new, so it is safe to retry.',+ idempotent: true,+ },+ props: {+ schema: mssqlAiProps.schema,+ table: mssqlAiProps.table,+ filters: mssqlAiProps.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: mssqlAiProps.maxRows({ verb: 'updated' }),+ },+ async run(context) {+ const { schema, table, filters, maxRows } = context.propsValue;+ const limit = mssqlAi.boundedInteger({ value: maxRows, defaultValue: mssqlAi.WRITE_GUARD_DEFAULT, min: 1, max: mssqlAi.WRITE_GUARD_MAX, label: 'Max Rows' });+ const set = mssqlAi.buildSet({ values: mssqlAi.parseValues({ value: context.propsValue.values, label: 'Values' }) });+ const where = mssqlAi.buildWhere({ filters });+ return mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const target = await mssqlAi.resolveObject({ pool, schema, name: table, kinds: mssqlAi.TABLE_KINDS, label: 'Table' });+ const meta = await mssqlCommon.getTableMeta({ pool, table: target });+ const quoted = mssqlCommon.quoteTable(target);+ return mssqlAi.guardedWrite({+ pool,+ target: quoted,+ where,+ maxRows: limit,+ verb: 'updated',+ withOutput: `UPDATE ${quoted} SET ${set.sql} OUTPUT ${mssqlAi.projection({ columns: meta.columns, prefix: 'INSERTED' })}${where.sql}`,+ withoutOutput: `UPDATE ${quoted} SET ${set.sql}${where.sql}`,+ params: { ...set.params, ...where.params },+ });+ },+ });+ },+});diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/upsert-row.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/upsert-row.tsnew file mode 100644index 00000000000..1d081c6387d--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/rows/upsert-row.ts@@ -0,0 +1,110 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import sql from 'mssql';+import { mssqlAuth } from '../../../auth';+import { MssqlTable, mssqlCommon } from '../../../common';+import { mssqlAi, mssqlAiProps } from '../../../common/ai';+import { microsoftSqlServerUpsertRowOutputSchema } from '../../../output-schemas';++export const upsertRow = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_upsert_row',+ outputSchema: microsoftSqlServerUpsertRowOutputSchema,+ displayName: 'Upsert Row',+ description: 'Inserts a row, or updates the existing row with the same key.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Inserts a row, or updates the row whose key columns already hold the same values (MERGE with HOLDLOCK). Key Columns default to the primary key and must cover a primary or unique key (see List Indexes); Values must give a non-null value for each of them. Update Columns limits which columns change on an existing row. Returns action (INSERT, UPDATE or unchanged) and the row as stored. Safe to retry.',+ idempotent: true,+ },+ props: {+ schema: mssqlAiProps.schema,+ table: mssqlAiProps.table,+ values: Property.Object({+ displayName: 'Values',+ description: 'Column names mapped to values, including the key columns, e.g. {"email": "[email protected]", "name": "Ada"}.',+ required: true,+ }),+ keyColumns: Property.Array({+ displayName: 'Key Columns',+ description: 'Columns that identify the row, e.g. ["email"]. Leave empty to use the primary key.',+ required: false,+ }),+ updateColumns: Property.Array({+ displayName: 'Update Columns',+ description: 'Columns to overwrite when the row already exists. Leave empty to overwrite every non-key column in Values.',+ required: false,+ }),+ },+ async run(context) {+ const { schema, table } = context.propsValue;+ const values = mssqlAi.parseValues({ value: context.propsValue.values, label: 'Values' });+ const columns = Object.keys(values);+ return mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const target = await mssqlAi.resolveObject({ pool, schema, name: table, kinds: ['U'], label: 'Table' });+ const meta = await mssqlCommon.getTableMeta({ pool, table: target });+ const requestedKeys = (context.propsValue.keyColumns ?? []).map(String);+ const keys = requestedKeys.length > 0 ? requestedKeys : meta.keyColumns;+ await assertUniqueKey({ pool, target, keys });+ const missing = keys.filter((key) => values[key] === undefined || values[key] === null);+ if (missing.length > 0) {+ throw new Error(`Values must give a non-null value for every key column; missing: ${missing.join(', ')}.`);+ }+ const requestedUpdates = (context.propsValue.updateColumns ?? []).map(String);+ const updates = requestedUpdates.length > 0 ? requestedUpdates : columns.filter((column) => !keys.includes(column));+ const notInValues = updates.filter((column) => !columns.includes(column));+ if (notInValues.length > 0) {+ throw new Error(`Update Columns must also be in Values; missing: ${notInValues.join(', ')}.`);+ }+ const q = mssqlCommon.quoteId;+ const source = columns.map((column, index) => `@v${index} AS ${q(column)}`).join(', ');+ const on = keys.map((key) => `t.${q(key)} = s.${q(key)}`).join(' AND ');+ const matched = updates.length > 0 ? ` WHEN MATCHED THEN UPDATE SET ${updates.map((column) => `t.${q(column)} = s.${q(column)}`).join(', ')}` : '';+ const notMatched = ` WHEN NOT MATCHED THEN INSERT (${columns.map(q).join(', ')}) VALUES (${columns.map((column) => `s.${q(column)}`).join(', ')})`;+ const merge = `MERGE ${mssqlCommon.quoteTable(target)} WITH (HOLDLOCK) AS t USING (SELECT ${source}) AS s ON ${on}${matched}${notMatched}`;+ const params = Object.fromEntries(columns.map((column, index) => [`v${index}`, values[column]]));+ const result = await mssqlCommon.writeReturningRows({+ bind: () => mssqlAi.bind({ request: pool.request(), params }),+ withOutput: `${merge} OUTPUT $action AS ${q(ACTION_ALIAS)}, ${mssqlAi.projection({ columns: meta.columns, prefix: 'INSERTED' })};`,+ withoutOutput: `${merge};`,+ });+ const first = result.rows[0];+ if (first === undefined) {+ return { action: result.rows_affected === 0 ? 'unchanged' : null, row: null, rows_affected: result.rows_affected };+ }+ const { [ACTION_ALIAS]: action, ...row } = first;+ return { action, row, rows_affected: result.rows_affected };+ },+ });+ },+});++async function assertUniqueKey({ pool, target, keys }: { pool: sql.ConnectionPool; target: MssqlTable; keys: string[] }): Promise<void> {+ const result = await pool+ .request()+ .input('name', mssqlCommon.quoteTable(target))+ .query<Record<string, unknown>>(+ `SELECT i.name AS index_name, c.name AS column_name+ FROM sys.indexes i+ JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 0+ JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id+ WHERE i.object_id = OBJECT_ID(@name) AND i.is_unique = 1 AND i.has_filter = 0 AND i.is_disabled = 0+ ORDER BY i.index_id, ic.key_ordinal`+ );+ const uniqueKeys = result.recordset.reduce<Record<string, string[]>>((acc, row) => {+ const indexName = String(row['index_name']);+ return { ...acc, [indexName]: [...(acc[indexName] ?? []), String(row['column_name'])] };+ }, {});+ const entries = Object.entries(uniqueKeys);+ if (entries.length === 0) {+ throw new Error(`Table "${target.table_schema}.${target.table_name}" has no primary or unique key, so an upsert cannot find an existing row. Use Insert Rows instead.`);+ }+ if (keys.length === 0 || !entries.some(([, columns]) => columns.every((column) => keys.includes(column)))) {+ const described = entries.map(([name, columns]) => `${name} (${columns.join(', ')})`).join('; ');+ throw new Error(`Key Columns must cover a primary or unique key: ${described}.`);+ }+}++const ACTION_ALIAS = '__ap_merge_action';diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/describe-table.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/describe-table.tsnew file mode 100644index 00000000000..2b26c27607f--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/describe-table.ts@@ -0,0 +1,67 @@+import { createAction } from '@activepieces/pieces-framework';+import { mssqlAuth } from '../../../auth';+import { mssqlCommon } from '../../../common';+import { mssqlAi, mssqlAiProps } from '../../../common/ai';+import { microsoftSqlServerDescribeTableOutputSchema } from '../../../output-schemas';++export const describeTable = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_describe_table',+ outputSchema: microsoftSqlServerDescribeTableOutputSchema,+ displayName: 'Describe Table',+ description: 'Lists the columns of a table or view with their types, keys, defaults and references.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description: 'Returns every column of a table or view in order: name, full data type (e.g. nvarchar(100)), nullability, identity, computed, default, whether it is in the primary key, and the table and column a foreign key references. Use before reading or writing rows to learn column names, required columns and keys. Schema and table names come from Get Tables. Read-only.',+ idempotent: true,+ },+ props: {+ schema: mssqlAiProps.schema,+ table: mssqlAiProps.table,+ },+ async run(context) {+ const { schema, table } = context.propsValue;+ return mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const target = await mssqlAi.resolveObject({ pool, schema, name: table, kinds: mssqlAi.TABLE_KINDS, label: 'Table' });+ const result = await pool+ .request()+ .input('name', mssqlCommon.quoteTable(target))+ .query<Record<string, unknown>>(+ `SELECT c.name, TYPE_NAME(c.user_type_id) AS type, c.max_length, c.precision, c.scale,+ c.is_nullable, c.is_identity, c.is_computed, dc.definition AS default_value,+ CAST(CASE WHEN pk.column_id IS NULL THEN 0 ELSE 1 END AS bit) AS is_primary_key,+ fk.references_table, fk.references_column+ FROM sys.columns c+ LEFT JOIN sys.default_constraints dc ON dc.object_id = c.default_object_id+ OUTER APPLY (+ SELECT TOP (1) ic.column_id FROM sys.indexes i+ JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id+ WHERE i.object_id = c.object_id AND i.is_primary_key = 1 AND ic.column_id = c.column_id+ ) pk+ OUTER APPLY (+ SELECT TOP (1)+ OBJECT_SCHEMA_NAME(f.referenced_object_id) + '.' + OBJECT_NAME(f.referenced_object_id) AS references_table,+ COL_NAME(f.referenced_object_id, f.referenced_column_id) AS references_column+ FROM sys.foreign_key_columns f+ WHERE f.parent_object_id = c.object_id AND f.parent_column_id = c.column_id+ ) fk+ WHERE c.object_id = OBJECT_ID(@name)+ ORDER BY c.column_id`+ );+ const columns = result.recordset.map(({ max_length, precision, scale, ...column }) => ({+ ...column,+ data_type: mssqlAi.typeLabel({+ type: String(column['type']),+ maxLength: Number(max_length),+ precision: Number(precision),+ scale: Number(scale),+ }),+ }));+ return { schema: target.table_schema, table: target.table_name, columns, count: columns.length };+ },+ });+ },+});diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/get-view-definition.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/get-view-definition.tsnew file mode 100644index 00000000000..6f034d2276c--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/get-view-definition.ts@@ -0,0 +1,45 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { mssqlAuth } from '../../../auth';+import { mssqlCommon } from '../../../common';+import { mssqlAi, mssqlAiProps } from '../../../common/ai';+import { microsoftSqlServerGetViewDefinitionOutputSchema } from '../../../output-schemas';++export const getViewDefinition = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_get_view_definition',+ outputSchema: microsoftSqlServerGetViewDefinitionOutputSchema,+ displayName: 'Get View Definition',+ description: 'Returns the CREATE VIEW statement behind a view.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description: 'Returns the T-SQL CREATE VIEW statement of one view, to understand which tables and filters it draws on. View names come from List Views. Fails when the view is encrypted or the login lacks VIEW DEFINITION. Read-only.',+ idempotent: true,+ },+ props: {+ schema: mssqlAiProps.schema,+ view: Property.ShortText({+ displayName: 'View',+ description: 'View name without the schema, as returned by List Views.',+ required: true,+ }),+ },+ async run(context) {+ const { schema, view } = context.propsValue;+ return mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const target = await mssqlAi.resolveObject({ pool, schema, name: view, kinds: ['V'], label: 'View' });+ const result = await pool+ .request()+ .input('name', mssqlCommon.quoteTable(target))+ .query<Record<string, unknown>>('SELECT OBJECT_DEFINITION(OBJECT_ID(@name)) AS definition');+ const definition = result.recordset[0]?.['definition'];+ if (typeof definition !== 'string') {+ throw new Error(`The definition of view "${target.table_schema}.${target.table_name}" is not readable: it is encrypted, or the login lacks VIEW DEFINITION on it.`);+ }+ return { schema: target.table_schema, view: target.table_name, definition };+ },+ });+ },+});diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/list-databases.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/list-databases.tsnew file mode 100644index 00000000000..8fc21ee8673--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/list-databases.ts@@ -0,0 +1,44 @@+import { createAction } from '@activepieces/pieces-framework';+import { mssqlAuth } from '../../../auth';+import { mssqlAi, mssqlAiProps } from '../../../common/ai';+import { microsoftSqlServerListDatabasesOutputSchema } from '../../../output-schemas';++export const listDatabases = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_list_databases',+ outputSchema: microsoftSqlServerListDatabasesOutputSchema,+ displayName: 'List Databases',+ description: 'Lists the databases on the server that the login can see.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Lists the databases on the server visible to the connection login: name, state, recovery model, compatibility level, collation and whether it is read-only, with the connection database flagged. Every other action works in the connection database, so use this to orient, not to switch databases. Read-only.',+ idempotent: true,+ },+ props: {+ namePattern: mssqlAiProps.namePattern,+ },+ async run(context) {+ const { namePattern } = context.propsValue;+ const hasPattern = namePattern !== undefined && namePattern !== '';+ const databases = await mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const request = pool.request();+ if (hasPattern) {+ request.input('pattern', namePattern);+ }+ const result = await request.query<Record<string, unknown>>(+ `SELECT name, database_id, state_desc AS state, recovery_model_desc AS recovery_model,+ compatibility_level, collation_name, is_read_only,+ CAST(CASE WHEN name = DB_NAME() THEN 1 ELSE 0 END AS bit) AS is_current,+ CONVERT(varchar(33), create_date, 126) AS create_date+ FROM sys.databases${hasPattern ? ' WHERE name LIKE @pattern' : ''}+ ORDER BY name`+ );+ return result.recordset;+ },+ });+ return { databases, count: databases.length };+ },+});diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/list-indexes.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/list-indexes.tsnew file mode 100644index 00000000000..5dcc758cfb7--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/list-indexes.ts@@ -0,0 +1,81 @@+import { createAction } from '@activepieces/pieces-framework';+import { mssqlAuth } from '../../../auth';+import { mssqlCommon } from '../../../common';+import { mssqlAi, mssqlAiProps } from '../../../common/ai';+import { microsoftSqlServerListIndexesOutputSchema } from '../../../output-schemas';++export const listIndexes = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_list_indexes',+ outputSchema: microsoftSqlServerListIndexesOutputSchema,+ displayName: 'List Indexes',+ description: 'Lists the indexes of a table with their key and included columns.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Lists the indexes of a table or indexed view: name, type (CLUSTERED, NONCLUSTERED, ...), whether it is the primary key, unique or a unique constraint, disabled, its filter, its key columns in order with direction, and its included columns. Use to find the unique keys Upsert Row can match on, or to see which filters are indexed. Read-only.',+ idempotent: true,+ },+ props: {+ schema: mssqlAiProps.schema,+ table: mssqlAiProps.table,+ },+ async run(context) {+ const { schema, table } = context.propsValue;+ return mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const target = await mssqlAi.resolveObject({ pool, schema, name: table, kinds: mssqlAi.TABLE_KINDS, label: 'Table' });+ const result = await pool+ .request()+ .input('name', mssqlCommon.quoteTable(target))+ .query<Record<string, unknown>>(+ `SELECT i.index_id, i.name, i.type_desc AS type, i.is_primary_key, i.is_unique,+ i.is_unique_constraint, i.is_disabled, i.filter_definition AS filter,+ c.name AS column_name, ic.is_descending_key, ic.is_included_column+ FROM sys.indexes i+ LEFT JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id+ LEFT JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id+ WHERE i.object_id = OBJECT_ID(@name) AND i.index_id > 0+ ORDER BY i.index_id, ic.is_included_column, ic.key_ordinal, ic.index_column_id`+ );+ const indexes = groupIndexes({ rows: result.recordset });+ return { schema: target.table_schema, table: target.table_name, indexes, count: indexes.length };+ },+ });+ },+});++function groupIndexes({ rows }: { rows: Record<string, unknown>[] }): IndexEntry[] {+ const ids = [...new Set(rows.map((row) => Number(row['index_id'])))];+ return ids.map((id) => {+ const members = rows.filter((row) => Number(row['index_id']) === id);+ const first = members[0];+ const named = members.filter((row) => row['column_name'] !== null);+ return {+ name: String(first['name']),+ type: String(first['type']),+ is_primary_key: Boolean(first['is_primary_key']),+ is_unique: Boolean(first['is_unique']),+ is_unique_constraint: Boolean(first['is_unique_constraint']),+ is_disabled: Boolean(first['is_disabled']),+ filter: first['filter'] ?? null,+ key_columns: named+ .filter((row) => !row['is_included_column'])+ .map((row) => ({ name: String(row['column_name']), descending: Boolean(row['is_descending_key']) })),+ included_columns: named.filter((row) => row['is_included_column']).map((row) => String(row['column_name'])),+ };+ });+}++type IndexEntry = {+ name: string;+ type: string;+ is_primary_key: boolean;+ is_unique: boolean;+ is_unique_constraint: boolean;+ is_disabled: boolean;+ filter: unknown;+ key_columns: { name: string; descending: boolean }[];+ included_columns: string[];+};diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/list-routines.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/list-routines.tsnew file mode 100644index 00000000000..66ad715a639--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/list-routines.ts@@ -0,0 +1,107 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { mssqlAuth } from '../../../auth';+import { mssqlAi, mssqlAiProps } from '../../../common/ai';+import { microsoftSqlServerListRoutinesOutputSchema } from '../../../output-schemas';++export const listRoutines = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_list_routines',+ outputSchema: microsoftSqlServerListRoutinesOutputSchema,+ displayName: 'List Routines',+ description: 'Lists stored procedures and functions with their parameters.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Lists the stored procedures and user-defined functions in the connection database, optionally filtered by schema, kind and name pattern: schema, name, kind (PROCEDURE, SCALAR_FUNCTION, TABLE_FUNCTION) and the parameters in order with type and whether each is OUTPUT. Procedures run through Call Procedure; functions are used inside Run Select Query. Read-only.',+ idempotent: true,+ },+ props: {+ schema: {+ ...mssqlAiProps.schema,+ description: 'Only list routines in this schema. Leave empty for all schemas.',+ },+ kind: Property.StaticDropdown({+ displayName: 'Kind',+ description: 'Only list this kind of routine. Leave empty for all.',+ required: false,+ options: {+ options: [+ { label: 'Procedure', value: 'PROCEDURE' },+ { label: 'Scalar function', value: 'SCALAR_FUNCTION' },+ { label: 'Table function', value: 'TABLE_FUNCTION' },+ ],+ },+ }),+ namePattern: mssqlAiProps.namePattern,+ },+ async run(context) {+ const { schema, kind, namePattern } = context.propsValue;+ if (kind !== undefined && kind !== null && !KINDS.some((entry) => entry === kind)) {+ throw new Error(`Kind must be one of: ${KINDS.join(', ')}.`);+ }+ const rows = await mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const request = pool+ .request()+ .input('schema', schema || null)+ .input('kind', kind || null)+ .input('pattern', namePattern || null);+ const result = await request.query<Record<string, unknown>>(+ `SELECT o.object_id, SCHEMA_NAME(o.schema_id) AS [schema], o.name,+ CASE WHEN o.type IN ('P', 'PC') THEN 'PROCEDURE'+ WHEN o.type IN ('FN', 'FS') THEN 'SCALAR_FUNCTION'+ ELSE 'TABLE_FUNCTION' END AS kind,+ p.name AS parameter_name, TYPE_NAME(p.user_type_id) AS parameter_type,+ p.max_length, p.precision, p.scale, p.is_output+ FROM sys.objects o+ LEFT JOIN sys.parameters p ON p.object_id = o.object_id AND p.parameter_id > 0+ WHERE o.type IN ('P', 'PC', 'FN', 'FS', 'IF', 'TF', 'FT') AND o.is_ms_shipped = 0+ AND (@schema IS NULL OR SCHEMA_NAME(o.schema_id) = @schema)+ AND (@pattern IS NULL OR o.name LIKE @pattern)+ AND (@kind IS NULL OR @kind = CASE WHEN o.type IN ('P', 'PC') THEN 'PROCEDURE'+ WHEN o.type IN ('FN', 'FS') THEN 'SCALAR_FUNCTION'+ ELSE 'TABLE_FUNCTION' END)+ ORDER BY [schema], o.name, p.parameter_id`+ );+ return result.recordset;+ },+ });+ const routines = groupRoutines({ rows });+ return { routines, count: routines.length };+ },+});++function groupRoutines({ rows }: { rows: Record<string, unknown>[] }): Routine[] {+ const ids = [...new Set(rows.map((row) => Number(row['object_id'])))];+ return ids.map((id) => {+ const members = rows.filter((row) => Number(row['object_id']) === id);+ const first = members[0];+ return {+ schema: String(first['schema']),+ name: String(first['name']),+ kind: String(first['kind']),+ parameters: members+ .filter((row) => row['parameter_name'] !== null)+ .map((row) => ({+ name: String(row['parameter_name']),+ data_type: mssqlAi.typeLabel({+ type: String(row['parameter_type']),+ maxLength: Number(row['max_length']),+ precision: Number(row['precision']),+ scale: Number(row['scale']),+ }),+ is_output: Boolean(row['is_output']),+ })),+ };+ });+}++const KINDS = ['PROCEDURE', 'SCALAR_FUNCTION', 'TABLE_FUNCTION'] as const;++type Routine = {+ schema: string;+ name: string;+ kind: string;+ parameters: { name: string; data_type: string; is_output: boolean }[];+};diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/list-schemas.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/list-schemas.tsnew file mode 100644index 00000000000..b2d09714670--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/list-schemas.ts@@ -0,0 +1,38 @@+import { createAction } from '@activepieces/pieces-framework';+import { mssqlAuth } from '../../../auth';+import { mssqlAi } from '../../../common/ai';+import { microsoftSqlServerListSchemasOutputSchema } from '../../../output-schemas';++export const listSchemas = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_list_schemas',+ outputSchema: microsoftSqlServerListSchemasOutputSchema,+ displayName: 'List Schemas',+ description: 'Lists the schemas in the connection database.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Lists the user schemas in the connection database with their owner and how many tables and views each holds, and flags the connection user\'s default schema (used when an action\'s Schema is left empty). System and fixed-role schemas are left out. Read-only.',+ idempotent: true,+ },+ props: {},+ async run(context) {+ const schemas = await mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const result = await pool.request().query<Record<string, unknown>>(+ `SELECT s.name, p.name AS owner,+ (SELECT COUNT(*) FROM sys.tables t WHERE t.schema_id = s.schema_id) AS table_count,+ (SELECT COUNT(*) FROM sys.views v WHERE v.schema_id = s.schema_id) AS view_count,+ CAST(CASE WHEN s.name = SCHEMA_NAME() THEN 1 ELSE 0 END AS bit) AS is_default+ FROM sys.schemas s+ LEFT JOIN sys.database_principals p ON p.principal_id = s.principal_id+ WHERE s.schema_id < 16384 AND s.name NOT IN ('sys', 'INFORMATION_SCHEMA', 'guest')+ ORDER BY s.name`+ );+ return result.recordset;+ },+ });+ return { schemas, count: schemas.length };+ },+});diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/list-views.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/list-views.tsnew file mode 100644index 00000000000..27e748e0cb7--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/schema/list-views.ts@@ -0,0 +1,48 @@+import { createAction } from '@activepieces/pieces-framework';+import { mssqlAuth } from '../../../auth';+import { mssqlAi, mssqlAiProps } from '../../../common/ai';+import { microsoftSqlServerListViewsOutputSchema } from '../../../output-schemas';++export const listViews = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_list_views',+ outputSchema: microsoftSqlServerListViewsOutputSchema,+ displayName: 'List Views',+ description: 'Lists the views in the connection database.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Lists the views in the connection database, optionally in one schema and matching a name pattern: schema, name, whether it is schema-bound or indexed, and when it was created and last changed. Views can be read with Find Rows and Count Rows like tables; use Get View Definition for the query behind one. Read-only.',+ idempotent: true,+ },+ props: {+ schema: {+ ...mssqlAiProps.schema,+ description: 'Only list views in this schema. Leave empty for all schemas.',+ },+ namePattern: mssqlAiProps.namePattern,+ },+ async run(context) {+ const { schema, namePattern } = context.propsValue;+ const views = await mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const request = pool.request().input('schema', schema || null).input('pattern', namePattern || null);+ const result = await request.query<Record<string, unknown>>(+ `SELECT SCHEMA_NAME(v.schema_id) AS [schema], v.name,+ CAST(OBJECTPROPERTY(v.object_id, 'IsSchemaBound') AS bit) AS is_schema_bound,+ CAST(OBJECTPROPERTY(v.object_id, 'IsIndexed') AS bit) AS is_indexed,+ CONVERT(varchar(33), v.create_date, 126) AS create_date,+ CONVERT(varchar(33), v.modify_date, 126) AS modify_date+ FROM sys.views v+ WHERE v.is_ms_shipped = 0+ AND (@schema IS NULL OR SCHEMA_NAME(v.schema_id) = @schema)+ AND (@pattern IS NULL OR v.name LIKE @pattern)+ ORDER BY [schema], v.name`+ );+ return result.recordset;+ },+ });+ return { views, count: views.length };+ },+});diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/server/get-server-info.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/server/get-server-info.tsnew file mode 100644index 00000000000..c0bacc8e721--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/server/get-server-info.ts@@ -0,0 +1,42 @@+import { createAction } from '@activepieces/pieces-framework';+import { mssqlAuth } from '../../../auth';+import { mssqlAi } from '../../../common/ai';+import { microsoftSqlServerGetServerInfoOutputSchema } from '../../../output-schemas';++export const getServerInfo = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_get_server_info',+ outputSchema: microsoftSqlServerGetServerInfoOutputSchema,+ displayName: 'Get Server Info',+ description: 'Returns the server version, edition and the connection\'s database, login and user.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description: 'Returns the SQL Server version and edition (engine_edition 5 is Azure SQL Database), server name, collation, the connection database with its compatibility level, the login, database user and default schema, and the server time. Use first to learn which T-SQL features are available. Read-only.',+ idempotent: true,+ },+ props: {},+ async run(context) {+ return mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const result = await pool.request().query<Record<string, unknown>>(+ `SELECT @@VERSION AS version,+ CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(128)) AS product_version,+ CAST(SERVERPROPERTY('ProductLevel') AS nvarchar(128)) AS product_level,+ CAST(SERVERPROPERTY('Edition') AS nvarchar(128)) AS edition,+ CAST(SERVERPROPERTY('EngineEdition') AS int) AS engine_edition,+ @@SERVERNAME AS server_name,+ CAST(SERVERPROPERTY('Collation') AS nvarchar(128)) AS server_collation,+ DB_NAME() AS [database],+ (SELECT compatibility_level FROM sys.databases WHERE name = DB_NAME()) AS compatibility_level,+ SUSER_SNAME() AS login,+ USER_NAME() AS [user],+ SCHEMA_NAME() AS default_schema,+ CONVERT(varchar(40), SYSDATETIMEOFFSET(), 127) AS server_time`+ );+ return result.recordset[0];+ },+ });+ },+});diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/server/list-sessions.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/server/list-sessions.tsnew file mode 100644index 00000000000..e194525a8ff--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/ai/server/list-sessions.ts@@ -0,0 +1,46 @@+import { createAction } from '@activepieces/pieces-framework';+import { mssqlAuth } from '../../../auth';+import { mssqlAi, mssqlAiProps } from '../../../common/ai';+import { microsoftSqlServerListSessionsOutputSchema } from '../../../output-schemas';++export const listSessions = createAction({+ auth: mssqlAuth,+ name: 'microsoft_sql_server_list_sessions',+ outputSchema: microsoftSqlServerListSessionsOutputSchema,+ displayName: 'List Sessions',+ description: 'Lists the user sessions on the server and what each is running.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Lists user sessions, longest-running request first: session id, login, host, program, database, status, the running command, wait type, the session blocking it, elapsed and CPU milliseconds, and the statement text. Without VIEW SERVER STATE (VIEW DATABASE STATE on Azure SQL) only the connection\'s own session is listed. Use to find long-running or blocked queries. Read-only.',+ idempotent: true,+ },+ props: {+ limit: mssqlAiProps.limit,+ },+ async run(context) {+ const max = mssqlAi.boundedInteger({ value: context.propsValue.limit, defaultValue: mssqlAi.READ_DEFAULT_LIMIT, min: 1, max: mssqlAi.READ_MAX_LIMIT, label: 'Limit' });+ const sessions = await mssqlAi.withPool({+ auth: context.auth,+ fn: async (pool) => {+ const result = await pool+ .request()+ .input('limit', max)+ .query<Record<string, unknown>>(+ `SELECT TOP (@limit) s.session_id, s.login_name, s.host_name, s.program_name,+ DB_NAME(s.database_id) AS [database], s.status, r.command, r.wait_type,+ r.blocking_session_id, r.total_elapsed_time AS elapsed_ms, r.cpu_time AS cpu_ms,+ t.text AS sql_text, CONVERT(varchar(33), s.login_time, 126) AS login_time,+ CAST(CASE WHEN s.session_id = @@SPID THEN 1 ELSE 0 END AS bit) AS is_current+ FROM sys.dm_exec_sessions s+ LEFT JOIN sys.dm_exec_requests r ON r.session_id = s.session_id+ OUTER APPLY sys.dm_exec_sql_text(r.sql_handle) t+ WHERE s.is_user_process = 1+ ORDER BY r.total_elapsed_time DESC, s.session_id`+ );+ return result.recordset;+ },+ });+ return { sessions, count: sessions.length };+ },+});diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/delete-rows.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/delete-rows.tsindex be6efe85444..3017e91ec40 100644--- a/packages/pieces/community/microsoft-sql-server/src/lib/actions/delete-rows.ts+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/delete-rows.ts@@ -10,7 +10,7 @@ export const deleteRowsAction = createAction({name: 'delete_rows',displayName: 'Delete Rows',description: 'Deletes every row whose search column matches a value',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Deletes every row in a SQL Server table whose search column equals a given value, and returns the rows that were removed. Use to delete records matched on a single column; for anything more complex use Run Query. Idempotent: once the matching rows are gone, re-running deletes nothing further.',diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/find-rows.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/find-rows.tsindex 41f621688a4..97337d43ce7 100644--- a/packages/pieces/community/microsoft-sql-server/src/lib/actions/find-rows.ts+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/find-rows.ts@@ -10,7 +10,7 @@ export const findRowsAction = createAction({name: 'find_rows',displayName: 'Find Rows',description: 'Reads rows from a table',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Reads rows from one SQL Server table, optionally filtered by a WHERE condition, restricted to chosen columns, sorted, and capped to a maximum number of rows. Use to look up or list records without writing a full query. The condition is inserted into the statement as written, so pass dynamic values through the Parameters map as named @placeholders instead of embedding them. Not idempotent in general: the condition is raw T-SQL, so a statement that writes can be smuggled through it and repeating the call would repeat the write.',diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/get-tables.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/get-tables.tsindex 2f65034ed34..ff6dd6aa458 100644--- a/packages/pieces/community/microsoft-sql-server/src/lib/actions/get-tables.ts+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/get-tables.ts@@ -8,6 +8,7 @@ export const getTablesAction = createAction({name: 'get_tables',displayName: 'Get Tables',description: 'Returns a list of tables in the database',+ classification: 'SEARCH',audience: 'both',aiMetadata: {description:diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/insert-row.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/insert-row.tsindex a755e3573f9..f846d510db3 100644--- a/packages/pieces/community/microsoft-sql-server/src/lib/actions/insert-row.ts+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/insert-row.ts@@ -10,6 +10,7 @@ export const insertRowAction = createAction({name: 'insert_row',displayName: 'Insert Row',description: 'Inserts a new row into a table and returns it',+ classification: 'WRITE',audience: 'both',aiMetadata: {description:diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/insert-rows.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/insert-rows.tsindex abf33f9a685..c3abab201be 100644--- a/packages/pieces/community/microsoft-sql-server/src/lib/actions/insert-rows.ts+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/insert-rows.ts@@ -12,7 +12,7 @@ export const insertRowsAction = createAction({classification: 'WRITE',displayName: 'Insert Multiple Rows',description: 'Inserts many rows into a table in a single transaction',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Inserts an array of rows into a SQL Server 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 row count and, when Return Inserted Rows is on, the stored rows including IDENTITY ids. Use instead of repeated single inserts for bulk loads. Not idempotent: each call appends new rows, so repeating it adds duplicates or fails on a unique-key collision.',diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/run-query.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/run-query.tsindex fcf832322c0..813b42a18fc 100644--- a/packages/pieces/community/microsoft-sql-server/src/lib/actions/run-query.ts+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/run-query.ts@@ -9,6 +9,7 @@ export const runQueryAction = createAction({name: 'run_query',displayName: 'Run Query',description: 'Runs a T-SQL statement and returns the rows it produced',+ classification: 'DESTRUCTIVE',audience: 'both',aiMetadata: {description:diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/actions/update-rows.ts b/packages/pieces/community/microsoft-sql-server/src/lib/actions/update-rows.tsindex 2c7c696ea86..47b23d0114a 100644--- a/packages/pieces/community/microsoft-sql-server/src/lib/actions/update-rows.ts+++ b/packages/pieces/community/microsoft-sql-server/src/lib/actions/update-rows.ts@@ -10,7 +10,7 @@ export const updateRowsAction = createAction({name: 'update_rows',displayName: 'Update Rows',description: 'Updates every row whose search column matches a value',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Updates every row in a SQL Server table whose search column equals a given value, setting the supplied column-to-value pairs, and returns the updated rows. Use to modify existing records matched on a single column; for anything more complex use Run Query. Idempotent: re-running with the same input writes the same values and changes nothing further.',diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/common/ai.ts b/packages/pieces/community/microsoft-sql-server/src/lib/common/ai.tsnew file mode 100644index 00000000000..539cbc9927b--- /dev/null+++ b/packages/pieces/community/microsoft-sql-server/src/lib/common/ai.ts@@ -0,0 +1,436 @@+import { isNil, Property } from '@activepieces/pieces-framework';+import sql from 'mssql';+import { MssqlAuth, MssqlColumn, MssqlTable, mssqlCommon } from '.';+import { cursorUtils } from './cursor';++async function withPool<T>({+ auth,+ requestTimeoutMs,+ fn,+}: {+ auth: MssqlAuth;+ requestTimeoutMs?: number;+ fn: (pool: sql.ConnectionPool) => Promise<T>;+}): Promise<T> {+ const pool = await mssqlCommon.connect({ auth, requestTimeoutMs });+ pool.on('error', () => undefined);+ try {+ return await fn(pool);+ } finally {+ await pool.close().catch(() => undefined);+ }+}++async function withTransaction<T>({+ pool,+ fn,+}: {+ pool: sql.ConnectionPool;+ fn: (transaction: sql.Transaction) => Promise<T>;+}): Promise<T> {+ const transaction = new sql.Transaction(pool);+ await transaction.begin();+ try {+ const result = await fn(transaction);+ await transaction.commit();+ return result;+ } catch (error) {+ await transaction.rollback().catch(() => undefined);+ throw error;+ }+}++function qualifiedName({ schema, name }: { schema: string | undefined; name: string }): string {+ return isNil(schema) || schema === ''+ ? mssqlCommon.quoteId(name)+ : `${mssqlCommon.quoteId(schema)}.${mssqlCommon.quoteId(name)}`;+}++async function resolveObject({+ pool,+ schema,+ name,+ kinds,+ label,+}: {+ pool: sql.ConnectionPool;+ schema: string | undefined;+ name: string;+ kinds: readonly string[];+ label: string;+}): Promise<MssqlTable> {+ const result = await pool+ .request()+ .input('name', qualifiedName({ schema, name }))+ .query<Record<string, unknown>>(+ `SELECT SCHEMA_NAME(o.schema_id) AS table_schema, o.name AS table_name, RTRIM(o.type) AS type+ FROM sys.objects o WHERE o.object_id = OBJECT_ID(@name)`+ );+ const row = result.recordset[0];+ if (isNil(row) || !kinds.includes(String(row['type']))) {+ const where = isNil(schema) || schema === '' ? 'the default schema' : `schema "${schema}"`;+ throw new Error(`${label} "${name}" was not found in ${where}. ${HINTS[label] ?? ''}`.trim());+ }+ return { table_schema: String(row['table_schema']), table_name: String(row['table_name']) };+}++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 toBindValue({ value }: { value: unknown }): unknown {+ const isStructured =+ typeof value === 'object' && value !== null && !(value instanceof Date) && !Buffer.isBuffer(value);+ return isStructured ? JSON.stringify(value) : value ?? null;+}++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;+}++function bind({ request, params }: { request: sql.Request; params: Record<string, unknown> }): sql.Request {+ return Object.entries(params).reduce((req, [name, value]) => req.input(name, toBindValue({ value })), request);+}++function buildWhere({ filters }: { filters: unknown }): SqlFragment {+ const parts = parseFilters({ filters }).map((filter, index) => filterToSql({ filter, index }));+ if (parts.length === 0) {+ return { sql: '', params: {} };+ }+ return {+ sql: ` WHERE ${parts.map((part) => part.sql).join(' AND ')}`,+ params: Object.assign({}, ...parts.map((part) => part.params)),+ };+}++function buildSet({ values }: { values: Record<string, unknown> }): SqlFragment {+ const columns = Object.keys(values);+ return {+ sql: columns.map((column, index) => `${mssqlCommon.quoteId(column)} = @v${index}`).join(', '),+ params: Object.fromEntries(columns.map((column, index) => [`v${index}`, values[column]])),+ };+}++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 `${mssqlCommon.quoteId(entry['column'])} ${direction}`;+ });+ return parts.join(', ');+}++function projection({ columns, selected, prefix }: { columns: MssqlColumn[]; selected?: string[]; prefix?: string }): string {+ if (isNil(selected) || selected.length === 0) {+ return cursorUtils.exactProjection({ columns, prefix });+ }+ const byName = new Map(columns.map((column) => [column.name, column]));+ return selected+ .map((name) => {+ const column = byName.get(name);+ if (isNil(column)) {+ throw new Error(`Column "${name}" does not exist. Use Describe Table to list the columns.`);+ }+ return cursorUtils.exactColumn({ column, prefix });+ })+ .join(', ');+}++async function guardedWrite({+ pool,+ target,+ where,+ maxRows,+ verb,+ withOutput,+ withoutOutput,+ params,+}: {+ pool: sql.ConnectionPool;+ target: string;+ where: SqlFragment;+ maxRows: number;+ verb: string;+ withOutput: string;+ withoutOutput: string;+ params: Record<string, unknown>;+}): Promise<WriteResult> {+ if (where.sql === '') {+ throw new Error(`Provide at least one filter; this action never ${verb} a whole table.`);+ }+ return withTransaction({+ pool,+ fn: async (transaction) => {+ const counted = await bind({ request: transaction.request(), params: where.params }).query<Record<string, unknown>>(+ `SELECT COUNT_BIG(*) AS total FROM ${target} WITH (UPDLOCK, HOLDLOCK)${where.sql}`+ );+ const total = Number(counted.recordset[0]?.['total'] ?? 0);+ if (total > maxRows) {+ throw new Error(+ `The filters match ${total} rows, more than Max Rows (${maxRows}). Nothing was ${verb}; narrow the filters or raise Max Rows.`+ );+ }+ return mssqlCommon.writeReturningRows({+ bind: () => bind({ request: transaction.request(), params }),+ withOutput,+ withoutOutput,+ });+ },+ });+}++function assertReadOnlyQuery({ query }: { query: string }): void {+ const code = stripLiterals({ query });+ const firstWord = (code.trimStart().match(/^[A-Za-z]+/)?.[0] ?? '').toUpperCase();+ if (firstWord !== 'SELECT' && firstWord !== 'WITH') {+ throw new Error(+ `Only a SELECT query (optionally starting with WITH) is allowed here; the query starts with "${firstWord || code.trim().slice(0, 20)}". Use Run Query or the row actions to change data.`+ );+ }+ const words = new Set((code.match(/[A-Za-z_]+/g) ?? []).map((word) => word.toUpperCase()));+ if (/;\s*\S/.test(code)) {+ throw new Error('Only one statement is allowed in a read-only query; remove everything after the first semicolon.');+ }+ const blocked = WRITE_KEYWORDS.filter((keyword) => words.has(keyword));+ if (blocked.length > 0) {+ throw new Error(+ `The query contains ${blocked.join(', ')}, which is not allowed in a read-only query. Use Run Query to change data.`+ );+ }+}++function stripLiterals({ query }: { query: string }): string {+ return query.replace(LEXICAL_TOKENS, (token) => {+ if (token.startsWith('/*') || token.startsWith('--')) {+ return ' ';+ }+ return token.startsWith('[') || token.startsWith('"') ? '[x]' : "''";+ });+}++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 = mssqlCommon.quoteId(filter.column);+ if (filter.operator === 'IS NULL' || filter.operator === 'IS NOT NULL') {+ return { sql: `${column} ${filter.operator}`, params: {} };+ }+ if (filter.operator === 'IS EMPTY' || filter.operator === 'IS NOT EMPTY') {+ return { sql: `${column} ${filter.operator === 'IS EMPTY' ? '=' : '<>'} N''`, params: {} };+ }+ if (isNil(filter.value)) {+ throw new Error(`Filter on "${filter.column}" with ${filter.operator} needs a value. Use IS NULL to match NULL, or IS EMPTY to match empty text.`);+ }+ if (filter.operator === 'IN' || filter.operator === 'NOT IN') {+ const list = Array.isArray(filter.value) ? filter.value : parseList({ text: String(filter.value) });+ if (list.length === 0) {+ throw new Error(`Filter on "${filter.column}" with ${filter.operator} needs at least one value.`);+ }+ const names = list.map((_, position) => `f${index}_${position}`);+ return {+ sql: `${column} ${filter.operator} (${names.map((name) => `@${name}`).join(', ')})`,+ params: Object.fromEntries(names.map((name, position) => [name, list[position]])),+ };+ }+ const operator = filter.operator === '!=' ? '<>' : filter.operator;+ return { sql: `${column} ${operator} @f${index}`, params: { [`f${index}`]: filter.value } };+}++function parseList({ text }: { text: string }): unknown[] {+ 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 (isNil(value) || value === '') {+ return [];+ }+ if (!Array.isArray(value)) {+ throw new Error(`${label} must be a list.`);+ }+ return value;+}++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);+}++function typeLabel({ type, maxLength, precision, scale }: { type: string; maxLength: number; precision: number; scale: number }): string {+ const length = (bytes: number) => (bytes === -1 ? 'max' : String(bytes));+ switch (type) {+ case 'varchar':+ case 'char':+ case 'varbinary':+ case 'binary':+ return `${type}(${length(maxLength)})`;+ case 'nvarchar':+ case 'nchar':+ return `${type}(${maxLength === -1 ? 'max' : maxLength / 2})`;+ case 'decimal':+ case 'numeric':+ return `${type}(${precision},${scale})`;+ case 'datetime2':+ case 'datetimeoffset':+ case 'time':+ return `${type}(${scale})`;+ default:+ return type;+ }+}++const LEXICAL_TOKENS = /\/\*[\s\S]*?\*\/|--[^\n]*|N?'(?:[^']|'')*'|\[(?:[^\]]|\]\])*\]|"(?:[^"]|"")*"/g;++const FILTER_OPERATORS = ['=', '!=', '<', '<=', '>', '>=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'] as const;++const WRITE_KEYWORDS = [+ 'INSERT', 'UPDATE', 'DELETE', 'MERGE', 'TRUNCATE', 'DROP', 'ALTER', 'CREATE', 'GRANT', 'REVOKE', 'DENY',+ 'EXEC', 'EXECUTE', 'INTO', 'BEGIN', 'COMMIT', 'ROLLBACK', 'SAVE', 'SET', 'USE', 'DBCC', 'KILL', 'SHUTDOWN',+ 'RECONFIGURE', 'BACKUP', 'RESTORE', 'BULK', 'OPENROWSET', 'OPENQUERY', 'OPENDATASOURCE', 'WAITFOR',+];++const HINTS: Record<string, string> = {+ Table: 'Use Get Tables to list the tables.',+ View: 'Use List Views to list the views.',+ Procedure: 'Use List Routines to list the procedures.',+};++const READ_DEFAULT_LIMIT = 100;+const READ_MAX_LIMIT = 1000;+const WRITE_GUARD_DEFAULT = 100;+const WRITE_GUARD_MAX = 10000;++export const mssqlAi = {+ withPool,+ withTransaction,+ qualifiedName,+ resolveObject,+ boundedInteger,+ toBindValue,+ parseValues,+ bind,+ buildWhere,+ buildSet,+ buildOrderBy,+ projection,+ guardedWrite,+ assertReadOnlyQuery,+ isRecord,+ typeLabel,+ TABLE_KINDS: ['U', 'V'],+ READ_DEFAULT_LIMIT,+ READ_MAX_LIMIT,+ WRITE_GUARD_DEFAULT,+ WRITE_GUARD_MAX,+};++export const mssqlAiProps = {+ schema: Property.ShortText({+ displayName: 'Schema',+ description: 'Schema name, as returned by Get Tables (table_schema) or List Schemas. Leave empty for the connection user\'s default schema, usually dbo.',+ required: false,+ }),+ table: Property.ShortText({+ displayName: 'Table',+ description: 'Table or view name without the schema, as returned by Get Tables (table_name).',+ required: true,+ }),+ namePattern: Property.ShortText({+ displayName: 'Name Pattern',+ description: 'Optional SQL LIKE pattern on the name, e.g. %order%. Leave empty to list all.',+ 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, IS EMPTY and IS NOT EMPTY take no value; use IS EMPTY to match empty text.${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 FilterOperator = (typeof FILTER_OPERATORS)[number];++type Filter = {+ column: string;+ operator: FilterOperator;+ value: unknown;+};++type WriteResult = {+ rows: Record<string, unknown>[];+ rows_affected: number;+};++export type SqlFragment = {+ sql: string;+ params: Record<string, unknown>;+};diff --git a/packages/pieces/community/microsoft-sql-server/src/lib/output-schemas.ts b/packages/pieces/community/microsoft-sql-server/src/lib/output-schemas.tsindex d26f2d2b8b9..c871cb34951 100644--- a/packages/pieces/community/microsoft-sql-server/src/lib/output-schemas.ts+++ b/packages/pieces/community/microsoft-sql-server/src/lib/output-schemas.ts@@ -106,3 +106,292 @@ export const writeRowsActionOutputSchema: OutputSchema = {},],};++export const microsoftSqlServerCallProcedureOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'result_sets',+ label: 'Result Sets',+ description: 'Every result set the procedure selected, in order, each a list of rows.',+ },+ {+ key: 'output_parameters',+ label: 'Output Parameters',+ value: '',+ dynamicKey: true,+ description: 'The final value of each OUTPUT parameter, keyed by its name without the @.',+ },+ { key: 'return_value', label: 'Return Value', format: 'number' },+ { key: 'rows_affected', label: 'Rows Affected', format: 'number' },+ ],+};++export const microsoftSqlServerCountRowsOutputSchema: OutputSchema = {+ fields: [{ key: 'count', label: 'Row Count', format: 'number' }],+};++export const microsoftSqlServerDescribeTableOutputSchema: OutputSchema = {+ fields: [+ { key: 'schema', label: 'Schema' },+ { key: 'table', label: 'Table' },+ {+ key: 'columns',+ label: 'Columns',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'type', label: 'Base Type' },+ { key: 'is_nullable', label: 'Nullable', format: 'boolean' },+ { key: 'is_identity', label: 'Identity', format: 'boolean' },+ { key: 'is_computed', label: 'Computed', format: 'boolean' },+ { key: 'default_value', label: 'Default Value' },+ { key: 'is_primary_key', label: 'Primary Key', format: 'boolean' },+ { key: 'references_table', label: 'References Table' },+ { key: 'references_column', label: 'References Column' },+ { key: 'data_type', label: 'Data Type' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const microsoftSqlServerExplainQueryOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'plans',+ label: 'Plans',+ description: 'The estimated execution plan of each statement, as showplan XML.',+ },+ { key: 'count', label: 'Plan Count', format: 'number' },+ ],+};++export const microsoftSqlServerFindRowsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'rows',+ label: 'Found Rows',+ value: '',+ description:+ 'The matching rows of this page, with the columns you asked for or all of them. Decimal, money and date and time columns arrive as exact strings.',+ },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ { key: 'next_offset', label: 'Next Offset', format: 'number' },+ ],+};++export const microsoftSqlServerGetRowByKeyOutputSchema: OutputSchema = {+ fields: [+ { key: 'found', label: 'Found', format: 'boolean' },+ {+ key: 'row',+ label: 'Row',+ value: '',+ dynamicKey: true,+ description:+ 'The matching row with every column of the table, or null when none matched. Decimal, money and date and time columns arrive as exact strings.',+ },+ ],+};++export const microsoftSqlServerGetServerInfoOutputSchema: OutputSchema = {+ fields: [+ { key: 'version', label: 'Version' },+ { key: 'product_version', label: 'Product Version' },+ { key: 'product_level', label: 'Product Level' },+ { key: 'edition', label: 'Edition' },+ { key: 'engine_edition', label: 'Engine Edition', format: 'number' },+ { key: 'server_name', label: 'Server Name' },+ { key: 'server_collation', label: 'Server Collation' },+ { key: 'database', label: 'Database' },+ { key: 'compatibility_level', label: 'Compatibility Level', format: 'number' },+ { key: 'login', label: 'Login' },+ { key: 'user', label: 'User' },+ { key: 'default_schema', label: 'Default Schema' },+ { key: 'server_time', label: 'Server Time', format: 'datetime' },+ ],+};++export const microsoftSqlServerGetViewDefinitionOutputSchema: OutputSchema = {+ fields: [+ { key: 'schema', label: 'Schema' },+ { key: 'view', label: 'View' },+ { key: 'definition', label: 'Definition' },+ ],+};++export const microsoftSqlServerListDatabasesOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'databases',+ label: 'Databases',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'database_id', label: 'Database ID', format: 'number' },+ { key: 'state', label: 'State' },+ { key: 'recovery_model', label: 'Recovery Model' },+ { key: 'compatibility_level', label: 'Compatibility Level', format: 'number' },+ { key: 'collation_name', label: 'Collation' },+ { key: 'is_read_only', label: 'Read Only', format: 'boolean' },+ { key: 'is_current', label: 'Current', format: 'boolean' },+ { key: 'create_date', label: 'Created', format: 'datetime' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const microsoftSqlServerListIndexesOutputSchema: OutputSchema = {+ fields: [+ { key: 'schema', label: 'Schema' },+ { key: 'table', label: 'Table' },+ {+ key: 'indexes',+ label: 'Indexes',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'type', label: 'Type' },+ { key: 'is_primary_key', label: 'Primary Key', format: 'boolean' },+ { key: 'is_unique', label: 'Unique', format: 'boolean' },+ { key: 'is_unique_constraint', label: 'Unique Constraint', format: 'boolean' },+ { key: 'is_disabled', label: 'Disabled', format: 'boolean' },+ { key: 'filter', label: 'Filter' },+ {+ key: 'key_columns',+ label: 'Key Columns',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'descending', label: 'Descending', format: 'boolean' },+ ],+ },+ { key: 'included_columns', label: 'Included Columns' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const microsoftSqlServerListRoutinesOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'routines',+ label: 'Routines',+ labelKey: 'name',+ listItems: [+ { key: 'schema', label: 'Schema' },+ { key: 'name', label: 'Name' },+ { key: 'kind', label: 'Kind' },+ {+ key: 'parameters',+ label: 'Parameters',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'data_type', label: 'Data Type' },+ { key: 'is_output', label: 'Output', format: 'boolean' },+ ],+ },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const microsoftSqlServerListSchemasOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'schemas',+ label: 'Schemas',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'owner', label: 'Owner' },+ { key: 'table_count', label: 'Table Count', format: 'number' },+ { key: 'view_count', label: 'View Count', format: 'number' },+ { key: 'is_default', label: 'Default Schema', format: 'boolean' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const microsoftSqlServerListSessionsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'sessions',+ label: 'Sessions',+ listItems: [+ { key: 'session_id', label: 'Session ID', format: 'number' },+ { key: 'login_name', label: 'Login Name' },+ { key: 'host_name', label: 'Host Name' },+ { key: 'program_name', label: 'Program Name' },+ { key: 'database', label: 'Database' },+ { key: 'status', label: 'Status' },+ { key: 'command', label: 'Command' },+ { key: 'wait_type', label: 'Wait Type' },+ { key: 'blocking_session_id', label: 'Blocking Session ID', format: 'number' },+ { key: 'elapsed_ms', label: 'Elapsed (ms)', format: 'number' },+ { key: 'cpu_ms', label: 'CPU Time (ms)', format: 'number' },+ { key: 'sql_text', label: 'SQL Text' },+ { key: 'login_time', label: 'Login Time', format: 'datetime' },+ { key: 'is_current', label: 'Current', format: 'boolean' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const microsoftSqlServerListViewsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'views',+ label: 'Views',+ labelKey: 'name',+ listItems: [+ { key: 'schema', label: 'Schema' },+ { key: 'name', label: 'Name' },+ { key: 'is_schema_bound', label: 'Schema Bound', format: 'boolean' },+ { key: 'is_indexed', label: 'Indexed', format: 'boolean' },+ { key: 'create_date', label: 'Created', format: 'datetime' },+ { key: 'modify_date', label: 'Modified', format: 'datetime' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const microsoftSqlServerRunSelectQueryOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'rows',+ label: 'Rows',+ value: '',+ description: 'The rows of the first result set, with whatever columns the query selected.',+ },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'has_more', label: 'Has More', format: 'boolean' },+ ],+};++export const microsoftSqlServerUpsertRowOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'action',+ label: 'Action',+ description: 'INSERT or UPDATE; unchanged when the row existed and there was nothing to update; null when the table has triggers.',+ },+ {+ key: 'row',+ label: 'Row',+ value: '',+ dynamicKey: true,+ description:+ 'The row as stored after the insert or update, with every column of the table. Null when the table has triggers or nothing changed.',+ },+ { key: 'rows_affected', label: 'Rows Affected', format: 'number' },+ ],+};