Creating a dialect

A dialect tells Hop how one database differs from plain JDBC. It is a class implementing IDatabase, which in practice means extending BaseDatabaseMeta and overriding only what is actually different.

The smallest possible dialect

java
@DatabaseMetaPlugin(
    type = "ACME",
    typeDescription = "ACME Database",
    classLoaderGroup = "acme-db",
    documentationUrl = "/database/databases/acme.html")
@GuiPlugin(id = "GUI-AcmeDatabaseMeta")
public class AcmeDatabaseMeta extends BaseDatabaseMeta implements IDatabase {

  @Override
  public String getDriverClass() {
    return "com.acme.jdbc.Driver";
  }

  @Override
  public String getURL(String hostname, String port, String databaseName) {
    return "jdbc:acme://" + hostname + ":" + port + "/" + databaseName;
  }

  @Override
  public int getDefaultDatabasePort() {
    return 5555;
  }
}

Everything else has a default in BaseDatabaseMeta. Start there and override as the differences show up, rather than working through the whole interface.

The annotation

type

The identifier for this dialect, uppercase by convention. It is stored in saved connections, so changing it later breaks existing projects. It is also how other plugins refer to this dialect without compiling against it, so pick something stable and obvious.

typeDescription

What the user sees in the connection dialog.

classLoaderGroup

Give every dialect one, named after the module, and give the same group to every other plugin class in the module. See Classloading and the JDBC driver.

documentationUrl

Path to the page in the user manual, which the connection dialog links to.

Capabilities

Most of IDatabase is questions about what the database supports. They are ordinary methods with sensible defaults, and the ones that matter most in practice are these.

Method What it controls

isSupportsBooleanDataType()

Whether a Hop boolean can be written as BOOLEAN, or has to become a one character column.

isSupportsTimestampDataType()

Whether timestamps survive as timestamps, or collapse to dates.

isSupportsAutoInc()

Whether the database can generate technical keys itself.

isFetchSizeSupported()

Whether the JDBC fetch size can be set at all.

isSupportsErrorHandling()

Set this false for databases that invalidate a statement, or the whole connection, when a statement fails. SQLite is the example in the tree.

getDmlSyntax()

The upsert forms (MERGE, ON CONFLICT, ON DUPLICATE KEY) and the statements of several rows the database has, or null for plain one-row statements only. See DML statements.

getLimitClause(int)

The clause appended after the FROM clause to limit rows, such as " LIMIT 10".

getLimitClausePrefix(int)

The clause placed directly after SELECT instead, such as " TOP 10". Databases use one form or the other, so override this or getLimitClause, not both.

getBatchFailureContract()

What the JDBC driver does with a batch when one of its rows fails, measured against a real server, or null when nobody has measured it. See Batch failure contract.

Both include their own leading space, and both default to returning nothing. A dialect that offers neither still works: the row count is capped while reading, so it simply fetches a little more than it needs.

Prefer overriding a capability over overriding behaviour. A capability is a fact about the database that Hop can act on in several places; overridden behaviour only fixes the one place you overrode.

Batch failure contract

When a row in a JDBC batch fails, drivers disagree about what happened to the other rows of the batch, and about what BatchUpdateException.getUpdateCounts() means. A dialect that knows what its driver does returns it from getBatchFailureContract(), and Table output, Update, Delete, Insert/Update, Synchronize after merge and pgvector upsert then use it to keep batching with an error hop attached and still send every row of a failed batch to exactly one stream, in input order:

MARKS_FAILED_ROWS

The driver runs every row and marks the failed ones with EXECUTE_FAILED. The rows it applied are committed, and the failed ones are rejected.

KEEPS_PREFIX

The driver stops at the first failing row; the counts array is as long as the rows before it, and the rows behind it were never sent. The prefix is committed, the failing row rejected, and the rest is sent again.

LOSES_WHOLE_BATCH

No row of the batch survives. The batch is rolled back and run again in halves until the failing rows are isolated. The failed batch entry a driver names in its message (getFailedBatchEntry) can save most of those round trips.

