Advertisement
Guest User

Untitled

a guest
Jun 7th, 2018
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.15 KB | None | 0 0
  1. import vertica_python as vp
  2. import sys
  3.  
  4. conn_info = {'host': '192.168.217.132',
  5. 'port': 5433,
  6. 'user': 'Artem',
  7. 'password': '111',
  8. 'database': ''
  9. }
  10.  
  11.  
  12. class Vertica:
  13. def __init__(self, host, port, user, password, database=''):
  14. self.conn = vp.connect(host=host, port=port, user=user, password=password, database=database)
  15. self.cursor = self.conn.cursor()
  16.  
  17. def finalize(self):
  18. self.conn.close()
  19.  
  20. def create_table(self, name, columns, pk=None):
  21. try:
  22. self.cursor.execute("CREATE TABLE {0} ({1} INT);".format(name, " INT, ".join(columns)))
  23. except vp.errors.DuplicateObject:
  24. print("CREATE TABLE ERROR: Table already exists.")
  25. return
  26.  
  27. if pk is not None:
  28. self.add_primary_key(name, pk)
  29.  
  30. def drop_table(self, name):
  31. try:
  32. self.cursor.execute("DROP TABLE {0} CASCADE;".format(name))
  33. except vp.errors.MissingRelation:
  34. print("DROP TABLE ERROR: Table does not exist.")
  35.  
  36. def add_primary_key(self, table, columns):
  37. columns = ', '.join(columns)
  38. try:
  39. self.cursor.execute("ALTER TABLE {0} ADD CONSTRAINT {2} PRIMARY KEY ({1}) ENABLED;".
  40. format(table, columns, table + "_" + "pk"))
  41. except vp.errors.MissingColumn:
  42. print("ADD PRIMARY KEY ERROR: Column does not exist.")
  43.  
  44. def add_foreign_key(self, table_from, columns_from, table_to, columns_to):
  45. if not len(columns_from) == len(columns_to):
  46. print("ADD FOREIGN KEY ERROR: Number of primary and foreign keys must be the same.")
  47. return
  48.  
  49. columns_from = ', '.join(columns_from)
  50. columns_to = ', '.join(columns_to)
  51. try:
  52. self.cursor.execute("ALTER TABLE {0} ADD CONSTRAINT {4} FOREIGN KEY ({1}) REFERENCES {2} ({3})".
  53. format(table_from, columns_from, table_to, columns_to, table_from + "_" + table_to + "_fk"))
  54. except vp.errors.QueryError:
  55. print("ADD FOREIGN KEY ERROR: Referenced table or primary key does not exist.")
  56. raise
  57.  
  58. def get_tables(self):
  59. self.cursor.execute("SELECT TABLE_NAME FROM v_catalog.tables;")
  60. return list(map(lambda x: x[0], self.cursor.fetchall()))
  61.  
  62. def get_columns(self, table):
  63. self.cursor.execute("SELECT COLUMN_NAME FROM v_catalog.columns WHERE TABLE_NAME = '{}'".format(table))
  64. return list(map(lambda x: x[0], self.cursor.fetchall()))
  65.  
  66. def get_primary_keys(self, table):
  67. self.cursor.execute("SELECT COLUMN_NAME FROM v_catalog.primary_keys WHERE TABLE_NAME = '{}';".format(table))
  68. return list(map(lambda x: x[0], self.cursor.fetchall()))
  69.  
  70. def get_foreign_keys(self, table):
  71. self.cursor.execute("SELECT COLUMN_NAME, REFERENCE_TABLE_NAME, REFERENCE_COLUMN_NAME \
  72. FROM v_catalog.foreign_keys WHERE TABLE_NAME = '{}';".format(table))
  73. return self.cursor.fetchall()
  74.  
  75.  
  76. """
  77. try:
  78. vertica = Vertica(**conn_info)
  79. except vp.errors.ConnectionError:
  80. print("Error while connecting. Please, verify connection configuration.")
  81. sys.exit()
  82.  
  83. vertica.drop_table("t2")
  84. vertica.drop_table("t3")
  85. vertica.create_table("t2", ["id", "A", "B", "C", "D", "E", "F"], pk=["id, A"])
  86. vertica.create_table("t3", ["id", "AA", "BB", "CC", "DD", "EE", "FF"], pk=["id"])
  87. vertica.add_foreign_key("t3", ["AA", "FF"], "t2", ["id", "A"])
  88. tables = vertica.get_tables()
  89. for t in tables:
  90. print(t)
  91. print(vertica.get_columns(t))
  92. print(vertica.get_primary_keys(t))
  93. print(vertica.get_foreign_keys(t))
  94. """
  95.  
  96.  
  97. def help(l):
  98. if l == 0:
  99. print("Welcome to database functional dependencies analyzer for Vertica/PostgreSQL!")
  100. print("Enter 'q' to quit or 'h' to display this message again.")
  101. print("Choose your DBMS:")
  102. print("1. Vertica")
  103. print("2. PostgreSQL")
  104. elif l == 1:
  105. print("Enter 'q' to quit or 'h' to display this message again.")
  106. print("1. List all relations")
  107. print("2. List all functional dependencies")
  108. print("3. Disconnect from DBMS")
  109.  
  110.  
  111. def main():
  112. dbms = None
  113. help(0)
  114.  
  115. while True:
  116. c0 = input("Enter command:")
  117.  
  118. if c0 == "q":
  119. if dbms:
  120. dbms.finalize()
  121. sys.exit()
  122. elif c0 == "h":
  123. help(0)
  124. elif c0 == "1":
  125. conn_info = dict()
  126. conn_info["host"] = input("Enter host name or ip address:")
  127. conn_info["port"] = int(input("Enter port:"))
  128. conn_info["user"] = input("Enter user name:")
  129. conn_info["password"] = input("Enter user password:")
  130. conn_info["database"] = input("Enter database name:")
  131. try:
  132. dbms = Vertica(**conn_info)
  133. except vp.errors.ConnectionError:
  134. print("Error while connecting. Please, verify connection configuration.")
  135. continue
  136.  
  137. print("Successfully connected to Vertica!")
  138. elif c0 == "2":
  139. print("PostgreSQL not supported yet... :(")
  140. continue
  141. else:
  142. print("Incorrect command.")
  143.  
  144. if dbms:
  145. tables = dbms.get_tables()
  146. attrs, fds = [0], [0]
  147. help(1)
  148. while True:
  149. c1 = input("Enter command:")
  150.  
  151. if c1 == "q":
  152. dbms.finalize()
  153. sys.exit()
  154. elif c1 == "h":
  155. help(1)
  156. elif c1 == "3":
  157. dbms.finalize()
  158. print("Successfully disconnected.")
  159. break
  160. if c1 == "1":
  161. print("All available relations:")
  162. for i, t in enumerate(tables):
  163. print("{0}. {1}".format(i + 1, t))
  164. elif c1 == "2":
  165. print("All available functional dependencies:")
  166. else:
  167. print("Incorrect command.")
  168.  
  169. if __name__ == '__main__':
  170. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement