Skip to main content

Actions

The PostgreSQL connector is distributed across two libraries:

  • ballerinax/postgresql
  • ballerinax/postgresql.driver

Available clients:

ClientPurpose
ClientProvides standard SQL operations against a PostgreSQL database: query, single-row query, execute (DML/DDL), batch execute, stored procedure call, and connection management.

For event-driven integration, see the Trigger Reference.


Client

Provides standard SQL operations against a PostgreSQL database: query, single-row query, execute (DML/DDL), batch execute, stored procedure call, and connection management.

Configuration

FieldTypeDefaultDescription
hoststring"localhost"PostgreSQL server hostname or IP address.
usernamestring?"postgres"Database username.
passwordstring?()Database password.
databasestring?()Name of the database to connect to.
portint5432PostgreSQL server port.
optionsOptions?()Advanced PostgreSQL-specific connection options (SSL, timeouts, prepared statement caching, and more).
connectionPoolsql:ConnectionPool?()Connection pool configuration. If not provided, the global shared pool is used.

Initializing the client

import ballerinax/postgresql;
import ballerinax/postgresql.driver as _;

configurable string host = ?;
configurable string username = ?;
configurable string password = ?;
configurable string database = ?;
configurable int port = 5432;

postgresql:Client dbClient = check new (
host = host,
username = username,
password = password,
database = database,
port = port
);

Operations

Query operations

query

Executes a SQL SELECT query and returns multiple results as a stream of records.

Parameters:

NameTypeRequiredDescription
sqlQuerysql:ParameterizedQueryYesSQL query with optional parameters (for example, `SELECT * FROM customers WHERE country = ${country}`).
rowTypetypedesc<record {}>NoRecord type to map query results to.

Returns: stream<rowType, sql:Error?>

Sample code:

type Customer record {|
int customerId;
string firstName;
string lastName;
int registrationId;
float creditLimit;
string country;
|};

stream<Customer, sql:Error?> resultStream = dbClient->query(`SELECT * FROM Customers`);

Sample response:

{"customerId": 1, "firstName": "Peter", "lastName": "Stuart", "registrationId": 1, "creditLimit": 5000.75, "country": "USA"}
{"customerId": 2, "firstName": "Dan", "lastName": "Brown", "registrationId": 2, "creditLimit": 10000.00, "country": "UK"}
queryRow

Executes a SQL query expected to return a single row or a scalar value. Returns sql:NoRowsError if no results are found.

Parameters:

NameTypeRequiredDescription
sqlQuerysql:ParameterizedQueryYesSQL query expected to return one row or value.
returnTypetypedesc<anydata>NoExpected return type: a record for a full row, or a primitive type for a scalar value.

Returns: returnType|sql:Error

Sample code:

type Customer record {|
int customerId;
string firstName;
string lastName;
int registrationId;
float creditLimit;
string country;
|};

int customerId = 1;
Customer customer = check dbClient->queryRow(
`SELECT * FROM Customers WHERE customerId = ${customerId}`
);

Sample response:

{"customerId": 1, "firstName": "Peter", "lastName": "Stuart", "registrationId": 1, "creditLimit": 5000.75, "country": "USA"}

Execute operations

execute

Executes a SQL DDL or DML statement (CREATE, INSERT, UPDATE, DELETE) and returns execution metadata.

Parameters:

NameTypeRequiredDescription
sqlQuerysql:ParameterizedQueryYesSQL statement with optional parameters.

Returns: sql:ExecutionResult|sql:Error

Sample code:

sql:ExecutionResult result = check dbClient->execute(
`INSERT INTO Customers (firstName, lastName, registrationId, creditLimit, country)
VALUES (${"Peter"}, ${"Stuart"}, ${1}, ${5000.75}, ${"USA"})`
);

Sample response:

{"affectedRowCount": 1, "lastInsertId": 1}
batchExecute

Executes a batch of parameterized SQL statements in a single call, useful for bulk inserts or updates.

Parameters:

NameTypeRequiredDescription
sqlQueriessql:ParameterizedQueryYesArray of parameterized SQL statements to execute as a batch.

Returns: sql:ExecutionResult[]|sql:Error

note

Passing an empty array returns an sql:ApplicationError. Filter or guard upstream if your input may be empty.

Sample code:

var customers = [
{firstName: "Peter", lastName: "Stuart", country: "USA"},
{firstName: "Dan", lastName: "Brown", country: "UK"},
{firstName: "Anna", lastName: "Lee", country: "SG"}
];

sql:ParameterizedQuery[] batch = from var c in customers
select `INSERT INTO Customers (firstName, lastName, country)
VALUES (${c.firstName}, ${c.lastName}, ${c.country})`;

sql:ExecutionResult[] results = check dbClient->batchExecute(batch);

Sample response:

[{"affectedRowCount": 1, "lastInsertId": 1}, {"affectedRowCount": 1, "lastInsertId": 2}, {"affectedRowCount": 1, "lastInsertId": 3}]

Stored procedures

call

Calls a stored procedure or function and returns result sets and output parameter values.

Parameters:

NameTypeRequiredDescription
sqlQuerysql:ParameterizedCallQueryYesStored procedure call query (for example, `CALL InsertStudent(${id}, ${name}, ${age})`).
rowTypestypedesc<record {}>[]NoArray of record types for mapping result sets returned by the procedure.

Returns: sql:ProcedureCallResult|sql:Error

Sample code:

int personId = 1;
string personName = "Alice";
int personAge = 25;

sql:ProcedureCallResult result = check dbClient->call(
`CALL InsertStudent(${personId}, ${personName}, ${personAge})`
);
result.close();

Sample response:

{"executionResult": {"affectedRowCount": 1}, "queryResult": null}

Connection management

close

Closes the client and releases the associated connection pool (if not shared by other clients). Call this only at the end of the application lifetime.

Returns: sql:Error?

Sample code:

check dbClient.close();

Supporting types

Options

Advanced PostgreSQL connection options. Passed to Client.init through the options parameter.

FieldTypeDefaultDescription
sslSecureSocket?()SSL/TLS security settings.
connectTimeoutdecimal0Connection timeout in seconds. 0 means the JDBC driver default (typically no timeout).
socketTimeoutdecimal0Socket read/write timeout in seconds (0 means no timeout).
loginTimeoutdecimal0Time, in seconds, allowed to complete the database login (0 means no timeout).
rowFetchSizeint?()Number of rows to fetch in a single round trip when streaming results.
cachedMetadataFieldsCountint?()Number of fields cached per connection.
cachedMetadataFieldSizeint?()Size, in bytes, of metadata fields cached per connection.
preparedStatementThresholdint?()Number of PreparedStatement executions required before switching to a server-side prepared statement.
preparedStatementCacheQueriesint?()Maximum number of prepared statements cached per connection.
preparedStatementCacheSizeint?()Maximum size, in mebibytes, of the prepared statement cache per connection.
cancelSignalTimeoutdecimal10Time, in seconds, by which the cancel command is sent out of band over its own connection.
keepAliveTcpProbeboolean?()Enable TCP keep-alive probes on the socket.
binaryTransferboolean?()Use the binary protocol for sending and receiving data when supported.
currentSchemastring?()The schema to be used by the client.

SecureSocket

FieldTypeDefaultDescription
modeSSLModePREFERSSL mode (see below).
rootcertstring?()File name of the SSL root certificate. Defaults to ${user.home}/.postgresql/root.crt on Unix or %appdata%/postgresql/root.crt on Windows.
keycrypto:KeyStore|CertKey?()Client certificate configuration. Use a crypto:KeyStore for JKS or PKCS#12 keystores, or a CertKey record for PEM files.

CertKey

Represents a client certificate, private key, and optional key password loaded from PEM files. Use as an alternative to crypto:KeyStore in SecureSocket.key.

FieldTypeDefaultDescription
certFilestringRequiredPath to the file containing the client certificate.
keyFilestringRequiredPath to the file containing the client private key.
keyPasswordstring?()Password for the private key, if it is encrypted.

SSLMode

The supported SSL connection modes:

ConstantValueDescription
PREFER"PREFER"Try an encrypted connection first and fall back to unencrypted if the server does not support it.
REQUIRE"REQUIRE"Require an encrypted connection. Does not verify the server certificate.
DISABLE"DISABLE"Establish an unencrypted connection.
ALLOW"ALLOW"Try an unencrypted connection first and fall back to an encrypted one if the server requires it.
VERIFY_CA"VERIFY-CA"Require an encrypted connection and verify the server CA certificate.
VERIFY_FULL"VERIFY-FULL"Require an encrypted connection, verify the CA, and verify the server hostname.

sql:ConnectionPool

Connection pool configuration is provided by the parent ballerina/sql library. See the sql:ConnectionPool API reference for the full field list and pool-handling semantics.