A dialect that returns null, the default, is treated as UNKNOWN: a failed batch is handled the way Hop always handled it. Users get that behaviour back on a dialect with a contract by choosing As before for When a batch fails, the driver on the Advanced tab of the connection, or with the variable HOP_DATABASE_BATCH_RECOVERY=LEGACY for every connection.

Measure, don’t guess

Return a contract only after measuring the driver against a real server, with the driver version Hop ships and the connection options the dialect writes. org.apache.hop.core.database.batch.BatchContractProbe does the measurement on any open connection: it commits two rows into a scratch table, sends a batch of ten rows of which two repeat those keys, commits, and reports the update counts and the rows that survived. Put the failing rows at the start, in the middle and at the end of a batch, and also try a batch large enough for the driver to split it into several statements or packets.

A contract often only holds for some connection options. Read them with getConnectionOption(name), which looks at the extra options and a manual URL, and return null for any option value that was not measured. Return the contract for your own dialect class only (getClass() == MyDatabaseMeta.class), so a dialect that extends yours doesn’t inherit a contract nobody measured for its driver.

Every declared contract is checked against the real driver in a test that uses org.apache.hop.junit.batch.DialectContractCheck from the hop-core test jar: the probe must see exactly what the dialect declares, through the URL the dialect builds, and a batch recovered by that contract must report exactly the rows that end up in the table, also for a batch the driver splits. For a connection option that makes the dialect declare nothing, the check confirms the driver indeed behaves differently with it. The drivers that run in process are checked in unit tests, for example H2BatchContractTest and DerbyNetworkBatchContractTest. PostgreSQL, MySQL, SQL Server and Oracle are checked in *BatchContractIT classes in their plugins, in Testcontainers images; the drivers Hop downloads on demand are fetched at the dialect’s DriverDownload version. The MySQL, SQL Server and Oracle ones run with -Dhop.it.batchContracts=true.

What was measured

Dialect Driver Contract Not declared with

PostgreSQL

pgjdbc 42.7

LOSES_WHOLE_BATCH, also with reWriteBatchedInserts and every autosave setting

SQL Server (Microsoft driver)

mssql-jdbc 13.4

MARKS_FAILED_ROWS

useBulkCopyForBatchInsert=true, XACT_ABORT in the connection SQL

Oracle

ojdbc11 23.26

KEEPS_PREFIX

MySQL

Connector/J 9.7

MARKS_FAILED_ROWS; KEEPS_PREFIX with continueBatchOnError=false

rewriteBatchedStatements=true, another driver class

H2

H2 2.5 (memory, file and TCP)

MARKS_FAILED_ROWS

Derby

Derby 10.17

MARKS_FAILED_ROWS with a hostname (network client), KEEPS_PREFIX without (embedded)

DuckDB

DuckDB JDBC 1.5.6

LOSES_WHOLE_BATCH

Not declared, after measuring: SQLite (it stops at the failed row but reports no counts), MariaDB with its own driver (a batch that spans several packets keeps the other packets while every row is reported as failed), and SQL Server through jTDS. The dialects that extend PostgreSQL and MySQL (Greenplum, Redshift, CockroachDB, CrateDB, MariaDB, Doris, Infobright) declare nothing either: their drivers or servers were not measured.

DML statements

Hop writes INSERT, UPDATE, DELETE and upsert statements through one builder, org.apache.hop.core.database.dml.DmlStatementBuilder. A statement can carry several rows: generating one INSERT …​ VALUES (…​), (…​) in Hop is cheaper than letting a driver parse or rewrite N one-row statements. What a dialect declares in the DmlSyntax it returns from getDmlSyntax() decides which forms are used; anything it leaves out is written one row per statement, which every database runs:

sql
INSERT INTO target (a, b) VALUES (?, ?)
UPDATE target SET b = ? WHERE a = ?
DELETE FROM target WHERE a = ?

An upsert is written in one of the declared upserts, in order of preference. The standard MERGE needs nothing but the statement:

