Skip to content

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

feat(mysql): let AI agents explore schemas, query and safely write rows (#17072)

Kishan Parmar1703e6fc3bbd
diff --git a/bun.lock b/bun.lock
index 078e03d7094..578b1954618 100644
--- a/bun.lock
+++ b/bun.lock
@@ -6435,7 +6435,7 @@
},
"packages/pieces/community/mysql": {
"name": "@activepieces/piece-mysql",
- "version": "0.4.0",
+ "version": "0.5.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
diff --git a/packages/pieces/community/mysql/package.json b/packages/pieces/community/mysql/package.json
index 5ebdf26200f..d161b3d65df 100644
--- a/packages/pieces/community/mysql/package.json
+++ b/packages/pieces/community/mysql/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-mysql",
- "version": "0.4.0",
+ "version": "0.5.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"dependencies": {
diff --git a/packages/pieces/community/mysql/src/index.ts b/packages/pieces/community/mysql/src/index.ts
index 15bc9d6e9e9..34726f51201 100644
--- a/packages/pieces/community/mysql/src/index.ts
+++ b/packages/pieces/community/mysql/src/index.ts
@@ -1,43 +1,9 @@
-import {
- PieceAuth,
- Property,
- createPiece,
-} from '@activepieces/pieces-framework';
+export { mysqlAuth } from './lib/auth';
+import { createPiece } from '@activepieces/pieces-framework';
import { PieceCategory } from '@activepieces/pieces-framework';
+import { mysqlAuth } from './lib/auth';
import actions from './lib/actions';
-
-export const mysqlAuth = PieceAuth.CustomAuth({
- props: {
- host: Property.ShortText({
- displayName: 'Host',
- required: true,
- description: "The server's hostname or IP address.",
- placeholder: 'db.example.com',
- }),
- port: Property.Number({
- displayName: 'Port',
- defaultValue: 3306,
- description: 'The port the server listens on, usually 3306.',
- required: true,
- }),
- user: Property.ShortText({
- displayName: 'Username',
- required: true,
- description: 'The database user to sign in as.',
- }),
- password: PieceAuth.SecretText({
- displayName: 'Password',
- description: 'The password for that user.',
- required: true,
- }),
- database: Property.ShortText({
- displayName: 'Database',
- description: 'The database to use. Only Run Query works without one.',
- required: false,
- }),
- },
- required: true,
-});
+import { mysqlAiActions } from './lib/actions/ai';
export const mysql = createPiece({
displayName: 'MySQL',
@@ -48,6 +14,6 @@ export const mysql = createPiece({
categories: [PieceCategory.DEVELOPER_TOOLS],
authors: ["JanHolger","kishanprmr","khaledmashaly","abuaboud"],
auth: mysqlAuth,
- actions,
+ actions: [...actions, ...mysqlAiActions],
triggers: [],
});
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/index.ts b/packages/pieces/community/mysql/src/lib/actions/ai/index.ts
new file mode 100644
index 00000000000..982ac32e44e
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/index.ts
@@ -0,0 +1,39 @@
+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 { 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 { listViews } from './schema/list-views';
+import { getServerInfo } from './server/get-server-info';
+import { listProcesses } from './server/list-processes';
+
+export const mysqlAiActions = [
+ listDatabases,
+ describeTable,
+ listIndexes,
+ listViews,
+ getViewDefinition,
+ listRoutines,
+ findRowsAi,
+ getRowByKey,
+ countRows,
+ insertRowsAi,
+ upsertRow,
+ updateRowsAi,
+ deleteRowsAi,
+ runSelectQuery,
+ explainQuery,
+ callProcedure,
+ getServerInfo,
+ listProcesses,
+];
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/queries/call-procedure.ts b/packages/pieces/community/mysql/src/lib/actions/ai/queries/call-procedure.ts
new file mode 100644
index 00000000000..6b5e608e0dd
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/queries/call-procedure.ts
@@ -0,0 +1,104 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { Connection } from 'promise-mysql';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi } from '../../../common/ai';
+import { sanitizeColumnName } from '../../../common';
+import { mysqlCallProcedureOutputSchema } from '../../../output-schemas';
+
+export const callProcedure = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_call_procedure',
+ outputSchema: mysqlCallProcedureOutputSchema,
+ displayName: 'Call Procedure',
+ description: 'Calls a stored procedure and returns its result sets and OUT parameters.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description: 'Calls a stored procedure. Arguments are the values for its IN and INOUT parameters in order, skipping OUT parameters; returns every result set it selects, the affected-row count and the final OUT and INOUT values by name. Procedure names and parameters come from List Routines. Not idempotent: the effect depends on the procedure.',
+ idempotent: false,
+ },
+ props: {
+ procedure: Property.ShortText({
+ displayName: 'Procedure',
+ description: 'Procedure name, as returned by List Routines. Use database.procedure for one outside the connection database.',
+ required: true,
+ }),
+ args: Property.Array({
+ displayName: 'Arguments',
+ description: 'Values for the IN and INOUT parameters, in order. Leave out OUT parameters.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { procedure } = context.propsValue;
+ const args = (context.propsValue.args ?? []).map((value) => mysqlAi.toBindValue({ value }));
+ return mysqlAi.withConnection({
+ auth: context.auth,
+ fn: async (conn) => {
+ const parameters = await loadParameters({ conn, procedure });
+ const inputCount = parameters.filter((parameter) => parameter.mode !== 'OUT').length;
+ if (args.length !== inputCount) {
+ throw new Error(`Procedure "${procedure}" takes ${inputCount} argument(s) for its IN and INOUT parameters, but ${args.length} were given.`);
+ }
+ const plan = buildCall({ parameters, args });
+ for (const statement of plan.setup) {
+ await conn.query(statement.sql, statement.values);
+ }
+ const result: unknown = await conn.query(`CALL ${sanitizeColumnName(procedure)}(${plan.placeholders.join(', ')})`, plan.values);
+ const outParams = await readOutParams({ conn, parameters });
+ const parts = Array.isArray(result) ? result : [result];
+ const status = parts.find((part) => mysqlAi.isRecord(part));
+ return {
+ resultSets: parts.filter((part) => Array.isArray(part)),
+ affectedRows: mysqlAi.isRecord(status) ? Number(status['affectedRows'] ?? 0) : 0,
+ outParams,
+ };
+ },
+ });
+ },
+});
+
+async function loadParameters({ conn, procedure }: { conn: Connection; procedure: string }): Promise<ProcedureParameter[]> {
+ const [schema, name] = procedure.includes('.') ? procedure.split('.', 2) : [null, procedure];
+ const rows: Record<string, unknown>[] = await conn.query(
+ "SELECT parameter_mode AS mode, parameter_name AS name FROM information_schema.parameters WHERE specific_schema = COALESCE(?, DATABASE()) AND specific_name = ? AND routine_type = 'PROCEDURE' ORDER BY ordinal_position",
+ [schema, name],
+ );
+ return rows.map((row, index) => ({ mode: String(row['mode']), name: String(row['name']), variable: `@ap_param_${index}` }));
+}
+
+function buildCall({ parameters, args }: { parameters: ProcedureParameter[]; args: unknown[] }): CallPlan {
+ const inputs = parameters.filter((parameter) => parameter.mode !== 'OUT');
+ const argFor = (parameter: ProcedureParameter): unknown => args[inputs.indexOf(parameter)];
+ return {
+ setup: parameters
+ .filter((parameter) => parameter.mode !== 'IN')
+ .map((parameter) => ({ sql: `SET ${parameter.variable} = ?`, values: [parameter.mode === 'INOUT' ? argFor(parameter) : null] })),
+ placeholders: parameters.map((parameter) => (parameter.mode === 'IN' ? '?' : parameter.variable)),
+ values: parameters.filter((parameter) => parameter.mode === 'IN').map((parameter) => argFor(parameter)),
+ };
+}
+
+async function readOutParams({ conn, parameters }: { conn: Connection; parameters: ProcedureParameter[] }): Promise<Record<string, unknown>> {
+ const outputs = parameters.filter((parameter) => parameter.mode !== 'IN');
+ if (outputs.length === 0) {
+ return {};
+ }
+ const rows: Record<string, unknown>[] = await conn.query(
+ `SELECT ${outputs.map((parameter, index) => `${parameter.variable} AS ${sanitizeColumnName(`p${index}`)}`).join(', ')}`,
+ );
+ const row = rows[0] ?? {};
+ return Object.fromEntries(outputs.map((parameter, index) => [parameter.name, row[`p${index}`]]));
+}
+
+type ProcedureParameter = {
+ mode: string;
+ name: string;
+ variable: string;
+};
+
+type CallPlan = {
+ setup: { sql: string; values: unknown[] }[];
+ placeholders: string[];
+ values: unknown[];
+};
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/queries/explain-query.ts b/packages/pieces/community/mysql/src/lib/actions/ai/queries/explain-query.ts
new file mode 100644
index 00000000000..176b0827522
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/queries/explain-query.ts
@@ -0,0 +1,42 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi } from '../../../common/ai';
+import { mysqlExplainQueryOutputSchema } from '../../../output-schemas';
+
+export const explainQuery = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_explain_query',
+ outputSchema: mysqlExplainQueryOutputSchema,
+ displayName: 'Explain Query',
+ description: 'Shows how MySQL would execute a query, without running it.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Returns the execution plan of a SELECT, INSERT, UPDATE, DELETE or REPLACE statement as JSON (EXPLAIN FORMAT=JSON) without running it: tables read, access type, indexes used and estimated rows. Use to check a slow or risky query before Run Query or Run Select Query. Pass the statement without EXPLAIN. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ query: Property.LongText({
+ displayName: 'Query',
+ description: 'The statement to explain, without the EXPLAIN keyword. Write ? where each value goes.',
+ required: true,
+ }),
+ args: Property.Array({
+ displayName: 'Arguments',
+ description: 'Values for each ? in the query, in order.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { query, args } = context.propsValue;
+ if (/^\s*(EXPLAIN|DESCRIBE|DESC|ANALYZE)\b/i.test(query)) {
+ throw new Error('Pass the statement without EXPLAIN, DESCRIBE or ANALYZE; this action adds EXPLAIN FORMAT=JSON itself.');
+ }
+ const rows: Record<string, unknown>[] = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: (conn) => conn.query(`EXPLAIN FORMAT=JSON ${query}`, args ?? []),
+ });
+ const plan = rows[0]?.['EXPLAIN'];
+ return { plan: typeof plan === 'string' ? JSON.parse(plan) : plan };
+ },
+});
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/queries/run-select-query.ts b/packages/pieces/community/mysql/src/lib/actions/ai/queries/run-select-query.ts
new file mode 100644
index 00000000000..6fa06cc1c82
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/queries/run-select-query.ts
@@ -0,0 +1,46 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi, mysqlAiProps } from '../../../common/ai';
+import { mysqlRunSelectQueryOutputSchema } from '../../../output-schemas';
+
+export const runSelectQuery = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_run_select_query',
+ outputSchema: mysqlRunSelectQueryOutputSchema,
+ displayName: 'Run Select Query',
+ description: 'Runs a read-only SQL query and returns up to a limit of rows.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description: 'Runs one read-only statement (SELECT, WITH, SHOW, DESCRIBE, EXPLAIN, TABLE, VALUES) inside a read-only transaction and returns up to Limit rows, with hasMore when the query produced more; add your own LIMIT for large tables. Pass dynamic values as ? placeholders in Arguments. Use for joins and aggregates that Find Rows cannot express; use Run Query to change data. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ query: Property.LongText({
+ displayName: 'Query',
+ description: 'One read-only SQL statement. Write ? where each value goes, e.g. SELECT * FROM orders WHERE status = ?',
+ required: true,
+ }),
+ args: Property.Array({
+ displayName: 'Arguments',
+ description: 'Values for each ? in the query, in order.',
+ required: false,
+ }),
+ limit: mysqlAiProps.limit,
+ },
+ async run(context) {
+ const { query, args, limit } = context.propsValue;
+ mysqlAi.assertReadOnlyQuery({ query });
+ const max = mysqlAi.boundedInteger({ value: limit, defaultValue: mysqlAi.READ_DEFAULT_LIMIT, min: 1, max: mysqlAi.READ_MAX_LIMIT, label: 'Limit' });
+ const { rows, hasMore } = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: (conn) =>
+ mysqlAi.inTransaction({
+ conn,
+ readOnly: true,
+ fn: () => mysqlAi.queryCapped({ conn, sql: query, values: args ?? [], max }),
+ }),
+ });
+ return { rows, count: rows.length, hasMore };
+ },
+});
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/rows/count-rows.ts b/packages/pieces/community/mysql/src/lib/actions/ai/rows/count-rows.ts
new file mode 100644
index 00000000000..caeeb62d790
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/rows/count-rows.ts
@@ -0,0 +1,32 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi, mysqlAiProps } from '../../../common/ai';
+import { sanitizeColumnName } from '../../../common';
+import { mysqlCountRowsOutputSchema } from '../../../output-schemas';
+
+export const countRows = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_count_rows',
+ outputSchema: mysqlCountRowsOutputSchema,
+ displayName: 'Count Rows',
+ description: 'Counts the rows of a table that match the filters.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description: 'Returns the number of rows in a table or view matching all given filters, or the whole table without filters. Use before Update Rows or Delete Rows to check how many rows a filter hits, or instead of paging through Find Rows for a total. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ table: mysqlAiProps.table,
+ filters: mysqlAiProps.filters({ required: false }),
+ },
+ async run(context) {
+ const { table, filters } = context.propsValue;
+ const where = mysqlAi.buildWhere({ filters });
+ const rows: Record<string, unknown>[] = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: (conn) => conn.query(`SELECT COUNT(*) AS count FROM ${sanitizeColumnName(table)}${where.sql}`, where.values),
+ });
+ return { count: Number(rows[0]?.['count'] ?? 0) };
+ },
+});
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/rows/delete-rows.ts b/packages/pieces/community/mysql/src/lib/actions/ai/rows/delete-rows.ts
new file mode 100644
index 00000000000..6c24366faca
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/rows/delete-rows.ts
@@ -0,0 +1,43 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi, mysqlAiProps } from '../../../common/ai';
+import { sanitizeColumnName } from '../../../common';
+import { mysqlDeleteRowsOutputSchema } from '../../../output-schemas';
+
+export const deleteRowsAi = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_delete_rows',
+ outputSchema: mysqlDeleteRowsOutputSchema,
+ 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); this cannot be undone. Runs in a transaction and deletes nothing if more than Max Rows match; check with Count Rows first. Not idempotent: a repeat may delete rows added since.',
+ idempotent: false,
+ },
+ props: {
+ table: mysqlAiProps.table,
+ filters: mysqlAiProps.filters({ required: true }),
+ maxRows: mysqlAiProps.maxRows({ verb: 'deleted' }),
+ },
+ async run(context) {
+ const { table, filters, maxRows } = context.propsValue;
+ const limit = mysqlAi.boundedInteger({ value: maxRows, defaultValue: mysqlAi.WRITE_GUARD_DEFAULT, min: 1, max: mysqlAi.WRITE_GUARD_MAX, label: 'Max Rows' });
+ const where = mysqlAi.buildWhere({ filters });
+ const quotedTable = sanitizeColumnName(table);
+ const result = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: (conn) =>
+ mysqlAi.guardedWrite({
+ conn,
+ quotedTable,
+ where,
+ maxRows: limit,
+ verb: 'deleted',
+ write: { sql: `DELETE FROM ${quotedTable}${where.sql}`, values: where.values },
+ }),
+ });
+ return { deletedRows: result.affectedRows };
+ },
+});
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/rows/find-rows.ts b/packages/pieces/community/mysql/src/lib/actions/ai/rows/find-rows.ts
new file mode 100644
index 00000000000..337cd6719eb
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/rows/find-rows.ts
@@ -0,0 +1,65 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi, mysqlAiProps } from '../../../common/ai';
+import { sanitizeColumnName } from '../../../common';
+import { mysqlFindRowsOutputSchema } from '../../../output-schemas';
+
+export const findRowsAi = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_find_rows',
+ outputSchema: mysqlFindRowsOutputSchema,
+ displayName: 'Find Rows',
+ description: 'Finds rows in a table using structured filters, sort and paging.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description: 'Returns rows of a table or view matching all given filters (column, operator, value), optionally limited to chosen columns and sorted, with offset paging (hasMore, nextOffset). Values are sent as bound parameters. Use Count Rows for totals and Get Row by Key for one row by its key. Column names come from Describe Table. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ table: mysqlAiProps.table,
+ filters: mysqlAiProps.filters({ required: false }),
+ columns: Property.Array({
+ displayName: 'Columns',
+ description: 'Columns to return. Leave empty for all columns.',
+ required: false,
+ }),
+ sort: Property.Array({
+ displayName: 'Sort',
+ description: 'Sort order; each entry has a column and a direction (ASC or DESC). Set a sort when paging so pages are stable.',
+ required: false,
+ properties: {
+ column: Property.ShortText({ displayName: 'Column', required: true }),
+ direction: Property.StaticDropdown({
+ displayName: 'Direction',
+ required: false,
+ defaultValue: 'ASC',
+ options: { options: [{ label: 'ASC', value: 'ASC' }, { label: 'DESC', value: 'DESC' }] },
+ }),
+ },
+ }),
+ limit: mysqlAiProps.limit,
+ offset: Property.Number({
+ displayName: 'Offset',
+ description: 'Number of rows to skip, for paging. Use nextOffset from the previous call with the same filters and sort.',
+ required: false,
+ defaultValue: 0,
+ }),
+ },
+ async run(context) {
+ const { table, filters, columns, sort, limit, offset } = context.propsValue;
+ const max = mysqlAi.boundedInteger({ value: limit, defaultValue: mysqlAi.READ_DEFAULT_LIMIT, min: 1, max: mysqlAi.READ_MAX_LIMIT, label: 'Limit' });
+ const skip = mysqlAi.boundedInteger({ value: offset, defaultValue: 0, min: 0, max: Number.MAX_SAFE_INTEGER, label: 'Offset' });
+ const where = mysqlAi.buildWhere({ filters });
+ const columnList = (columns ?? []).map((column) => sanitizeColumnName(String(column)));
+ const select = columnList.length > 0 ? columnList.join(', ') : '*';
+ const sql = `SELECT ${select} FROM ${sanitizeColumnName(table)}${where.sql}${mysqlAi.buildOrderBy({ sort })} LIMIT ${max + 1} OFFSET ${skip}`;
+ const found: unknown[] = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: (conn) => conn.query(sql, where.values),
+ });
+ const hasMore = found.length > max;
+ const rows = found.slice(0, max);
+ return { rows, count: rows.length, hasMore, nextOffset: hasMore ? skip + max : null };
+ },
+});
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/rows/get-row-by-key.ts b/packages/pieces/community/mysql/src/lib/actions/ai/rows/get-row-by-key.ts
new file mode 100644
index 00000000000..2d8fd4999d4
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/rows/get-row-by-key.ts
@@ -0,0 +1,46 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi, mysqlAiProps } from '../../../common/ai';
+import { sanitizeColumnName } from '../../../common';
+import { mysqlGetRowByKeyOutputSchema } from '../../../output-schemas';
+
+export const getRowByKey = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_get_row_by_key',
+ outputSchema: mysqlGetRowByKeyOutputSchema,
+ displayName: 'Get Row by Key',
+ description: 'Gets the one row whose key column equals a value.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Returns the single row whose key column equals the given value, usually the primary key (see List Indexes or Describe Table). Fails if no row matches, or if more than one does because the column is not unique; use Find Rows for those cases. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ table: mysqlAiProps.table,
+ keyColumn: Property.ShortText({
+ displayName: 'Key Column',
+ description: 'A primary-key or unique column, e.g. id.',
+ required: true,
+ }),
+ keyValue: Property.ShortText({
+ displayName: 'Key Value',
+ description: 'The value of the key column, e.g. the insertId returned by Insert Row.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const { table, keyColumn, keyValue } = context.propsValue;
+ const rows: unknown[] = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: (conn) => conn.query(`SELECT * FROM ${sanitizeColumnName(table)} WHERE ${sanitizeColumnName(keyColumn)} = ? LIMIT 2`, [keyValue]),
+ });
+ if (rows.length === 0) {
+ throw new Error(`No row in "${table}" where ${keyColumn} = ${keyValue}.`);
+ }
+ if (rows.length > 1) {
+ throw new Error(`More than one row in "${table}" has ${keyColumn} = ${keyValue}; that column is not unique. Use Find Rows instead.`);
+ }
+ return { row: rows[0] };
+ },
+});
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/rows/insert-rows.ts b/packages/pieces/community/mysql/src/lib/actions/ai/rows/insert-rows.ts
new file mode 100644
index 00000000000..74598cd6c53
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/rows/insert-rows.ts
@@ -0,0 +1,53 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi, mysqlAiProps, MysqlOkPacket } from '../../../common/ai';
+import { sanitizeColumnName } from '../../../common';
+import { insertRowsUtils } from '../../insert-rows';
+import { mysqlInsertRowsOutputSchema } from '../../../output-schemas';
+
+export const insertRowsAi = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_insert_rows',
+ outputSchema: mysqlInsertRowsOutputSchema,
+ displayName: 'Insert Rows',
+ description: 'Inserts a list of rows into a table in one transaction.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description: 'Inserts a list of rows, each an object of column names to values, in one transaction: on InnoDB tables, 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 row count and the auto-increment id of the first row. Use Upsert Row to insert-or-update by key. Not idempotent: repeating it inserts the rows again.',
+ idempotent: false,
+ },
+ props: {
+ table: mysqlAiProps.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 { table, rows } = context.propsValue;
+ const records = insertRowsUtils.toRecords({ rows, keepEmptyStrings: true });
+ const columns = insertRowsUtils.collectColumns({ records });
+ const statements = insertRowsUtils.buildStatements({ quotedTable: sanitizeColumnName(table), columns, records });
+ const results: MysqlOkPacket[] = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: (conn) =>
+ mysqlAi.inTransaction({
+ conn,
+ readOnly: false,
+ fn: async () => {
+ const packets: MysqlOkPacket[] = [];
+ for (const statement of statements) {
+ packets.push(await conn.query(statement.text, statement.values));
+ }
+ return packets;
+ },
+ }),
+ });
+ return {
+ affectedRows: results.reduce((total, result) => total + result.affectedRows, 0),
+ firstInsertId: results[0]?.insertId ?? 0,
+ };
+ },
+});
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/rows/update-rows.ts b/packages/pieces/community/mysql/src/lib/actions/ai/rows/update-rows.ts
new file mode 100644
index 00000000000..cd82bf196a6
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/rows/update-rows.ts
@@ -0,0 +1,49 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi, mysqlAiProps } from '../../../common/ai';
+import { sanitizeColumnName } from '../../../common';
+import { mysqlUpdateRowsOutputSchema } from '../../../output-schemas';
+
+export const updateRowsAi = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_update_rows',
+ outputSchema: mysqlUpdateRowsOutputSchema,
+ 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). Runs in a transaction and changes nothing if more than Max Rows match; check with Count Rows first. matchedRows counts rows the filters hit, changedRows those whose values actually changed. Setting the same values again changes nothing, so it is safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ table: mysqlAiProps.table,
+ filters: mysqlAiProps.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: mysqlAiProps.maxRows({ verb: 'updated' }),
+ },
+ async run(context) {
+ const { table, filters, maxRows } = context.propsValue;
+ const limit = mysqlAi.boundedInteger({ value: maxRows, defaultValue: mysqlAi.WRITE_GUARD_DEFAULT, min: 1, max: mysqlAi.WRITE_GUARD_MAX, label: 'Max Rows' });
+ const set = mysqlAi.buildSet({ values: mysqlAi.parseValues({ value: context.propsValue.values, label: 'Values' }) });
+ const where = mysqlAi.buildWhere({ filters });
+ const quotedTable = sanitizeColumnName(table);
+ const result = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: (conn) =>
+ mysqlAi.guardedWrite({
+ conn,
+ quotedTable,
+ where,
+ maxRows: limit,
+ verb: 'updated',
+ write: { sql: `UPDATE ${quotedTable} SET ${set.sql}${where.sql}`, values: [...set.values, ...where.values] },
+ }),
+ });
+ return { matchedRows: result.affectedRows, changedRows: result.changedRows };
+ },
+});
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/rows/upsert-row.ts b/packages/pieces/community/mysql/src/lib/actions/ai/rows/upsert-row.ts
new file mode 100644
index 00000000000..55cfc73d366
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/rows/upsert-row.ts
@@ -0,0 +1,80 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { Connection } from 'promise-mysql';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi, mysqlAiProps, MysqlOkPacket } from '../../../common/ai';
+import { sanitizeColumnName } from '../../../common';
+import { mysqlUpsertRowOutputSchema } from '../../../output-schemas';
+
+export const upsertRow = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_upsert_row',
+ outputSchema: mysqlUpsertRowOutputSchema,
+ displayName: 'Upsert Row',
+ description: 'Inserts a row, or updates the existing row with the same primary or unique key.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description: 'Inserts a row, or updates the row that already has the same primary or unique key (INSERT ... ON DUPLICATE KEY UPDATE). Values must give a non-null value for every column of at least one primary or unique key (see List Indexes); it fails otherwise. Update Columns limits which columns change on an existing row. affectedRows is 1 for an insert and 2 for an update. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ table: mysqlAiProps.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,
+ }),
+ updateColumns: Property.Array({
+ displayName: 'Update Columns',
+ description: 'Columns to overwrite when the row already exists. Leave empty to overwrite every column in Values.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { table, updateColumns } = context.propsValue;
+ const values = mysqlAi.parseValues({ value: context.propsValue.values, label: 'Values' });
+ const columns = Object.keys(values);
+ const toUpdate = (updateColumns ?? []).length > 0 ? (updateColumns ?? []).map((column) => String(column)) : columns;
+ const missing = toUpdate.filter((column) => !hasColumn({ columns, column }));
+ if (missing.length > 0) {
+ throw new Error(`Update Columns must also be in Values; missing: ${missing.join(', ')}.`);
+ }
+ const quotedColumns = columns.map((column) => sanitizeColumnName(column));
+ const updates = toUpdate.map((column) => `${sanitizeColumnName(column)} = VALUES(${sanitizeColumnName(column)})`);
+ const sql = `INSERT INTO ${sanitizeColumnName(table)} (${quotedColumns.join(', ')}) VALUES (${columns.map(() => '?').join(', ')}) ON DUPLICATE KEY UPDATE ${updates.join(', ')}`;
+ const result: MysqlOkPacket = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: async (conn) => {
+ await assertKeyCovered({ conn, table, values });
+ return conn.query(sql, columns.map((column) => mysqlAi.toBindValue({ value: values[column] })));
+ },
+ });
+ return { affectedRows: result.affectedRows, insertId: result.insertId };
+ },
+});
+
+async function assertKeyCovered({ conn, table, values }: { conn: Connection; table: string; values: Record<string, unknown> }): Promise<void> {
+ const { schema, name } = mysqlAi.splitTable({ table });
+ const identifying = Object.keys(values).filter((column) => values[column] !== null && values[column] !== undefined);
+ const rows: Record<string, unknown>[] = await conn.query(
+ 'SELECT index_name AS indexName, column_name AS columnName FROM information_schema.statistics WHERE table_schema = COALESCE(?, DATABASE()) AND table_name = ? AND non_unique = 0',
+ [schema, name],
+ );
+ const keys = rows.reduce<Record<string, string[]>>((acc, row) => {
+ const indexName = String(row['indexName']);
+ return { ...acc, [indexName]: [...(acc[indexName] ?? []), String(row['columnName'])] };
+ }, {});
+ const keyList = Object.entries(keys);
+ if (keyList.length === 0) {
+ throw new Error(`Table "${table}" has no primary or unique key, so an upsert would always insert. Use Insert Rows instead.`);
+ }
+ const covered = keyList.some(([, keyColumns]) => keyColumns.every((column) => hasColumn({ columns: identifying, column })));
+ if (!covered) {
+ const described = keyList.map(([indexName, keyColumns]) => `${indexName} (${keyColumns.join(', ')})`).join('; ');
+ throw new Error(`Values must give a non-null value for every column of a primary or unique key: ${described}.`);
+ }
+}
+
+function hasColumn({ columns, column }: { columns: string[]; column: string }): boolean {
+ return columns.some((candidate) => candidate.toLowerCase() === column.toLowerCase());
+}
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/schema/describe-table.ts b/packages/pieces/community/mysql/src/lib/actions/ai/schema/describe-table.ts
new file mode 100644
index 00000000000..51be64d6df0
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/schema/describe-table.ts
@@ -0,0 +1,44 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi, mysqlAiProps } from '../../../common/ai';
+import { mysqlDescribeTableOutputSchema } from '../../../output-schemas';
+
+export const describeTable = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_describe_table',
+ outputSchema: mysqlDescribeTableOutputSchema,
+ displayName: 'Describe Table',
+ description: 'Lists the columns of a table with their types, keys and defaults.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Returns every column of a table in order: name, data and column type, nullability, default, key (PRI, UNI, MUL) and extra (auto_increment, generated). Use before reading or writing rows to learn column names, required columns and the primary key. Table names come from Get Tables. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ table: mysqlAiProps.table,
+ database: mysqlAiProps.database,
+ },
+ async run(context) {
+ const { table, database } = context.propsValue;
+ const columns: Record<string, unknown>[] = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: async (conn) => {
+ const { schema: tableSchema, name } = mysqlAi.splitTable({ table });
+ const schema = tableSchema ?? (await mysqlAi.resolveDatabase({ conn, database }));
+ return conn.query(
+ 'SELECT column_name AS name, data_type AS dataType, column_type AS columnType, is_nullable AS nullable, column_default AS defaultValue, column_key AS columnKey, extra AS extra, column_comment AS comment FROM information_schema.columns WHERE table_schema = ? AND table_name = ? ORDER BY ordinal_position',
+ [schema, name],
+ );
+ },
+ });
+ if (columns.length === 0) {
+ throw new Error(`Table "${table}" was not found. Use Get Tables to list the tables.`);
+ }
+ return {
+ table,
+ columns: columns.map((column) => ({ ...column, nullable: column['nullable'] === 'YES' })),
+ count: columns.length,
+ };
+ },
+});
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/schema/get-view-definition.ts b/packages/pieces/community/mysql/src/lib/actions/ai/schema/get-view-definition.ts
new file mode 100644
index 00000000000..3f03f1ae405
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/schema/get-view-definition.ts
@@ -0,0 +1,39 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi } from '../../../common/ai';
+import { sanitizeColumnName } from '../../../common';
+import { mysqlGetViewDefinitionOutputSchema } from '../../../output-schemas';
+
+export const getViewDefinition = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_get_view_definition',
+ outputSchema: mysqlGetViewDefinitionOutputSchema,
+ displayName: 'Get View Definition',
+ description: 'Returns the CREATE VIEW statement of a view.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Returns the CREATE VIEW statement behind a view (SHOW CREATE VIEW), to see which tables and joins it reads. View names come from List Views. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ view: Property.ShortText({
+ displayName: 'View',
+ description: 'View name, as returned by List Views. Use database.view for a view outside the connection database.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const rows: Record<string, unknown>[] = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: (conn) => conn.query(`SHOW CREATE VIEW ${sanitizeColumnName(context.propsValue.view)}`),
+ });
+ const row = rows[0] ?? {};
+ return {
+ view: row['View'],
+ definition: row['Create View'],
+ characterSetClient: row['character_set_client'],
+ collationConnection: row['collation_connection'],
+ };
+ },
+});
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/schema/list-databases.ts b/packages/pieces/community/mysql/src/lib/actions/ai/schema/list-databases.ts
new file mode 100644
index 00000000000..8a5da327a7b
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/schema/list-databases.ts
@@ -0,0 +1,31 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi, mysqlAiProps } from '../../../common/ai';
+import { mysqlListDatabasesOutputSchema } from '../../../output-schemas';
+
+export const listDatabases = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_list_databases',
+ outputSchema: mysqlListDatabasesOutputSchema,
+ displayName: 'List Databases',
+ description: 'Lists the databases the connection user can see.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description: 'Lists the databases visible to the connection user (SHOW DATABASES), optionally filtered by a LIKE pattern. Use to find the database name that Describe Table, List Views and List Routines take. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ namePattern: mysqlAiProps.namePattern,
+ },
+ async run(context) {
+ const { namePattern } = context.propsValue;
+ const hasPattern = namePattern !== undefined && namePattern !== '';
+ const rows: Record<string, unknown>[] = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: (conn) => conn.query(hasPattern ? 'SHOW DATABASES LIKE ?' : 'SHOW DATABASES', hasPattern ? [namePattern] : []),
+ });
+ const databases = rows.map((row) => String(Object.values(row)[0]));
+ return { databases, count: databases.length };
+ },
+});
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/schema/list-indexes.ts b/packages/pieces/community/mysql/src/lib/actions/ai/schema/list-indexes.ts
new file mode 100644
index 00000000000..59258749fb4
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/schema/list-indexes.ts
@@ -0,0 +1,57 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi, mysqlAiProps } from '../../../common/ai';
+import { mysqlListIndexesOutputSchema } from '../../../output-schemas';
+
+export const listIndexes = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_list_indexes',
+ outputSchema: mysqlListIndexesOutputSchema,
+ displayName: 'List Indexes',
+ description: 'Lists the indexes of a table and the columns each one covers.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Returns the indexes of a table (PRIMARY first), each with whether it is unique, its type and its columns in order. Use to find the primary or unique key that Get Row by Key and Upsert Row rely on, or which filters are indexed. Table names come from Get Tables. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ table: mysqlAiProps.table,
+ database: mysqlAiProps.database,
+ },
+ async run(context) {
+ const { table, database } = context.propsValue;
+ const rows: Record<string, unknown>[] = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: async (conn) => {
+ const { schema: tableSchema, name } = mysqlAi.splitTable({ table });
+ const schema = tableSchema ?? (await mysqlAi.resolveDatabase({ conn, database }));
+ return conn.query(
+ "SELECT index_name AS name, non_unique AS nonUnique, index_type AS type, column_name AS columnName FROM information_schema.statistics WHERE table_schema = ? AND table_name = ? ORDER BY index_name <> 'PRIMARY', index_name, seq_in_index",
+ [schema, name],
+ );
+ },
+ });
+ const indexes = groupIndexes({ rows });
+ return { table, indexes, count: indexes.length };
+ },
+});
+
+function groupIndexes({ rows }: { rows: Record<string, unknown>[] }): IndexInfo[] {
+ return rows.reduce<IndexInfo[]>((indexes, row) => {
+ const name = String(row['name']);
+ const last = indexes[indexes.length - 1];
+ const column = String(row['columnName']);
+ if (last !== undefined && last.name === name) {
+ return [...indexes.slice(0, -1), { ...last, columns: [...last.columns, column] }];
+ }
+ return [...indexes, { name, unique: Number(row['nonUnique']) === 0, type: String(row['type']), columns: [column] }];
+ }, []);
+}
+
+type IndexInfo = {
+ name: string;
+ unique: boolean;
+ type: string;
+ columns: string[];
+};
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/schema/list-routines.ts b/packages/pieces/community/mysql/src/lib/actions/ai/schema/list-routines.ts
new file mode 100644
index 00000000000..40a25c4a932
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/schema/list-routines.ts
@@ -0,0 +1,48 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi, mysqlAiProps } from '../../../common/ai';
+import { mysqlListRoutinesOutputSchema } from '../../../output-schemas';
+
+export const listRoutines = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_list_routines',
+ outputSchema: mysqlListRoutinesOutputSchema,
+ displayName: 'List Routines',
+ description: 'Lists the stored procedures and functions in a database with their parameters.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description: 'Lists stored procedures and functions in a database, each with its type, return type (functions), comment and ordered parameters (mode, name, type), optionally filtered by a LIKE pattern on the name. Use to find a procedure and its argument order for Call Procedure. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ database: mysqlAiProps.database,
+ namePattern: mysqlAiProps.namePattern,
+ },
+ async run(context) {
+ const { database, namePattern } = context.propsValue;
+ const hasPattern = namePattern !== undefined && namePattern !== '';
+ const { routines, parameters } = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: async (conn) => {
+ const schema = await mysqlAi.resolveDatabase({ conn, database });
+ const routineRows: Record<string, unknown>[] = await conn.query(
+ `SELECT routine_name AS name, routine_type AS type, dtd_identifier AS returns, routine_comment AS comment FROM information_schema.routines WHERE routine_schema = ?${hasPattern ? ' AND routine_name LIKE ?' : ''} ORDER BY routine_name`,
+ hasPattern ? [schema, namePattern] : [schema],
+ );
+ const parameterRows: Record<string, unknown>[] = await conn.query(
+ 'SELECT specific_name AS routine, routine_type AS routineType, parameter_mode AS mode, parameter_name AS name, dtd_identifier AS type FROM information_schema.parameters WHERE specific_schema = ? AND ordinal_position > 0 ORDER BY specific_name, ordinal_position',
+ [schema],
+ );
+ return { routines: routineRows, parameters: parameterRows };
+ },
+ });
+ const result = routines.map((routine) => ({
+ ...routine,
+ parameters: parameters
+ .filter((parameter) => parameter['routine'] === routine['name'] && parameter['routineType'] === routine['type'])
+ .map((parameter) => ({ mode: parameter['mode'], name: parameter['name'], type: parameter['type'] })),
+ }));
+ return { routines: result, count: result.length };
+ },
+});
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/schema/list-views.ts b/packages/pieces/community/mysql/src/lib/actions/ai/schema/list-views.ts
new file mode 100644
index 00000000000..c7ab36f6c2d
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/schema/list-views.ts
@@ -0,0 +1,40 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi, mysqlAiProps } from '../../../common/ai';
+import { mysqlListViewsOutputSchema } from '../../../output-schemas';
+
+export const listViews = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_list_views',
+ outputSchema: mysqlListViewsOutputSchema,
+ displayName: 'List Views',
+ description: 'Lists the views in a database.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description: 'Lists the views in a database with whether each is updatable and its security type, optionally filtered by a LIKE pattern on the name. Views can be read with Find Rows like tables; use Get View Definition for the SQL behind one. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ database: mysqlAiProps.database,
+ namePattern: mysqlAiProps.namePattern,
+ },
+ async run(context) {
+ const { database, namePattern } = context.propsValue;
+ const hasPattern = namePattern !== undefined && namePattern !== '';
+ const views: Record<string, unknown>[] = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: async (conn) => {
+ const schema = await mysqlAi.resolveDatabase({ conn, database });
+ return conn.query(
+ `SELECT table_name AS name, is_updatable AS updatable, security_type AS securityType, definer AS definer FROM information_schema.views WHERE table_schema = ?${hasPattern ? ' AND table_name LIKE ?' : ''} ORDER BY table_name`,
+ hasPattern ? [schema, namePattern] : [schema],
+ );
+ },
+ });
+ return {
+ views: views.map((view) => ({ ...view, updatable: view['updatable'] === 'YES' })),
+ count: views.length,
+ };
+ },
+});
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/server/get-server-info.ts b/packages/pieces/community/mysql/src/lib/actions/ai/server/get-server-info.ts
new file mode 100644
index 00000000000..8ba95945435
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/server/get-server-info.ts
@@ -0,0 +1,30 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi } from '../../../common/ai';
+import { mysqlGetServerInfoOutputSchema } from '../../../output-schemas';
+
+export const getServerInfo = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_get_server_info',
+ outputSchema: mysqlGetServerInfoOutputSchema,
+ displayName: 'Get Server Info',
+ description: 'Returns the server version, current database and user, time zone and SQL mode.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Returns the MySQL server version, the connection database and user, the server and session time zones, the SQL mode and whether the server is read-only. Use to check which SQL features are available or why a write is refused. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ async run(context) {
+ const rows: Record<string, unknown>[] = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: (conn) =>
+ conn.query(
+ 'SELECT VERSION() AS version, @@version_comment AS versionComment, DATABASE() AS `database`, CURRENT_USER() AS currentUser, @@system_time_zone AS systemTimeZone, @@time_zone AS timeZone, @@sql_mode AS sqlMode, @@read_only AS readOnly',
+ ),
+ });
+ const info = rows[0] ?? {};
+ return { ...info, readOnly: Number(info['readOnly']) === 1 };
+ },
+});
diff --git a/packages/pieces/community/mysql/src/lib/actions/ai/server/list-processes.ts b/packages/pieces/community/mysql/src/lib/actions/ai/server/list-processes.ts
new file mode 100644
index 00000000000..d8a280f0099
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/actions/ai/server/list-processes.ts
@@ -0,0 +1,33 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { mysqlAuth } from '../../../..';
+import { mysqlAi, mysqlAiProps } from '../../../common/ai';
+import { mysqlListProcessesOutputSchema } from '../../../output-schemas';
+
+export const listProcesses = createAction({
+ auth: mysqlAuth,
+ name: 'mysql_list_processes',
+ outputSchema: mysqlListProcessesOutputSchema,
+ displayName: 'List Processes',
+ description: 'Lists the connections running on the server and what each is doing.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description: 'Lists server connections, longest-running first: id, user, host, database, command, seconds in the current state, state and the statement being run. Without the PROCESS privilege only the connection user\'s own sessions are listed. Use to find long-running or blocking queries. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ limit: mysqlAiProps.limit,
+ },
+ async run(context) {
+ const max = mysqlAi.boundedInteger({ value: context.propsValue.limit, defaultValue: mysqlAi.READ_DEFAULT_LIMIT, min: 1, max: mysqlAi.READ_MAX_LIMIT, label: 'Limit' });
+ const processes: unknown[] = await mysqlAi.withConnection({
+ auth: context.auth,
+ fn: (conn) =>
+ conn.query(
+ 'SELECT id, user, host, db AS `database`, command, time AS seconds, state, info AS statement FROM information_schema.processlist ORDER BY time DESC LIMIT ?',
+ [max],
+ ),
+ });
+ return { processes, count: processes.length };
+ },
+});
diff --git a/packages/pieces/community/mysql/src/lib/actions/delete-row.ts b/packages/pieces/community/mysql/src/lib/actions/delete-row.ts
index 1e6598c2be8..c8ee0a4dbce 100644
--- a/packages/pieces/community/mysql/src/lib/actions/delete-row.ts
+++ b/packages/pieces/community/mysql/src/lib/actions/delete-row.ts
@@ -8,7 +8,7 @@ export default createAction({
name: 'delete_row',
displayName: 'Delete Row',
description: 'Deletes one or more rows from a table',
- audience: 'both',
+ audience: 'human',
outputSchema: deleteRowOutputSchema,
aiMetadata: { description: 'Deletes every row in a MySQL table whose search column equals a given value. Use to remove records matched by a single column. Idempotent: once the matching rows are gone, re-running with the same input deletes nothing further.', idempotent: true },
props: {
diff --git a/packages/pieces/community/mysql/src/lib/actions/find-rows.ts b/packages/pieces/community/mysql/src/lib/actions/find-rows.ts
index e1152f79061..9684c70f7c8 100644
--- a/packages/pieces/community/mysql/src/lib/actions/find-rows.ts
+++ b/packages/pieces/community/mysql/src/lib/actions/find-rows.ts
@@ -8,7 +8,7 @@ export default createAction({
name: 'find_rows',
displayName: 'Find Rows',
description: 'Reads rows from a table',
- audience: 'both',
+ audience: 'human',
outputSchema: findRowsOutputSchema,
aiMetadata: { description: 'Reads rows from a MySQL table that match a SQL WHERE condition, optionally limited to specific columns. Use to look up or filter records by arbitrary criteria. The condition is required and is interpolated raw into the query, so pass dynamic values through the args array (referenced as ? placeholders) to avoid SQL injection. Read-only and idempotent.', idempotent: true },
propertyGroups: [
diff --git a/packages/pieces/community/mysql/src/lib/actions/insert-rows.ts b/packages/pieces/community/mysql/src/lib/actions/insert-rows.ts
index ebf5d822747..fd1ea7d55ad 100644
--- a/packages/pieces/community/mysql/src/lib/actions/insert-rows.ts
+++ b/packages/pieces/community/mysql/src/lib/actions/insert-rows.ts
@@ -10,7 +10,7 @@ export const insertRows = createAction({
classification: 'WRITE',
displayName: 'Insert Multiple Rows',
description: 'Inserts many rows into a table in a single transaction',
- audience: 'both',
+ audience: 'human',
outputSchema: insertRowsOutputSchema,
aiMetadata: {
description: 'Inserts an array of rows into a MySQL 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 (InnoDB tables only). Columns a row omits get the column default. Returns the inserted row count and the auto-increment id of the first inserted row. Use instead of repeated single inserts for bulk loads. Not idempotent: each call appends new rows, so repeating it adds duplicates or errors on a unique-key collision.',
diff --git a/packages/pieces/community/mysql/src/lib/actions/update-row.ts b/packages/pieces/community/mysql/src/lib/actions/update-row.ts
index 881bef0078d..25ab0dd40ca 100644
--- a/packages/pieces/community/mysql/src/lib/actions/update-row.ts
+++ b/packages/pieces/community/mysql/src/lib/actions/update-row.ts
@@ -8,7 +8,7 @@ export default createAction({
name: 'update_row',
displayName: 'Update Row',
description: 'Updates one or more rows in a table',
- audience: 'both',
+ audience: 'human',
outputSchema: updateRowOutputSchema,
aiMetadata: { description: 'Updates every row in a MySQL table whose search column equals a given value, setting the supplied column-to-value pairs. Use to modify existing records matched by a single column. Idempotent: re-running with the same input writes the same values and has no additional effect.', idempotent: true },
props: {
diff --git a/packages/pieces/community/mysql/src/lib/auth.ts b/packages/pieces/community/mysql/src/lib/auth.ts
new file mode 100644
index 00000000000..7c097d10db6
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/auth.ts
@@ -0,0 +1,34 @@
+import { PieceAuth, Property } from '@activepieces/pieces-framework';
+
+export const mysqlAuth = PieceAuth.CustomAuth({
+ props: {
+ host: Property.ShortText({
+ displayName: 'Host',
+ required: true,
+ description: "The server's hostname or IP address.",
+ placeholder: 'db.example.com',
+ }),
+ port: Property.Number({
+ displayName: 'Port',
+ defaultValue: 3306,
+ description: 'The port the server listens on, usually 3306.',
+ required: true,
+ }),
+ user: Property.ShortText({
+ displayName: 'Username',
+ required: true,
+ description: 'The database user to sign in as.',
+ }),
+ password: PieceAuth.SecretText({
+ displayName: 'Password',
+ description: 'The password for that user.',
+ required: true,
+ }),
+ database: Property.ShortText({
+ displayName: 'Database',
+ description: 'The database to use. Only Run Query works without one.',
+ required: false,
+ }),
+ },
+ required: true,
+});
diff --git a/packages/pieces/community/mysql/src/lib/common/ai.ts b/packages/pieces/community/mysql/src/lib/common/ai.ts
new file mode 100644
index 00000000000..d28711284a0
--- /dev/null
+++ b/packages/pieces/community/mysql/src/lib/common/ai.ts
@@ -0,0 +1,329 @@
+import { AppConnectionValueForAuthProperty, Property } from '@activepieces/pieces-framework';
+import { Connection } from 'promise-mysql';
+import { mysqlAuth } from '../..';
+import { mysqlConnect, sanitizeColumnName } from '.';
+
+async function withConnection<T>({ auth, fn }: { auth: MysqlAuthValue; fn: (conn: Connection) => Promise<T> }): Promise<T> {
+ const conn = await mysqlConnect(auth, {});
+ conn.on('error', () => undefined);
+ try {
+ return await fn(conn);
+ } finally {
+ await conn.end().catch(() => conn.destroy());
+ }
+}
+
+async function inTransaction<T>({ conn, readOnly, fn }: { conn: Connection; readOnly: boolean; fn: () => Promise<T> }): Promise<T> {
+ await conn.query(readOnly ? 'START TRANSACTION READ ONLY' : 'START TRANSACTION');
+ try {
+ const result = await fn();
+ await conn.query(readOnly ? 'ROLLBACK' : 'COMMIT');
+ return result;
+ } catch (error) {
+ await conn.query('ROLLBACK').catch(() => undefined);
+ throw error;
+ }
+}
+
+function splitTable({ table }: { table: string }): { schema: string | null; name: string } {
+ const dot = table.indexOf('.');
+ return dot === -1 ? { schema: null, name: table } : { schema: table.slice(0, dot), name: table.slice(dot + 1) };
+}
+
+async function resolveDatabase({ conn, database }: { conn: Connection; database: string | undefined }): Promise<string> {
+ if (database !== undefined && database !== '') {
+ return database;
+ }
+ const rows: Record<string, unknown>[] = await conn.query('SELECT DATABASE() AS name');
+ const name = rows[0]?.['name'];
+ if (typeof name !== 'string') {
+ throw new Error('No database selected: set Database, or set one on the connection.');
+ }
+ return name;
+}
+
+function buildWhere({ filters }: { filters: unknown }): SqlFragment {
+ const parts = parseFilters({ filters }).map((filter) => filterToSql({ filter }));
+ if (parts.length === 0) {
+ return { sql: '', values: [] };
+ }
+ return {
+ sql: ` WHERE ${parts.map((part) => part.sql).join(' AND ')}`,
+ values: parts.flatMap((part) => part.values),
+ };
+}
+
+function buildOrderBy({ sort }: { sort: unknown }): string {
+ const entries = toList({ value: sort, label: 'Sort' });
+ const parts = entries.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 `${sanitizeColumnName(entry['column'])} ${direction}`;
+ });
+ return parts.length > 0 ? ` ORDER BY ${parts.join(', ')}` : '';
+}
+
+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;
+}
+
+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 buildSet({ values }: { values: Record<string, unknown> }): SqlFragment {
+ const columns = Object.keys(values);
+ return {
+ sql: columns.map((column) => `${sanitizeColumnName(column)} = ?`).join(', '),
+ values: columns.map((column) => toBindValue({ value: values[column] })),
+ };
+}
+
+async function guardedWrite({ conn, quotedTable, where, maxRows, write, verb }: {
+ conn: Connection;
+ quotedTable: string;
+ where: SqlFragment;
+ maxRows: number;
+ write: SqlFragment;
+ verb: string;
+}): Promise<MysqlOkPacket> {
+ if (where.sql === '') {
+ throw new Error(`Provide at least one filter; this action never ${verb} a whole table.`);
+ }
+ await conn.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ');
+ return inTransaction({
+ conn,
+ readOnly: false,
+ fn: async () => {
+ const rows: Record<string, unknown>[] = await conn.query(
+ `SELECT COUNT(*) AS total FROM ${quotedTable}${where.sql} FOR UPDATE`,
+ where.values,
+ );
+ const total = Number(rows[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 conn.query(write.sql, write.values);
+ },
+ });
+}
+
+function assertReadOnlyQuery({ query }: { query: string }): void {
+ if (query.includes('/*!') || query.includes('/*+')) {
+ throw new Error('Executable and optimizer-hint comments (/*! ... */, /*+ ... */) are not allowed here.');
+ }
+ const code = query.replace(LEADING_NOISE, '');
+ const firstWord = (code.match(/^[A-Za-z]+/)?.[0] ?? '').toUpperCase();
+ if (!READ_ONLY_FIRST_WORDS.includes(firstWord)) {
+ throw new Error(`Only read-only statements are allowed here (${READ_ONLY_FIRST_WORDS.join(', ')}); the query starts with "${firstWord || code.slice(0, 20)}". Use Run Query or the row actions to change data.`);
+ }
+ if (/\bINTO\b[\s\S]*\b(OUTFILE|DUMPFILE)\b/i.test(code)) {
+ throw new Error('SELECT ... INTO OUTFILE / DUMPFILE is not allowed here.');
+ }
+}
+
+function queryCapped({ conn, sql, values, max }: { conn: Connection; sql: string; values: unknown[]; max: number }): Promise<CappedRows> {
+ return new Promise((resolve, reject) => {
+ const rows: unknown[] = [];
+ let hasMore = false;
+ const query = conn.queryStream(sql, values);
+ query.on('result', (row: unknown) => {
+ if (rows.length < max) {
+ rows.push(row);
+ } else {
+ hasMore = true;
+ }
+ });
+ query.on('error', reject);
+ query.on('end', () => resolve({ rows, hasMore }));
+ });
+}
+
+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 }: { filter: Filter }): SqlFragment {
+ const column = sanitizeColumnName(filter.column);
+ if (filter.operator === 'IS NULL' || filter.operator === 'IS NOT NULL') {
+ return { sql: `${column} ${filter.operator}`, values: [] };
+ }
+ if (filter.value === undefined || filter.value === null || filter.value === '') {
+ throw new Error(`Filter on "${filter.column}" with ${filter.operator} needs a value. Use IS NULL to match empty values.`);
+ }
+ if (filter.operator === 'IN' || filter.operator === 'NOT IN') {
+ const list = Array.isArray(filter.value) ? filter.value : parseList({ text: String(filter.value) });
+ return { sql: `${column} ${filter.operator} (${list.map(() => '?').join(', ')})`, values: list };
+ }
+ return { sql: `${column} ${filter.operator} ?`, values: [toBindValue({ value: 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 (value === undefined || value === null || 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);
+}
+
+const FILTER_OPERATORS = ['=', '!=', '<', '<=', '>', '>=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'IS NULL', 'IS NOT NULL'] as const;
+
+const READ_ONLY_FIRST_WORDS = ['SELECT', 'WITH', 'SHOW', 'DESCRIBE', 'DESC', 'EXPLAIN', 'TABLE', 'VALUES'];
+
+const LEADING_NOISE = /^(?:\s+|\/\*[\s\S]*?\*\/|--[^\n]*(?:\n|$)|#[^\n]*(?:\n|$)|\()*/;
+
+const READ_DEFAULT_LIMIT = 100;
+const READ_MAX_LIMIT = 1000;
+const WRITE_GUARD_DEFAULT = 100;
+const WRITE_GUARD_MAX = 10000;
+
+export const mysqlAi = {
+ withConnection,
+ inTransaction,
+ splitTable,
+ resolveDatabase,
+ buildWhere,
+ buildOrderBy,
+ buildSet,
+ boundedInteger,
+ toBindValue,
+ parseValues,
+ guardedWrite,
+ assertReadOnlyQuery,
+ queryCapped,
+ isRecord,
+ READ_DEFAULT_LIMIT,
+ READ_MAX_LIMIT,
+ WRITE_GUARD_DEFAULT,
+ WRITE_GUARD_MAX,
+};
+
+export const mysqlAiProps = {
+ table: Property.ShortText({
+ displayName: 'Table',
+ description: 'Table name, as returned by Get Tables. Use database.table to reach a table outside the connection database.',
+ required: true,
+ }),
+ database: Property.ShortText({
+ displayName: 'Database',
+ description: 'Database name, as returned by List Databases. Leave empty to use the connection database.',
+ required: false,
+ }),
+ namePattern: Property.ShortText({
+ displayName: 'Name Pattern',
+ description: 'Optional SQL LIKE pattern on the name, e.g. %order%. Leave empty to list all.',
+ required: false,
+ }),
+ filters: ({ required }: { required: boolean }) =>
+ Property.Array({
+ displayName: 'Filters',
+ description: `Conditions combined with AND. Each has a column, an operator (${FILTER_OPERATORS.join(', ')}) and a value. For IN / NOT IN pass a JSON list such as ["a", "b"] or comma-separated values; IS NULL / IS NOT NULL take no value.${required ? ' At least one filter is required.' : ''}`,
+ required,
+ properties: {
+ column: Property.ShortText({ displayName: 'Column', required: true }),
+ operator: Property.StaticDropdown({
+ displayName: 'Operator',
+ required: true,
+ defaultValue: '=',
+ options: { options: FILTER_OPERATORS.map((operator) => ({ label: operator, value: operator })) },
+ }),
+ value: Property.ShortText({ displayName: 'Value', required: false }),
+ },
+ }),
+ limit: Property.Number({
+ displayName: 'Limit',
+ description: `Maximum number of rows to return (1-${READ_MAX_LIMIT}). Defaults to ${READ_DEFAULT_LIMIT}.`,
+ required: false,
+ defaultValue: READ_DEFAULT_LIMIT,
+ }),
+ maxRows: ({ verb }: { verb: string }) =>
+ Property.Number({
+ displayName: 'Max Rows',
+ description: `Refuse, changing nothing, if more rows than this would be ${verb} (1-${WRITE_GUARD_MAX}). Defaults to ${WRITE_GUARD_DEFAULT}.`,
+ required: false,
+ defaultValue: WRITE_GUARD_DEFAULT,
+ }),
+};
+
+type MysqlAuthValue = AppConnectionValueForAuthProperty<typeof mysqlAuth>;
+
+type FilterOperator = (typeof FILTER_OPERATORS)[number];
+
+type Filter = {
+ column: string;
+ operator: FilterOperator;
+ value: unknown;
+};
+
+type CappedRows = {
+ rows: unknown[];
+ hasMore: boolean;
+};
+
+export type SqlFragment = {
+ sql: string;
+ values: unknown[];
+};
+
+export type MysqlOkPacket = {
+ affectedRows: number;
+ insertId: number;
+ changedRows: number;
+ warningCount: number;
+ message: string;
+};
diff --git a/packages/pieces/community/mysql/src/lib/output-schemas.ts b/packages/pieces/community/mysql/src/lib/output-schemas.ts
index f4f6e1423ae..9f465c02a2e 100644
--- a/packages/pieces/community/mysql/src/lib/output-schemas.ts
+++ b/packages/pieces/community/mysql/src/lib/output-schemas.ts
@@ -72,3 +72,222 @@ export const getTablesOutputSchema: OutputSchema = {
},
],
};
+
+export const mysqlListDatabasesOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'databases', label: 'Databases', description: 'Names of the databases the connection user can see.' },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+};
+
+export const mysqlDescribeTableOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'table', label: 'Table' },
+ {
+ key: 'columns',
+ label: 'Columns',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Name' },
+ { key: 'dataType', label: 'Data Type' },
+ { key: 'columnType', label: 'Column Type', description: 'Full type with length and options, e.g. varchar(120) or int unsigned.' },
+ { key: 'nullable', label: 'Nullable', format: 'boolean' },
+ { key: 'defaultValue', label: 'Default Value' },
+ { key: 'columnKey', label: 'Key', description: 'PRI for primary key, UNI for unique, MUL for a non-unique index, empty otherwise.' },
+ { key: 'extra', label: 'Extra', description: 'auto_increment, DEFAULT_GENERATED, VIRTUAL GENERATED and similar.' },
+ { key: 'comment', label: 'Comment' },
+ ],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+};
+
+export const mysqlListIndexesOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'table', label: 'Table' },
+ {
+ key: 'indexes',
+ label: 'Indexes',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Name' },
+ { key: 'unique', label: 'Unique', format: 'boolean' },
+ { key: 'type', label: 'Type' },
+ { key: 'columns', label: 'Columns', description: 'Column names in index order.' },
+ ],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+};
+
+export const mysqlListViewsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'views',
+ label: 'Views',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Name' },
+ { key: 'updatable', label: 'Updatable', format: 'boolean' },
+ { key: 'securityType', label: 'Security Type' },
+ { key: 'definer', label: 'Definer' },
+ ],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+};
+
+export const mysqlGetViewDefinitionOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'view', label: 'View' },
+ { key: 'definition', label: 'Definition', description: 'The CREATE VIEW statement.' },
+ { key: 'characterSetClient', label: 'Character Set Client' },
+ { key: 'collationConnection', label: 'Collation Connection' },
+ ],
+};
+
+export const mysqlListRoutinesOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'routines',
+ label: 'Routines',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Name' },
+ { key: 'type', label: 'Type', description: 'PROCEDURE or FUNCTION.' },
+ { key: 'returns', label: 'Returns', description: 'Return type of a function; empty for procedures.' },
+ { key: 'comment', label: 'Comment' },
+ {
+ key: 'parameters',
+ label: 'Parameters',
+ labelKey: 'name',
+ listItems: [
+ { key: 'mode', label: 'Mode', description: 'IN, OUT or INOUT; empty for function parameters.' },
+ { key: 'name', label: 'Name' },
+ { key: 'type', label: 'Type' },
+ ],
+ },
+ ],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+};
+
+export const mysqlFindRowsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'rows', label: 'Rows', description: 'Matching rows; each row\'s fields are the columns of the table.' },
+ { key: 'count', label: 'Count', format: 'number', description: 'Rows on this page.' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+ { key: 'nextOffset', label: 'Next Offset', format: 'number', description: 'Offset for the next page; empty on the last page.' },
+ ],
+};
+
+export const mysqlGetRowByKeyOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'row', label: 'Row', description: 'The matching row; its fields are the columns of the table.' },
+ ],
+};
+
+export const mysqlCountRowsOutputSchema: OutputSchema = {
+ fields: [{ key: 'count', label: 'Count', format: 'number' }],
+};
+
+export const mysqlInsertRowsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'affectedRows', label: 'Inserted Rows', format: 'number' },
+ {
+ key: 'firstInsertId',
+ label: 'First Insert ID',
+ format: 'number',
+ description: 'Auto-increment id of the first inserted row (0 when the table has no auto-increment column).',
+ },
+ ],
+};
+
+export const mysqlUpsertRowOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'affectedRows', label: 'Affected Rows', format: 'number', description: '1 when a row was inserted, 2 when an existing row was updated.' },
+ { key: 'insertId', label: 'Insert ID', format: 'number', description: 'Auto-increment id of the inserted or updated row (0 when the table has none).' },
+ ],
+};
+
+export const mysqlUpdateRowsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'matchedRows', label: 'Matched Rows', format: 'number' },
+ { key: 'changedRows', label: 'Changed Rows', format: 'number', description: 'Matched rows whose values actually changed.' },
+ ],
+};
+
+export const mysqlDeleteRowsOutputSchema: OutputSchema = {
+ fields: [{ key: 'deletedRows', label: 'Deleted Rows', format: 'number' }],
+};
+
+export const mysqlRunSelectQueryOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'rows', label: 'Rows', description: 'Rows the query returned; each row\'s fields are the selected columns.' },
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean', description: 'True when the query produced more rows than Limit.' },
+ ],
+};
+
+export const mysqlExplainQueryOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'plan',
+ label: 'Plan',
+ description: 'EXPLAIN FORMAT=JSON output; its shape follows the query (tables, joins, subqueries).',
+ children: [
+ {
+ key: 'query_block',
+ label: 'Query Block',
+ children: [
+ { key: 'select_id', label: 'Select ID', format: 'number' },
+ { key: 'cost_info', label: 'Cost Info', children: [{ key: 'query_cost', label: 'Query Cost' }] },
+ ],
+ },
+ ],
+ },
+ ],
+};
+
+export const mysqlCallProcedureOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'resultSets', label: 'Result Sets', description: 'One list of rows per SELECT the procedure ran, in order.' },
+ { key: 'affectedRows', label: 'Affected Rows', format: 'number' },
+ { key: 'outParams', label: 'OUT Parameters', description: 'Final values of the OUT and INOUT parameters, keyed by parameter name.' },
+ ],
+};
+
+export const mysqlGetServerInfoOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'version', label: 'Version' },
+ { key: 'versionComment', label: 'Version Comment' },
+ { key: 'database', label: 'Database' },
+ { key: 'currentUser', label: 'Current User' },
+ { key: 'systemTimeZone', label: 'System Time Zone' },
+ { key: 'timeZone', label: 'Time Zone' },
+ { key: 'sqlMode', label: 'SQL Mode' },
+ { key: 'readOnly', label: 'Read Only', format: 'boolean' },
+ ],
+};
+
+export const mysqlListProcessesOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'processes',
+ label: 'Processes',
+ labelKey: 'id',
+ listItems: [
+ { key: 'id', label: 'ID', format: 'number' },
+ { key: 'user', label: 'User' },
+ { key: 'host', label: 'Host' },
+ { key: 'database', label: 'Database' },
+ { key: 'command', label: 'Command' },
+ { key: 'seconds', label: 'Seconds', format: 'number', description: 'Seconds in the current state.' },
+ { key: 'state', label: 'State' },
+ { key: 'statement', label: 'Statement' },
+ ],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+};