0
Execute arbitrary Query in Bun
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 238 days ago Viewed 8363 times
0
Submitted by henri186 Bun
Verified 238 days ago
1
import { createConnection } from 'mysql';
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
// The main function that will execute a query on a Mysql resource
14
export async function main(mysqlResource: Mysql, query: string): Promise<any> {
15
  // Create a promise to handle the MySQL connection and query execution
16
  return new Promise((resolve, reject) => {
17
    // Create a connection to the MySQL database using the resource credentials
18
    const connection = createConnection({
19
      host: mysqlResource.host,
20
      port: mysqlResource.port,
21
      user: mysqlResource.user,
22
      password: mysqlResource.password,
23
      database: mysqlResource.database,
24
      ssl: mysqlResource.ssl
25
    });
26

27
    // Connect to the MySQL database
28
    connection.connect(err => {
29
      if (err) {
30
        reject(err);
31
        return;
32
      }
33

34
      // Execute the query provided as a parameter
35
      connection.query(query, (error, results) => {
36
        // Close the connection after the query execution
37
        connection.end();
38

39
        if (error) {
40
          reject(error);
41
        } else {
42
          resolve(results);
43
        }
44
      });
45
    });
46
  });
47
}