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

FOREIGN KEY violation when []byte(nil) is used

Open foxcpp opened this issue 1 year ago • 3 comments

When I pass []byte(nil) as an argument to INSERT, unexpected FOREIGN KEY violation happens.

Expected behavior Row is successfully inserted.

Actual behavior Error is returned from INSERT: constraint failed: FOREIGN KEY constraint failed (787)

However:

  1. Using modernc.org/[email protected] as a driver works fine.
  2. Using github.com/mattn/[email protected] as a driver works fine.
  3. Passing nil (not []byte(nil)) works fine.
  4. If foreign key constraints are disabled, the row is inserted successfully and has correct NULL value as parent_id.
Code to reproduce

package main

import (
        "database/sql"
        "log"
        _ "github.com/glebarez/go-sqlite"
)

func main() {
        db, err := sql.Open("sqlite", ":memory:?_pragma=foreign_keys(1)&_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)")
        if err != nil {
                log.Fatalln(err)
        }
        defer db.Close()
        db.SetMaxOpenConns(1)
        db.SetMaxIdleConns(1)

        _, err = db.Exec(`CREATE TABLE test(id BLOB NOT NULL PRIMARY KEY, parent_id BLOB DEFAULT NULL REFERENCES test(id))`)
        if err != nil {
                log.Fatalln(err)
        }
        log.Println("create table ok")

        _, err = db.Exec(`INSERT INTO test(id, parent_id) VALUES (?, ?)`, []byte("abc"), []byte(nil))
        if err != nil {
                log.Fatalln(err)
        }

        log.Println("insert ok")
}

foxcpp avatar Feb 26 '25 20:02 foxcpp