#NEWLINE# @ has_access #NEWLINE# @ expose ( '/runsql/' , methods = [ 'POST' , 'GET' ] ) #NEWLINE# @ log_this #NEWLINE# def runsql( self ) : #NEWLINE# #INDENT# 'Runs arbitrary sql and returns and html table' #NEWLINE# session = db . session ( ) #NEWLINE# limit = 1000 #NEWLINE# data = json . loads ( request . form . get ( 'data' ) ) #NEWLINE# sql = data . get ( 'sql' ) #NEWLINE# database_id = data . get ( 'database_id' ) #NEWLINE# mydb = session . query ( models . Database ) . filter_by ( id = database_id ) . first ( ) #NEWLINE# if ( not self . appbuilder . sm . has_access ( 'all_datasource_access' , 'all_datasource_access' ) ) : #NEWLINE# #INDENT# raise Exception ( 'This view requires the `all_datasource_access` permission' ) #NEWLINE# #UNINDENT# content = '' #NEWLINE# if mydb : #NEWLINE# #INDENT# eng = mydb . get_sqla_engine ( ) #NEWLINE# if limit : #NEWLINE# #INDENT# sql = sql . strip ( ) . strip ( ';' ) #NEWLINE# qry = select ( '*' ) . select_from ( TextAsFrom ( text ( sql ) , [ '*' ] ) . alias ( 'inner_qry' ) ) . limit ( limit ) #NEWLINE# sql = str ( qry . compile ( eng , compile_kwargs = { #NEWLINE# #INDENT# 'literal_binds' : True , #NEWLINE# #UNINDENT# } ) ) #NEWLINE# #UNINDENT# try : #NEWLINE# #INDENT# df = pd . read_sql_query ( sql = sql , con = eng ) #NEWLINE# content = df . to_html ( index = False , na_rep = '' , classes = 'dataframe table table-striped table-bordered table-condensed sql_results' . split ( ' ' ) ) #NEWLINE# #UNINDENT# except Exception as e : #NEWLINE# #INDENT# content = '<div class="alert alert-danger">{}</div>' . format ( e . message ) #NEWLINE# #UNINDENT# #UNINDENT# session . commit ( ) #NEWLINE# return content