sql
MERGE INTO target t
USING (VALUES (?, ?, ?)) AS s (id, name, amount)
ON (t.id = s.id)
WHEN MATCHED [AND (changed)] THEN UPDATE SET name = s.name, amount = s.amount
WHEN NOT MATCHED THEN INSERT (id, name, amount) VALUES (s.id, s.name, s.amount)

ON_CONFLICT (INSERT …​ ON CONFLICT (keys) DO UPDATE SET c = EXCLUDED.c) needs a primary key or unique index on exactly the key columns, and ON_DUPLICATE_KEY (INSERT …​ ON DUPLICATE KEY UPDATE c = VALUES(c)) needs that to be the table’s only unique index, since MySQL reacts to any of them. Both can only update columns they also insert. org.apache.hop.core.database.dml.DmlSupport.plan(…​) checks all of this on the open connection, with DatabaseMetaData.getPrimaryKeys and getIndexInfo, and picks the first form that qualifies, or the one the user asked for. DmlSupport.planStatements(…​) does the same for any statement and also picks the rows per statement.

What a DmlSyntax holds:

rowSource

How rows of parameters become a derived table, aliased s: VALUES ((VALUES (?, ?), (?, ?)) AS s (a, b): H2, DuckDB, PostgreSQL, SQL Server, DB2), SELECT ((SELECT ? AS a, ? AS b UNION ALL SELECT ?, ?) s: SQLite, MySQL), SELECT_FROM_DUAL (Oracle) or SELECT_FROM_SYSDUMMY1. It is the source of a MERGE, and of a multi-row UPDATE or DELETE that joins.

castParameters

Whether each parameter of that derived table is written as CAST(? AS type), on every row. PostgreSQL, SQL Server and DB2 need this: pgjdbc sends timestamps, and strings bound for other columns, untyped, and PostgreSQL turns an untyped value in a VALUES list into text. A cast on the first row only is not enough: it types the untyped parameters of the other rows, but a typed one that differs (a bigint for a varchar column) then fails with "VALUES types character varying and bigint cannot be matched". The types come from the table, through DmlColumns.fromTable(…​), and the dialect writes each as a cast target in IDatabase.getDmlCastType(…​). The cast only gives the parameter its column’s type: the column must still decide whether the value fits, as it does for a plain INSERT or UPDATE. A cast must therefore change no value. PostgreSQL cuts a string cast to varchar(5) to five characters without an error and rounds a key cast to numeric(5,2) before it is compared, so its casts name the type without length or precision (varchar, bpchar, numeric, and varbit for bit(n)). SQL Server cuts in the same way, so it casts to varchar(max), nvarchar(max) and varbinary(max), and a decimal(p,s) to decimal(38, 38-(p-s)). The default keeps the length, precision and scale, as a cast without them can mean CHAR(1) or a scale of 0: right for DB2, which refuses a value too long for CAST(? AS VARCHAR(5)) (SQLCODE -302) as it refuses it in a plain statement. Check a new dialect with RealDriverCastScenario, which writes overlong and over-precise values through every declared form and through the plain one-row statements and compares the outcomes. Plain VALUES lists of an INSERT and IN lists are not cast.

castValuesLists

Also cast the plain VALUES list of an INSERT (or ON CONFLICT, ON DUPLICATE KEY) when it carries several rows. SQL Server needs it: it types a multi-row VALUES list from its parameters before it assigns the rows, mssql-jdbc declares a BigDecimal as decimal(38, scale), and two scales together overflow 38 digits, so 1 and 2.25 are silently written as 1.00 and 2.00 into a numeric(10,2) column. Each parameter is cast to IDatabase.getDmlValuesListCastType(…​), by default the column’s cast type. SQL Server casts character types to nvarchar(max) there: a cast to varchar converts the value to the code page of the database’s default collation, so a column with another collation (a _UTF8 one, say) would get ? for every character that code page lacks, without an error.

upserts

DmlSyntax.Upsert entries, each with its form, multiRow (whether a test ran it with several source rows), minimumMajorVersion and minimumMinorVersion (checked against DatabaseMetaData when the transform connects: PostgreSQL 15 for MERGE and 9.5 for ON CONFLICT, SQL Server 2008 (10), Oracle 10g, SQLite 3.24), the terminator of a MERGE (SQL Server wants ;), its changedCondition (standard SQL has WHEN MATCHED AND (…​); Oracle has no such form and takes UPDATE SET …​ WHERE (…​) instead) and rowAlias: an ON DUPLICATE KEY that names the inserted row INSERT …​ VALUES (…​) AS new …​ c = new.c instead of the VALUES(c) function MySQL deprecated in 8.0.20. A form can be declared twice for two ranges of server versions; the first entry the server qualifies for is used, also when the user asked for that form. MySQL declares the row alias from 8.1 and VALUES(c) for every version.

insertForm

How several rows go into one INSERT: VALUES_LIST (INSERT INTO t (a, b) VALUES (?, ?), (?, ?)). null inserts one row per statement.

updateForm

FROM_SOURCE (UPDATE t AS t SET c = s.c FROM (source) s WHERE t.k = s.k: PostgreSQL, DuckDB, SQLite), FROM_JOIN (SQL Server), JOIN_SET (MySQL) or MERGE with only WHEN MATCHED.

deleteForm

For a composite key: OR_OF_ANDS, ROW_VALUE_IN ((a, b) IN ?, ?), (?, ?), USING_SOURCE, JOIN or MERGE …​ WHEN MATCHED THEN DELETE. A single key column is always key IN (?, ?, …​).

maxParameters, maxRowsPerStatement

Limits of one statement, 0 for none: PostgreSQL and MySQL (with server-side prepared statements) take 65535 parameters, SQL Server 2098 parameters with mssql-jdbc (the server’s 2100 less two of the driver’s) and 1000 rows in an INSERT, SQLite 32766 parameters and 500 terms in a compound SELECT, H2 100000 parameters. Oracle takes 65535 binds and 1000 values in an IN list, but Hop keeps an Oracle statement at 100 rows and 1000 binds: the hard parse of a UNION ALL source grows with the square of its binds. Derby compiles a statement to Java bytecode and refuses one that is too complex (42ZA0): its budget is about 6 per row plus 1 per parameter, so it declares 50000 parameters and 1000 rows, which stay well inside it for every column type. The rows per statement are the number asked for, capped by both limits, so on a wide table the parameters decide: 1000 columns on PostgreSQL leave 65 rows per statement.

What the verified dialects declare:

Database Upsert INSERT UPDATE DELETE (composite key) Row source, casts Limits

PostgreSQL 14, 18

MERGE (15+), ON_CONFLICT (9.5+), both multi-row

VALUES_LIST

FROM_SOURCE

USING_SOURCE

VALUES, cast

65535 parameters

SQL Server 2022

MERGE (2008+), multi-row

VALUES_LIST

FROM_JOIN

JOIN

VALUES, cast, also INSERT lists

2098 parameters, 1000 rows

Oracle 23

MERGE (10g+), multi-row

none

none (one row per statement is faster)

ROW_VALUE_IN

SELECT_FROM_DUAL

1000 binds, 100 rows (the parse of a UNION ALL source grows with the square of its binds)

MySQL 9

ON_DUPLICATE_KEY with row alias (8.1+), with VALUES(c) (any)

VALUES_LIST (strict SQL mode only)

JOIN_SET

ROW_VALUE_IN

SELECT

65535 parameters, max_allowed_packet bytes; InnoDB and NDB tables only

H2

MERGE, multi-row

VALUES_LIST

none (one row per statement is faster in process)

none (same)

VALUES

100000 parameters

DuckDB

MERGE, ON_CONFLICT, multi-row

VALUES_LIST

FROM_SOURCE

ROW_VALUE_IN

VALUES

SQLite (see below)

ON_CONFLICT (3.24+), multi-row

VALUES_LIST

FROM_SOURCE

ROW_VALUE_IN

SELECT

32766 parameters, 500 rows

Derby

none

