def get_table_names_from_sql(context, sql):
 def _get_table_names_from_plan(plan):
  table_names = []
  if plan.get('Relation Name'):
   table_names.append(plan['Relation Name'])
  if ('Plans' in plan):
   for child_plan in plan['Plans']:
    table_name = _get_table_names_from_plan(child_plan)
    if table_name:
     table_names.extend(table_name)
  return table_names
 result = context['connection'].execute('EXPLAIN (FORMAT JSON) {0}'.format(sql.encode('utf-8'))).fetchone()
 table_names = []
 try:
  query_plan = json.loads(result['QUERY PLAN'])
  plan = query_plan[0]['Plan']
  table_names.extend(_get_table_names_from_plan(plan))
 except ValueError:
  log.error('Could not parse query plan')
 return table_names

def get_table_names_from_sql ( context , sql ) : def _get_table_names_from_plan ( plan ) : table_names = [ ] if plan . get ( 'Relation Name' ) : table_names . append ( plan [ 'Relation Name' ] ) if ( 'Plans' in plan ) : for child_plan in plan [ 'Plans' ] : table_name = _get_table_names_from_plan ( child_plan ) if table_name : table_names . extend ( table_name ) return table_names result = context [ 'connection' ] . execute ( 'EXPLAIN (FORMAT JSON) {0}' . format ( sql . encode ( 'utf-8' ) ) ) . fetchone ( ) table_names = [ ] try : query_plan = json . loads ( result [ 'QUERY PLAN' ] ) plan = query_plan [ 0 ] [ 'Plan' ] table_names . extend ( _get_table_names_from_plan ( plan ) ) except ValueError : log . error ( 'Could not parse query plan' ) return table_names
parses the output of explain looking for table names it performs an explain query against the provided sql .