Exemple #1
0
class Foo(Model):
    __tablename__ = 'foo'
    query_class = FooQuery

    _id = Column(types.Integer(), primary_key=True)
    string = Column(types.String())
    string2 = Column(types.String())
    number = Column(types.Integer())
    boolean = Column(types.Boolean(), default=True)
    deferred1_col1 = orm.deferred(Column(types.Boolean()), group='deferred_1')
    deferred1_col2 = orm.deferred(Column(types.Boolean()), group='deferred_1')
    deferred2_col3 = orm.deferred(Column(types.Boolean()), group='deferred_2')
    deferred2_col4 = orm.deferred(Column(types.Boolean()), group='deferred_2')

    bars = orm.relationship('Bar', lazy=True)
    quxs = orm.relationship('Qux', lazy=True)

    @orm.validates('number')
    def validate_number(self, key, value):
        if value < 0:
            raise ValueError('"number" must be positive')
        return value

    def view_joined(self):
        return self.query.options(
            orm.joinedload('bars').joinedload('bazs'), orm.joinedload('quxs'))
Exemple #2
0
class Bar(Model):
    __tablename__ = 'bar'
    query_class = BarQuery

    _id = Column(types.Integer(), primary_key=True)
    string = Column(types.String())
    number = Column(types.Integer())
    foo_id = Column(types.Integer(), ForeignKey('foo._id'))
    deferred1_col1 = orm.deferred(Column(types.Boolean()),
                                  group='bar_deferred_1')
    deferred2_col2 = orm.deferred(Column(types.Boolean()),
                                  group='bar_deferred_2')

    foo = orm.relationship('Foo')
    bazs = orm.relationship('Baz')
Exemple #3
0
def upgrade_3(session, metadata):
    """
    Version 3 upgrade.

    This upgrade adds a temporary song flag to the songs table
    """
    op = get_upgrade_op(session)
    songs_table = Table('songs', metadata, autoload=True)
    if 'temporary' not in [col.name for col in songs_table.c.values()]:
        if metadata.bind.url.get_dialect().name == 'sqlite':
            op.add_column('songs', Column('temporary', types.Boolean(create_constraint=False), server_default=false()))
        else:
            op.add_column('songs', Column('temporary', types.Boolean(), server_default=false()))
    else:
        log.warning('Skipping upgrade_3 step of upgrading the song db')
Exemple #4
0
class User(AutoTableMixin, UserMixin, BaseAuthModel):
    """Basic user model"""

    __tablename__ = 'users'

    # TODO: Replace this with something real
    user_database = {'admin': ('admin', 'admin'), 'guest': ('guest', 'guest')}

    id = Column(types.Integer, primary_key=True)
    display_name = Column(types.String)
    email = Column(types.String, unique=True)
    username = Column(types.String, unique=True)
    password = Column(types.String)
    active = Column(types.Boolean())
    confirmed_at = Column(types.DateTime())
    roles = orm.relationship('Role',
                             secondary=roles_users,
                             backref=orm.backref('users', lazy='dynamic'))

    def __init__(self, username, password, email):
        self.password = password
        self.email = email
        self.username = username

    @classmethod
    def get(cls, id):
        return cls.user_database.get(id)

    def __repr__(self):
        cname = self.__class__.__name__
        name = ':{} "{}"'.format(self.username, self.display_name)
        string = '<{cname}{name}>'.format(cname=cname, name=name)
        return string
Exemple #5
0
class User(models.Base):
    __tablename__ = 'users'

    id = Column(types.Integer(), primary_key=True, autoincrement=True)
    fullname = Column(types.String(50), nullable=False)
    username = Column(types.String(50),
                      nullable=False,
                      unique=True,
                      index=True)
    password_hash = Column(types.String(128), nullable=False)
    is_active = Column(types.Boolean(), default=False, nullable=False)
    created_at = Column(types.TIMESTAMP, default=func.now())
    updated_at = Column(types.TIMESTAMP, onupdate=func.now())

    @property
    def password(self):
        raise ValueError('This is a only read attribute')

    @password.getter
    def password(self):
        return self.password_hash

    @password.setter
    def password(self, raw_password):
        self.password_hash = generate_password_hash(raw_password)

    def verify_password(self, raw_password):
        return check_password_hash(self.password_hash, raw_password)
Exemple #6
0
class CategoriaModel(bd.Model):
    __tablename__ = "t_categoria"
    categoriaId = Column(name='cat_id',
                         type_=types.Integer,
                         primary_key=True,
                         autoincrement=True,
                         unique=True,
                         nullable=True)

    categoriaNombre = Column(name='cat_nombre',
                             type_=types.String(45),
                             nullable=False)

    categoriaOrden = Column(name='cat_orden',
                            type_=types.Integer,
                            nullable=False)

    categoriaEstado = Column(name='cat_estado',
                             type_=types.Boolean(),
                             default=True,
                             nullable=False)

    conocimientos = relationship('ConocimientoModel',
                                 backref='categoriaConocimientos',
                                 cascade='all, delete')

    def __init__(self, nombre, orden, estado):
        self.categoriaNombre = nombre,
        self.categoriaOrden = orden
        if estado:
            self.categoriaEstado = estado

    def save(self):
        bd.session.add(self)
        bd.session.commit()
Exemple #7
0
class SwitchesState(Model):

    __tablename__ = 'switches'

    id = Column(types.Integer(), primary_key=True)
    key = Column(types.BINARY(length=16), nullable=False, unique=True)
    one = Column(types.Boolean(), nullable=False)
    two = Column(types.Boolean(), nullable=False)
    touched = Column(types.TIMESTAMP(timezone=True),
                     nullable=False,
                     server_default=sql.func.now(),
                     onupdate=sql.func.now())

    def __init__(self):
        self.key = uuid4().bytes
        self.one = False
        self.two = False
def update_steam_game_info():
    print('Parse app info and dump to databse')
    dic_steam_app = {}
    with open(path_app_info, 'rb') as f:
        lst_raw_string = f.readlines()
        total_count = len(lst_raw_string)
        current_count = 0
        for i in lst_raw_string:
            app_info = json.loads(i)
            dic_steam_app.update(parse_steam_app_info(app_info))
            show_work_status(1, total_count, current_count)
            current_count += 1

    df_steam_app = pd.DataFrame.from_dict(dic_steam_app, 'index')
    df_steam_app = df_steam_app.loc[:, [
        'app_id', 'name', 'release_date', 'type', 'currency', 'initial_price',
        'developers', 'publishers', 'required_age', 'linux', 'mac', 'windows',
        'fullgame', 'critic_score', 'recommendation', 'supported_languages',
        'header_image', 'short_description', 'success'
    ]]
    df_steam_app.to_sql('game_steam_app',
                        engine,
                        if_exists='replace',
                        index=False,
                        dtype={
                            'app_id': types.Integer(),
                            'name': types.String(200),
                            'release_date': types.Date,
                            'type': types.String(50),
                            'currency': types.String(5),
                            'initial_price': types.Float(),
                            'developers': types.String(500),
                            'publishers': types.String(500),
                            'required_age': types.Integer(),
                            'linux': types.Boolean(),
                            'mac': types.Boolean(),
                            'windows': types.Boolean(),
                            'fullgame': types.Integer(),
                            'critic_score': types.Integer(),
                            'recommendation': types.Integer(),
                            'supported_languages': types.String(500),
                            'header_image': types.String(500),
                            'short_description': types.String(1000),
                            'success': types.Boolean()
                        })
class Feed(Base):
    id = Column(types.Integer(), primary_key=True, autoincrement=True)
    url_id = Column(ForeignKey('url.id', ondelete=RESTRICT, onupdate=CASCADE),
                    nullable=False)
    title = Column(types.Text(), nullable=False)
    dead = Column(types.Boolean())

    @declared_attr
    def __table_args__(self):
        return (Index(None, 'url_id', unique=True), )
Exemple #10
0
class SurveyStatistics(model.BaseObject):
    """Data table to store survey (tool) information."""

    __tablename__ = "statistics_surveys"

    zodb_path = schema.Column(types.String(512), primary_key=True)
    language = schema.Column(types.String(128), nullable=True)
    published = schema.Column(types.Boolean(), nullable=True)
    published_date = schema.Column(types.DateTime, nullable=True)
    creation_date = schema.Column(types.DateTime, nullable=True)
Exemple #11
0
class CategoriaModel(bd.Model):
    __tablename__ = 't_categoria'
    categoriaId = Column(name='cat_id',
                         type_=types.Integer,
                         primary_key=True,
                         autoincrement=True,
                         unique=True,
                         nullable=False)
    categoriaNombre = Column(name='cat_nombre',
                             type_=types.String(45),
                             nullable=False)
    categoriaOrden = Column(name='cat_orden',
                            type_=types.Integer,
                            nullable=False)
    categoriaEstado = Column(
        name='cat_estado',
        type_=types.Boolean(),
        # el default es el valor por defecto si es que no se ingresa uno
        default=True,
        nullable=False)
    # FK
    usuario = Column(ForeignKey('t_usuario.usuario_id'),
                     name='usuario_id',
                     type_=types.Integer,
                     nullable=False)
    # el parametro cascade sirve para indicar que va a suceder cuando se elimine un padre, en este caso al poner 'all, delete', todos los hijos se van a eliminar consecuentemente
    # https://docs.sqlalchemy.org/en/14/orm/cascades.html
    conocimientos = relationship('ConocimientoModel',
                                 backref='categoriaConocimientos',
                                 cascade='all, delete')

    def __init__(self, nombre, orden, estado, usuario):
        self.categoriaNombre = nombre
        self.categoriaOrden = orden
        self.usuario = usuario
        if estado:
            self.categoriaEstado = estado

    def save(self):
        bd.session.add(self)
        bd.session.commit()

    def delete(self):
        bd.session.delete(self)
        bd.session.commit()

    def json(self):
        return {
            'cat_id': self.categoriaId,
            'cat_nombre': self.categoriaNombre,
            'cat_orden': self.categoriaOrden,
            'cat_estado': self.categoriaEstado
        }
