MySQL and SQL Server clients
Besides the PostgreSQL and native protocols, the server can speak the MySQL / MariaDB client protocol and the SQL Server (TDS) protocol. Use them to point an existing MySQL or SQL Server application, driver or command-line tool at RasterizedDB without changing its database layer. Both serve the same databases and the same roles as the PostgreSQL listener; a table made over one protocol is visible over every other.
Each front end translates its dialect (MySQL SQL or T-SQL) into the engine's SQL. Where MySQL or SQL Server would give an answer the engine cannot reproduce exactly, the statement is refused with an error, never answered differently.
Enabling the listeners
Both listeners are off until you give a port or a socket path. They run beside whichever --protocol you chose.
export RASTERIZEDDB_PG_PASSWORD='change-me'
rasterizeddb --location /var/lib/rasterizeddb \
--protocol pgwire \
--mysql-port 3306 \
--mssql-port 1433To accept connections from other machines, also set the listen address and give real certificates:
rasterizeddb --location /var/lib/rasterizeddb \
--protocol pgwire \
--pg-cert /etc/rasterizeddb/server.crt --pg-key /etc/rasterizeddb/server.key \
--mysql-addr 0.0.0.0 --mysql-port 3306 --mysql-tls require \
--mssql-addr 0.0.0.0 --mssql-port 1433 --mssql-tls requireLogins use the server's roles. On a new data directory, the role named by --pg-user (default rasterized) with the password from RASTERIZEDDB_PG_PASSWORD (or --pg-password) is created, and it logs in over every protocol. Create more roles as described in Security.
The connection limits and timeouts of the PostgreSQL listener (--max-connections, --authentication-timeout, --idle-in-transaction-session-timeout, --idle-session-timeout) apply to MySQL and SQL Server sessions too; see Configuration.
MySQL flags
| Flag | Default | What it does |
|---|---|---|
--mysql-port <PORT> | off | Serve the MySQL protocol on this TCP port (3306 is MySQL's). |
--mysql-addr <ADDR> | 127.0.0.1 | Address the MySQL listener binds. |
--mysql-socket <PATH> | off | Also serve it on this unix socket (what mysql --socket=PATH connects to). No TLS on it. Permissions come from --socket-mode and --socket-group. |
--mysql-auth <password|trust> | password | password checks the role's password (caching_sha2_password); trust lets any role in without one. |
--mysql-socket-auth <password|trust> | --mysql-auth | Authentication on the unix socket. trust is refused on a socket that admits users outside its owner and group. Needs --mysql-socket. |
--mysql-tls <disable|prefer|require> | prefer | TLS on the TCP port. A role's first password login over TCP needs TLS. |
--mysql-cert <PATH> | --pg-cert, else self-signed | PEM certificate chain for the MySQL listener. |
--mysql-key <PATH> | --pg-key | PEM private key for it. |
SQL Server flags
| Flag | Default | What it does |
|---|---|---|
--mssql-port <PORT> | off | Serve the SQL Server (TDS) protocol on this TCP port (1433 is SQL Server's). |
--mssql-addr <ADDR> | 127.0.0.1 | Address the TDS listener binds. |
--mssql-socket <PATH> | off | Also serve it on this unix socket. No TLS on it. Permissions come from --socket-mode and --socket-group. |
--mssql-auth <password|trust> | password | password is SQL Server authentication against the role catalogue; trust lets any role in without one. |
--mssql-socket-auth <password|trust> | --mssql-auth | Authentication on the unix socket. Needs --mssql-socket. |
--mssql-tls <disable|prefer|require> | prefer | TLS. A client that asks for encryption gets the whole connection encrypted; under prefer a client that declines is served in the clear, password included; under require it is refused. |
--mssql-cert <PATH> | --pg-cert, else self-signed | PEM certificate chain for the TDS listener. |
--mssql-key <PATH> | --pg-key | PEM private key for it. |
--mssql-collation <ci|bin> | ci | The collation a text column made over TDS takes when it names none: ci is case-insensitive, like SQL Server's default; bin compares bytes. |
--mssql-unique-index-error <2601|2627> | 2601 | Error number for a duplicate in a unique index. 2627 (what a PRIMARY KEY or UNIQUE constraint reports) suits applications that only test that number. |
--mssql-guid-order <sqlserver|binary> | sqlserver | How uniqueidentifier columns made over TDS sort: as SQL Server sorts them, or by their bytes like PostgreSQL's uuid. |
Connecting
mysql and mariadb clients
mysql -h 127.0.0.1 -P 3306 -u rasterized -p --ssl-mode=REQUIRED postgresThe last argument is the database (postgres is the default one). With the server started with --mysql-socket /run/rasterizeddb/mysql.sock, a local client needs no TLS:
mysql --socket=/run/rasterizeddb/mysql.sock -u rasterized -p postgresThere is no RSA key exchange, so a role's first password login over plain TCP is refused with Authentication requires a secure connection: connect with TLS (or over the unix socket) for the first login. Connect once with TLS (or over the socket); later logins of that role use MySQL's fast authentication. A client asking for another plugin, such as MariaDB's mysql_native_password, is switched to caching_sha2_password.
Drivers connect as they would to MySQL. For example, a JDBC URL:
jdbc:mysql://db.internal:3306/postgres?sslMode=REQUIRED&useCursorFetch=truesqlcmd
sqlcmd -S tcp:127.0.0.1,1433 -U rasterized -P 'change-me' -d postgres -N -C-N asks for encryption and -C trusts the server's certificate, which you need with the self-signed one the server makes when given none. Only SQL Server authentication is supported; Windows authentication is refused.
master, model, msdb and tempdb all open the default database, so tools that log in to master first work.
.NET (Microsoft.Data.SqlClient)
using Microsoft.Data.SqlClient;
var cs = "Server=db.internal,1433;Database=postgres;User Id=rasterized;Password=change-me;" +
"Encrypt=True;TrustServerCertificate=True";
await using var conn = new SqlConnection(cs);
await conn.OpenAsync();
await using var cmd = new SqlCommand("SELECT COUNT(*) FROM orders WHERE customer_id = @id", conn);
cmd.Parameters.AddWithValue("@id", 42);
var count = await cmd.ExecuteScalarAsync();With a certificate your clients trust, drop TrustServerCertificate. Encrypt=Strict (TDS 8.0) is supported too; the client then validates the certificate, so use a real one.
Common to both
- Names are case-insensitive, as in both databases' defaults. A result column is named as written in the select list (
SELECT UserIdreturnsUserId);SELECT *returns lower-case names. - Index names are per table in MySQL and SQL Server and per database here; an index made through either protocol is stored under a name that includes its table and shown under its own name.
- An error inside a transaction fails only its statement, as in both databases. A deadlock or serialization failure rolls the whole transaction back.
- Errors carry the database's own numbers (MySQL 1062, 1146, 1054, …; SQL Server 2627, 208, 207, …), with the PostgreSQL SQLSTATE at the end of the message.
- Tables whose names start with
__are the server's own bookkeeping. MySQL'sSHOW TABLESdoes not list them. - Transactions, savepoints, isolation levels, prepared statements, cancellation, timeouts and privileges behave exactly as on the PostgreSQL protocol; see Transactions.
MySQL / MariaDB
Connection
Protocol 4.1 with multi-statements and multi-results, TLS on TCP, the unix socket, and server-side cursors (COM_STMT_FETCH, as Connector/J's useCursorFetch uses). Character sets other than utf8mb4, utf8, utf8mb3, ascii and binary are refused.
What is translated
| MySQL | Runs as |
|---|---|
`name`, "str" (without ANSI_QUOTES), 'it\'s', x'ff', b'101' | names, standard strings, bytea |
LIMIT a, b | LIMIT b OFFSET a |
/ | exact division; DIV is integer division |
<=>, &&, || (unless PIPES_AS_CONCAT), !, REGEXP | IS NOT DISTINCT FROM, AND, OR, NOT, ~ |
TRUE / FALSE | 1 / 0 |
AUTO_INCREMENT | serial / bigserial; the insert id comes back as MySQL's |
INSERT IGNORE, ON DUPLICATE KEY UPDATE … VALUES(c), AS new | ON CONFLICT … DO NOTHING / DO UPDATE |
REPLACE naming every column | ON CONFLICT DO UPDATE |
UPDATE / DELETE … ORDER BY … LIMIT n | by primary key in a subquery |
UPDATE a JOIN b …, DELETE a FROM a JOIN b … (two tables) | UPDATE … FROM, DELETE … USING |
CREATE TABLE with MySQL types, KEY, UNIQUE KEY, ENUM, table options | engine types and indexes; an ENUM gets a CHECK |
ALTER TABLE … ADD / MODIFY / CHANGE / DROP …, FIRST / AFTER | one engine ALTER per change |
IFNULL, IF, GROUP_CONCAT, DATE_FORMAT, DATE_ADD, JSON_EXTRACT, ->>, … | engine functions |
SQL_CALC_FOUND_ROWS + FOUND_ROWS() | a count of the query without its LIMIT |
SHOW DATABASES / TABLES / COLUMNS / INDEX / CREATE TABLE / VARIABLES, DESCRIBE | answered from the catalogue |
information_schema … TABLE_SCHEMA = 'db' | the database name, as MySQL tools expect |
Session behaviour MySQL tools rely on:
SET autocommit = 0holds work in a transaction untilCOMMIT. DDL commits what is open first, as in MySQL.SET FOREIGN_KEY_CHECKS = 0holds back the foreign keys aCREATE TABLEdeclares and adds them when it is switched back on, which is how amysqldumpfile loads.LOCK TABLESis accepted and does nothing. Comment-only queries answer OK.
A dump made by mysqldump loads as it is:
mysql -h 127.0.0.1 -P 3306 -u rasterized -p --ssl-mode=REQUIRED shop < shop.sqlText and collations
Text compares by bytes unless a column says otherwise; the server reports utf8mb4_bin as its default. A table's default collation (DEFAULT COLLATE=…, which mysqldump writes on every table) is not applied. A column's own case-insensitive collation is honoured: …_as_ci becomes the engine's rdb_ci, any other …_ci (utf8mb4_0900_ai_ci, utf8mb4_general_ci) becomes rdb_ci_ai. See Text search and collations for what those columns support.
Kept by the front end
These MySQL features have no engine counterpart and are provided by the MySQL front end itself. They work only over the MySQL protocol.
- Stored procedures:
CREATE [DEFINER=…] PROCEDURE,DROP PROCEDURE,CALL,SHOW PROCEDURE STATUS,SHOW CREATE PROCEDURE. Bodies supportIN/OUT/INOUTparameters,DECLARE,SET,IF,CASE,WHILE,REPEAT, labelledLOOP,LEAVE,ITERATE,SELECT … INTO, cursors,CONTINUE/EXIThandlers,SIGNAL,RESIGNALand nestedCALL. CREATE TEMPORARY TABLE: a table for the connection that hides a table of the same name and goes when the connection closes or is reset. Making one costs what making a table costs.ON UPDATE CURRENT_TIMESTAMP:UPDATEandON DUPLICATE KEY UPDATEsent over the MySQL protocol set the column when a value changes and the statement does not set it.LOAD DATA LOCAL INFILE, with field, enclosure, escape and line options, a column list andIGNORE n LINES, in one transaction. A server-side file (LOAD DATA INFILEwithoutLOCAL) is refused, as undersecure_file_priv.- Full-text search: a
FULLTEXTkey (inCREATE TABLE,ALTER TABLE … ADD FULLTEXT, orCREATE FULLTEXT INDEX) becomes the engine's full-text index, andMATCH (cols) AGAINST (…)in natural-language and boolean mode (+,-,*,"phrases", groups) uses it. InnoDB's default stop words and its word-length limits apply. Relevance scores are the engine's, not InnoDB's, so rows with close scores can come back in another order.
Not supported over MySQL
Refused with an error: stored functions, triggers and events; SPATIAL indexes; full-text WITH QUERY EXPANSION and WITH PARSER; PARTITION BY; CREATE TABLE … LIKE and CREATE TABLE … SELECT; generated columns in MySQL's syntax; indexes on expressions; XOR; multi-table UPDATE or DELETE over more than two tables; LOAD DATA … SET; a REPLACE that leaves columns out (MySQL resets them to their defaults); := outside SET, and SELECT @v = @v + … over more than one row (use GROUP_CONCAT or SUM); sql_select_limit.
BIGINT UNSIGNED is a signed bigint: values past 2^63 are refused.
MySQL's account statements (CREATE USER 'u'@'%' IDENTIFIED BY …, ALTER USER, DROP USER, SET PASSWORD, GRANT / REVOKE) manage the server's roles; you can also manage them over the PostgreSQL protocol.
SQL Server
Connection and requests
TDS 7.4 with TLS negotiated in PRELOGIN, or TDS 8.0 (Encrypt=Strict). The unix socket has no TLS. Supported requests: SQL batches; the RPC calls sp_executesql, sp_prepare, sp_prepexec, sp_execute, sp_unprepare and sp_reset_connection, with typed parameters bound by the engine (never pasted into the SQL); SqlConnection.BeginTransaction; the reset flag of pooled connections; attention (cancel).
Batches
Batches run as SQL Server runs them: statements need no ;, an error ends its statement and the batch goes on (unless SET XACT_ABORT ON), and these work:
DECLARE,SET @v,SELECT @v = …IF … ELSE,BEGIN … END,WHILE,BEGIN TRY … END TRY BEGIN CATCH … END CATCHwithERROR_MESSAGE()and the other error functionsPRINT,RAISERROR,THROW,RETURNEXEC('…')andEXEC sp_executesqlBEGIN TRANnesting with@@TRANCOUNT,SET IMPLICIT_TRANSACTIONS ON,SET TRANSACTION ISOLATION LEVEL
What is translated
| T-SQL | Runs as |
|---|---|
[name], "name", N'…', dbo. / db.dbo. prefixes | names (one schema), strings |
TOP (n), OFFSET … FETCH | LIMIT … OFFSET …; UPDATE / DELETE TOP by primary key |
a + b with a string side | string concatenation |
IDENTITY(1,1), SCOPE_IDENTITY(), @@IDENTITY | serial, and the captured value |
OUTPUT INSERTED.x / DELETED.x | RETURNING x |
EF Core's MERGE … ON 1=0 WHEN NOT MATCHED THEN INSERT … OUTPUT | a multi-row INSERT … RETURNING |
UPDATE a SET … FROM t a JOIN …, DELETE p FROM t AS p … | UPDATE … FROM, DELETE FROM … |
ISNULL, LEN, GETDATE, DATEADD, DATEDIFF, CONVERT(…, style), IIF, CHARINDEX, … | engine functions |
WITH (NOLOCK), OPTION (…), ON [PRIMARY], CLUSTERED | dropped |
sys.tables / columns / objects / indexes / types / schemas / databases, INFORMATION_SCHEMA.TABLES / COLUMNS, OBJECT_ID, SERVERPROPERTY, @@VERSION | built from the catalogue |
Text and collations
A text column made over TDS without a COLLATE is case-insensitive by default, as under SQL Server's default collation; --mssql-collation bin makes such columns compare by bytes instead. A column's own collation is honoured: …_CI_AI becomes rdb_ci_ai and any other …_CI_… becomes rdb_ci. Columns made over the other protocols compare by bytes unless they say otherwise. See Text search and collations.
Kept by the front end
These work only over the TDS protocol.
- Stored procedures:
CREATE [OR ALTER],ALTERandDROP PROCEDURE;EXECwith positional and named arguments, defaults,OUTPUTparameters and the return status; calls by RPC (CommandType.StoredProcedure). Nesting stops at 32 levels. #temptables,##globaltables and table variables (DECLARE @t TABLE): real tables for the connection, dropped when their batch, procedure or connection ends, or when a pooled connection is reset. A table variable is rolled back with a transaction here, where SQL Server keeps its rows.- Cursors:
DECLARE … CURSOR [LOCAL] [SCROLL | STATIC | FAST_FORWARD] FOR SELECT,OPEN,FETCH NEXT / PRIOR / FIRST / LAST / ABSOLUTE / RELATIVE [INTO],@@FETCH_STATUS,CLOSE,DEALLOCATE. MERGEwithWHEN MATCHED [AND …] THEN UPDATE / DELETE,WHEN NOT MATCHED [BY TARGET] THEN INSERTandWHEN NOT MATCHED BY SOURCE, from a table, a subquery orVALUES, run atomically. A target row matched twice is error 8672.FOR JSON PATH / AUTO(ROOT,INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER, nested) andFOR XML PATH(withTYPEand.value('.', …), asSTUFF((… FOR XML PATH('')), 1, n, '')string joins use).- Bulk load:
INSERT BULKand the bulk-load messagesSqlBulkCopyandbcpsend, in one transaction.SET FMTONLY ONanswers a query's columns. - Full-text search:
CREATE FULLTEXT INDEX ON t (cols) KEY INDEX …builds the engine's full-text indexes.CONTAINS(words, phrases, prefixes,AND/OR/AND NOT,FORMSOF(INFLECTIONAL, …),NEAR),FREETEXT,CONTAINSTABLEandFREETEXTTABLE(withKEYandRANK) use them. The index is current after every write; full-text catalogs, stop lists and population commands are accepted and change nothing. There is no noise-word list,CONTAINS(*, …)is refused (name the columns), andALTER FULLTEXT INDEX … ADD / DROPis refused (drop and recreate the index).RANKcomes from the engine's ranking, not SQL Server's.
Also supported: CROSS APPLY / OUTER APPLY; OPENJSON; sp_getapplock, sp_releaseapplock and APPLOCK_TEST; table, column and database names shown as declared rather than folded to lower case; SQL Server's own wording for constraint errors, with 547 for a foreign key and 2601 for a unique index; uniqueidentifier ordering as SQL Server's; datetime2(7) and time(7) kept to 100 ns; NULLs sorting first ascending; TRY_CAST / TRY_CONVERT returning NULL; COL_LENGTH; TDS session recovery for pooled connections across a server restart; T-SQL logins, users and GRANT / REVOKE; and full support for EF Core 10's SQL Server provider (Migrate(), ASP.NET Identity, filtered unique indexes).
Not supported over SQL Server
Refused with an error: MERGE … OUTPUT (other than EF Core's insert form) and a MERGE that updates a column its ON reads; FOR XML RAW / AUTO / EXPLICIT; stored functions and triggers; rowversion; computed columns; filtered unique indexes other than key IS NOT NULL [AND …] over their own key columns (a filtered index that is not unique is built over every row); SET ROWCOUNT; TOP … PERCENT and WITH TIES; OUTPUT … INTO; SELECT @v = @v + … FROM over more than one row; updatable cursors (FOR UPDATE, WHERE CURRENT OF); DENY (REVOKE the grant instead), DBCC, BACKUP, RESTORE, KILL and GOTO; Windows authentication.
Sharded clusters
--frontend-upstream <HOST:PORT> runs a server as a front-end node for a sharded cluster: MySQL and SQL Server sessions are sent to the gateway at that address (its PostgreSQL listener), logged in as each client's own role, and MySQL logins then need TLS. See the gateway.
Known differences
- The engine has no temporary tables, procedures or
ON UPDATEtimestamps of its own; the front ends provide them, so they work only over the protocol that made them, and a temporary table costs what creating a table costs. - A table's or database's default collation is not applied to its columns; only a column's own collation is.
- Integers are signed: MySQL's unsigned types do not hold values past the signed range.
- Full-text relevance scores differ from InnoDB's and SQL Server's, so ties and near-ties can order differently.
- Stored functions and triggers are refused over both protocols.