コード例 #1
0
def wirte_to_mysqldb(df, result_tb = 'data_health_examination', user='******', \
                     psw='liangzhi123', host='192.168.1.22', db='datamining', \
                     if_exists='append', dtype={u'db_name':sqltypes.NVARCHAR(length=255),
                                                 u'table_name':sqltypes.NVARCHAR(length=255),
                                                 u'part_date':sqltypes.NVARCHAR(length=255),
                                                 u'create_date':sqltypes.DateTime(),
                                                 u'field_name':sqltypes.NVARCHAR(length=255),
                                                 u'field_type':sqltypes.NVARCHAR(length=255),
                                                 u'missing_value_num':sqltypes.BigInteger(),
                                                 u'missing_value_prop':sqltypes.Float(),
                                                 u'other_missing_value_num':sqltypes.BigInteger(),
                                                 u'other_missing_value_prop':sqltypes.Float(),
                                                 u'abnormal_value_index':sqltypes.Text(),
                                                 u'abnormal_value_num':sqltypes.BigInteger(),
                                                 u'abnormal_value_prop':sqltypes.Float(),
                                                 u'if_exist_probability_plot':sqltypes.Integer(),
                                                 u'probability_plot_result':sqltypes.NVARCHAR(length=255),
                                                 u'probability_plot_script':sqltypes.Text(),
                                                 u'if_exist_frequency_plot':sqltypes.Integer(),
                                                 u'frequency_plot_result':sqltypes.NVARCHAR(length=255),
                                                 u'frequency_plot_script':sqltypes.Text(),
                                                 u'if_exist_rules':sqltypes.Integer(),
                                                 u'show_Chn_rules':sqltypes.NVARCHAR(length=255),
                                                 u'show_Eng_rules':sqltypes.NVARCHAR(length=255),
                                                 u'rules_result':sqltypes.NVARCHAR(length=255)}):
    engine = sqlalchemy.create_engine(str(r"mysql+mysqldb://%s:" + '%s' + "@%s/%s?%s")\
                                      % (user, psw, host, db, 'charset=utf8'))
    df.to_sql(result_tb, engine, if_exists=if_exists, index=False, dtype=dtype)
コード例 #2
0
class Visitor(db.Model):
    __tablename__ = 'visitor'

    visitorId = db.Column(db.String(10), primary_key=True)
    platform = db.Column(db.String(15))
    browser = db.Column(db.String(10))
    language = db.Column(db.String(10))
    version = db.Column(db.String(20))
    cl_lat = db.Column(types.Float(25), nullable=True)
    cl_lng = db.Column(types.Float(25), nullable=True)
    count = db.Column(Integer)
    referrer = db.Column(db.String(150), nullable=True)
    ip = db.Column(db.String(20))
    coord_errorcode = db.Column(db.Integer, nullable=True)
    visitdatetime = db.Column(DateTime(timezone=True))
    timezone = db.Column(db.String(24))

    def __init__(self, platform, browser, visitor_time, timezone, visitorId,
                 lat, lng, language, referrer, version, ip):
        self.platform = platform
        self.browser = browser
        self.timezone = timezone
        self.visitor_time = visitor_time
        self.visitorId = visitorId
        self.cl_lat = lat
        self.cl_lng = lng
        self.language = language
        self.referrer = referrer
        self.version = version
        self.ip = ip
コード例 #3
0
class Stop(Base, ToJSONMixin, Versioned, GTFSBase):
    __tablename__ = 'stops'

    stop_id = Column(types.Integer, primary_key=True)
    stop_code = Column(types.String(50))
    stop_desc = Column(types.String(250))
    stop_name = Column(types.String(250))
    stop_lat = Column(types.Float(precision=53))
    stop_lon = Column(types.Float(precision=53))
    stop_calle = Column(types.String(250))
    stop_numero = Column(types.String(50))
    stop_entre = Column(types.String(250))
    stop_esquina = Column(types.String(250))
