Awesome Go

firebirdsql

CategoryDatabase Drivers
SubcategoryRelational Database Drivers
Stars269

Firebird RDBMS SQL driver for Go

About firebirdsql

firebirdsql (Go firebird sql driver)

Firebird RDBMS https://firebirdsql.org SQL driver for Go

Requirements

  • Firebird 2.5 or higher
  • Go 1.22 or higher

Example

package main

import (
    "fmt"
    "database/sql"
    _ "github.com/nakagami/firebirdsql"
)

func main() {
    var n int
    conn, _ := sql.Open("firebirdsql", "user:password@servername/foo/bar.fdb")
    defer conn.Close()
    conn.QueryRow("SELECT Count(*) FROM rdb$relations").Scan(&n)
    fmt.Println("Relations count=", n)

}

See also driver_test.go

   package main

      import (
       "fmt"
       "github.com/nakagami/firebirdsql"
   )

   func main() {
       dsn := "user:password@servername/foo/bar.fdb"
       events := []string{"my_event", "order_created"}
       fbEvent, _ := firebirdsql.NewFBEvent(dsn)
       defer fbEvent.Close()
       sbr, _ := fbEvent.Subscribe(events, func(event firebirdsql.Event) { //or use SubscribeChan
           fmt.Printf("event: %s, count: %d, id: %d, remote id:%d \n", event.Name, event.Count, event.ID, event.RemoteID)
       })
       defer sbr.Unsubscribe()
       go func() {
               fbEvent.PostEvent(events[0])
               fbEvent.PostEvent(events[1])
       }()
       <- make(chan struct{}) //wait
   }

See also _example

Connection string

user:password@servername[:port_number]/database_name_or_file[?params1=value1[&param2=value2]...]

Examples:

# Basic connection
user:password@localhost/path/to/database.fdb

# With wire compression enabled (for better performance over slow networks)
user:password@localhost/path/to/database.fdb?wire_compress=true

# With multiple parameters
user:password@localhost/path/to/database.fdb?wire_crypt=true&wire_compress=true&role=admin

Reserved characters

