8000 Disable quote_schema on Redshift dialect by Tin-Nguyen · Pull Request #290 · sqlalchemy-redshift/sqlalchemy-redshift · GitHub
[go: up one dir, main page]

Skip to content

Disable quote_schema on Redshift dialect #290

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 23 additions & 7 deletions sqlalchemy_redshift/dialect.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import re
from collections import defaultdict, namedtuple
from logging import getLogger
from typing import Any, Optional

import pkg_resources
import sqlalchemy as sa
Expand Down Expand Up @@ -438,9 +439,9 @@ def __new__(cls, name, schema=None, connection=None):

def __str__(self):
if self.schema is None:
return self.name
return RelationKey._unquote(self.name)
else:
return self.schema + "." + self.name
return RelationKey._unquote(self.schema) + "." + RelationKey._unquote(self.name)

@staticmethod
def _unquote(part):
Expand Down Expand Up @@ -654,6 +655,9 @@ def visit_HLLSKETCH(self, type_, **kw):
class RedshiftIdentifierPreparer(PGIdentifierPreparer):
reserved_words = RESERVED_WORDS

def quote_schema(self, schema: Any, force: Optional[bool] = ...) -> str:
return schema


class RedshiftDialectMixin(DefaultDialect):
"""
Expand All @@ -670,6 +674,7 @@ class RedshiftDialectMixin(DefaultDialect):
statement_compiler = RedshiftCompiler
ddl_compiler = RedshiftDDLCompiler
preparer = RedshiftIdentifierPreparer
identifier_preparer = RedshiftIdentifierPreparer
type_compiler = RedshiftTypeCompiler
construct_arguments = [
(sa.schema.Index, {
Expand Down Expand Up @@ -793,12 +798,12 @@ def get_check_constraints(self, connection, table_name, schema=None, **kw):
def get_table_oid(self, connection, table_name, schema=None, **kw):
"""Fetch the oid for schema.table_name.
Return null if not found (external table does not have table oid)"""
schema_field = '"{schema}".'.format(schema=schema) if schema else ""
schema_field = '{schema}.'.format(schema=schema) if schema else ""

result = connection.execute(
sa.text(
"""
select '{schema_field}"{table_name}"'::regclass::oid;
select '{schema_field}{table_name}'::regclass::oid;
""".format(
schema_field=schema_field,
table_name=table_name
Expand Down Expand Up @@ -857,8 +862,8 @@ def get_foreign_keys(self, connection, table_name, schema=None, **kw):
fkey_d = {
'name': conname,
'constrained_columns': constrained_columns,
'referred_schema': referred_schema,
'referred_table': referred_table,
'referred_schema': self.unquote(referred_schema),
'referred_table': self.unquote(referred_table),
'referred_columns': referred_columns,
}
fkeys.append(fkey_d)
Expand Down Expand Up @@ -908,6 +913,16 @@ def get_indexes(self, connection, table_name, schema, **kw):
"""
return []

@staticmethod
def unquote(text):
if text is None:
return None

if text.startswith('"') and text.endswith('"'):
return text[1:-1]

return text

@reflection.cache
def get_unique_constraints(self, connection, table_name,
schema=None, **kw):
Expand Down Expand Up @@ -977,7 +992,7 @@ def _get_table_or_view_names(self, relkind, connection, schema=None, **kw):
relation_names = []
for key, relation in all_relations.items():
if key.schema == schema and relation.relkind == relkind:
relation_names.append(key.name)
relation_names.append(self.unquote(key.name))
return relation_names

def _get_column_info(self, *args, **kwargs):
Expand Down Expand Up @@ -1110,6 +1125,7 @@ def _get_all_relation_info(self, connection, **kw):
@reflection.cache
def _get_schema_column_info(self, connection, **kw):
schema = kw.get('schema', None)
schema = self.unquote(schema)
schema_clause = (
"AND schema = '{schema}'".format(schema=schema) if schema else ""
)
Expand Down
11 changes: 11 additions & 0 deletions tests/rs_sqla_test_utils/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,17 @@ class BasicInOtherSchema(Base):
col1 = sa.Column(sa.Integer(), primary_key=True)


class BasicInIncludingDotSchema(Base):
__tablename__ = 'basic'
__table_args__ = (
{'schema': 'dotted.schema',
'redshift_diststyle': 'KEY',
'redshift_distkey': 'col1',
'redshift_sortkey': 'col1'}
)
col1 = sa.Column(sa.Integer(), primary_key=True)


class ReflectionDistKey(Base):
__tablename__ = 'reflection_distkey'
col1 = sa.Column(sa.Integer(), primary_key=True)
Expand Down
9 changes: 9 additions & 0 deletions tests/test_compiler.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
from sqlalchemy import func, select

from tests.rs_sqla_test_utils import models


def test_func_now(stub_redshift_dialect):
dialect = stub_redshift_dialect
s = select([func.NOW().label("time")])
compiled = s.compile(dialect=dialect)
assert str(compiled) == "SELECT SYSDATE AS time"

def test_unquoting_schema(stub_redshift_dialect):
dialect = stub_redshift_dialect
s = select(models.BasicInIncludingDotSchema.col1).where(models.BasicInIncludingDotSchema.col1 == 1)
compiled = s.compile(dialect=dialect)
assert "dotted.schema" in str(compiled)
assert "\"dotted.schema\"" not in str(compiled)
0