Skip to content
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

Fix templating in sqla datasource [has migration] #4971

Merged
merged 3 commits into from
May 10, 2018
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ describe('VisualizeModal', () => {
schema: 'test_schema',
sql: wrapper.instance().props.query.sql,
dbId: wrapper.instance().props.query.dbId,
templateParams: wrapper.instance().props.templateParams,
});
});

Expand Down
1 change: 1 addition & 0 deletions superset/assets/src/SqlLab/components/VisualizeModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ class VisualizeModal extends React.PureComponent {
columns: this.state.columns,
sql: this.props.query.sql,
dbId: this.props.query.dbId,
templateParams: this.props.query.templateParams,
};
}
buildVisualizeAdvise() {
Expand Down
5 changes: 3 additions & 2 deletions superset/connectors/sqla/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,13 +272,14 @@ class SqlaTable(Model, BaseDatasource):
schema = Column(String(255))
sql = Column(Text)
is_sqllab_view = Column(Boolean, default=False)
template_params = Column(Text)

baselink = 'tablemodelview'

export_fields = (
'table_name', 'main_dttm_col', 'description', 'default_endpoint',
'database_id', 'offset', 'cache_timeout', 'schema',
'sql', 'params')
'sql', 'params', 'template_params')
export_parent = 'database'
export_children = ['metrics', 'columns']

Expand Down Expand Up @@ -491,8 +492,8 @@ def get_sqla_query( # sqla
'to_dttm': to_dttm,
'filter': filter,
'columns': {col.column_name: col for col in self.columns},

}
template_kwargs.update(self.template_params_dict)
template_processor = self.get_template_processor(**template_kwargs)
db_engine_spec = self.database.db_engine_spec

Expand Down
6 changes: 5 additions & 1 deletion superset/connectors/sqla/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ class TableModelView(DatasourceModelView, DeleteMixin, YamlExportMixin): # noqa
'fetch_values_predicate', 'database', 'schema',
'description', 'owner',
'main_dttm_col', 'default_endpoint', 'offset', 'cache_timeout',
'is_sqllab_view',
'is_sqllab_view', 'template_params',
]
base_filters = [['id', DatasourceFilter, lambda: []]]
show_columns = edit_columns + ['perm']
Expand Down Expand Up @@ -220,6 +220,9 @@ class TableModelView(DatasourceModelView, DeleteMixin, YamlExportMixin): # noqa
'is_sqllab_view': _(
"Whether the table was generated by the 'Visualize' flow "
'in SQL Lab'),
'template_params': _(
'A set of parameters that become available in the query using '
'Jinja templating syntax'),
}
label_columns = {
'slices': _('Associated Charts'),
Expand All @@ -238,6 +241,7 @@ class TableModelView(DatasourceModelView, DeleteMixin, YamlExportMixin): # noqa
'main_dttm_col': _('Main Datetime Column'),
'description': _('Description'),
'is_sqllab_view': _('SQL Lab View'),
'template_params': _('Template parameters'),
}

def pre_add(self, table):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""add template_params to tables

Revision ID: e502db2af7be
Revises: 5ccf602336a0
Create Date: 2018-05-09 23:45:14.296283

"""

# revision identifiers, used by Alembic.
revision = 'e502db2af7be'
down_revision = '5ccf602336a0'

from alembic import op
import sqlalchemy as sa


def upgrade():
op.add_column('tables',
sa.Column('template_params', sa.Text(), nullable=True))


def downgrade():
try:
op.drop_column('tables', 'template_params')
except Exception as e:
logging.warning(str(e))
20 changes: 14 additions & 6 deletions superset/models/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@
from superset.utils import QueryStatus


def json_to_dict(json_str):
if json_str:
val = re.sub(',[ \t\r\n]+}', '}', json_str)
val = re.sub(',[ \t\r\n]+\]', ']', val)
return json.loads(val)
else:
return {}


class ImportMixin(object):
export_parent = None
# The name of the attribute
Expand Down Expand Up @@ -216,12 +225,11 @@ def alter_params(self, **kwargs):

@property
def params_dict(self):
if self.params:
params = re.sub(',[ \t\r\n]+}', '}', self.params)
params = re.sub(',[ \t\r\n]+\]', ']', params)
return json.loads(params)
else:
return {}
return json_to_dict(self.params)

@property
def template_params_dict(self):
return json_to_dict(self.template_params)


class AuditMixinNullable(AuditMixin):
Expand Down
2 changes: 2 additions & 0 deletions superset/views/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -2144,6 +2144,7 @@ def sqllab_viz(self):
SqlaTable = ConnectorRegistry.sources['table']
data = json.loads(request.form.get('data'))
table_name = data.get('datasourceName')
template_params = data.get('templateParams')
table = (
db.session.query(SqlaTable)
.filter_by(table_name=table_name)
Expand All @@ -2153,6 +2154,7 @@ def sqllab_viz(self):
table = SqlaTable(table_name=table_name)
table.database_id = data.get('dbId')
table.schema = data.get('schema')
table.template_params = data.get('templateParams')
table.is_sqllab_view = True
q = SupersetQuery(data.get('sql'))
table.sql = q.stripped()
Expand Down