/examples/extract_table_names.py

http://github.com/andialbrecht/sqlparse · Python · 68 lines · 41 code · 12 blank · 15 comment · 17 complexity · 4e0694cb0d7e856f534a4820025d2826 MD5 · raw file

  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2009-2020 the sqlparse authors and contributors
  4. # <see AUTHORS file>
  5. #
  6. # This example is part of python-sqlparse and is released under
  7. # the BSD License: https://opensource.org/licenses/BSD-3-Clause
  8. #
  9. # This example illustrates how to extract table names from nested
  10. # SELECT statements.
  11. #
  12. # See:
  13. # https://groups.google.com/forum/#!forum/sqlparse/browse_thread/thread/b0bd9a022e9d4895
  14. import sqlparse
  15. from sqlparse.sql import IdentifierList, Identifier
  16. from sqlparse.tokens import Keyword, DML
  17. def is_subselect(parsed):
  18. if not parsed.is_group:
  19. return False
  20. for item in parsed.tokens:
  21. if item.ttype is DML and item.value.upper() == 'SELECT':
  22. return True
  23. return False
  24. def extract_from_part(parsed):
  25. from_seen = False
  26. for item in parsed.tokens:
  27. if from_seen:
  28. if is_subselect(item):
  29. yield from extract_from_part(item)
  30. elif item.ttype is Keyword:
  31. return
  32. else:
  33. yield item
  34. elif item.ttype is Keyword and item.value.upper() == 'FROM':
  35. from_seen = True
  36. def extract_table_identifiers(token_stream):
  37. for item in token_stream:
  38. if isinstance(item, IdentifierList):
  39. for identifier in item.get_identifiers():
  40. yield identifier.get_name()
  41. elif isinstance(item, Identifier):
  42. yield item.get_name()
  43. # It's a bug to check for Keyword here, but in the example
  44. # above some tables names are identified as keywords...
  45. elif item.ttype is Keyword:
  46. yield item.value
  47. def extract_tables(sql):
  48. stream = extract_from_part(sqlparse.parse(sql)[0])
  49. return list(extract_table_identifiers(stream))
  50. if __name__ == '__main__':
  51. sql = """
  52. select K.a,K.b from (select H.b from (select G.c from (select F.d from
  53. (select E.e from A, B, C, D, E), F), G), H), I, J, K order by 1,2;
  54. """
  55. tables = ', '.join(extract_tables(sql))
  56. print('Tables: {}'.format(tables))