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

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

Created by henri186 286 days ago Viewed 8607 times
0
Submitted by henri186 Bun
Verified 286 days ago
1
import * as wmill from 'windmill-client';
2
import { Client } from 'pg';
3

4
// Define the resource type as specified
5
type Postgresql = {
6
  host: string,
7
  port: number,
8
  user: string,
9
  dbname: string,
10
  sslmode: string,
11
  password: string,
12
  root_certificate_pem: string
13
}
14

15
// The main function that will execute a query on a Postgresql database
16
export async function main(query = 'SELECT * FROM demo', pg_resource: Postgresql) {
17
  // Initialize the PostgreSQL client with SSL configuration disabled for strict certificate validation
18
  const client = new Client({
19
    host: pg_resource.host,
20
    port: pg_resource.port,
21
    user: pg_resource.user,
22
    password: pg_resource.password,
23
    database: pg_resource.dbname,
24
    ssl: pg_resource.ssl,
25
  });
26

27
  try {
28
    // Connect to the database
29
    await client.connect();
30

31
    // Execute the query
32
    const res = await client.query(query);
33

34
    // Close the connection
35
    await client.end();
36

37
    // Return the query result
38
    return res.rows;
39
  } catch (error) {
40
    console.error('Database query failed:', error);
41
    // Rethrow the error to handle it outside or log it appropriately
42
    throw error;
43
  }
44
}
Other submissions