NAME
DBIO::DB2::Storage - IBM DB2 support for DBIO
VERSION
version 0.900007
DESCRIPTION
Storage driver for IBM DB2 databases. Handles autoincrement column retrieval via IDENTITY_VAL_LOCAL(), queries the server name separator from DBI, and sets the datetime parser to DBIO::DB2::Storage::DateTimeFormat (DateTime::Format::DB2 with a working parse_time).
Uses DBIO::DB2::SQLMaker for SQL generation with DB2-specific LIMIT/OFFSET support (ROW_NUMBER() OVER() for OFFSET, FETCH FIRST n ROWS ONLY otherwise).
Existence queries
"results_exist" in DBIO::ResultSet and its two siblings work here because this class declares the supports_exists_query capability (ADR 0037). Core defaults that capability to 0 and throws on all three methods without it, rather than degrading silently to "has_rows" in DBIO::ResultSet -- which stays the portable alternative for callers that must also run against a driver which has not declared it.
Declaring it alone would not be enough: core's base rendering of "_exists_value_sql" in DBIO::Storage::DBI is SELECT CASE WHEN EXISTS <inner> THEN 1 ELSE 0 END, a SELECT with no FROM clause, and DB2's subselect has no FROM-less form. The override appends FROM SYSIBM.SYSDUMMY1 -- the one-row catalog view IBM provides for exactly this, "for SQL statements in which a table reference is required, but the contents of the table are not important" (SQL Reference, SYSIBM.SYSDUMMY1) -- and leaves the CASE spelling to core, so there is one copy of it. It is the same table _dbh_last_insert_id already selects IDENTITY_VAL_LOCAL() from (ADR 0002), and both now read the name from "_dummy_table" rather than spelling it twice.
The CASE half needs nothing from this driver: a searched CASE's WHEN takes a search-condition, and EXISTS is a predicate, so core's base spelling is already the DB2 one -- only the missing FROM was ever the gap.
Set operations: all six, and no keyword to declare
This driver overrides nothing in "_set_operation_keyword" in DBIO::Storage::DBI: DB2 has all six set operations and spells each of them the ANSI way core's base map already answers with, so all of union, union_all, intersect, intersect_all, except and except_all are inherited (ADR 0039). That is a finding, not an omission, and t/51-set-operations.t pins all six so it can fail if it ever stops being true.
Sourced rather than assumed: the fullselect production in the Db2 for Linux, UNIX and Windows SQL Reference offers UNION | UNION ALL | EXCEPT | EXCEPT ALL | INTERSECT | INTERSECT ALL, and does so unchanged from 9.7 (2009) through 12.1. Db2 for z/OS 12 documents the same six.
DB2 also accepts MINUS: "For compatibility with other SQL implementations, MINUS can be specified as a synonym for EXCEPT" (same section, both platforms). That widens what the parser takes; it does not change what the engine is spelled. EXCEPT is the primary spelling of the syntax diagram in every documented version and there is no mode in which it stops being one, so there is no second per-engine spelling here for _set_operation_keyword to carry.
Db2 for i is the one Db2 that does not have all six -- its fullselect offers UNION [DISTINCT|ALL] but only EXCEPT [DISTINCT] and INTERSECT [DISTINCT], with no ALL form of either and no MINUS synonym (IBM i 7.5 SQL Reference, fullselect). It is not refused here because it is not a platform this distribution supports at all: every introspection and deployment query in DBIO::DB2::Introspect and DBIO::DB2::Deploy reads the SYSCAT catalog views, which exist on Db2 LUW and on neither Db2 for i nor Db2 for z/OS. Refusing except_all and intersect_all outright -- the only shape ADR 0039 section 7 would allow, since the platform is no more askable without a connection than a version is -- would withdraw two working operations from every server this driver can actually be used against, to protect one it cannot.
Random ordering
"rand" in DBIO::ResultSet asks the storage which function this engine spells "give me a random number" with ("_random_function" in DBIO::Storage::DBI) and drops the answer into an order_by literal. Core answers RANDOM(), which is right on PostgreSQL and SQLite and which the Db2 for Linux, UNIX and Windows SQL Reference does not document at all -- there is no such routine for the name to resolve to, and the server says so (SQL0440N, SQLSTATE 42884: no authorized routine of that name was found). This class overrides the hook with RAND(), the SYSFUN scalar function that Reference does document.
The parentheses stay, unlike Oracle's argument-less DBMS_RANDOM.VALUE: RAND is an ordinary scalar function and its zero-argument form is still an invocation. No seed is passed, and that is deliberate rather than an omission: "A specific seed value produces the same sequence of random numbers for a specific instance of a RAND function in a query each time the query is executed" (SQL Reference, RAND (SYSFUN schema) scalar function), so a seeded ORDER BY is a repeatable order -- the one thing "rand" in DBIO::ResultSet must not be.
Db2 for z/OS is the one platform of the family where core's inherited answer would have worked: it documents RANDOM as a synonym of RAND. LUW is the platform this distribution supports (its whole introspection path reads SYSCAT, see above), so the LUW spelling is the one that counts here.
RAND() is evaluated per row. The Reference calls it "a non-deterministic function" and says the seed "is used only for the first invocation of an instance of the RAND function within a statement", which describes a function invoked repeatedly within one statement, but no documented sentence says outright that ORDER BY RAND() shuffles -- so it is measured instead: the live half of t/52-explain-query.t saw four runs come back in different orders on Db2 12.1.5. The failure mode this guards against is silent, not loud: an engine that evaluated its random function once per statement would sort every row by the same number and $rs->rand would quietly return an unshuffled prefix.
Query plans
"explain" in DBIO::ResultSet asks the storage for the whole operation of obtaining a query plan through "_explain_query" in DBIO::Storage::DBI (ADR 0040, which replaced the string-valued _explain_sql). DB2 is one of the engines that argument was made for: obtaining a plan here is two statements, and this class overrides the hook with both of them.
The first is EXPLAIN PLAN SELECTION FOR <query>, carrying the query's own bind values -- "if EXPLAIN is being dynamically prepared, the explainable-sql-statement can contain parameter markers" (SQL Reference, EXPLAIN statement). PLAN SELECTION rather than the bare PLAN Oracle uses: on LUW the Reference marks PLAN as supported "only for syntax toleration of existing Db2 for z/OS EXPLAIN statements. There is no PLAN table", equivalent to PLAN SELECTION, which is the native spelling and the one this driver emits.
That statement answers with nothing. It writes the access plan into the EXPLAIN_* tables, and the statement it explains "is not executed" (same topic), so the plan comes from a second statement of this driver's own, which core never rendered and knows nothing about:
SELECT OPERATOR_ID, OPERATOR_TYPE, TOTAL_COST, IO_COST, CPU_COST
FROM SYSTOOLS.EXPLAIN_OPERATOR
WHERE EXPLAIN_REQUESTER = SESSION_USER
AND EXPLAIN_TIME = (SELECT MAX(EXPLAIN_TIME) FROM SYSTOOLS.EXPLAIN_OPERATOR
WHERE EXPLAIN_REQUESTER = SESSION_USER)
ORDER BY OPERATOR_ID
one row per plan operator, in operator order, with the optimizer's cost columns (EXPLAIN_OPERATOR table, SQL Reference). DB2 has no in-SQL formatter to hand the way Oracle has DBMS_XPLAN.DISPLAY: its formatters, db2exfmt and db2expln, are OS commands outside DBI entirely, and IBM's own documentation points at writing a query against the explain tables instead. The plan tree -- which operator feeds which -- lives in EXPLAIN_STREAM and is not folded in here; ADR 0040 section 2 already says the contents of these rows are engine-specific and that nothing in DBIO normalises them.
Both statements go through "_execute_rendered" in DBIO::Storage::DBI, which the contract requires without engine-named exceptions. That is what keeps tracing and therefore "redact_bind_value" in DBIO::Storage::DBI (ADR 0025) over the query's own bind values, dbh_do retry over a dropped connection, DBIO::Storage::DBI::NoBindVars interpolation, and -- on a DBIO::Replicated::Storage -- the read handler instead of the master's.
What the session needs, and what happens when it does not have it
The explain tables must already exist; nothing here creates them. IBM's preferred route is
CALL SYSPROC.SYSINSTALLOBJECTS('EXPLAIN', 'C',
CAST (NULL AS VARCHAR(128)), CAST (NULL AS VARCHAR(128)))
which creates them under SYSTOOLS; EXPLAIN.DDL from the instance's sqllib/misc creates them under the current schema instead. Without them the first statement fails (SQLSTATE 42704 -- the Reference's own Example 4 is this case) and the exception propagates out of $rs->explain: there is no degraded mode answering an empty plan.
Which schema the second statement reads is "explain_table_schema", SYSTOOLS by default, because that is where SYSINSTALLOBJECTS puts them and where the Explain facility looks when the session's own schema has none. A session whose own schema carries explain tables must set it, since the facility then writes there: reading the wrong set is the one failure here that can be quiet rather than loud -- loud (SQLSTATE 42704) if the configured schema has no explain tables at all, quiet if it has some, holding somebody else's plan.
The plan is written at compile time, which is why caching is off
"For dynamic EXPLAIN statements, the explain tables are populated at the time the EXPLAIN statement is submitted for compilation. An EXPLAIN statement can be prepared with the PREPARE statement but, if executed, will perform no processing" (SQL Reference, EXPLAIN statement). The prepare does the work; the execute is a successful no-op. So _explain_query turns "disable_sth_caching" in DBIO::Storage::DBI on for the duration of the pair: DBI's prepare_cached hands back a cached handle without preparing again, which on this engine means no new plan is written -- and the read-back, which can only ask for the newest plan, would then answer with whatever was explained last. Identical statement, identical plan, no error: exactly the silent wrong answer that is worth a line of code to avoid.
What is verified, and what is not
The seam is verified against core's source: the hook's name and signature, that _explain_sql is gone rather than deprecated, that "explain" in DBIO::ResultSet strips as_query's parentheses before handing the statement over, and that t/52-explain-query.t sees both statements reach the storage layer.
DB2's half is not. No live server was available; every spelling above comes from the Db2 11.5 SQL Reference topics named beside it, and none of it has been executed against a server from this driver. Two things in particular are reasoned rather than observed: that EXPLAIN_OPERATOR is the closest in-SQL answer to what explain promises, and that keying the read-back on MAX(EXPLAIN_TIME) per SESSION_USER selects the plan just written -- the explain tables are ordinary persistent tables with no session column, so a concurrent explain by the same authorization ID in another session, landing between the two statements, would win that MAX. There is no narrower key to use: QUERYNO and QUERYTAG tag the row in EXPLAIN_STATEMENT but are neither unique nor carried on EXPLAIN_OPERATOR, so they would buy an eight-column join and no additional certainty.
METHODS
sql_name_sep
Returns the name separator character used by this DB2 server (e.g. .), queried from the server via SQL_QUALIFIER_NAME_SEPARATOR on first access.
_connect_params_dsn
The DSN seam of "_connect_params_dsn" in DBIO::Storage::DBI (ADR 0057), overridden because DBD::DB2 takes nothing of core's default form dbi:DB2:dbname=...;host=...;port=.... It connects in one of two ways, and which one the connection parameters mean is decided by host:
cataloged --
dbnamealonedbi:DB2:<dbname>dbnameis a database alias the client's database directory resolves; where the server is, the catalog knows.uncataloged --
dbname,hostandportdbi:DB2:DATABASE=<dbname>;HOSTNAME=<host>;PORT=<port>;PROTOCOL=TCPIPa CLI connection string naming the server itself. User and password are not put into it as
UID=/PWD=: they stay the arguments ofDBI->connect, as with every other connect form.
Everything else refuses rather than guess, each error naming what is missing and the ways out:
hostwithoutport. DB2 has no implied port -- an instance listens on whatever itsSVCENAMEsays -- so there is none to default to.portwithouthost. Beside a cataloged alias a port means nothing: the catalog's node entry holds it. Dropping the one given would connect to wherever the catalog says, silently.no
dbname. Both forms need it; there is no default database.
Anything these three parts cannot say -- SECURITY=SSL, any further CLI keyword -- goes in as the whole DSN: as dsn, or as a dbname that starts with dbi:DB2: (DBIO::AccessBroker::Static passes it on), which core takes as the DSN before this seam is asked.
Verified against a server (Db2 12.1.5, DBD::DB2 1.92 on the IBM CLI driver; t/54-connect-params-dsn-live.t): the driver accepts both strings exactly as built here -- the uncataloged form without the spaces and the trailing ; its own example carries, the cataloged form with the alias resolved from a db2dsdriver.cfg. An alias out of a full client's database directory (db2 catalog database) was not seen; the CLI driver has no such directory.
_bind_host_into_dsn
The HostBound seam of "_bind_host_into_dsn" in DBIO::Storage::DBI (core ADR 0013 addendum), overridden because core's default knows host=/port= and declines DB2's HOSTNAME=.
dbi:DB2:DATABASE=d;HOSTNAME=h;PORT=50000;PROTOCOL=TCPIP
The rule: the parts after dbi:DB2: must all be key=value, and one of them must be HOSTNAME (keys are case-insensitive; their spelling is kept). HOSTNAME= takes the view's host where it stands. PORT= takes the view's port where it stands; when the view has a port and the DSN has no PORT=, one is put right after HOSTNAME=, and when the view has no port the DSN's PORT= stays. Nothing else is touched -- PROTOCOL= is not invented.
It declines, naming the form and never a value of the DSN:
a DSN without a
dbi:Driver:prefix;a part that is not
key=value;a DSN without
HOSTNAME=-- a cataloged alias (dbi:DB2:testdb) leaves the server to the client's catalog, so there is nothing to rebind.
_connect
Wraps the HandleError that DBIO::Storage::DBI installs on every handle, so that a server warning is not an exception (ADR 0007).
DBD::DB2 reports SQL_SUCCESS_WITH_INFO the way it reports an error: it sets err to a true value, where the DBI contract has "0" or "" for a warning. With RaiseError and core's handler the statement that just ran then throws. The case that was measured (Db2 12.1.5, DBD::DB2 1.92) is a DELETE or UPDATE without a WHERE clause:
DELETE FROM "t" -- rv 3, err 513, SQLSTATE 01504,
-- SQL0513W The SQL statement will modify an entire
-- table or view
The rows are deleted, $rs->delete on an unrestricted resultset threw all the same, and inside a txn_do the exception rolled the delete back.
SQLSTATE says which of the two a message is. Class 01 is "completed, with a warning", so the wrapper answers a message of that class as handled and hands every other one to core's handler, which throws DBI Exception: ... as before. Three things follow, and they are meant:
The warning is silent. Nothing is printed and nothing is thrown. It is not lost:
err,stateanderrstrstay on the handle until its next call, for a caller who wants to know.my $rows = $storage->dbh_do(sub { my ($storage, $dbh) = @_; my $rv = $dbh->do('DELETE FROM "t"'); warn $dbh->errstr if $dbh->state =~ /^01/; $rv; });It is the class, not the one state. Every
01xxxmessage passes, not only01504; that one is the only member of the class seen so far.The return value is not looked at. A class
01message beside anundefreturn value is passed on as well:undefis what aNULLlooks like toselectrow_array, and the state is the server's word on the outcome. Where DBIO itself needs a true value -- afterexecute-- core still throws on a false one, with the handle'serrstr.
The seam is _connect because every handle of this storage is made there: a DSN connect, a connection coderef, an DBIO::AccessBroker, and each reconnect. Statements run on the raw handle are covered too -- "dbh_do" in DBIO::Storage::DBI, and the do calls of DBIO::DB2::Deploy. The wrapper keeps the blessing core tells its own handler by, so a handle that comes back through a connection coderef a second time is not refused as carrying a foreign HandleError.
SQL0605W is a warning too, and it is reported. CREATE INDEX over a column sequence that an index, a UNIQUE constraint or the primary key already has answers err 605, SQLSTATE 42S11 -- an error class although the message is a warning -- and creates nothing. The wrapper handles it (no exception) and carps a message with the index and table of the statement; the DDL emitters normally leave such an index out beforehand (ADR 0010).
With unsafe nothing is installed. Core installs no handler there and this method adds none: under "unsafe" in DBIO::Storage::DBI the error handling is the caller's, and with RaiseError on a DELETE without WHERE dies there as it does in plain DBI.
explain_table_schema
DBIO::DB2::Storage->explain_table_schema('MYSCHEMA');
$storage->explain_table_schema('MYSCHEMA');
The schema holding the EXPLAIN_* tables that $rs->explain reads its plan back from. Defaults to SYSTOOLS, where SYSPROC.SYSINSTALLOBJECTS creates them and where the Explain facility looks when the session's own schema has none; set it when the tables were created under a schema of their own (the EXPLAIN.DDL route).
The name is an identifier (ADR 0077): it reaches the SQL through the driver's identifier quoting, written exactly as the catalog stores it, so upper and lower case count (SYSTOOLS, not systools) and a " in it is doubled. See "Query plans".
_dummy_table
my $table = $storage->_dummy_table; # SYSIBM.SYSDUMMY1
my $table = $storage->_dummy_table($sep); # server's qualifier separator
The one-row catalog view this driver selects scalar expressions from, since DB2 has no FROM-less SELECT. Written once and read by both _dbh_last_insert_id (ADR 0002) and _exists_value_sql (ADR 0037, the override of "_exists_value_sql" in DBIO::Storage::DBI).
The optional argument is the qualifier separator; it defaults to .. Only a caller that already holds a $dbh may pass the server-reported "sql_name_sep", because resolving it probes the server.
deploy_setup
No-op stub for DB2. Present for API compatibility with other drivers that need to allocate resources before a deploy operation.
insert
An insert of no values, $rs->create({}), cannot be written as core's INSERT INTO t DEFAULT VALUES: Db2 does not know it (SQL0104N). It is sent as INSERT INTO t (col) VALUES (DEFAULT) for one column -- the first auto-increment column, else the first column of the source -- which leaves every column at its default, the named one too (an identity gets its value). That column is not a value of the row: it is not in what the insert hands back, unless the server returned it (the identity, read as for any insert).
bind_attribute_by_data_type
my $attr = $storage->bind_attribute_by_data_type('text'); # { TYPE => -99 }
A column of a character LOB type (clob, dbclob, text, mediumtext, longtext, tinytext) is bound with the type SQL_CLOB of DBD::DB2 (-99 in its CLI), so its value is a LOB parameter and not a VARCHAR one. Every other type is bound as core does.
select_single
"select_single" in DBIO::Storage::DBI (what find and single read through), with the row repaired as the cursor does ("decode_rows" in DBIO::DB2::Storage::Cursor): the character columns decoded, and a DECIMAL, NUMERIC, REAL, DOUBLE or DECFLOAT value delivered with a decimal point whatever the locale of the process is (the CLI writes a comma under a German locale; DBIO neither sets an environment nor changes the locale).
_utf8_database
True when the code set of the database is UTF-8 (SYSIBMADM.DBCFG, name codeset); asked once per storage. DBIO::DB2::Storage::Cursor decodes the text of a result only then. A server that does not answer is not taken for UTF-8.
_prep_for_execute
"_prep_for_execute" in DBIO::Storage::DBI, with two refusals made before the server is asked, both DBIO exceptions naming table and column:
An empty string for a
blobcolumn. DBD::DB2 reads an empty BLOB asNULL, so the value would not come back as it went in; it is not stored as something else. (An emptyCLOBis stored and read back as''.)A select or delete that compares a
clob/textcolumn with a value of more than 32672 bytes. Db2 compares a CLOB with aVARCHARand cannot (SQL0433N); the statement would fail on the server.
SEE ALSO
DBIO::DB2 - DB2 schema component
DBIO::Storage::DBI - Base DBI storage class
AUTHOR
DBIO & DBIx::Class Authors
COPYRIGHT AND LICENSE
Copyright (C) 2026 DBIO Authors Portions Copyright (C) 2005-2025 DBIx::Class Authors Based on DBIx::Class, heavily modified.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.