Restrict state connection search path (#342)

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.
This commit is contained in:
Andrew Farries 2024-04-22 08:38:11 +01:00 committed by GitHub
parent 37d2c28803
commit a444723691
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 32 additions and 1 deletions

View File

@ -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
}

View File

@ -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 {