Edits history of script submission #6002 for ' Execute arbitrary Query in Bun (postgresql)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    import * as wmill from 'windmill-client';
    import { Client } from 'pg';
    
    // Define the resource type as specified
    type Postgresql = {
      host: string,
      port: number,
      user: string,
      dbname: string,
      sslmode: string,
      password: string,
      root_certificate_pem: string
    }
    
    // The main function that will execute a query on a Postgresql database
    export async function main(query = 'SELECT * FROM demo', pg_resource: Postgresql) {
      // Initialize the PostgreSQL client with SSL configuration disabled for strict certificate validation
      const client = new Client({
        host: pg_resource.host,
        port: pg_resource.port,
        user: pg_resource.user,
        password: pg_resource.password,
        database: pg_resource.dbname,
        ssl: pg_resource.ssl,
      });
    
      try {
        // Connect to the database
        await client.connect();
    
        // Execute the query
        const res = await client.query(query);
    
        // Close the connection
        await client.end();
    
        // Return the query result
        return res.rows;
      } catch (error) {
        console.error('Database query failed:', error);
        // Rethrow the error to handle it outside or log it appropriately
        throw error;
      }
    }

    Submitted by hugo697 373 days ago

  • bun
    import * as wmill from 'windmill-client';
    import { Client } from 'pg';
    
    // Define the resource type as specified
    type Postgresql = {
      host: string,
      port: number,
      user: string,
      dbname: string,
      sslmode: string,
      password: string,
      root_certificate_pem: string
    }
    
    // The main function that will execute a query on a Postgresql database
    export async function main(query = 'SELECT * FROM demo', pg_resource: Postgresql) {
      // Initialize the PostgreSQL client with SSL configuration disabled for strict certificate validation
      const client = new Client({
        host: pg_resource.host,
        port: pg_resource.port,
        user: pg_resource.user,
        password: pg_resource.password,
        database: pg_resource.dbname,
        ssl: pg_resource.ssl,
      });
    
      try {
        // Connect to the database
        await client.connect();
    
        // Execute the query
        const res = await client.query(query);
    
        // Close the connection
        await client.end();
    
        // Return the query result
        return res.rows;
      } catch (error) {
        console.error('Database query failed:', error);
        // Rethrow the error to handle it outside or log it appropriately
        throw error;
      }
    }

    Submitted by henri186 794 days ago