The DSN is parsed as an RFC 3986 URI (the driver prepends firebird:// automatically). Reserved characters in the password or database path must be percent-encoded, otherwise they are misinterpreted as URI delimiters:

CharacterEncodedWhy it breaks things
@%40ends the userinfo section
:%3Asplits user from password
#%23starts the fragment (silently dropped)
?%3Fstarts the query string
/%2Fpath separator
&%26separates query parameters
=%3Dseparates a query key from its value
%%25the escape character itself
space%20invalid in a URI

Use url.QueryEscape to encode a password:

import "net/url"

pass := url.QueryEscape("p@ss:w#rd")  // → "p%40ss%3Aw%23rd"
dsn  := "sysdba:" + pass + "@localhost/var/lib/firebird/mydb.fdb"
db, err := sql.Open("firebirdsql", dsn)

Drivers

Two driver names are registered with database/sql:

  • "firebirdsql" - attach to an existing database.

  • "firebirdsql_createdb" - create the database, then attach. A database that already exists at that path is overwritten. This happens on every new connection the *sql.DB opens, not only the first one. If no other connection holds the database, for example after the pool closed its only connection, the new one wipes the data (Firebird 2.5 SuperServer was seen to hang instead). If another connection holds it, the create fails with object DATABASE is in use (Firebird 3 and later). Use it once to create the database, then open the database with "firebirdsql":

    db, err := sql.Open("firebirdsql_createdb", dsn)
    if err != nil {
        log.Fatal(err)
    }
    if err := db.Ping(); err != nil { // creates the database
        log.Fatal(err)
    }
    db.Close()
    
    db, err = sql.Open("firebirdsql", dsn)
    if err != nil {
        log.Fatal(err)
    }
    

    See _examples/service_manager.go for a usage example.

General

  • user: login user
  • password: login password
  • servername: Firebird server's host name or IP address.
  • port_number: Port number. default value is 3050.
  • database_name_or_file: Database path (or alias name).

Optional

param1, param2... are

NameDescriptionDefaultNote
auth_plugin_namePreferred authentication plugin. Must be a member of auth_plugin_list.Srp256Srp256/Srp/Legacy_Auth are available.
auth_plugin_listOrdered, comma-separated allow-list of acceptable authentication plugins (a subset of the supported Srp256,Srp,Legacy_Auth). The plugin the server selects must be a member, otherwise the connection is refused before the attach request is sent. Below wire protocol 13 there are no plugins and the only login is the Legacy_Auth hash, so the connection counts as Legacy_Auth. Omit a plugin to refuse it (e.g. Srp256,Srp to refuse a server-forced downgrade to Legacy_Auth, which would otherwise put a brute-forceable DES crypt(password) hash on the wire).Srp256,Srp,Legacy_AuthLegacy_Auth is kept in the default for backward compatibility but is weak; set Srp256,Srp to harden. Firebird 2.5 can't connect with a list that omits it.
column_name_to_lowerForce column name to lowerfalseFor "github.com/jmoiron/sqlx"
page_sizePage size in bytes for a database created with the firebirdsql_createdb driver: 4096, 8192, 16384 or 32768. When unset or empty, no page size is sent and the server uses its default (4096 on Firebird 2.5, 8192 on 3.0 and later); set page_size=4096 for the size older driver versions always used. Any other value is rejected before dialing. Only used by firebirdsql_createdb; validated on every DSN.server defaultFirebird 2.5/3.0 accept 4096-16384, 4.0/5.0 4096-32768 and 6.0 8192-32768; the server adjusts a size outside its range (4096 becomes 8192 on 6.0).
roleRole name
timezoneIANA time zone name (e.g. UTC, Europe/Berlin), or a fixed UTC offset (e.g. %2B05:30)Controls client-side decoding of naive DATE/TIME/TIMESTAMP and server session time zone (FB 4+). Write a fixed offset percent-encoded: a raw + in a URL query becomes a space. See "Time and timestamp handling" below.
wire_cryptWire-encryption policy, mirroring the server's WireCrypt setting. Tri-state disabled/enabled/required, with boolean aliases false=disabled and true=enabled. enabled encrypts when the server offers a cipher but tolerates plaintext; required fails the connection closed on every non-encrypting handshake outcome (including a legacy plain op_accept for protocol versions ≤ 12 and an op_accept_data with no negotiated cipher), refusing before the attach request is sent. It can't protect what the first packet already carried: with auth_plugin_name=Legacy_Auth, that includes the DES password hash. Note: enabled tolerates an active-MITM downgrade to plaintext; on untrusted networks use required.true (=enabled)For Firebird 3.0+. Against pre-3.0 / non-encrypting servers, required is refused (use enabled to allow plaintext).
wire_crypt_pluginOrdered, comma-separated allow-list of acceptable wire ciphers, mirroring the server's WireCryptPlugin. Order is client preference; omit a cipher to refuse it (e.g. ChaCha64,ChaCha to refuse the deprecated RC4/Arc4).ChaCha64,ChaCha,Arc4For Firebird 3.0+. Arc4 (RC4) is kept for FB 3.0 compatibility but is cryptographically weak.
wire_compressEnable wire protocol compression.falseFor Firebird 3.0+ (protocol version 13+)
charsetFirebird Charecter Set
max_inline_blob_sizeMax size of BLOBs the server may send inline with fetch/execute2 responses (protocol 19 / Firebird 5.0.3+). 0 disables. Alias: inline_blob_size.65536Negotiated only when the server picks protocol ≥ 19
max_blob_cache_sizeClient cache budget for inline BLOBs (bytes). Alias: blob_cache_size.10485760Also sent as DPB on attach when protocol ≥ 19

Credentials on the wire

What the driver sends to log in depends on the wire protocol and the plugin the server picks:

ProtocolPluginSent
13+ (Firebird 3.0+)Srp256, SrpAn SRP proof, never the password
13+Legacy_AuthThe DES crypt(password) hash, never the password
Below 13 (Firebird 2.5)noneThe same DES hash, as password_enc, never the password

The hash protects the password but not the login. Only the first 8 bytes of the password count, it can be brute-forced, and anyone who captures it can log in with it, with no cracking needed, on a server that accepts Legacy_Auth (always on Firebird 2.5; on 3.0+ only when AuthServer includes it). These protocols and Legacy_Auth have no wire encryption, so the hash is readable to anyone watching.

The server picks the protocol and plugin, so with default settings a fake server or an active attacker can ask for the hash. wire_crypt=required refuses such a connection, and so does an auth_plugin_list that omits Legacy_Auth. The service manager can't do so: it has no required mode and always allows Legacy_Auth, so an untrusted network isn't safe for it.

If a server moves on to Legacy_Auth partway through an SRP login, the driver refuses and sends no hash, unlike isql. This can happen on a server with AuthServer = Srp, Legacy_Auth, whatever wire_crypt says. There, a user who only has a Legacy_Auth entry can't log in that way, and a wrong password or an unknown user gets a login error that isn't always an FbError. A Legacy_Auth-only user can set auth_plugin_name=Legacy_Auth instead, with the effect described next.

With auth_plugin_name=Legacy_Auth, the hash is in the first packet, at every protocol, before the server has picked anything. wire_crypt=required can't stop that.

Passwords that change a user through UserManager, and any password in SQL text, are ordinary request data: only wire encryption protects them.

Wire protocols 16–19

The driver advertises Firebird wire protocols 10–19. The server chooses the highest mutually supported version.

  • Protocol 16+ (Firebird 4.0+): batch DML via PrepareBatch on the driver connection (sql.Conn.Raw). After op_batch_msg, protocol 17+ uses op_batch_sync; create/release still use op_ping. BLOB/array bind parameters are rejected. In autocommit mode, a successful Exec calls commit-retaining; any per-row error rolls back.
  • Protocol 18 (Firebird 5.0+): scrollable cursors. Use QueryScrollable on the driver connection via sql.Conn.Raw (not database/sql Rows, which is forward-only). Orientations: ScrollNext, ScrollPrior, ScrollFirst, ScrollLast, ScrollAbsolute, ScrollRelative.
  • Protocol 19 (Firebird 5.0.3+): inline BLOBs — small BLOB payloads arrive with fetch/sql responses and are served from a client cache on first read.

ExecImmediate runs SQL with op_execute_immediate (no OpExecute trailers). Reach it the same way through sql.Conn.Raw.

Inspect the negotiated version with ProtocolVersion() (same Raw pattern as WireCipher).

Deferred packets

On the lazy-send port type (ptype_lazy_send, negotiated with every server since Firebird 2.1) a request whose answer nothing depends on need not be waited for. The driver uses this in two ways:

  • Allocate + prepare go out in one write, and the two responses are read together (lazyResponseCount records how many responses the server still owes).
  • Cursor close (op_free_statement with DSQL_close, what rows.Close() sends when the statement stays prepared) is not written at all when it happens. It is queued and written in front of the next request on the connection, in the same packet, and its response is skipped when the next response is read. This is what fbclient (defer_packet), Jaybird (V11Statement: the close is written without a flush) and node-firebird do.

So a query on a prepared statement costs two packets in a transaction (execute, fetch) and three in autocommit mode (execute, fetch, commit retaining), instead of three and four. stmt.Close() (DSQL_drop) is still written immediately, so the statement's metadata locks are released at once; only its response is deferred. A queued close that is never followed by another request is dropped when the connection is closed: detaching releases every statement anyway.

The server processes the packets of one write in order, so a request that follows a queued close always sees the cursor closed. Deferred responses are plain op_response packets with no data; a response of another kind (fetch, sql, slice) can never be mistaken for one.

Local live tests

Protocol 18/19 integration tests use a read-only EMPLOYEE database:

localhost:3055
E:\Projects_2026\firebirdsql\EMPLOYEE.FDB

They skip automatically when that instance is unreachable.

Writable batch / ExecImmediate tests use GetTestDSN + firebirdsql_createdb on localhost:3050 (override with FIREBIRD_PORT) and also dial-skip when unreachable. Do not run DML against EMPLOYEE.

Optional 100k batch-vs-exec compare:

FIREBIRDSQL_BENCH=1 go test -run TestCompareBatchVsExecInsert100k -timeout 15m

Large batches may need BatchOptions.BufferBytes above the server default so all flushed rows fit until Exec.

Array columns

Firebird array columns are read through op_get_slice and written through op_put_slice. Metadata (element type, dimensions) is resolved from the system tables at prepare time.

// Write: generic wrappers, or plain slices (converted via the driver's NamedValueChecker)
db.ExecContext(ctx, "INSERT INTO t (id, ints) VALUES (?, ?)",
    1, firebirdsql.FlatArray[int64]{10, 20, 30})

// Read: 1-D flat target
var ints firebirdsql.FlatArray[int64]
rows.Scan(&ints)

// Multi-dimensional arrays keep their dimensions
db.ExecContext(ctx, "INSERT INTO t (id, grid) VALUES (?, ?)",
    1, firebirdsql.Array[int64]{Elements: []int64{1, 2, 3, 4},
        Dims:    []firebirdsql.ArrayDimension{{LowerBound: 0, Length: 2}, {LowerBound: 0, Length: 2}},
        Valid:   true})
var grid firebirdsql.Array[int64]
rows.Scan(&grid)

Element types: int16, int32, int64, float32, float64, string, time.Time (and bool for BOOLEAN arrays, Firebird 3+). Notes:

  • Writes shorter than the declared shape zero-fill the tail; reads always return the declared element count (never-written elements read as zeros / empty strings).
  • nil slices scan/param as SQL NULL. NULL elements inside an array are not representable in Firebird and are rejected on encode.
  • Scan targets must use FlatArray[T] / Array[T] (database/sql has no conversion from array columns to plain slices).
  • TIME/TIMESTAMP WITH TIME ZONE element types are not supported yet.
  • Array parameters are rejected in the batch API (server limitation).

Time and timestamp handling

Firebird's DATE, TIME, and TIMESTAMP types store wall-clock components without zone information - by design. When the driver decodes such a column into a Go time.Time, it must attach some *time.Location. Resolution order:

  1. If ?timezone=<IANA> is set on the DSN, that location is used; a fixed offset is also accepted (write it percent-encoded, ?timezone=%2B05:30; a raw + in a URL query becomes a space).
  2. Otherwise time.Local is used (matching Firebird's Java driver Jaybird, which uses the JVM default).

For cross-host determinism (e.g. app servers in different time zones all reading the same rows), set ?timezone=UTC on the DSN:

user:password@host/path/to/db?timezone=UTC

The same parameter also tells a Firebird 4+ server to evaluate CURRENT_TIMESTAMP and LOCALTIMESTAMP in that zone.

For applications that need explicit zone semantics at the schema level, use the Firebird 4+ types TIME WITH TIME ZONE and TIMESTAMP WITH TIME ZONE. Those columns carry their zone on the wire and are unaffected by the ?timezone= fallback.

Round-trip of naive time.Time values is wall-clock-preserving, not absolute-instant-preserving: inserting a value in zone A and reading it back on a host in zone B will return identical wall-clock components (year, month, day, hour, minute, second, nanosecond), but a.Equal(b) may be false. This matches Firebird's underlying storage model.

Transactions: READ COMMITTED + NOWAIT

Firebird supports NOWAIT transactions (lock conflicts return immediately instead of waiting). The standard database/sql sql.TxOptions doesn't have a knob for NOWAIT, so this driver exposes a driver-specific isolation level constant:

tx, err := db.BeginTx(ctx, &sql.TxOptions{
	Isolation: firebirdsql.LevelReadCommittedNoWait,
})

This maps to a transaction TPB containing READ COMMITTED, RECORD VERSION, and NOWAIT.

Row scanning on Go 1.27

When built with Go 1.27 or later, the driver implements database/sql/driver.RowsColumnScanner. Existing Rows.Next and Rows.Scan calls automatically use this path. A reusable row buffer calls the same driver.Rows.Next implementation as earlier Go versions, including BLOB and array fetching and errors. Exact int, int32, int64, float64, and bool destinations avoid reflection; out-of-range integers and other conversions use database/sql.ConvertAssign to preserve standard scan behavior and errors.

The minimum supported Go version remains 1.22. Earlier Go versions keep using driver.Rows.Next through database/sql.

On Go 1.27+, database/sql holds the connection lock while calling ScanColumn, including any custom sql.Scanner. A custom Scanner.Scan must not execute a query using the same *sql.Conn or *sql.Tx: this can deadlock, even if it worked with the earlier scanning path. Scan the values first, then run dependent queries after Rows.Scan returns.

GORM for Firebird

See https://github.com/flylink888/gorm-firebird

Frequently Asked Questions

What is firebirdsql?

firebirdsql is a Database Drivers library for the Go programming language. Firebird RDBMS SQL driver for Go

How do I install firebirdsql?

Install firebirdsql with the Go module system using `go get nakagami/firebirdsql`. Check the repository for the current installation instructions.

What category does firebirdsql belong to?

firebirdsql is listed under Database Drivers, specifically Relational Database Drivers.

← Back to Relational Database Drivers