go-sqlite3 icon indicating copy to clipboard operation
go-sqlite3 copied to clipboard

Include UUID extension

Open zepatrik opened this issue 8 months ago • 2 comments

There is a very handy extension for generating UUIDs in sqlite: https://sqlite.org/src/file/ext/misc/uuid.c It would be nice to include it into go-sqlite3 as a loadable extension. It's actually very small and shouldn't add too much overhead, so it could also be loaded per default.

I did not really understand how the upgrade tool pulls in extensions, or how I would add the extension there.

As an alternative, one can create a new instance of the driver with a go implementation. I successfully made that work, but it was basically impossible to use with other libraries like ORMs due to the self-initialization nature of the go SQL drivers.

zepatrik avatar Mar 29 '25 11:03 zepatrik

This would be a great addition imo.

For those wanting uuid functionality in the meantime, you can register it with the driver something like this (this specific one is in conjunction with sqlc):

import (
        "database/sql"
        "log"
        "os"

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

type Database struct {
        Conn    *sql.DB
        Queries *Queries
}

// opens the `DB_STRING` sqlite database.
func (db *Database) Connect() {
        // register the sqlite driver with a uuid function
        sql.Register("sqlite3_uuid", &sqlite3.SQLiteDriver{
                ConnectHook: func(sc *sqlite3.SQLiteConn) error {
                        return sc.RegisterFunc("uuid", func() string {
                                return uuid.New().String()
                        }, true)
                },
        })

        // open the sqlite connection
        conn, err := sql.Open("sqlite3_uuid", os.Getenv("DB_STRING"))
        if err != nil {
                log.Fatalf("failed to open sqlite database: %v", err)
        }

        db.Conn = conn
        db.Queries = New(db.Conn)
}

dimmerz92 avatar Apr 12 '25 14:04 dimmerz92

It would clash with other uuid() extensions already in use. For instance we have our own monotonic uuid implementation, which I think is more useful in practise.

andelo avatar Jun 25 '25 16:06 andelo