コード例 #4
0
    def test_basic_reflection(self):
        meta = self.metadata

        users = Table(
            "engine_users",
            meta,
            Column("user_id", types.INT, primary_key=True),
            Column("user_name", types.VARCHAR(20), nullable=False),
            Column("test1", types.CHAR(5), nullable=False),
            Column("test2", types.Float(5), nullable=False),
            Column("test2.5", types.Float(), nullable=False),
            Column("test3", types.Text()),
            Column("test4", types.Numeric, nullable=False),
            Column("test4.5", types.Numeric(10, 2), nullable=False),
            Column("test5", types.DateTime),
            Column(
                "parent_user_id",
                types.Integer,
                ForeignKey("engine_users.user_id"),
            ),
            Column("test6", types.DateTime, nullable=False),
            Column("test7", types.Text()),
            Column("test8", types.LargeBinary()),
            Column("test_passivedefault2", types.Integer, server_default="5"),
            Column("test9", types.BINARY(100)),
            Column("test_numeric", types.Numeric()),
        )

        addresses = Table(
            "engine_email_addresses",
            meta,
            Column("address_id", types.Integer, primary_key=True),
            Column("remote_user_id", types.Integer,
                   ForeignKey(users.c.user_id)),
            Column("email_address", types.String(20)),
        )
        meta.create_all()

        meta2 = MetaData()
        reflected_users = Table("engine_users",
                                meta2,
                                autoload=True,
                                autoload_with=testing.db)
        reflected_addresses = Table(
            "engine_email_addresses",
            meta2,
            autoload=True,
            autoload_with=testing.db,
        )
        self.assert_tables_equal(users, reflected_users)
        self.assert_tables_equal(addresses, reflected_addresses)
コード例 #5
0
def save_models_to_sql_helper(trained_models,
                              ablation_set,
                              prefix,
                              if_exists='replace'):
    method = 'default'
    dfs = []
    for model in trained_models:
        cv = trained_models[model]
        k_range = cv.best_k[method]['k_range']
        for metric in models.METRICS:
            if metric in cv.results[method].keys():
                results = cv.results[method][metric]
                df = pd.DataFrame(results, columns=k_range)
                df['metric'] = metric.decode('utf-8', 'ignore')
                df['model'] = model
                dfs += [df]

    name = "%s_%s" % (prefix, ablation_set)

    df = pd.concat(dfs, axis=0, ignore_index=True)
    typedict = {
        col_name: types.Float(precision=5, asdecimal=True)
        for col_name in df
    }
    typedict['metric'] = types.NVARCHAR(length=255)
    typedict['model'] = types.NVARCHAR(length=255)
    df.to_sql(name, cnx, if_exists=if_exists, dtype=typedict)
コード例 #6
0
def upgrade(migrate_engine):
    meta.bind = migrate_engine
    stats = schema.Table(
        'apistats', meta, schema.Column('id',
                                        types.Integer(),
                                        primary_key=True),
        schema.Column('host', types.String(80)),
        schema.Column('request_count', types.BigInteger()),
        schema.Column('error_count', types.BigInteger()),
        schema.Column('average_response_time', types.Float()),
        schema.Column('requests_per_tenant', types.Text()),
        schema.Column('requests_per_second', types.Float()),
        schema.Column('errors_per_second', types.Float()),
        schema.Column('created', types.DateTime, nullable=False),
        schema.Column('updated', types.DateTime, nullable=False))
    stats.create()
コード例 #7
0
def main():

    #데이터베이스 설정
    dbRMS01 = Connection('spt', 'RMS01')
    dbMYSQL = Connection('python', 'TESTDB')

    #쿼리아이템 예제
    #쿼리 설정
    sql = \
     '''	SELECT TO_DATE(TRADE_DATE,'yyyymmdd') TRADE_DATE, PX_LAST 
			FROM spt.BL_DATA 
			WHERE TRADE_DATE='{trade_date}' AND TICKER='{ticker}' 
		'''
    col_info = {'TRADE_DATE': types.DateTime(), 'PX_LAST': types.Float()}
    index_col = 'TRADE_DATE'
    bind = {'trade_date': '20170531', 'ticker': 'HSCEI'}

    #결과출력
    testRESULT = dbRMS01.query(sql, bind)
    print(testRESULT)
    print('\n')

    #테이블아이템 예제
    #테이블 설정
    table_name = 'els_market_oper_hist'
    col_info = {'OPER_DATE': types.DateTime()}

    #결과출력
    testRESULT = dbMYSQL.select_table(table_name, col_info)
    print(testRESULT)
    print('\n')
