Skip to content

howto make pragma statements persistent, e.g. for foreign_keys checks #255

Closed
@bernhardreiter

Description

@bernhardreiter

Hello!

Writing a small RESTful webserver application, we rely on constrains in the sqlite db.
In our app the foreign_key checks were working once every second time. We figured that
go-sqlite3 will open several connections, probably recycling some, and some of the pool did not have
the "PRAGMA foreign_keys = ON" set.

Our solution was to use a connect_hook like

import (
        "database/sql"

        sqlite3 "github.com/mattn/go-sqlite3"
)

func init() {
        sql.Register("sqlite3_with_fk",
                &sqlite3.SQLiteDriver{
                        ConnectHook: func(conn *sqlite3.SQLiteConn) error {
                                _, err := conn.Exec("PRAGMA foreign_keys = ON", nil)
                                return err
                        },
                })
}

and later calling

sql.Open("sqlite3_with_fk", dataSourceName)

Is this the best way of doing this?

Because this is a common use case, people wanting to set some sqlite PRAGMAs
and use them everytims, we suggest to add a hint to the documentation.

Best Regards and thanks for creating go-sqlite3 as Free Software!
Bernhard

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions