0
Execute arbitrary Query in Deno
One script reply has been approved by the moderators Verified

Execute an arbitrary query on a MySQL resource, more at: https://www.windmill.dev/docs/getting_started/scripts_quickstart/sql

Created by henri186 255 days ago Viewed 9209 times
0
Submitted by henri186 Deno
Verified 255 days ago
1
import { createPool as createMysqlPool } from "npm:mysql2/promise";
2

3
// Define the MySQL resource type as specified
4
type Mysql = {
5
  ssl: boolean,
6
  host: string,
7
  port: number,
8
  user: string,
9
  database: string,
10
  password: string
11

12
}
13

14
// The main function that executes a query on a MySQL database
15
export async function main(
16
  mysqlResource: Mysql,
17
  query: string,
18
): Promise<any> {
19
  // Adjust the SSL configuration based on the mysqlResource.ssl value
20
  const sslConfig = mysqlResource.ssl ? { rejectUnauthorized: true } : false;
21

22
  // Create a new connection pool using the provided MySQL resource
23
  const pool = createMysqlPool({
24
    host: mysqlResource.host,
25
    user: mysqlResource.user,
26
    database: mysqlResource.database,
27
    password: mysqlResource.password,
28
    port: mysqlResource.port,
29
    // Use the adjusted SSL configuration
30
    ssl: sslConfig,
31
    waitForConnections: true,
32
    connectionLimit: 10,
33
    queueLimit: 0,
34
  });
35

36
  try {
37
    // Get a connection from the pool and execute the query
38
    const [rows] = await pool.query(query);
39
    return rows;
40
  } catch (error) {
41
    // If an error occurs, throw it to be handled by the caller
42
    throw new Error(`Failed to execute query: ${error}`);
43
  } finally {
44
    // Always close the pool after the operation is complete
45
    await pool.end();
46
  }
47
}