Skip to content

Commit

Permalink
Add example of custom numeric type
Browse files Browse the repository at this point in the history
The main trick is to specify the override on NewQuerierConfig and not on
ConnInfo.RegisterDataType. We can't easily get the data types for pgxpool.Pool
because we need to get a real *Conn which then fetches a connection from the
 pool.

Partially resolves #39.
  • Loading branch information
jschaf committed Sep 7, 2021
1 parent e7492c1 commit 7f87888
Show file tree
Hide file tree
Showing 9 changed files with 504 additions and 1 deletion.
8 changes: 8 additions & 0 deletions example/acceptance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,14 @@ func TestExamples(t *testing.T) {
"--go-type", "text=string",
},
},
{
name: "example/numeric_external",
args: []string{
"--schema-glob", "example/numeric_external/schema.sql",
"--query-glob", "example/numeric_external/query.sql",
"--go-type", "numeric=github.com/shopspring/decimal.Decimal",
},
},
{
name: "example/domain",
args: []string{
Expand Down
50 changes: 50 additions & 0 deletions example/numeric_external/codegen_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package numeric_external

import (
"github.com/jschaf/pggen"
"github.com/jschaf/pggen/internal/pgtest"
"github.com/stretchr/testify/assert"
"io/ioutil"
"path/filepath"
"testing"
)

func TestGenerate_Go_Example_Numeric_External(t *testing.T) {
conn, cleanupFunc := pgtest.NewPostgresSchema(t, []string{"schema.sql"})
defer cleanupFunc()

tmpDir := t.TempDir()
err := pggen.Generate(
pggen.GenerateOptions{
ConnString: conn.Config().ConnString(),
QueryFiles: []string{"query.sql"},
OutputDir: tmpDir,
GoPackage: "numeric_external",
Language: pggen.LangGo,
TypeOverrides: map[string]string{
"int4": "int",
"int8": "int",
"text": "string",
"numeric": "github.com/shopspring/decimal.Decimal",
},
})
if err != nil {
t.Fatalf("Generate(): %s", err)
}

wantQueriesFile := "query.sql.go"
gotQueriesFile := filepath.Join(tmpDir, "query.sql.go")
assert.FileExists(t, gotQueriesFile,
"Generate() should emit query.sql.go")
wantQueries, err := ioutil.ReadFile(wantQueriesFile)
if err != nil {
t.Fatalf("read wanted query.go.sql: %s", err)
}
gotQueries, err := ioutil.ReadFile(gotQueriesFile)
if err != nil {
t.Fatalf("read generated query.go.sql: %s", err)
}
assert.Equalf(t, string(wantQueries), string(gotQueries),
"Got file %s; does not match contents of %s",
gotQueriesFile, wantQueriesFile)
}
7 changes: 7 additions & 0 deletions example/numeric_external/query.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
-- name: InsertNumeric :exec
INSERT INTO numeric_external (num, num_arr)
VALUES (pggen.arg('num'), pggen.arg('num_arr'));

-- name: FindNumerics :many
SELECT num, num_arr
FROM numeric_external;
Loading

0 comments on commit 7f87888

Please sign in to comment.