Skip to content

Commit

Permalink
Restrict state connection search path (#342)
Browse files Browse the repository at this point in the history
Restrict the search path of the connection used by the state package to
only the state schema (the schema that contains the `migrations` table).

This ensures that any column types that might reside in other schema are
always qualified with the schema name in the internal schema
representation. Without the restriction of the search path, these type
names would be unqualified if they lived in a schema that was on the
search path used by the state connection.

The representation (qualified/unqualified) of type names in the internal
schema is ultimately due to how the
[format-type](https://www.postgresql.org/docs/9.5/functions-info.html)
function behaves; types in the `search_path` of the caller are
unqualified, otherwise they are qualified.
  • Loading branch information
andrew-farries committed Apr 22, 2024
1 parent 37d2c28 commit a444723
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
9 changes: 8 additions & 1 deletion pkg/state/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,14 @@ type State struct {
}

func New(ctx context.Context, pgURL, stateSchema string) (*State, error) {
conn, err := sql.Open("postgres", pgURL)
dsn, err := pq.ParseURL(pgURL)
if err != nil {
dsn = pgURL
}

dsn += " search_path=" + stateSchema

conn, err := sql.Open("postgres", dsn)
if err != nil {
return nil, err
}
Expand Down
24 changes: 24 additions & 0 deletions pkg/state/state_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -705,6 +705,30 @@ func TestReadSchema(t *testing.T) {
},
},
},
{
name: "column whose type is a UDT in another schema should have the type prefixed with the schema",
createStmt: "CREATE DOMAIN email_type AS varchar(255); CREATE TABLE public.table1 (a email_type);",
wantSchema: &schema.Schema{
Name: "public",
Tables: map[string]schema.Table{
"table1": {
Name: "table1",
Columns: map[string]schema.Column{
"a": {
Name: "a",
Type: "public.email_type",
Nullable: true,
},
},
PrimaryKey: []string{},
Indexes: map[string]schema.Index{},
ForeignKeys: map[string]schema.ForeignKey{},
CheckConstraints: map[string]schema.CheckConstraint{},
UniqueConstraints: map[string]schema.UniqueConstraint{},
},
},
},
},
}

for _, tt := range tests {
Expand Down

0 comments on commit a444723

Please sign in to comment.