Module ibm.db2
ballerinax/ibm.db2 Ballerina library
Overview
This package provides the functionality required to access and manipulate data stored in an IBM Db2 database.
IBM Db2 is a family of relational database servers that runs on Linux, UNIX and Windows (Db2 LUW), on IBM Z (Db2 for z/OS) and on IBM i, as well as a managed service on IBM Cloud and AWS.
Key features
- Query, execute, batch execute and stored procedure calls (IN, OUT, INOUT parameters and multiple result sets)
- Local transactions and distributed (XA) transactions
- Connection pooling, with a global pool shared by all clients by default
- Db2 data types, including
DECFLOAT,GRAPHIC/VARGRAPHIC/DBCLOB,XML,BOOLEAN,BINARY/VARBINARY,FOR BIT DATAcolumns andTIMESTAMP(12) - Readable server error messages with the SQLSTATE and SQLCODE available as error details
- TLS and DRDA security mechanisms, including TLS client certificate authentication
- Compile-time validation of connection pool and timeout values
Prerequisites
-
An IBM Db2 server, version 11.1 or later. For local development, run the free Db2 Community Edition. The first start creates the instance and the database, which takes a few minutes.
docker run -d --name db2 --privileged -p 50000:50000 \ -e LICENSE=accept -e DB2INST1_PASSWORD=<password> -e DBNAME=SAMPLE \ icr.io/db2_community/db2:12.1.2.0 -
The IBM Data Server Driver for JDBC and SQLJ (JCC). The connector does not bundle it. IBM publishes it on Maven Central as
com.ibm.db2:jccunder the IBM International Program License Agreement, and every application adds it as a platform dependency of its own (step 2 of the quickstart).
Quickstart
Step 1: Import the connector
import ballerina/io; import ballerina/sql; import ballerinax/ibm.db2;
Step 2: Add the Db2 driver
Add the IBM JCC driver as a platform dependency in the Ballerina.toml file of the application. Ballerina downloads it from Maven Central and puts it on the class path of the executable.
[[platform.java21.dependency]] groupId = "com.ibm.db2" artifactId = "jcc" version = "12.1.5.0"
To use a driver jar from a Db2 installation instead, point path at the file: path = "./lib/db2jcc4.jar".
In a project that also uses ballerina/http, the build warns that the driver conflicts with lz4-java. The driver carries its own copy of the LZ4 classes, and the warning can be ignored.
Step 3: Create a client
configurable string host = ?; configurable int port = 50000; configurable string user = ?; configurable string password = ?; configurable string database = ?; final db2:Client dbClient = check new (host, user, password, database, port);
The database is required. For Db2 for z/OS, it is the location name.
Step 4: Run operations
type Employee record {| int id; string name; decimal salary; |}; public function main() returns error? { // Create a table _ = check dbClient->execute(` CREATE TABLE EMPLOYEE ( ID INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, NAME VARCHAR(50) NOT NULL, SALARY DECIMAL(10, 2) NOT NULL )`); // Insert a row. Values are sent as bind parameters. string name = "Ann"; decimal salary = 9500.00; sql:ExecutionResult result = check dbClient->execute( `INSERT INTO EMPLOYEE (NAME, SALARY) VALUES (${name}, ${salary})`); io:println("Inserted employee ", result.lastInsertId); // Read the inserted data stream<Employee, sql:Error?> employees = dbClient->query(`SELECT ID, NAME, SALARY FROM EMPLOYEE`); check from Employee e in employees do { io:println(e); }; check dbClient.close(); }
Connection options
db2:Options options = { currentSchema: "PAYROLL", // resolves unqualified table names clientProgramName: "payroll-sync", // shown in MON_GET_CONNECTION and `db2 list applications` loginTimeout: 10, socketTimeout: 60, queryTimeout: 30, // statements running longer are cancelled (SQLSTATE 57014) secureSocket: { // The host name used to connect must match a name in the server certificate, // unless `verifyHostName: false` is set. cert: {path: "truststore.p12", password: "changeit"} } }; db2:Client dbClient = check new (host, user, password, database, port, options);
When securityMechanism is not set, the driver negotiates it with the server, and on a plain connection the user ID and password can be sent in clear text. Set secureSocket so that the whole session is encrypted, or choose an encrypted mechanism such as ENCRYPTED_USER_AND_PASSWORD. Use CLEAR_TEXT_PASSWORD only together with secureSocket.
Any other JCC property can be passed through properties, for example client reroute settings or IBM Cloud IAM authentication:
db2:Options options = { properties: {"securityMechanism": 15, "pluginName": "IBMIAMauth", "apiKey": apiKey} };
Db2 specifics
Type mapping
| Db2 type | Ballerina type |
|---|---|
SMALLINT, INTEGER, BIGINT | int |
DECIMAL, NUMERIC | decimal |
DECFLOAT(16), DECFLOAT(34) | decimal (float or string for Infinity/NaN) |
REAL, DOUBLE | float |
CHAR, VARCHAR, CLOB, GRAPHIC, VARGRAPHIC, DBCLOB | string |
BINARY, VARBINARY, BLOB, CHAR/VARCHAR FOR BIT DATA | byte[] |
DATE | time:Date or string |
TIME | time:TimeOfDay or string |
TIMESTAMP(p) | time:Civil, time:Utc, string or int (nanosecond precision; picoseconds are truncated) |
BOOLEAN | boolean (int and string are accepted too) |
XML | xml |
Every sql:*Value typed parameter of the ballerina/sql module is supported except the array values. The following rules come from Db2 and its driver:
- Nulls. A
()or a typed null such asnew sql:DecimalValue()can be bound to a column of any type. - Instants. Db2 has no time zone types. A
time:Utcvalue, and atime:Civilvalue with autcOffset, are stored as the UTC wall clock time with their full precision. ATIMESTAMPcolumn read astime:Utcorint(epoch milliseconds) is interpreted as UTC, so these values round-trip. Atime:TimeOfDaywith autcOffsetis rejected becauseTIMEhas no zone. - Fractions of a second.
TIMEhas no fractional seconds: the fraction of atime:TimeOfDayis dropped and a string such as"10:11:12.5"fails withSQL0180N.TIMESTAMPwithout a precision isTIMESTAMP(6), so a value with nanoseconds needsTIMESTAMP(9)or more; Db2 truncates extra digits without an error. Reads keep at most nine digits, even asstring. To read all twelve digits of aTIMESTAMP(12)column, cast it in the query (SELECT VARCHAR(TS) AS TS ...) and read it asstring. NaNandInfinity. Afloatthat is not finite cannot be bound:DOUBLEandREALhave no such values, and the driver cannot bind them forDECFLOAT. The connector rejects them with a clear error; use the SQL literalDECFLOAT('NaN')instead. Reading such aDECFLOATvalue into adecimalfield is an error; usefloatorstring.- Numeric conversions. An
intorfloatbound to aDECIMALcolumn and adecimalbound to aDOUBLEcolumn are converted by the server. Adecimalbound to anINTEGERcolumn is truncated by the driver (12.7becomes12). A value too large for the column fails:SQL0302N(SQLSTATE22001/22003) from the server, or-4461from the driver for anintoutsideSMALLINTorINTEGER. - Lengths are in bytes.
CHAR,VARCHARandCLOBlengths count UTF-8 bytes, soVARCHAR(50)holds 12 emoji (48 bytes) but not 13.GRAPHIC,VARGRAPHICandDBCLOBlengths count UTF-16 code units (an emoji needs two).LENGTH()returns bytes; useCHARACTER_LENGTH(x, CODEUNITS32)for characters. - Arrays. The driver cannot bind arrays, so
int[],string[]and thesql:*ArrayValuetypes are rejected. Pass the elements as separate parameters:WHERE ID IN (${a}, ${b}). CHARandGRAPHICvalues come back blank padded to the column length.
Parameter markers need a type
Db2 has to know the type of every parameter marker. A parameter whose type cannot be derived from the statement fails with SQL0418N (SQLSTATE 42610), and a parameter passed to an overloaded function such as LENGTH(?) fails with SQL0245N, so add a cast:
// Fails: SELECT ? FROM SYSIBM.SYSDUMMY1 int value = check dbClient->queryRow(`SELECT CAST(${5} AS INT) FROM SYSIBM.SYSDUMMY1`);
Stored procedures
call supports IN, OUT and INOUT parameters and any number of result sets. Read the OUT parameters before closing the sql:ProcedureCallResult, because the values live in the statement.
Use the OUT parameter classes of this module for binary and XML values. The ballerina/sql classes convert their values in a way the Db2 driver does not support, and the connector rejects them with a message that names the replacement:
| Db2 parameter type | OUT parameter class |
|---|---|
BINARY, CHAR FOR BIT DATA | db2:BinaryOutParameter |
VARBINARY, VARCHAR FOR BIT DATA | db2:VarBinaryOutParameter |
BLOB | db2:BlobOutParameter |
XML | db2:XmlOutParameter (read as xml or string) |
DECFLOAT | sql:DecimalOutParameter; sql:DoubleOutParameter or sql:VarcharOutParameter for NaN and Infinity |
GRAPHIC, VARGRAPHIC, DBCLOB | sql:NCharOutParameter, sql:NVarcharOutParameter, sql:NClobOutParameter |
| every other type | the matching sql:*OutParameter |
db2:BlobOutParameter image = new; sql:ProcedureCallResult result = check dbClient->call(`CALL GET_IMAGE(${id}, ${image})`); byte[] bytes = check image.get(); check result.close();
An INOUT parameter takes its SQL type from the value passed in. A () has no type, so the parameter is registered as VARCHAR and its value comes back as a string; pass a typed null such as new sql:DecimalValue() to keep the type. An xml value passed to an INOUT parameter also comes back as a string. A NULL returned through an sql:BooleanOutParameter cannot be read, because get requires a boolean, int or string.
Db2 procedures are called with CALL or the JDBC escape {CALL ...}. Functions cannot be called with CALL; use VALUES MYFUNC(${x}) or SELECT instead.
Batch operations
All statements in a batchExecute call must have the same SQL text, so pass every changing value as a parameter, including identifiers such as ${id} rather than a literal 1. The statements are sent in chunks of 1,000, and a batch can run inside a transaction block.
string[] names = ["Ann", "Bob", "Cara"]; sql:ParameterizedQuery[] inserts = from string employee in names select `INSERT INTO EMPLOYEE (NAME, SALARY) VALUES (${employee}, ${5000.00d})`; sql:ExecutionResult[] results = check dbClient->batchExecute(inserts);
Bind values with the same type as the column (for example a decimal for a DECIMAL column): mixing an int value into a DECIMAL column makes the driver convert every row and made batches about 40% slower in our tests.
Db2 keeps executing after a failed statement. The sql:BatchExecuteError carries an affectedRowCount of -3 for each failed statement and the driver's batch failure code -4229; the rows that succeeded stay applied unless the batch runs in a transaction. The driver does not report the generated keys of a batch, so lastInsertId is () for batched inserts; a single execute does return the identity value.
Special characters
Pass every value as a parameter. Quotes, backslashes, newlines, NUL characters, %, _, comments, semicolons and SQL keywords in a parameter are stored as data and never change the statement. % and _ keep their meaning in LIKE, so escape them: V LIKE ${"100\\%"} ESCAPE '\'. Question marks, braces and colons inside string literals of the SQL text are passed through unchanged.
Identifiers are folded to upper case unless quoted. A quoted identifier with spaces, a keyword or non-ASCII letters is returned under that exact name, so a record field for it needs a quoted identifier too: record {| int 'my\ id; string 'select; |}.
Db2 accepts one statement per call. A second statement after a ; fails with SQL0104N.
Errors
The connector asks the server for the message text, so errors read like "DB2INST1.ORDERS" is an undefined name instead of only an SQLCODE. The SQLSTATE and SQLCODE are available in the error detail:
sql:ExecutionResult|sql:Error result = dbClient->execute(`INSERT INTO ORDERS VALUES (${id})`); if result is sql:DatabaseError { int sqlCode = result.detail().errorCode; // e.g. -803 string? sqlState = result.detail().sqlState; // e.g. "23505" }
Examples
The examples directory shows how to use the connector:
- Basic operations - Create a table, insert, query, update and delete records.
- Stored procedures and transactions - Call a stored procedure with OUT parameters and a result set, and group statements in a transaction.
Import
import ballerinax/ibm.db2;Other versions
1.0.0