コード例 #8
0
    def sqlcol(dfparam, text=None):

        dtypedict = {}
        for i, j in zip(dfparam.columns, dfparam.dtypes):

            if "object" in str(j):
                if text == "postgresql-text":
                    dtypedict.update({i: TEXT()})
                else:
                    try:
                        x = int(df[i].str.len().max() / 40) + 1
                    except:
                        x = 50
                    dtypedict.update({i: types.VARCHAR(length=x * 80)})

            if "datetime" in str(j):
                dtypedict.update({i: types.DateTime()})

            if "float" in str(j):
                dtypedict.update({i: types.Float(precision=3, asdecimal=True)})

            if "int" in str(j):
                dtypedict.update({i: types.INT()})

        return dtypedict
コード例 #9
0
class Shape(Base, ToJSONMixin, Versioned, GTFSBase):
    __tablename__ = 'shapes'

    shape_id = Column(types.Integer, primary_key=True)
    shape_pt_lat = Column(types.Float(precision=53))
    shape_pt_lon = Column(types.Float(precision=53))
    shape_pt_time = Column(types.String(50))
    shape_pt_sequence = Column(types.Integer, primary_key=True)

    @classmethod
    def vertices(cls, shape_id):
        return db.session.query(cls)\
            .filter(cls.shape_id == shape_id)\
            .order_by(cls.shape_pt_sequence)

    @classmethod
    def get_vertices_array(cls, shape_id):
        return [[pt.shape_pt_lon, pt.shape_pt_lat]
                for pt in cls.vertices(shape_id).all()]
コード例 #10
0
ファイル: model.py プロジェクト: 2silver/example.trajectory
class Product(Base):
    implements(IProduct)

    __tablename__ = 'products'

    id = Column(types.Integer, primary_key=True)
    name = Column(types.Unicode())
    description = Column(types.Unicode())
    price = Column(types.Float())

    def __repr__(self):
        return "<%s %s(%s)>" % (self.__class__.__name__, self.name, self.id)
コード例 #11
0
class StopSeq(Base, ToJSONMixin, Versioned, GTFSBase):
    __tablename__ = 'stop_seq'

    trip_id = Column(types.Integer,
                     ForeignKey("trips.trip_id",
                                onupdate="CASCADE",
                                ondelete="CASCADE"),
                     primary_key=True)
    stop_id = Column(types.Integer,
                     ForeignKey("stops.stop_id",
                                onupdate="CASCADE",
                                ondelete="CASCADE"),
                     primary_key=True)
    stop_sequence = Column(types.Integer, primary_key=True)
    stop_time = Column(types.String(50))
    shape_dist_traveled = Column(types.Float(precision=53))
コード例 #12
0
class Item(Base):
    id = Column(types.Integer(), primary_key=True, autoincrement=True)

    url = Column(ForeignKey('url.id', ondelete=RESTRICT, onupdate=CASCADE),
                 nullable=False)
    source = Column(ForeignKey('url.id', ondelete=RESTRICT, onupdate=CASCADE),
                    nullable=False)

    title = Column(types.String())
    author = Column(types.String())
    published = Column(types.DateTime())
    updated = Column(types.DateTime())
    crawled = Column(types.Float())

    @declared_attr
    def __table_args__(self):
        return (Index(None, 'url', unique=True), )
コード例 #13
0
def individual(engine, data_filepath_list):
    """
    Create individual SQL tables for every CSV file within a directory
    """
    for filepath in data_filepath_list:
        table_name = os.path.splitext(os.path.basename(filepath))[
            0]  # set table name to basename of filepath
        logging.info("Reading data file:  " + filepath)
        line_count = sum(
            1 for line in open('On_Time_Performance_1993_2.csv')) - 1
        logging.info(str(line_count) + " rows will be inserted.")
        for dataframe in pandas.read_csv(filepath,
                                         low_memory=False,
                                         iterator=True,
                                         chunksize=1000000):  # infer dtypes
            dataframe.dropna(
                axis=1, thresh=len(dataframe.index) // 10,
                inplace=True)  # drop columns having more than 90% NaN values
            dataframe.columns = map(
                str.upper,
                map(underscore,
                    dataframe.columns))  # camelcase to underscore to uppercase
            dtype_dict = {}
            for column in dataframe.columns:  # map DataFrame dtypes to Database data types
                if dataframe[column].dtype in ['object']:
                    dtype_dict[column] = types.String(
                        int(dataframe[column].str.len().max()))
                elif dataframe[column].dtype in ['int64']:
                    dtype_dict[column] = types.Integer()
                elif dataframe[column].dtype in ['float64']:
                    dtype_dict[column] = types.Float()
                else:
                    logging.error(
                        str(dataframe[column].dtype) +
                        " dtype unsupported.  Dropping column:  " + column
                    )  # ['object_', 'string_', 'unicode_', 'unicode', 'int_', 'float_']
                    del dataframe[column]
            logging.info("Creating table and inserting data into table:  " +
                         table_name)
            dataframe.to_sql(table_name,
                             engine,
                             if_exists='append',
                             index=False,
                             chunksize=1000,
                             dtype=dtype_dict)
            logging.info("Successfully inserted data")
コード例 #14
0
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()
                        })
コード例 #15
0
    def test_basic_reflection(self):
        meta = self.metadata

        users = Table(
            'engine_users',
            meta,
            Column('user_id', types.INT, primary_key=True),
            Column('user_name', types.VARCHAR(20), nullable=False),
            Column('test1', types.CHAR(5), nullable=False),
            Column('test2', types.Float(5), nullable=False),
            Column('test3', types.Text()),
            Column('test4', types.Numeric, nullable=False),
            Column('test5', types.DateTime),
            Column('parent_user_id', types.Integer,
                   ForeignKey('engine_users.user_id')),
            Column('test6', types.DateTime, nullable=False),
            Column('test7', types.Text()),
            Column('test8', types.LargeBinary()),
            Column('test_passivedefault2', types.Integer, server_default='5'),
            Column('test9', types.BINARY(100)),
            Column('test_numeric', types.Numeric()),
        )

        addresses = Table(
            'engine_email_addresses',
            meta,
            Column('address_id', types.Integer, primary_key=True),
            Column('remote_user_id', types.Integer,
                   ForeignKey(users.c.user_id)),
            Column('email_address', types.String(20)),
        )
        meta.create_all()

        meta2 = MetaData()
        reflected_users = Table('engine_users',
                                meta2,
                                autoload=True,
                                autoload_with=testing.db)
        reflected_addresses = Table('engine_email_addresses',
                                    meta2,
                                    autoload=True,
                                    autoload_with=testing.db)
        self.assert_tables_equal(users, reflected_users)
        self.assert_tables_equal(addresses, reflected_addresses)
コード例 #16
0
def gen_types_from_pandas_to_sql(table):
    r"""
    Generate a dictionnary with the database types related to the dataframe dtypes
    """
    dtypedict = {}
    for i, j in zip(table.columns, table.dtypes):
        if 'object' in str(j):
            dtypedict.update({i: types.NVARCHAR(length=500)})
        if 'datetime' in str(j):
            dtypedict.update({i: types.DateTime()})
        if 'float' in str(j):
            dtypedict.update({i: types.Float(precision=3, asdecimal=True)})
        if 'int' in str(j):
            if max([l for l in table[i].tolist() if not pd.isnull(l)
                    ]) > cp.INT_LIMIT:
                dtypedict.update({i: types.BIGINT()})
            else:
                dtypedict.update({i: types.INT()})
    return dtypedict
コード例 #17
0
def np_to_sql_type(input_type):
    """
    Returns the SQL data type (as encoded by sqlalchemy)
    corresponding to a numpy dtype

    input_type is an element of a numpy.dtype array
    """
    name = input_type.name
    size = input_type.itemsize
    if name.startswith('float'):
        return satypes.Float(precision=16)
    if name == 'int64':
        return satypes.BIGINT()
    if name == 'int32':
        return satypes.Integer()
    if name.startswith('str') or str(input_type).startswith('S') or str(input_type).startswith('|S'):
        return satypes.String(length=size)

    raise RuntimeError("Do not know how to map %s to SQL" % str(input_type))