VALUES_LIST

none

none

50000 parameters, 1000 rows

Oracle declares no INSERT of several rows and writes one row per statement. Measured against Oracle Database 23 Free, INSERT …​ SELECT …​ FROM dual UNION ALL of several rows is no faster than a batch of one-row INSERTs, which the driver already sends as one array execution, while its hard parse grows with the square of its binds (about a second at 10,000 binds, 50 seconds at 65,000). The driver’s parameter metadata, which Hop asks for to bind a string to a VARCHAR2, NVARCHAR2 or CLOB column, did not finish on a statement of 65 rows of 1000 columns. Its multi-row MERGE reads its rows from SELECT …​ FROM dual UNION ALL, whose rows must agree in type: Hop binds a NULL with the type of its value, a NULL bound as VARCHAR next to a number fails with ORA-01790. With strict mode off, MySQL writes the implicit default into a NOT NULL column for a row of a multi-row INSERT or upsert and only warns, where a one-row statement fails; a table without transactions (MyISAM, MEMORY, …​) does the same in STRICT_TRANS_TABLES mode, and keeps the rows before a bad one of any statement in STRICT_ALL_TABLES mode. IDatabase.getMultiRowDmlRefusal(…​) is asked for every target table on the open connection; MySQL’s reads the session’s sql_mode and the table’s engine (SHOW CREATE TABLE) and falls back to one row per statement for either, or when it can’t read them. IDatabase.getMaxDmlStatementBytes(…​) gives the most bytes one statement may take on the connection; MySQL’s is max_allowed_packet, since Connector/J refuses a larger statement where a batch of one-row statements only needs each row to fit. MultiRowBatch then closes a statement early, at a power of two of rows, before an estimate of its values would pass the limit. MariaDB, Doris and Infobright, which extend the MySQL dialect, return null: MariaDB has no row alias and its own driver was not run. SQLite declares the multi-row INSERT and SqliteDmlTest runs it, but SQLite has no batch failure contract (see above), so Table output writes one row per statement there.

Return null, the default, when the database has none of these, or when you have not run them. Declare the syntax only for the dialect itself (if (getClass() != MyDatabaseMeta.class) return null;): a dialect that extends it, such as Greenplum, CockroachDB, CrateDB and Redshift for PostgreSQL, talks to another server and declares its own. Derby has a MERGE, but only with a base table or table function as the source, so it declares no upsert; it does declare a multi-row INSERT.

The rows go through org.apache.hop.core.database.batch.MultiRowBatch, the multi-row counterpart of RecoverableBatch. It cuts the rows into chunks of the chosen size, closes a chunk early when a key repeats in it (a statement can’t apply the same key twice in input order), and sends a shorter chunk as statements of power-of-two sizes. When a statement of several rows fails, which it does as a whole on every database, its rows are run again one by one so that exactly the bad rows go to the error hop. A row of a multi-row INSERT is reported with an update count of 1; a row of a multi-row UPDATE, DELETE or upsert with Statement.SUCCESS_NO_INFO, since only the statement’s total is known. A transform that needs the count of every row asks DmlSupport for that, and gets one row per statement.

Users can go back to one row per statement on a dialect that declares statements of several rows: with Write one row per statement on the Advanced tab of the connection, with the variable HOP_DATABASE_MULTI_ROW_DML=DISABLED for every connection, or with HOP_DATABASE_BATCH_RECOVERY=LEGACY, since only recovered batches carry several rows. DmlSupport.planStatements(…​) checks the first two when it is given the transform’s variables, so a transform must pass them.

Verify the declaration against a real database before returning it. The hop-core test jar has two scenarios:

  • org.apache.hop.junit.merge.RealDriverMergeScenario runs the one-row MERGE through a PreparedStatement and checks the table after each step: inserts and updates, NULLs compared as equal, insert-only, update-only-changed, the same key twice in one JDBC batch, and a RecoverableBatch with one failing row.

  • org.apache.hop.junit.dml.RealDriverDmlScenario runs every declared INSERT, UPDATE, DELETE and upsert form through a MultiRowBatch, with repeated keys, rows that fail on their own and amounts of different scales in one statement, and checks both the table and the verdict of every row. runAtLimits(…​) writes full statements at the dialect’s maxParameters and maxRowsPerStatement, so a limit that is too high fails the test. runWide(…​) does the same on a table as wide as the database allows, without recovering a failure, so a statement the server or the driver refuses for its size fails the test, and reads every value back. measure(…​) times one row per statement against several.