Exemple #12
0
class Company(BaseObject):
    """Information about a company."""

    __tablename__ = "company"

    id = schema.Column(types.Integer(), primary_key=True, autoincrement=True)
    session_id = schema.Column(
        types.Integer(),
        schema.ForeignKey("session.id", onupdate="CASCADE",
                          ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    session = orm.relation(
        "SurveySession",
        cascade="all,delete-orphan",
        single_parent=True,
        backref=orm.backref("company", uselist=False, cascade="all"),
    )

    country = schema.Column(types.String(3))
    employees = schema.Column(Enum([None, "1-9", "10-49", "50-249", "250+"]))
    conductor = schema.Column(Enum([None, "staff", "third-party", "both"]))
    referer = schema.Column(
        Enum([
            None,
            "employers-organisation",
            "trade-union",
            "national-public-institution",
            "eu-institution",
            "health-safety-experts",
            "other",
        ]))
    workers_participated = schema.Column(types.Boolean())
    needs_met = schema.Column(types.Boolean())
    recommend_tool = schema.Column(types.Boolean())
    timestamp = schema.Column(types.DateTime(), nullable=True)
Exemple #13
0
class ActionPlan(BaseObject):
    """Action plans for a known risk."""

    __tablename__ = "action_plan"

    id = schema.Column(types.Integer(), primary_key=True, autoincrement=True)
    risk_id = schema.Column(
        types.Integer(),
        schema.ForeignKey(Risk.id, onupdate="CASCADE", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    action_plan = schema.Column(types.UnicodeText())
    prevention_plan = schema.Column(types.UnicodeText())
    # The column "action" is the synthesis of "action_plan" and "prevention_plan"
    action = schema.Column(types.UnicodeText())
    requirements = schema.Column(types.UnicodeText())
    responsible = schema.Column(types.Unicode(256))
    budget = schema.Column(types.Integer())
    planning_start = schema.Column(types.Date())
    planning_end = schema.Column(types.Date())
    reference = schema.Column(types.Text())
    plan_type = schema.Column(
        Enum([
            "measure_custom",
            "measure_standard",
            "in_place_standard",
            "in_place_custom",
        ]),
        nullable=False,
        index=True,
        default="measure_custom",
    )
    solution_id = schema.Column(types.Unicode(20))
    used_in_training = schema.Column(
        types.Boolean(),
        default=True,
        index=True,
    )

    risk = orm.relation(
        Risk,
        backref=orm.backref("action_plans",
                            order_by=id,
                            cascade="all, delete, delete-orphan"),
    )
Exemple #14
0
class Boolean(PrimitiveType):
    sqltype = sqltypes.Boolean()
    @staticmethod
    def python_type(val):
        if isinstance(val, basestring):
            val = val.strip().lower()
            return val == 'true'
        return bool(val) # ???

    def matches(self, value, text):
        """
        Only "true" or "false" strings match, everything else do not
        """
        assert isinstance(value, bool)
        text = text.capitalize()
        if text in ('False', 'True'):
            return str(value) == text
        return False
Exemple #15
0
class Module(SurveyTreeItem):
    """A module.

    This is a dummy object needed to be able to put modules in the
    survey tree.
    """

    __tablename__ = "module"
    __mapper_args__ = dict(polymorphic_identity="module")

    sql_module_id = schema.Column(
        "id",
        types.Integer(),
        schema.ForeignKey(SurveyTreeItem.id,
                          onupdate="CASCADE",
                          ondelete="CASCADE"),
        primary_key=True,
    )
    module_id = schema.Column(types.String(16), nullable=False)
    solution_direction = schema.Column(types.Boolean(), default=False)
Exemple #16
0
def init():
    """define table settings and mapping"""

    # Database definition
    from sqlalchemy import types, orm
    from sqlalchemy.schema import Column, Table, Sequence, ForeignKey
    from sqlalchemy.orm import relationship, backref, relation, mapper

    from User import User

    t_settings = Table(
        'settings',
        db.metadata,
        Column('id',
               types.Integer,
               Sequence('settings_seq_id', optional=True),
               nullable=False,
               primary_key=True),
        Column('id_user', types.Integer, ForeignKey('user.id'),
               nullable=False),
        Column('display_date',
               types.Boolean(255),
               nullable=False,
               default=True),
        Column('planning_theme',
               types.Enum('default', 'pepper', 'blue', 'eggplant', 'lightness',
                          'mint'),
               nullable=False,
               default='pepper'),
    )

    mapper(Settings,
           t_settings,
           properties={
               'user':
               relationship(User,
                            backref=backref('settings',
                                            uselist=False,
                                            cascade="all, delete-orphan")),
           })
Exemple #17
0
    class Dewey(Model):
        __tablename__ = 'dewey'
        __events__ = None

        _id = Column(types.Integer(), primary_key=True)
        name = Column(types.String())
        number = Column(types.Integer())
        min_hueys = Column(types.Boolean())
        hueys = orm.relationship('Huey')

        @events.before_insert()
        def before_insert(mapper, connection, target):
            target.name = 'Dewey'

        @events.on_set('name', retval=True)
        def on_set_name(target, value, oldvalue, initator):
            if oldvalue is None or (
                    hasattr(oldvalue, '__class__')
                    and oldvalue.__class__.__name__ == 'symbol'):
                # oldvalue is a symbol for either NO_VALUE or NOT_SET so allow
                # update
                return value
            else:
                # value previously set, so prevent edit
                return oldvalue

        @events.on_append('hueys')
        def on_append_hueys(target, value, intiator):
            if len(target.hueys) >= 1:
                target.min_hueys = True

        @events.on_remove('hueys')
        def on_remove_hueys(target, value, initator):
            if not len(target.hueys) >= 1:
                target.min_hueys = False

        @events.before_insert_update()
        def before_edit(mapper, connection, target):
            target.number = (target.number or 0) + 1
Exemple #18
0
class UsuarioModel(bd.Model):
    __tablename__ = "t_usuario"
    usuarioId = Column(name="usuario_id",
                       type_=types.Integer,
                       autoincrement=True,
                       primary_key=True,
                       unique=True,
                       nullable=False)
    usuarioNombre = Column(name="usuario_nombre",
                           type_=types.String(25),
                           nullable=False)

    usuarioApellido = Column(name="usuario_apellido",
                             type_=types.String(45),
                             nullable=False)

    usuarioCorreo = Column(name="usuario_correo",
                           type_=types.String(45),
                           nullable=False)

    usuarioPassword = Column(name="usuario_password",
                             type_=types.TEXT,
                             nullable=False)

    usuarioFoto = Column(name="usuario_foto", type_=types.TEXT, nullable=False)

    usuarioTitulo = Column(name="usuario_titulo",
                           type_=types.String(45),
                           nullable=False)
    usuarioInfo = Column(name="usuario_info", type_=types.TEXT, nullable=False)

    usuarioCV = Column(name="usuario_cv", type_=types.TEXT, nullable=False)

    usuarioSuperUser = Column(name="usuario_superuser",
                              type_=types.Boolean(),
                              nullable=False)
def test_should_boolean_convert_boolean():
    assert get_field(types.Boolean()).type == graphene.Boolean
Exemple #20
0
class SurveyTreeItem(BaseObject):
    """A tree of questions.

    The data is stored in the form of a materialized tree. The path is built
    using a list of item numbers. Each item number has three digits and uses
    0-prefixing to make sure we can use simple string sorting to produce a
    sorted tree.
    """

    __tablename__ = "tree"
    __table_args__ = (
        schema.UniqueConstraint("session_id", "path"),
        schema.UniqueConstraint("session_id", "zodb_path", "profile_index"),
        {},
    )

    id = schema.Column(types.Integer(), primary_key=True, autoincrement=True)
    session_id = schema.Column(
        types.Integer(),
        schema.ForeignKey("session.id", onupdate="CASCADE",
                          ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    parent_id = schema.Column(
        types.Integer(),
        schema.ForeignKey("tree.id", onupdate="CASCADE", ondelete="CASCADE"),
        nullable=True,
        index=True,
    )
    type = schema.Column(
        Enum(["risk", "module"]),
        nullable=False,
        index=True,
    )
    path = schema.Column(
        types.String(40),
        nullable=False,
        index=True,
    )
    has_description = schema.Column(
        types.Boolean(),
        default=False,
        index=True,
    )
    zodb_path = schema.Column(
        types.String(512),
        nullable=False,
    )
    profile_index = schema.Column(
        types.Integer(),
        default=0,
        nullable=False,
    )
    depth = schema.Column(
        types.Integer(),
        default=0,
        nullable=False,
        index=True,
    )
    title = schema.Column(types.Unicode(512))
    postponed = schema.Column(types.Boolean())
    skip_children = schema.Column(
        types.Boolean(),
        default=False,
        nullable=False,
    )

    __mapper_args__ = dict(polymorphic_on=type)

    session = orm.relation(
        "SurveySession",
        cascade="all",
    )
    #    parent = orm.relation("SurveyTreeItem", uselist=False)

    @property
    def parent(self):
        # XXX Evil! Figure out why the parent relation does not work
        return self.parent_id and Session.query(SurveyTreeItem).get(
            self.parent_id)

    def getId(self):
        return self.path[-3:].lstrip("0")

    @property
    def short_path(self):
        def slice(path):
            while path:
                yield path[:3].lstrip("0")
                path = path[3:]

        return slice(self.path)

    @property
    def number(self):
        return ".".join(self.short_path)

    def children(self, filter=None):
        query = (Session.query(SurveyTreeItem).filter(
            SurveyTreeItem.session_id == self.session_id).filter(
                SurveyTreeItem.depth == self.depth + 1))
        if self.path:
            query = query.filter(SurveyTreeItem.path.like(self.path + "%"))
        if filter is not None:
            query = query.filter(filter)
        return query.order_by(SurveyTreeItem.path)

    def siblings(self, klass=None, filter=None):
        if not self.path:
            return []
        if klass is None:
            klass = SurveyTreeItem
        query = (Session.query(klass).filter(
            klass.session_id == self.session_id).filter(
                klass.parent_id == self.parent_id))
        if filter is not None:
            query = query.filter(sql.or_(klass.id == self.id, filter))
        return query.order_by(klass.path)

    def addChild(self, item):
        sqlsession = Session()
        query = (sqlsession.query(SurveyTreeItem.path).filter(
            SurveyTreeItem.session_id == self.session_id).filter(
                SurveyTreeItem.depth == self.depth + 1))
        if self.path:
            query = query.filter(SurveyTreeItem.path.like(self.path + "%"))

        last = query.order_by(SurveyTreeItem.path.desc()).first()
        if not last:
            index = 1
        else:
            index = int(last[0][-3:]) + 1

        item.session = self.session
        item.depth = self.depth + 1
        item.path = (self.path or "") + "%03d" % index
        item.parent_id = self.id
        if self.profile_index != -1:
            item.profile_index = self.profile_index
        sqlsession.add(item)
        self.session.touch()
        return item

    def removeChildren(self, excluded=[]):
        if self.id not in excluded:
            excluded.append(self.id)
        session = Session()
        if self.path:
            filter = sql.and_(
                SurveyTreeItem.session_id == self.session_id,
                SurveyTreeItem.path.like(self.path + "%"),
                sql.not_(SurveyTreeItem.id.in_(excluded)),
            )
        else:
            filter = sql.and_(
                SurveyTreeItem.session_id == self.session_id,
                sql.not_(SurveyTreeItem.id.in_(excluded)),
            )
        removed = session.query(SurveyTreeItem).filter(filter).all()
        session.execute(SurveyTreeItem.__table__.delete().where(filter))
        self.session.touch()
        datamanager.mark_changed(session)
        return removed
Exemple #21
0
class Risk(SurveyTreeItem):
    """Answer to risk."""

    __tablename__ = "risk"
    __mapper_args__ = dict(polymorphic_identity="risk")

    sql_risk_id = schema.Column(
        "id",
        types.Integer(),
        schema.ForeignKey(SurveyTreeItem.id,
                          onupdate="CASCADE",
                          ondelete="CASCADE"),
        primary_key=True,
    )
    risk_id = schema.Column(types.String(16), nullable=True)
    risk_type = schema.Column(Enum(["risk", "policy", "top5"]),
                              default="risk",
                              nullable=False,
                              index=True)
    #: Skip-evaluation flag. This is only used to indicate if the sector
    #: set the evaluation method to `fixed`, not for policy behaviour
    #: such as not evaluation top-5 risks. That policy behaviour is
    #: handled via the question_filter on client views so it can be modified
    #: in custom deployments.
    skip_evaluation = schema.Column(types.Boolean(),
                                    default=False,
                                    nullable=False)
    is_custom_risk = schema.Column(types.Boolean(),
                                   default=False,
                                   nullable=False)
    identification = schema.Column(Enum([None, "yes", "no", "n/a"]))
    frequency = schema.Column(types.Integer())
    effect = schema.Column(types.Integer())
    probability = schema.Column(types.Integer())
    priority = schema.Column(Enum([None, "low", "medium", "high"]))
    comment = schema.Column(types.UnicodeText())
    existing_measures = schema.Column(types.UnicodeText())
    training_notes = schema.Column(types.UnicodeText())
    custom_description = schema.Column(types.UnicodeText())
    image_data = schema.Column(types.LargeBinary())
    image_data_scaled = schema.Column(types.LargeBinary())
    image_filename = schema.Column(types.UnicodeText())

    @memoize
    def measures_of_type(self, plan_type):
        query = (Session.query(ActionPlan).filter(
            sql.and_(ActionPlan.risk_id == self.id),
            ActionPlan.plan_type == plan_type,
        ).order_by(ActionPlan.id))
        return query.all()

    @property
    def standard_measures(self):
        return self.measures_of_type("measure_standard")

    @property
    def custom_measures(self):
        return self.measures_of_type("measure_custom")

    @property
    def in_place_standard_measures(self):
        return self.measures_of_type("in_place_standard")

    @property
    def in_place_custom_measures(self):
        return self.measures_of_type("in_place_custom")
Exemple #22
0
        types.TIMESTAMP(timezone=True),
    ),
    (
        "VARCHAR",
        types.VARCHAR(),
    ),
)

unquoted_types = (
    (
        "BINARY",
        types.LargeBinary(),
    ),
    (
        "BOOLEAN",
        types.Boolean(),
    ),
    (
        "DECIMAL",
        types.DECIMAL(),
    ),
    (
        "FLOAT",
        types.FLOAT(),
    ),
    (
        "INTEGER",
        types.INTEGER(),
    ),
    (
        "BIGINT",
Exemple #23
0
def test_should_boolean_convert_boolean():
    assert_column_conversion(types.Boolean(), graphene.Boolean)
class PrestoEngineSpec(BaseEngineSpec):
    engine = "presto"
    engine_name = "Presto"

    _time_grain_expressions = {
        None:
        "{col}",
        "PT1S":
        "date_trunc('second', CAST({col} AS TIMESTAMP))",
        "PT1M":
        "date_trunc('minute', CAST({col} AS TIMESTAMP))",
        "PT1H":
        "date_trunc('hour', CAST({col} AS TIMESTAMP))",
        "P1D":
        "date_trunc('day', CAST({col} AS TIMESTAMP))",
        "P1W":
        "date_trunc('week', CAST({col} AS TIMESTAMP))",
        "P1M":
        "date_trunc('month', CAST({col} AS TIMESTAMP))",
        "P0.25Y":
        "date_trunc('quarter', CAST({col} AS TIMESTAMP))",
        "P1Y":
        "date_trunc('year', CAST({col} AS TIMESTAMP))",
        "P1W/1970-01-03T00:00:00Z":
        "date_add('day', 5, date_trunc('week', "
        "date_add('day', 1, CAST({col} AS TIMESTAMP))))",
        "1969-12-28T00:00:00Z/P1W":
        "date_add('day', -1, date_trunc('week', "
        "date_add('day', 1, CAST({col} AS TIMESTAMP))))",
    }

    @classmethod
    def get_allow_cost_estimate(cls, version: Optional[str] = None) -> bool:
        return version is not None and StrictVersion(version) >= StrictVersion(
            "0.319")

    @classmethod
    def get_table_names(cls, database: "Database", inspector: Inspector,
                        schema: Optional[str]) -> List[str]:
        tables = super().get_table_names(database, inspector, schema)
        if not is_feature_enabled("PRESTO_SPLIT_VIEWS_FROM_TABLES"):
            return tables

        views = set(cls.get_view_names(database, inspector, schema))
        actual_tables = set(tables) - views
        return list(actual_tables)

    @classmethod
    def get_view_names(cls, database: "Database", inspector: Inspector,
                       schema: Optional[str]) -> List[str]:
        """Returns an empty list

        get_table_names() function returns all table names and view names,
        and get_view_names() is not implemented in sqlalchemy_presto.py
        https://github.com/dropbox/PyHive/blob/e25fc8440a0686bbb7a5db5de7cb1a77bdb4167a/pyhive/sqlalchemy_presto.py
        """
        if not is_feature_enabled("PRESTO_SPLIT_VIEWS_FROM_TABLES"):
            return []

        if schema:
            sql = ("SELECT table_name FROM information_schema.views "
                   "WHERE table_schema=%(schema)s")
            params = {"schema": schema}
        else:
            sql = "SELECT table_name FROM information_schema.views"
            params = {}

        engine = cls.get_engine(database, schema=schema)
        with closing(engine.raw_connection()) as conn:
            with closing(conn.cursor()) as cursor:
                cursor.execute(sql, params)
                results = cursor.fetchall()

        return [row[0] for row in results]

    @classmethod
    def _create_column_info(cls, name: str, data_type: str) -> Dict[str, Any]:
        """
        Create column info object
        :param name: column name
        :param data_type: column data type
        :return: column info object
        """
        return {"name": name, "type": f"{data_type}"}

    @classmethod
    def _get_full_name(cls, names: List[Tuple[str, str]]) -> str:
        """
        Get the full column name
        :param names: list of all individual column names
        :return: full column name
        """
        return ".".join(column[0] for column in names if column[0])

    @classmethod
    def _has_nested_data_types(cls, component_type: str) -> bool:
        """
        Check if string contains a data type. We determine if there is a data type by
        whitespace or multiple data types by commas
        :param component_type: data type
        :return: boolean
        """
        comma_regex = r",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"
        white_space_regex = r"\s(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"
        return (re.search(comma_regex, component_type) is not None
                or re.search(white_space_regex, component_type) is not None)

    @classmethod
    def _split_data_type(cls, data_type: str, delimiter: str) -> List[str]:
        """
        Split data type based on given delimiter. Do not split the string if the
        delimiter is enclosed in quotes
        :param data_type: data type
        :param delimiter: string separator (i.e. open parenthesis, closed parenthesis,
               comma, whitespace)
        :return: list of strings after breaking it by the delimiter
        """
        return re.split(
            r"{}(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)".format(delimiter), data_type)

    @classmethod
    def _parse_structural_column(  # pylint: disable=too-many-locals,too-many-branches
        cls,
        parent_column_name: str,
        parent_data_type: str,
        result: List[Dict[str, Any]],
    ) -> None:
        """
        Parse a row or array column
        :param result: list tracking the results
        """
        formatted_parent_column_name = parent_column_name
        # Quote the column name if there is a space
        if " " in parent_column_name:
            formatted_parent_column_name = f'"{parent_column_name}"'
        full_data_type = f"{formatted_parent_column_name} {parent_data_type}"
        original_result_len = len(result)
        # split on open parenthesis ( to get the structural
        # data type and its component types
        data_types = cls._split_data_type(full_data_type, r"\(")
        stack: List[Tuple[str, str]] = []
        for data_type in data_types:
            # split on closed parenthesis ) to track which component
            # types belong to what structural data type
            inner_types = cls._split_data_type(data_type, r"\)")
            for inner_type in inner_types:
                # We have finished parsing multiple structural data types
                if not inner_type and stack:
                    stack.pop()
                elif cls._has_nested_data_types(inner_type):
                    # split on comma , to get individual data types
                    single_fields = cls._split_data_type(inner_type, ",")
                    for single_field in single_fields:
                        single_field = single_field.strip()
                        # If component type starts with a comma, the first single field
                        # will be an empty string. Disregard this empty string.
                        if not single_field:
                            continue
                        # split on whitespace to get field name and data type
                        field_info = cls._split_data_type(single_field, r"\s")
                        # check if there is a structural data type within
                        # overall structural data type
                        column_type = cls.get_sqla_column_type(field_info[1])
                        if column_type is None:
                            raise NotImplementedError(
                                _("Unknown column type: %(col)s",
                                  col=field_info[1]))
                        if field_info[1] == "array" or field_info[1] == "row":
                            stack.append((field_info[0], field_info[1]))
                            full_parent_path = cls._get_full_name(stack)
                            result.append(
                                cls._create_column_info(
                                    full_parent_path, column_type))
                        else:  # otherwise this field is a basic data type
                            full_parent_path = cls._get_full_name(stack)
                            column_name = "{}.{}".format(
                                full_parent_path, field_info[0])
                            result.append(
                                cls._create_column_info(
                                    column_name, column_type))
                    # If the component type ends with a structural data type, do not pop
                    # the stack. We have run across a structural data type within the
                    # overall structural data type. Otherwise, we have completely parsed
                    # through the entire structural data type and can move on.
                    if not (inner_type.endswith("array")
                            or inner_type.endswith("row")):
                        stack.pop()
                # We have an array of row objects (i.e. array(row(...)))
                elif inner_type in ("array", "row"):
                    # Push a dummy object to represent the structural data type
                    stack.append(("", inner_type))
                # We have an array of a basic data types(i.e. array(varchar)).
                elif stack:
                    # Because it is an array of a basic data type. We have finished
                    # parsing the structural data type and can move on.
                    stack.pop()
        # Unquote the column name if necessary
        if formatted_parent_column_name != parent_column_name:
            for index in range(original_result_len, len(result)):
                result[index]["name"] = result[index]["name"].replace(
                    formatted_parent_column_name, parent_column_name)

    @classmethod
    def _show_columns(cls, inspector: Inspector, table_name: str,
                      schema: Optional[str]) -> List[RowProxy]:
        """
        Show presto column names
        :param inspector: object that performs database schema inspection
        :param table_name: table name
        :param schema: schema name
        :return: list of column objects
        """
        quote = inspector.engine.dialect.identifier_preparer.quote_identifier
        full_table = quote(table_name)
        if schema:
            full_table = "{}.{}".format(quote(schema), full_table)
        columns = inspector.bind.execute(
            "SHOW COLUMNS FROM {}".format(full_table))
        return columns

    column_type_mappings = (
        (re.compile(r"^boolean.*", re.IGNORECASE), types.Boolean()),
        (re.compile(r"^tinyint.*", re.IGNORECASE), TinyInteger()),
        (re.compile(r"^smallint.*", re.IGNORECASE), types.SmallInteger()),
        (re.compile(r"^integer.*", re.IGNORECASE), types.Integer()),
        (re.compile(r"^bigint.*", re.IGNORECASE), types.BigInteger()),
        (re.compile(r"^real.*", re.IGNORECASE), types.Float()),
        (re.compile(r"^double.*", re.IGNORECASE), types.Float()),
        (re.compile(r"^decimal.*", re.IGNORECASE), types.DECIMAL()),
        (
            re.compile(r"^varchar(\((\d+)\))*$", re.IGNORECASE),
            lambda match: types.VARCHAR(int(match[2]))
            if match[2] else types.String(),
        ),
        (
            re.compile(r"^char(\((\d+)\))*$", re.IGNORECASE),
            lambda match: types.CHAR(int(match[2]))
            if match[2] else types.CHAR(),
        ),
        (re.compile(r"^varbinary.*", re.IGNORECASE), types.VARBINARY()),
        (re.compile(r"^json.*", re.IGNORECASE), types.JSON()),
        (re.compile(r"^date.*", re.IGNORECASE), types.DATE()),
        (re.compile(r"^time.*", re.IGNORECASE), types.Time()),
        (re.compile(r"^timestamp.*", re.IGNORECASE), types.TIMESTAMP()),
        (re.compile(r"^interval.*", re.IGNORECASE), Interval()),
        (re.compile(r"^array.*", re.IGNORECASE), Array()),
        (re.compile(r"^map.*", re.IGNORECASE), Map()),
        (re.compile(r"^row.*", re.IGNORECASE), Row()),
    )

    @classmethod
    def get_columns(cls, inspector: Inspector, table_name: str,
                    schema: Optional[str]) -> List[Dict[str, Any]]:
        """
        Get columns from a Presto data source. This includes handling row and
        array data types
        :param inspector: object that performs database schema inspection
        :param table_name: table name
        :param schema: schema name
        :return: a list of results that contain column info
                (i.e. column name and data type)
        """
        columns = cls._show_columns(inspector, table_name, schema)
        result: List[Dict[str, Any]] = []
        for column in columns:
            # parse column if it is a row or array
            if is_feature_enabled("PRESTO_EXPAND_DATA") and (
                    "array" in column.Type or "row" in column.Type):
                structural_column_index = len(result)
                cls._parse_structural_column(column.Column, column.Type,
                                             result)
                result[structural_column_index]["nullable"] = getattr(
                    column, "Null", True)
                result[structural_column_index]["default"] = None
                continue

            # otherwise column is a basic data type
            column_type = cls.get_sqla_column_type(column.Type)
            if column_type is None:
                raise NotImplementedError(
                    _("Unknown column type: %(col)s", col=column_type))
            column_info = cls._create_column_info(column.Column, column_type)
            column_info["nullable"] = getattr(column, "Null", True)
            column_info["default"] = None
            result.append(column_info)
        return result

    @classmethod
    def _is_column_name_quoted(cls, column_name: str) -> bool:
        """
        Check if column name is in quotes
        :param column_name: column name
        :return: boolean
        """
        return column_name.startswith('"') and column_name.endswith('"')

    @classmethod
    def _get_fields(cls, cols: List[Dict[str, Any]]) -> List[ColumnClause]:
        """
        Format column clauses where names are in quotes and labels are specified
        :param cols: columns
        :return: column clauses
        """
        column_clauses = []
        # Column names are separated by periods. This regex will find periods in a
        # string if they are not enclosed in quotes because if a period is enclosed in
        # quotes, then that period is part of a column name.
        dot_pattern = r"""\.                # split on period
                          (?=               # look ahead
                          (?:               # create non-capture group
                          [^\"]*\"[^\"]*\"  # two quotes
                          )*[^\"]*$)        # end regex"""
        dot_regex = re.compile(dot_pattern, re.VERBOSE)
        for col in cols:
            # get individual column names
            col_names = re.split(dot_regex, col["name"])
            # quote each column name if it is not already quoted
            for index, col_name in enumerate(col_names):
                if not cls._is_column_name_quoted(col_name):
                    col_names[index] = '"{}"'.format(col_name)
            quoted_col_name = ".".join(
                col_name if cls._is_column_name_quoted(col_name
                                                       ) else f'"{col_name}"'
                for col_name in col_names)
            # create column clause in the format "name"."name" AS "name.name"
            column_clause = literal_column(quoted_col_name).label(col["name"])
            column_clauses.append(column_clause)
        return column_clauses

    @classmethod
    def select_star(  # pylint: disable=too-many-arguments
        cls,
        database: "Database",
        table_name: str,
        engine: Engine,
        schema: Optional[str] = None,
        limit: int = 100,
        show_cols: bool = False,
        indent: bool = True,
        latest_partition: bool = True,
        cols: Optional[List[Dict[str, Any]]] = None,
    ) -> str:
        """
        Include selecting properties of row objects. We cannot easily break arrays into
        rows, so render the whole array in its own row and skip columns that correspond
        to an array's contents.
        """
        cols = cols or []
        presto_cols = cols
        if is_feature_enabled("PRESTO_EXPAND_DATA") and show_cols:
            dot_regex = r"\.(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"
            presto_cols = [
                col for col in presto_cols
                if not re.search(dot_regex, col["name"])
            ]
        return super().select_star(
            database,
            table_name,
            engine,
            schema,
            limit,
            show_cols,
            indent,
            latest_partition,
            presto_cols,
        )

    @classmethod
    def estimate_statement_cost(  # pylint: disable=too-many-locals
            cls, statement: str, database: "Database", cursor: Any,
            user_name: str) -> Dict[str, Any]:
        """
        Run a SQL query that estimates the cost of a given statement.

        :param statement: A single SQL statement
        :param database: Database instance
        :param cursor: Cursor instance
        :param username: Effective username
        :return: JSON response from Presto
        """
        parsed_query = ParsedQuery(statement)
        sql = parsed_query.stripped()

        sql_query_mutator = config["SQL_QUERY_MUTATOR"]
        if sql_query_mutator:
            sql = sql_query_mutator(sql, user_name, security_manager, database)

        sql = f"EXPLAIN (TYPE IO, FORMAT JSON) {sql}"
        cursor.execute(sql)

        # the output from Presto is a single column and a single row containing
        # JSON:
        #
        #   {
        #     ...
        #     "estimate" : {
        #       "outputRowCount" : 8.73265878E8,
        #       "outputSizeInBytes" : 3.41425774958E11,
        #       "cpuCost" : 3.41425774958E11,
        #       "maxMemory" : 0.0,
        #       "networkCost" : 3.41425774958E11
        #     }
        #   }
        result = json.loads(cursor.fetchone()[0])
        return result

    @classmethod
    def query_cost_formatter(
            cls, raw_cost: List[Dict[str, Any]]) -> List[Dict[str, str]]:
        """
        Format cost estimate.

        :param raw_cost: JSON estimate from Presto
        :return: Human readable cost estimate
        """
        def humanize(value: Any, suffix: str) -> str:
            try:
                value = int(value)
            except ValueError:
                return str(value)

            prefixes = ["K", "M", "G", "T", "P", "E", "Z", "Y"]
            prefix = ""
            to_next_prefix = 1000
            while value > to_next_prefix and prefixes:
                prefix = prefixes.pop(0)
                value //= to_next_prefix

            return f"{value} {prefix}{suffix}"

        cost = []
        columns = [
            ("outputRowCount", "Output count", " rows"),
            ("outputSizeInBytes", "Output size", "B"),
            ("cpuCost", "CPU cost", ""),
            ("maxMemory", "Max memory", "B"),
            ("networkCost", "Network cost", ""),
        ]
        for row in raw_cost:
            estimate: Dict[str, float] = row.get("estimate", {})
            statement_cost = {}
            for key, label, suffix in columns:
                if key in estimate:
                    statement_cost[label] = humanize(estimate[key],
                                                     suffix).strip()
            cost.append(statement_cost)

        return cost

    @classmethod
    def adjust_database_uri(cls,
                            uri: URL,
                            selected_schema: Optional[str] = None) -> None:
        database = uri.database
        if selected_schema and database:
            selected_schema = parse.quote(selected_schema, safe="")
            if "/" in database:
                database = database.split("/")[0] + "/" + selected_schema
            else:
                database += "/" + selected_schema
            uri.database = database

    @classmethod
    def convert_dttm(cls, target_type: str, dttm: datetime) -> Optional[str]:
        tt = target_type.upper()
        if tt == utils.TemporalType.DATE:
            return f"""from_iso8601_date('{dttm.date().isoformat()}')"""
        if tt == utils.TemporalType.TIMESTAMP:
            return f"""from_iso8601_timestamp('{dttm.isoformat(timespec="microseconds")}')"""  # pylint: disable=line-too-long
        return None

    @classmethod
    def epoch_to_dttm(cls) -> str:
        return "from_unixtime({col})"

    @classmethod
    def get_all_datasource_names(
            cls, database: "Database",
            datasource_type: str) -> List[utils.DatasourceName]:
        datasource_df = database.get_df(
            "SELECT table_schema, table_name FROM INFORMATION_SCHEMA.{}S "
            "ORDER BY concat(table_schema, '.', table_name)".format(
                datasource_type.upper()),
            None,
        )
        datasource_names: List[utils.DatasourceName] = []
        for _unused, row in datasource_df.iterrows():
            datasource_names.append(
                utils.DatasourceName(schema=row["table_schema"],
                                     table=row["table_name"]))
        return datasource_names

    @classmethod
    def expand_data(  # pylint: disable=too-many-locals,too-many-branches
        cls, columns: List[Dict[Any, Any]],
        data: List[Dict[Any, Any]]) -> Tuple[List[Dict[Any, Any]], List[Dict[
            Any, Any]], List[Dict[Any, Any]]]:
        """
        We do not immediately display rows and arrays clearly in the data grid. This
        method separates out nested fields and data values to help clearly display
        structural columns.

        Example: ColumnA is a row(nested_obj varchar) and ColumnB is an array(int)
        Original data set = [
            {'ColumnA': ['a1'], 'ColumnB': [1, 2]},
            {'ColumnA': ['a2'], 'ColumnB': [3, 4]},
        ]
        Expanded data set = [
            {'ColumnA': ['a1'], 'ColumnA.nested_obj': 'a1', 'ColumnB': 1},
            {'ColumnA': '',     'ColumnA.nested_obj': '',   'ColumnB': 2},
            {'ColumnA': ['a2'], 'ColumnA.nested_obj': 'a2', 'ColumnB': 3},
            {'ColumnA': '',     'ColumnA.nested_obj': '',   'ColumnB': 4},
        ]
        :param columns: columns selected in the query
        :param data: original data set
        :return: list of all columns(selected columns and their nested fields),
                 expanded data set, listed of nested fields
        """
        if not is_feature_enabled("PRESTO_EXPAND_DATA"):
            return columns, data, []

        # process each column, unnesting ARRAY types and
        # expanding ROW types into new columns
        to_process = deque((column, 0) for column in columns)
        all_columns: List[Dict[str, Any]] = []
        expanded_columns = []
        current_array_level = None
        while to_process:
            column, level = to_process.popleft()
            if column["name"] not in [
                    column["name"] for column in all_columns
            ]:
                all_columns.append(column)

            # When unnesting arrays we need to keep track of how many extra rows
            # were added, for each original row. This is necessary when we expand
            # multiple arrays, so that the arrays after the first reuse the rows
            # added by the first. every time we change a level in the nested arrays
            # we reinitialize this.
            if level != current_array_level:
                unnested_rows: Dict[int, int] = defaultdict(int)
                current_array_level = level

            name = column["name"]
            values: Optional[Union[str, List[Any]]]

            if column["type"].startswith("ARRAY("):
                # keep processing array children; we append to the right so that
                # multiple nested arrays are processed breadth-first
                to_process.append((get_children(column)[0], level + 1))

                # unnest array objects data into new rows
                i = 0
                while i < len(data):
                    row = data[i]
                    values = row.get(name)
                    if isinstance(values, str):
                        row[name] = values = destringify(values)
                    if values:
                        # how many extra rows we need to unnest the data?
                        extra_rows = len(values) - 1

                        # how many rows were already added for this row?
                        current_unnested_rows = unnested_rows[i]

                        # add any necessary rows
                        missing = extra_rows - current_unnested_rows
                        for _ in range(missing):
                            data.insert(i + current_unnested_rows + 1, {})
                            unnested_rows[i] += 1

                        # unnest array into rows
                        for j, value in enumerate(values):
                            data[i + j][name] = value

                        # skip newly unnested rows
                        i += unnested_rows[i]

                    i += 1

            if column["type"].startswith("ROW("):
                # expand columns; we append them to the left so they are added
                # immediately after the parent
                expanded = get_children(column)
                to_process.extendleft(
                    (column, level) for column in expanded[::-1])
                expanded_columns.extend(expanded)

                # expand row objects into new columns
                for row in data:
                    values = row.get(name) or []
                    if isinstance(values, str):
                        row[name] = values = cast(List[Any],
                                                  destringify(values))
                    for value, col in zip(values, expanded):
                        row[col["name"]] = value

        data = [{k["name"]: row.get(k["name"], "")
                 for k in all_columns} for row in data]

        return all_columns, data, expanded_columns

    @classmethod
    def extra_table_metadata(cls, database: "Database", table_name: str,
                             schema_name: str) -> Dict[str, Any]:
        metadata = {}

        indexes = database.get_indexes(table_name, schema_name)
        if indexes:
            cols = indexes[0].get("column_names", [])
            full_table_name = table_name
            if schema_name and "." not in table_name:
                full_table_name = "{}.{}".format(schema_name, table_name)
            pql = cls._partition_query(full_table_name, database)
            col_names, latest_parts = cls.latest_partition(table_name,
                                                           schema_name,
                                                           database,
                                                           show_first=True)

            if not latest_parts:
                latest_parts = tuple([None] * len(col_names))  # type: ignore
            metadata["partitions"] = {
                "cols": cols,
                "latest": dict(zip(col_names, latest_parts)),  # type: ignore
                "partitionQuery": pql,
            }

        # flake8 is not matching `Optional[str]` to `Any` for some reason...
        metadata["view"] = cast(
            Any, cls.get_create_view(database, schema_name, table_name))

        return metadata

    @classmethod
    def get_create_view(cls, database: "Database", schema: str,
                        table: str) -> Optional[str]:
        """
        Return a CREATE VIEW statement, or `None` if not a view.

        :param database: Database instance
        :param schema: Schema name
        :param table: Table (view) name
        """
        from pyhive.exc import DatabaseError

        engine = cls.get_engine(database, schema)
        with closing(engine.raw_connection()) as conn:
            with closing(conn.cursor()) as cursor:
                sql = f"SHOW CREATE VIEW {schema}.{table}"
                try:
                    cls.execute(cursor, sql)
                    polled = cursor.poll()

                    while polled:
                        time.sleep(0.2)
                        polled = cursor.poll()
                except DatabaseError:  # not a VIEW
                    return None
                rows = cls.fetch_data(cursor, 1)
        return rows[0][0]

    @classmethod
    def handle_cursor(cls, cursor: Any, query: Query,
                      session: Session) -> None:
        """Updates progress information"""
        query_id = query.id
        poll_interval = query.database.connect_args.get(
            "poll_interval", config["PRESTO_POLL_INTERVAL"])
        logger.info("Query %i: Polling the cursor for progress", query_id)
        polled = cursor.poll()
        # poll returns dict -- JSON status information or ``None``
        # if the query is done
        # https://github.com/dropbox/PyHive/blob/
        # b34bdbf51378b3979eaf5eca9e956f06ddc36ca0/pyhive/presto.py#L178
        while polled:
            # Update the object and wait for the kill signal.
            stats = polled.get("stats", {})

            query = session.query(type(query)).filter_by(id=query_id).one()
            if query.status in [QueryStatus.STOPPED, QueryStatus.TIMED_OUT]:
                cursor.cancel()
                break

            if stats:
                state = stats.get("state")

                # if already finished, then stop polling
                if state == "FINISHED":
                    break

                completed_splits = float(stats.get("completedSplits"))
                total_splits = float(stats.get("totalSplits"))
                if total_splits and completed_splits:
                    progress = 100 * (completed_splits / total_splits)
                    logger.info("Query {} progress: {} / {} "  # pylint: disable=logging-format-interpolation
                                "splits".format(query_id, completed_splits,
                                                total_splits))
                    if progress > query.progress:
                        query.progress = progress
                    session.commit()
            time.sleep(poll_interval)
            logger.info("Query %i: Polling the cursor for progress", query_id)
            polled = cursor.poll()

    @classmethod
    def _extract_error_message(cls, ex: Exception) -> str:
        if (hasattr(ex, "orig")
                and type(ex.orig).__name__ == "DatabaseError"  # type: ignore
                and isinstance(ex.orig[0], dict)  # type: ignore
            ):
            error_dict = ex.orig[0]  # type: ignore
            return "{} at {}: {}".format(
                error_dict.get("errorName"),
                error_dict.get("errorLocation"),
                error_dict.get("message"),
            )
        if type(ex).__name__ == "DatabaseError" and hasattr(
                ex, "args") and ex.args:
            error_dict = ex.args[0]
            return error_dict.get("message", _("Unknown Presto Error"))
        return utils.error_msg_from_exception(ex)

    @classmethod
    def _partition_query(  # pylint: disable=too-many-arguments,too-many-locals
        cls,
        table_name: str,
        database: "Database",
        limit: int = 0,
        order_by: Optional[List[Tuple[str, bool]]] = None,
        filters: Optional[Dict[Any, Any]] = None,
    ) -> str:
        """Returns a partition query

        :param table_name: the name of the table to get partitions from
        :type table_name: str
        :param limit: the number of partitions to be returned
        :type limit: int
        :param order_by: a list of tuples of field name and a boolean
            that determines if that field should be sorted in descending
            order
        :type order_by: list of (str, bool) tuples
        :param filters: dict of field name and filter value combinations
        """
        limit_clause = "LIMIT {}".format(limit) if limit else ""
        order_by_clause = ""
        if order_by:
            l = []
            for field, desc in order_by:
                l.append(field + " DESC" if desc else "")
            order_by_clause = "ORDER BY " + ", ".join(l)

        where_clause = ""
        if filters:
            l = []
            for field, value in filters.items():
                l.append(f"{field} = '{value}'")
            where_clause = "WHERE " + " AND ".join(l)

        presto_version = database.get_extra().get("version")

        # Partition select syntax changed in v0.199, so check here.
        # Default to the new syntax if version is unset.
        partition_select_clause = (
            f'SELECT * FROM "{table_name}$partitions"' if not presto_version
            or StrictVersion(presto_version) >= StrictVersion("0.199") else
            f"SHOW PARTITIONS FROM {table_name}")

        sql = textwrap.dedent(f"""\
            {partition_select_clause}
            {where_clause}
            {order_by_clause}
            {limit_clause}
        """)
        return sql

    @classmethod
    def where_latest_partition(  # pylint: disable=too-many-arguments
        cls,
        table_name: str,
        schema: Optional[str],
        database: "Database",
        query: Select,
        columns: Optional[List[Dict[str, str]]] = None,
    ) -> Optional[Select]:
        try:
            col_names, values = cls.latest_partition(table_name,
                                                     schema,
                                                     database,
                                                     show_first=True)
        except Exception:  # pylint: disable=broad-except
            # table is not partitioned
            return None

        if values is None:
            return None

        column_names = {column.get("name") for column in columns or []}
        for col_name, value in zip(col_names, values):
            if col_name in column_names:
                query = query.where(Column(col_name) == value)
        return query

    @classmethod
    def _latest_partition_from_df(cls,
                                  df: pd.DataFrame) -> Optional[List[str]]:
        if not df.empty:
            return df.to_records(index=False)[0].item()
        return None

    @classmethod
    def latest_partition(
        cls,
        table_name: str,
        schema: Optional[str],
        database: "Database",
        show_first: bool = False,
    ) -> Tuple[List[str], Optional[List[str]]]:
        """Returns col name and the latest (max) partition value for a table

        :param table_name: the name of the table
        :param schema: schema / database / namespace
        :param database: database query will be run against
        :type database: models.Database
        :param show_first: displays the value for the first partitioning key
          if there are many partitioning keys
        :type show_first: bool

        >>> latest_partition('foo_table')
        (['ds'], ('2018-01-01',))
        """
        indexes = database.get_indexes(table_name, schema)
        if not indexes:
            raise SupersetTemplateException(
                f"Error getting partition for {schema}.{table_name}. "
                "Verify that this table has a partition.")

        if len(indexes[0]["column_names"]) < 1:
            raise SupersetTemplateException(
                "The table should have one partitioned field")

        if not show_first and len(indexes[0]["column_names"]) > 1:
            raise SupersetTemplateException(
                "The table should have a single partitioned field "
                "to use this function. You may want to use "
                "`presto.latest_sub_partition`")

        column_names = indexes[0]["column_names"]
        part_fields = [(column_name, True) for column_name in column_names]
        sql = cls._partition_query(table_name, database, 1, part_fields)
        df = database.get_df(sql, schema)
        return column_names, cls._latest_partition_from_df(df)

    @classmethod
    def latest_sub_partition(cls, table_name: str, schema: Optional[str],
                             database: "Database", **kwargs: Any) -> Any:
        """Returns the latest (max) partition value for a table

        A filtering criteria should be passed for all fields that are
        partitioned except for the field to be returned. For example,
        if a table is partitioned by (``ds``, ``event_type`` and
        ``event_category``) and you want the latest ``ds``, you'll want
        to provide a filter as keyword arguments for both
        ``event_type`` and ``event_category`` as in
        ``latest_sub_partition('my_table',
            event_category='page', event_type='click')``

        :param table_name: the name of the table, can be just the table
            name or a fully qualified table name as ``schema_name.table_name``
        :type table_name: str
        :param schema: schema / database / namespace
        :type schema: str
        :param database: database query will be run against
        :type database: models.Database

        :param kwargs: keyword arguments define the filtering criteria
            on the partition list. There can be many of these.
        :type kwargs: str
        >>> latest_sub_partition('sub_partition_table', event_type='click')
        '2018-01-01'
        """
        indexes = database.get_indexes(table_name, schema)
        part_fields = indexes[0]["column_names"]
        for k in kwargs.keys():  # pylint: disable=consider-iterating-dictionary
            if k not in k in part_fields:  # pylint: disable=comparison-with-itself
                msg = "Field [{k}] is not part of the portioning key"
                raise SupersetTemplateException(msg)
        if len(kwargs.keys()) != len(part_fields) - 1:
            msg = ("A filter needs to be specified for {} out of the "
                   "{} fields.").format(
                       len(part_fields) - 1, len(part_fields))
            raise SupersetTemplateException(msg)

        for field in part_fields:
            if field not in kwargs.keys():
                field_to_return = field

        sql = cls._partition_query(table_name, database, 1,
                                   [(field_to_return, True)], kwargs)
        df = database.get_df(sql, schema)
        if df.empty:
            return ""
        return df.to_dict()[field_to_return][0]

    @classmethod
    @cache.memoize()
    def get_function_names(cls, database: "Database") -> List[str]:
        """
        Get a list of function names that are able to be called on the database.
        Used for SQL Lab autocomplete.

        :param database: The database to get functions for
        :return: A list of function names useable in the database
        """
        return database.get_df("SHOW FUNCTIONS")["Function"].tolist()
 },
 {
     'name': 'string',
     'type': types.String(),
     'nullable': True,
     'default': None
 },
 {
     'name': 'float',
     'type': types.Float(),
     'nullable': True,
     'default': None
 },
 {
     'name': 'boolean',
     'type': types.Boolean(),
     'nullable': True,
     'default': None
 },
 {
     'name': 'date',
     'type': types.DATE(),
     'nullable': True,
     'default': None
 },
 {
     'name': 'datetime',
     'type': types.DATETIME(),
     'nullable': True,
     'default': None
 },
Exemple #26
0
    40.76727216,
    decimal.Decimal("40.76727216"),
    False,
    datetime.date(2013, 10, 10),
    datetime.datetime(2013, 10, 10, 11, 27, 16),
    datetime.time(11, 27, 16),
    "test_bytes",
]

SAMPLE_COLUMNS = [
    {"name": "integer", "type": types.Integer(), "nullable": True, "default": None},
    {"name": "timestamp", "type": types.TIMESTAMP(), "nullable": True, "default": None},
    {"name": "string", "type": types.String(), "nullable": True, "default": None},
    {"name": "float", "type": types.Float(), "nullable": True, "default": None},
    {"name": "numeric", "type": types.Numeric(), "nullable": True, "default": None},
    {"name": "boolean", "type": types.Boolean(), "nullable": True, "default": None},
    {"name": "date", "type": types.DATE(), "nullable": True, "default": None},
    {"name": "datetime", "type": types.DATETIME(), "nullable": True, "default": None},
    {"name": "time", "type": types.TIME(), "nullable": True, "default": None},
    {"name": "bytes", "type": types.BINARY(), "nullable": True, "default": None},
    {
        "name": "record",
        "type": types.JSON(),
        "nullable": True,
        "default": None,
        "comment": "In Standard SQL this data type is a STRUCT<name STRING, age INT64>.",
    },
    {"name": "record.name", "type": types.String(), "nullable": True, "default": None},
    {"name": "record.age", "type": types.Integer(), "nullable": True, "default": None},
    {"name": "nested_record", "type": types.JSON(), "nullable": True, "default": None},
    {
Exemple #27
0
metadata = schema.MetaData()

openid_redirects_table = schema.Table(
    'openid_redirects', metadata,
    schema.Column('token', types.Unicode(255), primary_key=True),
    schema.Column('url', types.Text(), default=u''),
    schema.Column('site', types.Text(), default=u''),
    schema.Column('handle', types.Text(), default=u''))

openid_handles_table = schema.Table(
    'openid_handles', metadata,
    schema.Column('handler', types.Unicode(255), primary_key=True),
    schema.Column('secret', types.Text(), default=u''),
    schema.Column('assoc_type', types.Text(), default=u''),
    schema.Column('private', types.Boolean(), default=False))

openid_sites_table = schema.Table(
    'openid_sites', metadata,
    schema.Column('id',
                  types.Integer,
                  schema.Sequence('openid_sites_seq_id', optional=True),
                  primary_key=True), schema.Column('handle',
                                                   types.Unicode(255)),
    schema.Column('site', types.Text(), default=u''))

openid_user_table = schema.Table(
    'openid_user', metadata,
    schema.Column('user', types.Unicode(255), primary_key=True),
    schema.Column('token', types.Text(), default=u''),
    schema.Column('expire', types.Integer, default=0, index=True))
Exemple #28
0
 def __init__(self, left, right, operator=operators.eq):
     self.type = sqltypes.Boolean()
     self.left = expression._literal_as_binds(left)
     self.right = right
     self.operator = operator
Exemple #29
0
class Allocation(TimestampMixin, ORMBase, OtherModels):
    """Describes a timespan within which one or many timeslots can be
    reserved.

    There's an important concept to understand before working with allocations.
    The resource uuid of an alloction is not always pointing to the actual
    resource.

    A resource may in fact be a real resource, or an imaginary resource with
    a uuid derived from the real resource. This is a somewhat historical
    artifact.

    If you need to know which allocations belong to a real resource, the
    mirror_of field is what's relevant. The originally created allocation
    with the real_resource is also called the master-allocation and it is
    the one allocation with mirror_of and resource being equal.

    When in doubt look at the managed_* functions of seantis.reservation.db's
    Scheduler class.

    """

    __tablename__ = 'allocations'

    id = Column(types.Integer(), primary_key=True, autoincrement=True)
    resource = Column(customtypes.GUID(), nullable=False)
    mirror_of = Column(customtypes.GUID(), nullable=False)
    group = Column(customtypes.GUID(), nullable=False)
    quota = Column(types.Integer(), default=1)
    partly_available = Column(types.Boolean(), default=False)
    approve_manually = Column(types.Boolean(), default=False)

    reservation_quota_limit = Column(
        types.Integer(), default=0, nullable=False
    )

    # The dates are stored without any timzone information (unaware).
    # Therefore the times are implicitly stored in the timezone the resource
    # resides in.

    # This is fine and dandy as long as all resources are in the same timezone.
    # If they are not problems arise. So in the future the resource should
    # carry a timezone property which is applied to the dates which will then
    # be stored in UTC

    # => TODO
    _start = Column(types.DateTime(), nullable=False)
    _end = Column(types.DateTime(), nullable=False)
    _raster = Column(types.Integer(), nullable=False)

    recurrence_id = Column(types.Integer(),
                           ForeignKey('recurrences.id',
                                      onupdate='cascade',
                                      ondelete='cascade'))
    recurrence = relation('Recurrence', lazy='joined')

    __table_args__ = (
        Index('mirror_resource_ix', 'mirror_of', 'resource'),
        UniqueConstraint('resource', '_start', name='resource_start_ix')
    )

    def copy(self):
        allocation = Allocation()
        allocation.resource = self.resource
        allocation.mirror_of = self.mirror_of
        allocation.group = self.group
        allocation.quota = self.quota
        allocation.partly_available = self.partly_available
        allocation.approve_manually = self.approve_manually
        allocation._start = self._start
        allocation._end = self._end
        allocation._raster = self._raster
        allocation.recurrence_id = self.recurrence_id
        return allocation

    def get_start(self):
        return self._start

    def set_start(self, start):
        self._start = rasterize_start(start, self.raster)

    start = property(get_start, set_start)

    def get_end(self):
        return self._end

    def set_end(self, end):
        self._end = rasterize_end(end, self.raster)

    end = property(get_end, set_end)

    def get_raster(self):
        return self._raster

    def set_raster(self, raster):
        # the raster can only be set once!
        assert(not self._raster)
        self._raster = raster

    raster = property(get_raster, set_raster)

    @property
    def display_start(self):
        """Does nothing but to form a nice pair to display_end."""
        return self.start

    @property
    def display_end(self):
        """Returns the end plus one microsecond (nicer display)."""
        return self.end + timedelta(microseconds=1)

    @property
    def whole_day(self):
        """True if the allocation is a whole-day allocation.

        A whole-day allocation is not really special. It's just an allocation
        which starts at 0:00 and ends at 24:00 (or 23:59:59'999).

        As such it can actually also span multiple days, only hours and minutes
        count.

        The use of this is to display allocations spanning days differently.
        """

        s, e = self.display_start, self.display_end
        assert s != e  # this can never be, except when caused by cosmic rays

        return utils.whole_day(s, e)

    def overlaps(self, start, end):
        """ Returns true if the current timespan overlaps with the given
        start and end date.

        """
        start, end = rasterize_span(start, end, self.raster)
        return utils.overlaps(start, end, self.start, self.end)

    def contains(self, start, end):
        """ Returns true if the current timespan contains the given start
        and end date.

        """
        start, end = rasterize_span(start, end, self.raster)
        return self.start <= start and end <= self.end

    def free_slots(self, start=None, end=None):
        """ Returns the slots which are not yet reserved."""
        reserved = [slot.start for slot in self.reserved_slots]

        slots = []
        for start, end in self.all_slots(start, end):
            if not start in reserved:
                slots.append((start, end))

        return slots

    def align_dates(self, start=None, end=None):
        """ Aligns the given dates to the start and end date of the
        allocation.

        """

        start = start or self.start
        start = start < self.start and self.start or start

        end = end or self.end
        end = end > self.end and self.end or end

        return start, end

    def all_slots(self, start=None, end=None):
        """ Returns the slots which exist with this timespan. Reserved or free.

        """
        start, end = self.align_dates(start, end)

        if self.partly_available:
            for start, end in iterate_span(start, end, self.raster):
                yield start, end
        else:
            yield self.start, self.end

    def is_available(self, start=None, end=None):
        """ Returns true if the given daterange is completely available. """

        if not (start and end):
            start, end = self.start, self.end

        assert(self.overlaps(start, end))

        if self.is_blocked(start, end):
            return False

        reserved = [slot.start for slot in self.reserved_slots]
        for start, end in self.all_slots(start, end):
            if start in reserved:
                return False

        return True

    def is_blocked(self, start=None, end=None):
        if not (start and end):
            start, end = self.start, self.end
        else:
            start, end = utils.as_machine_date(start, end)

        BlockedPeriod = self.models.BlockedPeriod
        query = self._query_blocked_periods()
        query = query.filter(BlockedPeriod.start <= end)
        query = query.filter(BlockedPeriod.end >= start)

        return query.first() is not None

    def _query_blocked_periods(self):
        query = Session.query(self.models.BlockedPeriod)
        query = query.filter_by(resource=self.resource)
        return query

    @property
    def pending_reservations(self):
        """ Returns the pending reservations query for this allocation.
        As the pending reservations target the group and not a specific
        allocation this function returns the same value for masters and
        mirrors.

        """
        Reservation = self.models.Reservation
        query = Session.query(Reservation.id)
        query = query.filter(Reservation.target == self.group)
        query = query.filter(Reservation.status == u'pending')

        return query

    @property
    def waitinglist_length(self):
        return self.pending_reservations.count()

    @property
    def availability(self):
        """Returns the availability in percent."""

        if self.partly_available:
            total = sum(1 for s in self.all_slots())
        else:
            total = 1

        count = len(self.reserved_slots)
        for blocked_period in self._query_blocked_periods():
            count += len(list(iterate_span(blocked_period.start,
                                           blocked_period.end,
                                           self.raster)))

        if total == count:
            return 0.0

        if count == 0:
            return 100.0

        return 100.0 - (float(count) / float(total) * 100.0)

    @property
    def in_group(self):
        """True if the event is in any group."""

        query = Session.query(Allocation.id)
        query = query.filter(Allocation.resource == self.resource)
        query = query.filter(Allocation.group == self.group)
        query = query.limit(2)

        return len(query.all()) > 1

    @property
    def in_recurrence(self):
        """True if the event is attached to a recurrence."""

        return self.recurrence_id is not None

    @property
    def is_separate(self):
        """True if available separately (as opposed to available only as
        part of a group)."""
        if self.partly_available:
            return True

        if self.in_group:
            return False

        return True

    def availability_partitions(self, scheduler):
        """Partitions the space between start and end into blocks of either
        free, blocked or reserved time. Each block has a percentage
        representing the space the block occupies compared to the size of the
        whole allocation.

        The blocks are ordered from start to end. Each block is an item with
        two values. The first being the percentage, the second being the type.
        The type can be one of None, 'reserved' or 'blocked'.

        So given an allocation that goes from 8 to 9 and a reservation that
        goes from 8:15 until 8:30 and a block that goes from 8:30 to 9:00
        we get the following blocks:

        [
            (25%, None),
            (25%, 'reserved'),
            (50%, 'blocked')
        ]

        This is useful to divide an allocation block into different divs on the
        frontend, indicating to the user which parts of an allocation are
        available for reservation.

        Makes sure to only display slots that are within it's resources
        first_hour/last_hour timespan.

        """

        resource = get_resource_by_uuid(scheduler.uuid).getObject()
        min_start_resource = datetime.combine(self.start,
                                              time(resource.first_hour))
        max_end_resource = datetime.combine(self.end,
                                            time(resource.last_hour))

        display_start = max(min_start_resource, self.start)
        display_end = min(max_end_resource, self.end)

        reserved = dict((r.start, r) for r in self.reserved_slots if
                        r.start >= display_start and r.end <= display_end)
        blocked = set()
        for blocked_period in self._query_blocked_periods():
            blocked.update(start for start, end in
                           iterate_span(max(blocked_period.start,
                                            display_start),
                                        min(blocked_period.end,
                                            display_end),
                                        self.raster))

        if not (reserved or blocked):
            return [(100.0, None)]

        # Get the percentage one slot represents
        slots = list(self.all_slots(display_start, display_end))
        step = 100.0 / float(len(slots))

        # Create an entry for each slot with either True or False
        pieces = []
        for slot in slots:
            piece = None
            if slot[0] in reserved:
                reserved_slot = reserved[slot[0]]
                token = reserved_slot.reservation_token
                reservation = scheduler.reservation_by_token(token).one()
                piece = ('reserved', reservation.description, reservation.id)
            elif slot[0] in blocked:
                piece = ('blocked', None)
            pieces.append(piece)

        # Group by the None/'reserved'/'blocked' values in the pieces and sum
        # up the percentage
        partitions = []
        for flag, group in groupby(pieces, key=lambda p: p):
            percentage = len(list(group)) * step
            partitions.append([percentage, flag])

        # Make sure to get rid of floating point rounding errors
        total = sum([p[0] for p in partitions])
        diff = 100.0 - total
        partitions[-1:][0][0] -= diff

        return partitions

    @property
    def is_transient(self):
        """True if the allocation does not exist in the database, and is not
        about to be written to the database. If an allocation is transient it
        means that the given instance only exists in memory.

        See:
        http://www.sqlalchemy.org/docs/orm/session.html
        #quickie-intro-to-object-states
        http://stackoverflow.com/questions/3885601/
        sqlalchemy-get-object-instance-state

        """

        return object_session(self) is None and not has_identity(self)

    @property
    def is_master(self):
        """True if the allocation is a master allocation."""

        return self.resource == self.mirror_of

    def siblings(self, imaginary=True):
        """Returns the master/mirrors group this allocation is part of.

        If 'imaginary' is true, inexistant mirrors are created on the fly.
        those mirrors are transient (see self.is_transient)

        """

        # this function should always have itself in the result
        if not imaginary and self.is_transient:
            assert False, \
                'the resulting list would not contain this allocation'

        if self.quota == 1:
            assert(self.is_master)
            return [self]

        query = Session.query(Allocation)
        query = query.filter(Allocation.mirror_of == self.mirror_of)
        query = query.filter(Allocation._start == self._start)

        existing = dict(((e.resource, e) for e in query))

        master = self.is_master and self or existing[self.mirror_of]
        existing[master.resource] = master

        uuids = utils.generate_uuids(master.resource, master.quota)
        imaginary = imaginary and (master.quota - len(existing)) or 0

        siblings = [master]
        for uuid in uuids:
            if uuid in existing:
                siblings.append(existing[uuid])
            elif imaginary > 0:
                allocation = master.copy()
                allocation.resource = uuid
                siblings.append(allocation)

                imaginary -= 1

        return siblings
Exemple #30
0
class BQDialect(default.DefaultDialect):
    colspecs = {
        types.Unicode: BQString,
        types.Integer: BQInteger,
        types.SmallInteger: BQInteger,
        types.Numeric: BQFloat,
        types.Float: BQFloat,
        types.DateTime: BQTimestamp,
        types.Date: BQTimestamp,
        types.String: BQString,
        types.LargeBinary: BQBytes,
        types.Boolean: BQBoolean,
        types.Text: BQString,
        types.CHAR: BQString,
        types.TIMESTAMP: BQTimestamp,
        types.VARCHAR: BQString
    }

    __TYPE_MAPPINGS = {
        'TIMESTAMP': types.DateTime(),
        'STRING': types.String(),
        'FLOAT': types.Float(),
        'INTEGER': types.Integer(),
        'BOOLEAN': types.Boolean()
    }

    name = 'bigquery'
    driver = 'bq1'
    poolclass = pool.SingletonThreadPool
    statement_compiler = BQSQLCompiler
    ddl_compiler = BQDDLCompiler
    preparer = BQIdentifierPreparer
    execution_ctx_cls = BQExecutionContext

    supports_alter = False
    supports_unicode_statements = True
    supports_sane_multi_rowcount = False
    supports_sane_rowcount = False
    supports_sequences = False
    supports_native_enum = False

    positional = False
    paramstyle = 'named'

    default_sequence_base = 0
    default_schema_name = None

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
    def __init__(self, **kw):
        #
        # Create a dialect object
        #
        super(BQDialect, self).__init__(**kw)

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
    def create_connect_args(self, url):
        #
        # This function recovers connection parameters from the connection string
        #
        return [], {}

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
    def initialize(self, connection):
        """disable all dialect initialization"""

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
    @classmethod
    def dbapi(cls):
        return dbapi

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
    def do_execute(self, cursor, statement, parameters, context=None):
        cursor.execute(statement, parameters)

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
    def do_executemany(self, cursor, statement, parameters, context=None):
        cursor.executemany(statement, parameters)

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
    def get_schema_names(self, engine, **kw):
        return engine.connect().connection.get_schema_names()

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
    def get_view_names(self, connection, schema=None, **kw):
        raise NotImplementedError()

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
    def get_view_definition(self, connection, viewname, schema=None, **kw):
        raise NotImplementedError()

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
    def has_table(self, connection, table_name, schema=None):
        return table_name in connection.connection.get_table_names()

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
    @reflection.cache
    def get_table_names(self, engine, schema=None, **kw):
        return engine.connect().connection.get_table_names()

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
    def get_columns(self, engine, table_name, schema=None, **kw):
        cols = engine.connect().connection.get_columns(table_name)

        get_coldef = lambda x, y: {
            "name": x,
            "type": BQDialect.__TYPE_MAPPINGS.get(y, types.Binary()),
            "nullable": True,
            "default": None
        }

        return [get_coldef(*col) for col in cols]

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
    def get_primary_keys(self, engine, table_name, schema=None, **kw):
        return []

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
    def get_foreign_keys(self, engine, table_name, schema=None, **kw):
        return []

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
    def get_indexes(self, connection, table_name, schema=None, **kw):
        return []