コード例 #18
0
class ConocimientoModel(bd.Model):
    __tablename__ = 't_conocimiento'
    conocimientoId = Column(name='conocimiento_id',
                            type_=types.Integer,
                            primary_key=True,
                            autoincrement=True,
                            unique=True,
                            nullable=True)
    conocimientoTitulo = Column(name='conocimiento_titulo',
                                type_=types.String(45),
                                nullable=False)
    conocimientoPuntuacion = Column(name='conocimiento_puntuacion',
                                    type_=types.Float(2, 1),
                                    nullable=False)
    conocimientoImagenTN = Column(name='conocimiento_imagen_thumbnail',
                                  type_=types.TEXT,
                                  nullable=False)
    conocimientoImagenLarge = Column(name='conocimiento_image_large',
                                     type_=types.TEXT,
                                     nullable=False)
    conocimientoDescripcion = Column(name='conocimiento_descripcion',
                                     type_=types.TEXT,
                                     nullable=False)

    categoria = Column(ForeignKey('t_categoria.cat_id'),
                       name='cat_id',
                       type_=types.Integer,
                       nullable=False)

    usuario = Column(ForeignKey('t_usuario.usuario_id'),
                     name='usuario_id',
                     nullable=False,
                     type_=types.Integer)

    def __init__(self, titulo, puntuacion, imagen1, imagen2, descripcion,
                 categoria, usuario):
        self.conocimientoTitulo = titulo
        self.conocimientoPuntuacion = puntuacion
        self.conocimientoImagenTN = imagen1
        self.conocimientoImagenLarge = imagen2
        self.conocimientoDescripcion = descripcion
        self.categoria = categoria
        self.usuario = usuario
コード例 #19
0
ファイル: stoptime.py プロジェクト: todokku/gtfseditor
class StopTime(Base, ToJSONMixin, Versioned, GTFSBase):
    __tablename__ = 'stop_times'

    trip_id = Column(types.Integer,
                     ForeignKey("trips.trip_id",
                                onupdate="CASCADE",
                                ondelete="CASCADE"),
                     primary_key=True)
    stop_id = Column(types.Integer,
                     ForeignKey("stops.stop_id",
                                onupdate="CASCADE",
                                ondelete="CASCADE"),
                     primary_key=True)
    stop_sequence = Column(types.Integer, primary_key=True)
    arrival_time = Column(types.String(50))
    departure_time = Column(types.String(50))
    shape_dist_traveled = Column(types.Float(precision=53))

    stop = relationship("Stop", backref="stop_times")
    trip = relationship("Trip", backref="stop_times")
コード例 #20
0
ファイル: dbtools.py プロジェクト: gdyflxw/DataMiningSys
 def db_write(self,df,tb_name,dbtype='mssql',conp=None,rora='replace'):
     cs=None
     if len(df)>20000:cs=10000
     con=self.getconstr(dbtype,conp)
     dtypedict = {}
     for i,j in zip(df.columns, df.dtypes):
         if "object" in str(j):
             try:
                 x=int(df[i].str.len().max()/40)+1 
             except:
                 x=50
             dtypedict.update({i: types.VARCHAR(length=x*80)})
         if "datetime" in str(j):
             dtypedict.update({i: types.DateTime()})
         if "float" in str(j):
             dtypedict.update({i: types.Float(precision=3, asdecimal=True)})
         if "int" in str(j):
             dtypedict.update({i: types.INT()})        
     if dbtype in ['postgresql','mssql']:
         df.to_sql(tb_name,con,if_exists=rora,index=False,schema=conp[4],dtype=dtypedict,chunksize=cs)
     elif dbtype in ['oracle','mysql','sqlite']:
         df.to_sql(tb_name,con,if_exists=rora,index=False,dtype=dtypedict,chunksize=cs)
コード例 #21
0
def save_domain_adapt_to_sql_helper(da, model_name, if_exists='replace'):
    dfs = []
    name = "%s_%s" % (DOMAIN_ADAPTATION_RESULTS_PREFIX, model_name)
    for method in da.methods:
        k_range = da.best_k[method]['k_range']
        # for metric in ['roc', 'fms', 'acc']:
        for metric in ['fms', 'acc']:
            if metric in da.results[method].keys():
                results = da.results[method][metric]
                df = pd.DataFrame(results, columns=k_range)
                df['metric'] = metric.decode('utf-8', 'ignore')
                df['method'] = method.decode('utf-8', 'ignore')
                dfs += [df]

    df = pd.concat(dfs, axis=0, ignore_index=True)
    typedict = {
        col_name: types.Float(precision=5, asdecimal=True)
        for col_name in df
    }
    typedict['metric'] = types.NVARCHAR(length=255)
    typedict['method'] = types.NVARCHAR(length=255)
    df.to_sql(name, cnx, if_exists=if_exists, dtype=typedict)
コード例 #22
0
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()
コード例 #23
0
 },
 {
     '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': 'boolean',
     'type': types.Boolean(),
     'nullable': True,
     'default': None
 },
 {
     'name': 'date',
     'type': types.DATE(),
     'nullable': True,
     'default': None
 },
コード例 #24
0
:note:              - 이 모듈에서는 자주사용하는 샘플쿼리를 미리 정의함

"""
'''모듈 불러오기'''
from sqlalchemy import types  #ALCHEMY for engine
'''쿼리 인스턴스 임포트'''
#기본상품정보조회
#컬럼 데이터타입
basic_col = \
 {'ISIN_NO'  :types.NVARCHAR(length=50),
    'STD_DATE'  :types.DateTime(),
    'FIRST_AMT' :types.BigInteger(),
    'REMAIN_AMT' :types.BigInteger(),
    'EFF_DATE'  :types.DateTime(),
    'MAT_DATE'  :types.DateTime(),
    'PRSV_RATE' :types.Float()}
#쿼리문
basic_sql = \
 (
    "select ISIN_NO,"
    "		to_date(STD_DATE,'yyyymmdd') STD_DATE, "
    "		FIRST_AMT, REMAIN_AMT, "
    "		EFF_DATE, MAT_DATE, PRSV_RATE "
    "from "
    "( "
    "	select 	tblLATEST.ISIN_NO, "                    #ISIN번호
    "			greatest(tblLATEST.STND_DATE, nvl(tblREFUND.STND_DATE,0)) STD_DATE, "      #처리일자
    "			tblLATEST.FIRST_AMT/1000000 FIRST_AMT, "              #최초발행금액 (백만원)
    "			greatest(tblLATEST.FIRST_AMT-nvl(tblREFUND.REFUND,0),0)/1000000 REMAIN_AMT, "     #현재발행잔액 (백만원)
    "			tblLATEST.EFF_DATE, "                    #설정일자
    "			tblLATEST.MAT_DATE, "                  #만기일자
コード例 #25
0
def test_should_float_convert_float():
    assert_column_conversion(types.Float(), graphene.Float)
コード例 #26
0
    def reflecttable(self, connection, table):
        #TODO: map these better
        column_func = {
            14 : lambda r: sqltypes.String(r['FLEN']), # TEXT
            7  : lambda r: sqltypes.Integer(), # SHORT
            8  : lambda r: sqltypes.Integer(), # LONG
            9  : lambda r: sqltypes.Float(), # QUAD
            10 : lambda r: sqltypes.Float(), # FLOAT
            27 : lambda r: sqltypes.Float(), # DOUBLE
            35 : lambda r: sqltypes.DateTime(), # TIMESTAMP
            37 : lambda r: sqltypes.String(r['FLEN']), # VARYING
            261: lambda r: sqltypes.TEXT(), # BLOB
            40 : lambda r: sqltypes.Char(r['FLEN']), # CSTRING
            12 : lambda r: sqltypes.Date(), # DATE
            13 : lambda r: sqltypes.Time(), # TIME
            16 : lambda r: sqltypes.Numeric(precision=r['FPREC'], length=r['FSCALE'] * -1)  #INT64
            }
        tblqry = """
        SELECT DISTINCT R.RDB$FIELD_NAME AS FNAME,
                  R.RDB$NULL_FLAG AS NULL_FLAG,
                  R.RDB$FIELD_POSITION,
                  F.RDB$FIELD_TYPE AS FTYPE,
                  F.RDB$FIELD_SUB_TYPE AS STYPE,
                  F.RDB$FIELD_LENGTH AS FLEN,
                  F.RDB$FIELD_PRECISION AS FPREC,
                  F.RDB$FIELD_SCALE AS FSCALE
        FROM RDB$RELATION_FIELDS R
             JOIN RDB$FIELDS F ON R.RDB$FIELD_SOURCE=F.RDB$FIELD_NAME
        WHERE F.RDB$SYSTEM_FLAG=0 and R.RDB$RELATION_NAME=?
        ORDER BY R.RDB$FIELD_POSITION"""
        keyqry = """
        SELECT SE.RDB$FIELD_NAME SENAME
        FROM RDB$RELATION_CONSTRAINTS RC
             JOIN RDB$INDEX_SEGMENTS SE
               ON RC.RDB$INDEX_NAME=SE.RDB$INDEX_NAME
        WHERE RC.RDB$CONSTRAINT_TYPE=? AND RC.RDB$RELATION_NAME=?"""
        fkqry = """
        SELECT RC.RDB$CONSTRAINT_NAME CNAME,
               CSE.RDB$FIELD_NAME FNAME,
               IX2.RDB$RELATION_NAME RNAME,
               SE.RDB$FIELD_NAME SENAME
        FROM RDB$RELATION_CONSTRAINTS RC
             JOIN RDB$INDICES IX1
               ON IX1.RDB$INDEX_NAME=RC.RDB$INDEX_NAME
             JOIN RDB$INDICES IX2
               ON IX2.RDB$INDEX_NAME=IX1.RDB$FOREIGN_KEY
             JOIN RDB$INDEX_SEGMENTS CSE
               ON CSE.RDB$INDEX_NAME=IX1.RDB$INDEX_NAME
             JOIN RDB$INDEX_SEGMENTS SE
               ON SE.RDB$INDEX_NAME=IX2.RDB$INDEX_NAME AND SE.RDB$FIELD_POSITION=CSE.RDB$FIELD_POSITION
        WHERE RC.RDB$CONSTRAINT_TYPE=? AND RC.RDB$RELATION_NAME=?
        ORDER BY SE.RDB$INDEX_NAME, SE.RDB$FIELD_POSITION"""

        # get primary key fields
        c = connection.execute(keyqry, ["PRIMARY KEY", table.name.upper()])
        pkfields =[r['SENAME'] for r in c.fetchall()]

        # get all of the fields for this table

        def lower_if_possible(name):
            # Remove trailing spaces: FB uses a CHAR() type,
            # that is padded with spaces
            name = name.rstrip()
            # If its composed only by upper case chars, use
            # the lowered version, otherwise keep the original
            # (even if stripped...)
            lname = name.lower()
            if lname.upper() == name and not ' ' in name:
                return lname
            return name

        c = connection.execute(tblqry, [table.name.upper()])
        row = c.fetchone()
        if not row:
            raise exceptions.NoSuchTableError(table.name)

        while row:
            name = row['FNAME']
            args = [lower_if_possible(name)]

            kw = {}
            # get the data types and lengths
            args.append(column_func[row['FTYPE']](row))

            # is it a primary key?
            kw['primary_key'] = name in pkfields

            table.append_column(schema.Column(*args, **kw))
            row = c.fetchone()

        # get the foreign keys
        c = connection.execute(fkqry, ["FOREIGN KEY", table.name.upper()])
        fks = {}
        while True:
            row = c.fetchone()
            if not row: break

            cname = lower_if_possible(row['CNAME'])
            try:
                fk = fks[cname]
            except KeyError:
                fks[cname] = fk = ([], [])
            rname = lower_if_possible(row['RNAME'])
            schema.Table(rname, table.metadata, autoload=True, autoload_with=connection)
            fname = lower_if_possible(row['FNAME'])
            refspec = rname + '.' + lower_if_possible(row['SENAME'])
            fk[0].append(fname)
            fk[1].append(refspec)

        for name,value in fks.iteritems():
            table.append_constraint(schema.ForeignKeyConstraint(value[0], value[1], name=name))
コード例 #27
0
)

# esgf_node_manager tables

accessLoggingTable = Table(
    'access_logging',
    metadata,
    Column('id', types.Integer, primary_key=True, autoincrement=True),
    Column('user_id', types.String(), nullable=False),
    Column('email', types.String()),
    Column('url', types.String(), index=True, nullable=False),
    Column('file_id', types.String()),
    Column('remote_addr', types.String(), nullable=False),
    Column('user_agent', types.String()),
    Column('service_type', types.String()),
    Column('batch_update_time', types.Float(precision=53)),
    Column('date_fetched', types.Float(precision=53), nullable=False),
    Column('success', types.Boolean, default=False),
    Column('duration', types.Float(precision=53), default=0.0),
    schema='esgf_node_manager',
)

downloadTable = Table(
    'download',
    metadata,
    Column('userid', types.String(64)),
    Column('url', types.String(255)),
    schema='esgf_node_manager',
)

metricsRunLogTable = Table(
コード例 #28
0
    datetime.datetime(2013, 10, 10, 11, 27, 16, tzinfo=timezone("UTC")),
    "test",
    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},
コード例 #29
0
def test_should_float_convert_float():
    assert get_field(types.Float()).type == graphene.Float
コード例 #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 []