Copy H2MergeTest and H2DmlTest for an embedded database, or PostgreSqlMergeIT and PostgreSqlDmlIT for one in a Testcontainers image, and mark a form you could not run as not verified in its Javadoc. The *DmlIT classes of SQL Server (in the mssqlnative plugin), Oracle and MySQL run with -Dhop.it.dml=true, with drivers Hop downloads.

With reWriteBatchedInserts=true pgjdbc also folds a JDBC batch of Hop’s multi-row INSERTs into larger INSERTs (in powers of two) and then reports SUCCESS_NO_INFO. The rows come out the same; the failed batch entry pgjdbc names then counts its own statements, so the dialect gives no hint for a failed INSERT of several rows and the batch is recovered without one.

On every verified database a one-row MERGE that inserts or updates returns an update count of 1, and one that changes nothing (an insert-only MERGE on an existing key, or an unchanged row with update-only-changed) returns 0.

SQL differences

Where the SQL itself differs, override the statement the difference belongs to: getTruncateTableStatement, getAddColumnStatement, getModifyColumnStatement, getSqlListOfSchemas, and so on.

Column types are not done this way. They have their own mechanism, described in Column types and type rules, and a new dialect should use that rather than overriding getFieldDefinition.

When one of those statements has to name a column type, call getColumnDefinition(v, tk, pk, useAutoIncrement, addFieldName, addCr, purpose) rather than getFieldDefinition(…​). It asks the type rules first, so a column is spelled in an ALTER TABLE exactly the way it is in the CREATE TABLE; calling getFieldDefinition directly skips the rules and the two drift apart. Pass ColumnContext.Purpose.ADD_COLUMN or MODIFY_COLUMN to say which statement is being built.

addFieldName means only whether the returned definition is prefixed with the column name. A dialect whose ALTER syntax puts the name somewhere else writes that name into the statement itself and asks for the definition with addFieldName false, as Firebird, Interbase and SAPDB do:

java
return "ALTER TABLE " + tableName + " ALTER COLUMN " + v.getName() + " TYPE "
    + getColumnDefinition(v, tk, pk, useAutoinc, false, false, ColumnContext.Purpose.MODIFY_COLUMN);

Classloading and the JDBC driver

Hop loads each plugin in its own classloader so that two plugins can use incompatible versions of the same library. Plugins that declare the same classLoaderGroup share one classloader instead.

This matters for two reasons.

Within your own module, the dialect loads the JDBC driver, and any bulk loader you ship needs the same driver classes. If the dialect declares a group and the bulk loader does not, they end up in different classloaders and the bulk loader cannot see the driver. Give every plugin class in the module the same group.

Across modules, a plugin from somewhere else can join your group by naming it, which is how somebody can add support for a database specific type without a change to your plugin. Choose a group name that reads as public API, because it is.

Registering the driver

Hop does not bundle most JDBC drivers. Declare the dependency as provided in the module’s pom.xml, so the plugin builds against it without shipping it, and document which jar the user has to drop into the plugin folder.

Checklist

  • The dialect extends BaseDatabaseMeta and carries @DatabaseMetaPlugin.

  • Every plugin class in the module carries the same classLoaderGroup.

  • Column types are declared as rules, not as an overridden getFieldDefinition.

  • There is a golden test for the generated DDL, see Testing a database plugin.

  • getDmlSyntax() declares only forms that a test ran against the database, or returns null, and only for the dialect’s own class.

  • There is a page in the user manual, and documentationUrl points at it.

  • getBatchFailureContract() returns a measured value, or null if nobody has measured the driver.