From ac69fd6f91bdbeaa019fe593cfcb3365cfdcedb4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 1 Feb 2025 20:02:03 +0000 Subject: [PATCH 1/6] Bump golang.org/x/term from 0.27.0 to 0.28.0 Bumps [golang.org/x/term](https://github.com/golang/term) from 0.27.0 to 0.28.0. - [Commits](https://github.com/golang/term/compare/v0.27.0...v0.28.0) --- updated-dependencies: - dependency-name: golang.org/x/term dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- go.mod | 4 ++-- go.sum | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index 4932be8d..463d7941 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,7 @@ require ( github.com/pganalyze/pg_query_go/v5 v5.1.0 github.com/stretchr/testify v1.10.0 golang.org/x/sync v0.10.0 - golang.org/x/term v0.27.0 + golang.org/x/term v0.28.0 gopkg.in/yaml.v3 v3.0.1 modernc.org/sqlite v1.34.4 ) @@ -28,7 +28,7 @@ require ( github.com/tetratelabs/wazero v1.8.0 // indirect github.com/wasilibs/wazero-helpers v0.0.0-20240604052452-61d7981e9a38 // indirect golang.org/x/crypto v0.24.0 // indirect - golang.org/x/sys v0.28.0 // indirect + golang.org/x/sys v0.29.0 // indirect golang.org/x/text v0.19.0 // indirect modernc.org/libc v1.55.3 // indirect modernc.org/mathutil v1.6.0 // indirect diff --git a/go.sum b/go.sum index 2aded7cd..9ef576de 100644 --- a/go.sum +++ b/go.sum @@ -77,10 +77,10 @@ golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= -golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q= -golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= +golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU= +golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.28.0 h1:/Ts8HFuMR2E6IP/jlo7QVLZHggjKQbhu/7H0LJFr3Gg= +golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek= golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM= golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg= From 3b17a7ca39884571b03492f26fe99613eeca0ebf Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 1 Feb 2025 20:02:09 +0000 Subject: [PATCH 2/6] Bump modernc.org/sqlite from 1.34.4 to 1.34.5 Bumps [modernc.org/sqlite](https://gitlab.com/cznic/sqlite) from 1.34.4 to 1.34.5. - [Commits](https://gitlab.com/cznic/sqlite/compare/v1.34.4...v1.34.5) --- updated-dependencies: - dependency-name: modernc.org/sqlite dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- go.mod | 6 +----- go.sum | 8 ++------ 2 files changed, 3 insertions(+), 11 deletions(-) diff --git a/go.mod b/go.mod index 463d7941..5aa44413 100644 --- a/go.mod +++ b/go.mod @@ -15,7 +15,7 @@ require ( golang.org/x/sync v0.10.0 golang.org/x/term v0.28.0 gopkg.in/yaml.v3 v3.0.1 - modernc.org/sqlite v1.34.4 + modernc.org/sqlite v1.34.5 ) require ( @@ -33,18 +33,14 @@ require ( modernc.org/libc v1.55.3 // indirect modernc.org/mathutil v1.6.0 // indirect modernc.org/memory v1.8.0 // indirect - modernc.org/strutil v1.2.0 // indirect - modernc.org/token v1.1.0 // indirect ) require ( filippo.io/edwards25519 v1.1.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/dustin/go-humanize v1.0.1 // indirect - github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect github.com/ncruces/go-strftime v0.1.9 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/wasilibs/go-pgquery v0.0.0-20241011013927-817756c5aae4 google.golang.org/protobuf v1.31.0 // indirect - modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect ) diff --git a/go.sum b/go.sum index 9ef576de..b9160cad 100644 --- a/go.sum +++ b/go.sum @@ -32,8 +32,6 @@ github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlG github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= -github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/jessevdk/go-flags v1.6.1 h1:Cvu5U8UGrLay1rZfv/zP7iLpSHGUZ/Ou68T0iX1bBK4= github.com/jessevdk/go-flags v1.6.1/go.mod h1:Mk8T1hIAWpOiJiHa9rJASDK2UGWji0EuPGBnNLMooyc= github.com/k0kubun/pp/v3 v3.4.1 h1:1WdFZDRRqe8UsR61N/2RoOZ3ziTEqgTPVqKrHeb779Y= @@ -101,8 +99,6 @@ modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE= modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw= modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU= -modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI= -modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4= modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U= modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w= modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= @@ -113,8 +109,8 @@ modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc= modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss= -modernc.org/sqlite v1.34.4 h1:sjdARozcL5KJBvYQvLlZEmctRgW9xqIZc2ncN7PU0P8= -modernc.org/sqlite v1.34.4/go.mod h1:3QQFCG2SEMtc2nv+Wq4cQCH7Hjcg+p/RMlS1XK+zwbk= +modernc.org/sqlite v1.34.5 h1:Bb6SR13/fjp15jt70CL4f18JIN7p7dnMExd+UFnF15g= +modernc.org/sqlite v1.34.5/go.mod h1:YLuNmX9NKs8wRNK2ko1LW1NGYcc9FkBO69JOt1AR9JE= modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA= modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0= modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= From dd807b572844c06819f5007692db6a8d5bb11af5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 1 Feb 2025 20:09:55 +0000 Subject: [PATCH 3/6] Bump dependabot/fetch-metadata from 2.1.0 to 2.3.0 Bumps [dependabot/fetch-metadata](https://github.com/dependabot/fetch-metadata) from 2.1.0 to 2.3.0. - [Release notes](https://github.com/dependabot/fetch-metadata/releases) - [Commits](https://github.com/dependabot/fetch-metadata/compare/5e5f99653a5b510e8555840e80cbf1514ad4af38...d7267f607e9d3fb96fc2fbe83e0af444713e90b7) --- updated-dependencies: - dependency-name: dependabot/fetch-metadata dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/dependabot.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dependabot.yml b/.github/workflows/dependabot.yml index dedfbe47..f8c082d7 100644 --- a/.github/workflows/dependabot.yml +++ b/.github/workflows/dependabot.yml @@ -9,7 +9,7 @@ jobs: if: ${{ github.actor == 'dependabot[bot]' || github.actor == 'github-actions[bot]' }} steps: - name: Dependabot metadata - uses: dependabot/fetch-metadata@5e5f99653a5b510e8555840e80cbf1514ad4af38 # v2.1.0 + uses: dependabot/fetch-metadata@d7267f607e9d3fb96fc2fbe83e0af444713e90b7 # v2.3.0 id: metadata - name: Wait for status checks uses: lewagon/wait-on-check-action@ccfb013c15c8afb7bf2b7c028fb74dc5a068cccc # v1.3.4 From dba794be3400083c86ba7531126103a8255c8679 Mon Sep 17 00:00:00 2001 From: aki-s Date: Mon, 3 Feb 2025 01:11:23 +0900 Subject: [PATCH 4/6] [psqldef] Handle case when DDL didn't specify schema Partial fix for https://github.com/sqldef/sqldef/issues/605 --- cmd/psqldef/tests.yml | 75 +++++++++++++++++++++++++++++ schema/parser.go | 109 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 182 insertions(+), 2 deletions(-) diff --git a/cmd/psqldef/tests.yml b/cmd/psqldef/tests.yml index 5de622d5..09cd0f3d 100644 --- a/cmd/psqldef/tests.yml +++ b/cmd/psqldef/tests.yml @@ -570,6 +570,81 @@ CommentOnNonStandardDefaultSchema: COMMENT ON TABLE foo.users is 'users table updated'; COMMENT ON COLUMN foo.users.id is 'users id'; user: psqldef_user +#; TODO: Enable to pass the following comment outed case 'CommentUnset'. +#; 'Unsetting comment' is seen as 'change' false positively as of now (ref. +#; https://github.com/sqldef/sqldef/issues/605 ), because the specified comment +#; has no comment already before the application of sqldef, +# but then 'COMMENT ON ... IS NULL' clause is requested as a change. +#CommentUnset: +# current: | +# CREATE TABLE users ( +# id bigint +# ); +# COMMENT ON TABLE users IS 'users table is before update'; +# COMMENT ON COLUMN users.id IS 'users id column is before update'; +# desired: | +# CREATE TABLE users ( +# id bigint +# ); +# COMMENT ON TABLE users IS NULL; +# COMMENT ON COLUMN users.id IS null; +# output: | +# COMMENT ON TABLE public.users IS NULL; +# COMMENT ON COLUMN public.users.id IS null; +CommentWithoutSchema: + current: | + CREATE TABLE users ( + id bigint + ); + desired: | + CREATE TABLE users ( + id bigint + ); + COMMENT ON TABLE users is 'users table is updated'; + COMMENT ON COLUMN users.id is 'users id column is updated'; + output: | + COMMENT ON TABLE foo.users is 'users table is updated'; + COMMENT ON COLUMN foo.users.id is 'users id column is updated'; + user: psqldef_user # in cmd/psqldef/psqldef_test.go schema 'foo' is used if 'user' is provided. +CommentWithoutSchemaWithoutTableNameQuoted: + current: | + CREATE TABLE users ( + id bigint, + "update" boolean + ); + desired: | + CREATE TABLE users ( + id bigint, + "update" boolean + ); + COMMENT ON TABLE users IS 'users table is updated'; + COMMENT ON COLUMN users.id IS 'users.id column is updated'; + COMMENT ON COLUMN users."update" IS '"users."update" column is updated'; + # Default schema 'public' is needed be prefixed in output to prevent false positive detection of DDL change. + output: | + COMMENT ON TABLE public.users IS 'users table is updated'; + COMMENT ON COLUMN public.users.id IS 'users.id column is updated'; + COMMENT ON COLUMN public.users."update" IS '"users."update" column is updated'; +CommentWithoutSchemaWithTableNameQuoted: + current: | + CREATE TABLE "select" ( + id bigint, + "update" boolean + ); + desired: | + CREATE TABLE "select" ( + id bigint, + "update" boolean + ); + COMMENT ON TABLE "select" IS '"select" table is updated'; + COMMENT ON COLUMN "select".id IS '"select".id column is updated'; + COMMENT ON COLUMN "select"."update" IS '"select"."update" column is updated'; + # Default schema 'public' is needed be prefixed in output to prevent false positive detection of DDL change. + output: | + COMMENT ON TABLE public."select" IS '"select" table is updated'; + COMMENT ON COLUMN public."select".id IS '"select".id column is updated'; + COMMENT ON COLUMN public."select"."update" IS '"select"."update" column is updated'; + CommentContainingQuote: current: | CREATE TABLE public.test ( diff --git a/schema/parser.go b/schema/parser.go index 3965b305..7fac631c 100644 --- a/schema/parser.go +++ b/schema/parser.go @@ -4,6 +4,7 @@ package schema import ( "fmt" + "regexp" "strconv" "strings" @@ -174,8 +175,8 @@ func parseDDL(mode GeneratorMode, ddl string, stmt parser.Statement, defaultSche }, nil } else if stmt.Action == parser.CommentOn { return &Comment{ - statement: ddl, - comment: *stmt.Comment, + statement: normalizeTableInCommentOnStmt(mode, stmt.Comment, ddl, defaultSchema), + comment: *normalizeTableInComment(mode, stmt.Comment, defaultSchema), }, nil } else if stmt.Action == parser.CreateExtension { return &Extension{ @@ -675,6 +676,110 @@ func normalizeCollate(collate string, table parser.TableSpec) string { } } +func normalizeTableInComment(mode GeneratorMode, comment *parser.Comment, defaultSchema string) *parser.Comment { + switch mode { + case GeneratorModePostgres: + // Expected format is [schema.]table.column + objs := strings.Split(comment.Object, ".") + switch len(objs) { + case 0: // abnormal-case. fallback + return comment + case 1, 2: + switch comment.ObjectType { + case "OBJECT_TABLE": + if len(objs) == 1 { + objs = append([]string{defaultSchema}, objs...) + } + case "OBJECT_COLUMN": + if len(objs) == 2 { + objs = append([]string{defaultSchema}, objs...) + } + } + case 3: // complete-case (schema.table.column). no-op + return comment + case 4: // abnormal-case. fallback + return comment + } + // db.schema.table + return &parser.Comment{ + ObjectType: comment.ObjectType, + Object: strings.Join(objs, "."), + Comment: comment.Comment, + } + default: + return comment + } +} + +var regexCommentOnClause = regexp.MustCompile(`(?i)^(\s*COMMENT\s+ON\s+(?:TABLE|COLUMN)\s+)(?P.*)(\s+IS\s+(?:'[^']*'|NULL)\s*$)`) + +// Assume that give 'defaultSchema' is not quoted with double-quote and not surrounded with whitespaces. +func normalizeTableInCommentOnStmt(mode GeneratorMode, comment *parser.Comment, ddl string, defaultSchema string) string { + if defaultSchema == "" { + return ddl // fallback + } + if mode != GeneratorModePostgres { + return ddl // no special handling for non-Postgres + } else { + // Ignore line comment + if ok, _ := regexp.MatchString(`^\s*--`, ddl); ok { + // err is returned from MatchString only when pattern is invalid, so just ignore. + return ddl + } + matches := regexCommentOnClause.FindStringSubmatch(ddl) + if len(matches) != 4 { + // Neither table nor column name is found in COMMENT + return ddl // fallback + } + objs := make([]string, 0, 3) // objects of 'schema, table, and column' + sb := strings.Builder{} + q := false // true if in double quoting. + for _, c := range matches[2] { + switch c { + case '.': + if q { // '.' is a char if double-quoted. + sb.WriteRune(c) + } else { // "." is a separator. + if sb.Len() > 0 { // separate with '.' if not separated by `"` previously. + objs = append(objs, sb.String()) + sb.Reset() + } + } + case '"': // If either schema, table or column is double-quoted. + sb.WriteRune(c) + if q { // End double quoting. + objs = append(objs, sb.String()) + sb.Reset() + } + q = !q + default: + sb.WriteRune(c) + } + } + if sb.Len() > 0 { // flush buffer. + objs = append(objs, sb.String()) + sb.Reset() + } + switch l := len(objs); { + case l == 1 || l == 2: + switch comment.ObjectType { + case "OBJECT_TABLE": + if len(objs) == 1 { + return fmt.Sprintf(`%s%s.%s%s`, matches[1], defaultSchema, objs[0], matches[3]) + } + case "OBJECT_COLUMN": + if len(objs) == 2 { + return fmt.Sprintf(`%s%s.%s.%s%s`, matches[1], defaultSchema, objs[0], objs[1], matches[3]) + } + } + case l == 3: + return ddl // no need to normalize. + } + // fallback in other exceptional cases + return ddl + } +} + // Convert back `type BoolVal bool` func castBool(val parser.BoolVal) bool { ret, _ := strconv.ParseBool(fmt.Sprint(val)) From 62dba8cc65108b510e6ffc83e92dcb4371d8f013 Mon Sep 17 00:00:00 2001 From: ismk21 Date: Fri, 10 Jan 2025 15:35:39 +0900 Subject: [PATCH 5/6] Change the pkey using constraints --- cmd/psqldef/psqldef_test.go | 10 +++++----- database/postgres/database.go | 37 ++++++++++++++++++++++++++++++++--- schema/generator.go | 7 +++++-- 3 files changed, 44 insertions(+), 10 deletions(-) diff --git a/cmd/psqldef/psqldef_test.go b/cmd/psqldef/psqldef_test.go index fc7ab5e8..1767a960 100644 --- a/cmd/psqldef/psqldef_test.go +++ b/cmd/psqldef/psqldef_test.go @@ -1285,7 +1285,7 @@ func TestPsqldefExport(t *testing.T) { "c_char_10" character(10), "c_varchar_10" character varying(10), "c_varchar_unlimited" character varying, - PRIMARY KEY ("id") + CONSTRAINT users_pkey PRIMARY KEY ("id") ); ALTER TABLE "public"."users" ADD CONSTRAINT "users_c_char_1_key" UNIQUE (c_char_1); @@ -1312,7 +1312,7 @@ func TestPsqldefExportCompositePrimaryKey(t *testing.T) { "col1" character varying(40) NOT NULL, "col2" character varying(6) NOT NULL, "created_at" timestamp NOT NULL, - PRIMARY KEY ("col1", "col2") + CONSTRAINT users_pkey PRIMARY KEY ("col1", "col2") ); `, )) @@ -1351,17 +1351,17 @@ func TestPsqldefExportConcurrency(t *testing.T) { assertEquals(t, outputDefault, stripHeredoc(` CREATE TABLE "public"."users_1" ( "id" bigint NOT NULL, - PRIMARY KEY ("id") + CONSTRAINT users_1_pkey PRIMARY KEY ("id") ); CREATE TABLE "public"."users_2" ( "id" bigint NOT NULL, - PRIMARY KEY ("id") + CONSTRAINT users_2_pkey PRIMARY KEY ("id") ); CREATE TABLE "public"."users_3" ( "id" bigint NOT NULL, - PRIMARY KEY ("id") + CONSTRAINT users_3_pkey PRIMARY KEY ("id") ); `, )) diff --git a/database/postgres/database.go b/database/postgres/database.go index 54e28af5..f7c364ee 100644 --- a/database/postgres/database.go +++ b/database/postgres/database.go @@ -301,6 +301,14 @@ func (d *PostgresDatabase) dumpTableDDL(table string) (string, error) { if err != nil { return "", err } + // if pkey cols exist, retrieve the pkey name + pkeyName := "" + if len(pkeyCols) > 0 { + pkeyName, err = d.getPrimaryKeyName(table) + if err != nil { + return "", err + } + } indexDefs, err := d.getIndexDefs(table) if err != nil { return "", err @@ -329,10 +337,10 @@ func (d *PostgresDatabase) dumpTableDDL(table string) (string, error) { if err != nil { return "", err } - return buildDumpTableDDL(table, cols, pkeyCols, indexDefs, foreignDefs, exclusionDefs, policyDefs, comments, checkConstraints, uniqueConstraints, d.GetDefaultSchema()), nil + return buildDumpTableDDL(table, cols, pkeyName, pkeyCols, indexDefs, foreignDefs, exclusionDefs, policyDefs, comments, checkConstraints, uniqueConstraints, d.GetDefaultSchema()), nil } -func buildDumpTableDDL(table string, columns []column, pkeyCols, indexDefs, foreignDefs, exclusionDefs, policyDefs, comments []string, checkConstraints, uniqueConstraints map[string]string, defaultSchema string) string { +func buildDumpTableDDL(table string, columns []column, pkeyName string, pkeyCols, indexDefs, foreignDefs, exclusionDefs, policyDefs, comments []string, checkConstraints, uniqueConstraints map[string]string, defaultSchema string) string { var queryBuilder strings.Builder schema, table := splitTableName(table, defaultSchema) fmt.Fprintf(&queryBuilder, "CREATE TABLE %s.%s (", escapeSQLName(schema), escapeSQLName(table)) @@ -357,7 +365,7 @@ func buildDumpTableDDL(table string, columns []column, pkeyCols, indexDefs, fore } if len(pkeyCols) > 0 { fmt.Fprint(&queryBuilder, ",\n"+indent) - fmt.Fprintf(&queryBuilder, "PRIMARY KEY (\"%s\")", strings.Join(pkeyCols, "\", \"")) + fmt.Fprintf(&queryBuilder, "CONSTRAINT %s PRIMARY KEY (\"%s\")", pkeyName, strings.Join(pkeyCols, "\", \"")) } for constraintName, constraintDef := range checkConstraints { fmt.Fprint(&queryBuilder, ",\n"+indent) @@ -680,6 +688,29 @@ WHERE constraint_type = 'PRIMARY KEY' AND tc.table_schema=$1 AND tc.table_name=$ return columnNames, nil } +func (d *PostgresDatabase) getPrimaryKeyName(table string) (string, error) { + schema, table := splitTableName(table, d.GetDefaultSchema()) + query := fmt.Sprintf(`SELECT + conname from pg_constraint where conrelid = '%s.%s'::regclass and contype = 'p'`, schema, table) + //tableWithSchema := fmt.Sprintf("'%s.%s'::regclass", schema, table) + rows, err := d.db.Query(query) + if err != nil { + return "", err + } + defer rows.Close() + + var keyName string + if rows.Next() { + err = rows.Scan(&keyName) + if err != nil { + return "", err + } + } else { + return "", err + } + return keyName, nil +} + // refs: https://gist.github.com/PickledDragon/dd41f4e72b428175354d func (d *PostgresDatabase) getForeignDefs(table string) ([]string, error) { const query = `SELECT diff --git a/schema/generator.go b/schema/generator.go index 71a3942a..2d14aca8 100644 --- a/schema/generator.go +++ b/schema/generator.go @@ -625,8 +625,7 @@ func (g *Generator) generateDDLsForCreateTable(currentTable Table, desired Creat case GeneratorModeMysql: ddls = append(ddls, fmt.Sprintf("ALTER TABLE %s DROP PRIMARY KEY", g.escapeTableName(desired.table.name))) case GeneratorModePostgres: - tableName := strings.SplitN(desired.table.name, ".", 2)[1] // without schema - ddls = append(ddls, fmt.Sprintf("ALTER TABLE %s DROP CONSTRAINT %s", g.escapeTableName(desired.table.name), g.escapeSQLName(tableName+"_pkey"))) + ddls = append(ddls, fmt.Sprintf("ALTER TABLE %s DROP CONSTRAINT %s", g.escapeTableName(desired.table.name), g.escapeSQLName(currentPrimaryKey.name))) case GeneratorModeMssql: ddls = append(ddls, fmt.Sprintf("ALTER TABLE %s DROP CONSTRAINT %s", g.escapeTableName(desired.table.name), g.escapeSQLName(currentPrimaryKey.name))) default: @@ -1361,6 +1360,10 @@ func (g *Generator) generateAddIndex(table string, index Index) string { "ALTER TABLE %s ADD ", g.escapeTableName(table), ) + if strings.ToUpper(index.indexType) == "PRIMARY KEY" && index.primary && + (index.name != "" && index.name != "PRIMARY" && index.name != index.columns[0].column) { + ddl += fmt.Sprintf("CONSTRAINT %s ", g.escapeSQLName(index.name)) + } if strings.ToUpper(index.indexType) == "UNIQUE KEY" { ddl += "CONSTRAINT" } else { From 5a601d84120950dac71b2c77f919a9700c27bf15 Mon Sep 17 00:00:00 2001 From: Kazuhito Hokamura Date: Mon, 10 Feb 2025 08:29:47 +0900 Subject: [PATCH 6/6] Version v0.17.30 --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d695025a..caf6e903 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +## v0.17.30 + +* psqldef: Change the pkey using constraints [#609](https://github.com/sqldef/sqldef/pull/609) +* psqldef: Handle case when schema is not specified in COMMENT ON clause [#606](https://github.com/sqldef/sqldef/pull/606) + ## v0.17.29 * psqldef: Fix altering partitions [#597](https://github.com/sqldef/sqldef/pull/597)