Advertisement
Guest User

Untitled

a guest
Nov 28th, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. import psycopg2
  2. from itertools import chain, permutations
  3. from graphviz import Digraph
  4.  
  5.  
  6. DB_SETTINGS = dict(
  7. host='localhost',
  8. database='database_name',
  9. user='user',
  10. password='*****',
  11. )
  12.  
  13. def get_relations():
  14. # db
  15. conn = psycopg2.connect(**DB_SETTINGS)
  16. cur = conn.cursor()
  17.  
  18. # fetch database objects (views, functions, tables)
  19. cur.execute('''
  20. select proname, prosrc
  21. from pg_proc
  22. where proname ~* '_vs_';
  23. ''')
  24. functions = cur.fetchall()
  25.  
  26. cur.execute('''
  27. select viewname, definition
  28. from pg_views
  29. where schemaname in ('api', 'public');
  30. ''')
  31. views = cur.fetchall()
  32.  
  33. # find relations between database objects.
  34. relations = set()
  35. for a, b in permutations(chain(views, functions), 2):
  36. a_name, a_source = a
  37. b_name, b_source = b
  38. if a_name == b_name: # ignore self references.
  39. continue
  40. if (a_name in b_source):
  41. # "a" is referenced in "b" definition.
  42. relations.add((a_name, b_name))
  43. return relations
  44.  
  45.  
  46. def make_graph_file(relations):
  47. dot = Digraph()
  48. dot.format = 'png'
  49. dot.graph_attr['rankdir'] = 'LR'
  50. dot.graph_attr['engine'] = 'dot'
  51. dot.node_attr['style'] = 'filled'
  52. dot.node_attr['shape'] = 'box'
  53.  
  54. nodes = set(chain(*relations))
  55. for n in nodes:
  56. # highlight some nodes based on their names
  57. dot.node(n, fillcolor=("yellow" if '_vs_' in n else None))
  58.  
  59. dot.edges(relations)
  60.  
  61. # saves gv and png files
  62. dot.render()
  63.  
  64.  
  65. relations = get_relations()
  66. make_graph_file(relations)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement