6.10.94-stable

PostgreSQL Client

@library("sql", "0.0.0");

This library provides an implementation of a Postgres client. The client allows you to interact with a PostgreSQL database, enabling you to execute queries, manage transactions, and import/export data in CSV format.

NOTE: For massive queries, please use the cursor based query_to_csv method instead of sending the query command by the execute method.

Type: Postgres

Represents the Postgres client.

Properties

  • url: String: The URL of the PostgreSQL server.
  • port: String: The port number of the PostgreSQL server.
  • db_name: String: The name of the PostgreSQL database.
  • login: String?: The login username for the PostgreSQL database. This field is optional.
  • password: String?: The password for the PostgreSQL database. This field is optional.

Methods

  • begin(): Begin a new transaction.
  • rollback(): Rollback the current transaction.
  • commit(): Commit the current transaction.
  • execute(query: String): any?: Execute a SQL query on the PostgreSQL database. If the query is a SELECT statement, the result(s) are returned, otherwise, null is returned.
  • csv_to_table(path: String, table_name: String, cols_name: Array<String>?, sep: char): Import data from a CSV file into a specified table. Optionally specify column names and the separator character.
  • query_to_csv(path: String, query: String, sep: char): Export the results of a SQL query to a CSV file using the specified separator character.

Be aware

The csv_to_table method requires the COPY command to be enabled in the PostgreSQL server. Make sure the user has the necessary permissions to use these commands. Also, COPY commands and transactions are mutually exclusive, make sure to terminate any ongoing transaction before using these methods.

Demo

@library("sql", "0.0.0");

use postgres;
use util;

use io;

fn main(){
    var pg = Postgres{
        url: "127.0.0.1", 
        port: "5432", 
        db_name: "example_db",
        login: "user",
        password: "password"
    };

    // Begin a new transaction
    pg.begin();
    
    // Execute a SQL query that returns the current timestamp
    var res = pg.execute("SELECT NOW();");

    // Commit the transaction
    pg.commit();

    // Import data from a CSV file into a table
    pg.csv_to_table("/path/to/file.csv", "example_table", null, ',');

    // Export the result of a query to a CSV file
    pg.query_to_csv("/path/to/output.csv", "SELECT * FROM example_table;", ',');
}