sqlc icon indicating copy to clipboard operation
sqlc copied to clipboard

Generated sqlite query to update on conflict fails with missing param

Open joeriddles opened this issue 9 months ago • 6 comments

Version

1.27.0

What happened?

Using the schema and query to update a row on insertion conflict with the following Go test fails:

package db

import (
	"context"
	"database/sql"
	"os"
	"testing"
	"time"

	_ "modernc.org/sqlite"
)

func TestSavePin(t *testing.T) {
	_, err := os.Create("test.sqlite")
	if err != nil {
		t.Fatal(err.Error())
	}

	db, err := sql.Open("sqlite", "test.sqlite")
	if err != nil {
		t.Fatal(err.Error())
	}

	schema, err := os.ReadFile("../schema.sql")
	if err != nil {
		t.Fatal(err.Error())
	}

	_, err = db.Exec(string(schema))
	if err != nil {
		t.Fatal(err.Error())
	}

	q := New(db)

	pin, err := q.SavePin(context.Background(), SavePinParams{
		Title:     "title",
		Url:       sql.NullString{String: "url", Valid: true},
		ImageUrl:  sql.NullString{},
		CreatedAt: time.Now().UnixMilli(),
	})
	if err != nil {
		t.Fatal(err.Error())
	}
	_ = pin
}

The test fails with this output:

--- FAIL: TestSavePin (0.00s)
    query_test.go:43: missing argument with index 5
FAIL
FAIL    github.com/joeriddles/patina/server/db  0.521s
FAIL

Relevant log output

--- FAIL: TestSavePin (0.00s)
    query_test.go:43: missing argument with index 5
FAIL
FAIL    github.com/joeriddles/patina/server/db  0.521s
FAIL

Database schema

-- schema.sql
CREATE TABLE pins (
  id INTEGER PRIMARY KEY,
  title TEXT NOT NULL,
  url TEXT,
  image_url TEXT,
  created_at INTEGER NOT NULL
);

CREATE UNIQUE INDEX unique_url_idx ON pins (url);

SQL queries

-- name: SavePin :one
INSERT INTO pins (
  title, url, image_url, created_at
) VALUES (
  ?, ?, ?, ?
)
ON CONFLICT (url)
DO UPDATE SET title = ?, image_url = ?
RETURNING *;

Configuration

version: "2"
sql:
  - engine: "sqlite"
    schema: "schema.sql"
    queries: "query.sql"
    gen:
      go:
        package: "db"
        out: "db"
        emit_json_tags: true

Playground URL

https://play.sqlc.dev/p/f96a629951bbdfebc68f4cfd2810025dc258c82e832ad2b8d6792946b71379f1

https://play.sqlc.dev/p/a5be075614744d3a900e38b3061c790b5962f4966f1b09be4d57ec28aa65c792 (named params)

What operating system are you using?

macOS

What database engines are you using?

SQLite

What type of code are you generating?

Go

joeriddles avatar Feb 11 '25 03:02 joeriddles