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

5.6 KB
Raw Blame
import { ApFile, createAction, Property } from '@activepieces/pieces-framework';

import { DuckDBInstance } from '@duckdb/node-api';
import { quotedIdentifier } from '@duckdb/node-api/lib/sql';
import { parse as parseCsv } from 'csv-parse/sync';

export const createAndQueryDB = createAction({
  name: 'createAndQueryDB',
  displayName: 'Create and Query DB',
  description: 'Create DB from data and run query',
  audience: 'human',
  props: {
    markdown: Property.MarkDown({
      value: `
      **DO NOT** insert dynamic input directly into the query string. Instead, use $1, $2, $3 and add them in args for parameterized queries to prevent **SQL injection.**`,
    }),
    tables: Property.Array({
      displayName: 'Tables',
      description: 'List of tables to create in the database',
      required: true,
      properties: {
        name: Property.ShortText({
          displayName: 'Table Name',
          description: 'Name of the table to create',
          required: true,
        }),
        data: Property.Json({
          displayName: 'JSON Data',
          description:
            'Table data as a JSON array of objects. Object keys are taken as column names. Takes priority over the file below if set.',
          required: false,
          defaultValue: [],
        }),
        file: Property.File({
          displayName: 'CSV/JSON File',
          description:
            'Upload a CSV or JSON file as the table source, used only if JSON Data above is empty. Format is detected from the file extension.',
          required: false,
        }),
        schema: Property.Json({
          displayName: 'Schema in JSON format',
          description: `
Provide the schema as a JSON object. Note that only the specified columns would be loaded.
Leave empty to autodetect schema, although it is recommended to specify the schema for consistency and avoid unexpected behaviour.

A column type that doesn't match the actual shape of the row data (e.g. a STRUCT/array type for a column that's a plain string, which is always the case for CSV-sourced tables) silently loads as null instead of erroring - double check this against autodetected schema if a column is unexpectedly empty.

More information on data types and accepted values:
- https://duckdb.org/2023/03/03/json
- https://duckdb.org/docs/stable/sql/data_types/overview
          `.trim(),
          required: false,
          defaultValue: {},
        }),
        keepNestedFields: Property.Checkbox({
          displayName: 'Keep Nested Fields',
          description:
            'When off, a nested object/struct field is split into individual top-level columns (e.g. "meta": {"a":1} becomes column "a"). Turn on to keep it as a single nested column instead, queryable with dot notation (e.g. "meta.a").',
          required: false,
          defaultValue: false,
        }),
      },
    }),
    query: Property.ShortText({
      displayName: 'Query',
      description:
        'Please use $1, $2, etc. for parameterized queries to avoid SQL injection.',
      required: true,
    }),
    args: Property.Array({
      displayName: 'Arguments',
      description: 'Arguments to be used in the query',
      required: false,
    }),
  },
  async run(context) {
    const instance = await DuckDBInstance.create(':memory:');
    const connection = await instance.connect();

    await connection.run(`
      SET enable_logging = 0;
      SET enable_external_access = false;
      SET lock_configuration = true;
    `);

    const dbTables: any[] = context.propsValue.tables ?? [];
    for (const dbTable of dbTables) {
      const tableName = quotedIdentifier(dbTable.name);
      const dbData = JSON.stringify(resolveTableRows(dbTable));
      let dbSchema = null;

      const hasSchema = dbTable.schema && Object.keys(dbTable.schema).length > 0;
      if (hasSchema) {
        dbSchema = JSON.stringify([dbTable.schema]);
      } else {
        const schemaResult = await connection.run(
          'SELECT json_structure($sourceData) AS schema',
          { sourceData: dbData }
        );

        const detectedSchema = await schemaResult.getRows();
        dbSchema = detectedSchema[0][0];
      }

      const shouldFlatten = !dbTable.keepNestedFields;
      const createTableQuery = shouldFlatten
        ? `
          CREATE TABLE ${tableName} AS
            SELECT UNNEST(JSON_TRANSFORM($sourceData, $sourceSchema), recursive := true);
        `
        : `
          CREATE TABLE ${tableName} AS
            SELECT row.* FROM (SELECT UNNEST(JSON_TRANSFORM($sourceData, $sourceSchema)) AS row) t;
        `;

      await connection.run(createTableQuery, {
        sourceData: dbData,
        sourceSchema: dbSchema,
      });
    }

    const queryArgs = context.propsValue.args ?? [];
    const formattedArgs: Record<string, any> = {};
    for (let i = 0; i < queryArgs.length; i++) {
      const idx = (i + 1).toString();
      formattedArgs[idx] = queryArgs[i];
    }

    const reader = await connection.runAndReadAll(
      context.propsValue.query,
      formattedArgs
    );

    const results = reader.getRowObjectsJson();

    connection.closeSync();

    return results;
  },
});

function resolveTableRows(dbTable: { data?: unknown; file?: ApFile }): unknown {
  if (Array.isArray(dbTable.data) ? dbTable.data.length > 0 : dbTable.data) {
    return dbTable.data;
  }

  if (!dbTable.file) {
    return dbTable.data;
  }

  const text = dbTable.file.data.toString('utf-8');
  return dbTable.file.extension?.toLowerCase() === 'csv'
    ? parseCsv(text, {
        columns: true,
        skip_empty_lines: true,
        bom: true,
        relax_column_count: true,
      })
    : JSON.parse(text.replace(/^/, ''));
}