Skip to content

use current_schema for postgres TableExists, if schema is unspecified#884

Merged
mfridman merged 2 commits intopressly:masterfrom
AndersSoee:use-current-schema-for-postgres-table-exists
Jan 7, 2025
Merged

use current_schema for postgres TableExists, if schema is unspecified#884
mfridman merged 2 commits intopressly:masterfrom
AndersSoee:use-current-schema-for-postgres-table-exists

Conversation

@AndersSoee
Copy link
Copy Markdown
Contributor

This will check if the table exists in the schema where it will otherwise be created.
The current solution will fail if the table exists in another schema

return fmt.Sprintf(q, schemaName, tableName)
}
q := `SELECT EXISTS ( SELECT 1 FROM pg_tables WHERE tablename = '%s' )`
q := `SELECT EXISTS ( SELECT 1 FROM pg_tables WHERE schemaname = current_schema() AND tablename = '%s' )`
Copy link
Copy Markdown
Collaborator

@mfridman mfridman Jan 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we go down this route, then we should also handle the edge case where current_schema () returns NULL.

Returns the name of the schema that is first in the search path (or a null value if the search path is empty). This is the schema that will be used for any tables or other named objects that are created without specifying a target schema.

E.g., SET search_path TO '';

So the suggestion is to update the predicate to:

- AND schemaname = current_schema()
+ AND (current_schema() IS NULL OR schemaname = current_schema())

What do you think?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm all for being defensive here.
Updated the PR.

In practice, though, you get a [3F000] ERROR: no schema has been selected to create in when trying to create a table and current_schema() is NULL, so the later steps would fail.

@mfridman mfridman merged commit 4337eb2 into pressly:master Jan 7, 2025
@mfridman
Copy link
Copy Markdown
Collaborator

mfridman commented Jan 7, 2025

lgtm, thanks for your input!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants