Advertisement
Guest User

Untitled

a guest
Jan 31st, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.36 KB | None | 0 0
  1. import psycopg2
  2. import sys
  3.  
  4.  
  5. class DatabaseClass(object):
  6. def __init__(self):
  7. pass
  8.  
  9. def execute(self, query):
  10. try:
  11. cursor = self.conn.cursor()
  12. cursor.execute(query)
  13. res = cursor.fetchall()
  14. cursor.close()
  15. return res
  16. except psycopg2.Error as e:
  17. print "psycopg2 error ({0}): {1}".format(e.pgcode, e.pgerror)
  18. self.conn.rollback()
  19.  
  20.  
  21. class Adapter(DatabaseClass):
  22. def __init__(self, db, user, pw):
  23. try:
  24. self.conn = psycopg2.connect(
  25. "dbname={0} user={1} password={2}".format(db, user, pw))
  26. except psycopg2.Error as e:
  27. print "psycopg2 error ({0}): {1}".format(e.pgcode, e.pgerror)
  28. raise AdapterException("init", "failed to establish connection")
  29. self.tables = self.get_tables()
  30.  
  31. def get_tables(self):
  32. query = """SELECT table_name FROM information_schema.tables
  33. WHERE table_schema = 'public'"""
  34. results = self.execute(query)
  35. tables = []
  36. for table in results:
  37. tbl = Table(table, self.conn)
  38. tables.append(tbl)
  39. return tables
  40.  
  41. def close(self, save=True):
  42. if save:
  43. for tbl in tables:
  44. table.save()
  45. try:
  46. self.conn.close()
  47. except psycopg2.Error as e:
  48. print "psycopg2 error ({0}): {1}".format(e.pgcode, e.pgerror)
  49. raise AdapterException("logout", "unable to logout")
  50.  
  51.  
  52. class Table(DatabaseClass):
  53. def __init__(self, name, db, conn):
  54. self.conn = conn
  55. self.name = name
  56. self.cols = self.get_cols()
  57. # this list structure stores all rows we currently have loaded into
  58. # "memory"
  59. self.rows = []
  60.  
  61. def __str__(self):
  62. return self.name
  63.  
  64. def __repr__(self):
  65. return "Table Name: {0}, Columns: {1}".format(self.name, self.cols)
  66.  
  67. def get_cols(self):
  68. query = "SELECT * FROM {0} LIMIT 0".format(self.name)
  69. row = self.execute(query)
  70. return [desc[0] for desc in row.description]
  71.  
  72. # THIS NEEDS TO BE THOUGHT ABOUT. We do not want to potentially return
  73. # 1 million rows. How should we 'paginate' this? Perhaps a supplied arg
  74. # to specify range? Say, start = 0, end = 25 would return the first
  75. # 25 rows?
  76. #
  77. # What about filtering? ... WHERE?
  78. def get_rows(self, start, end):
  79. pass
  80.  
  81. # eg. format should follow format of:
  82. # self.edit("colName", "SET DEFAULT expression")
  83. def edit(self, col, query):
  84. res = self.execute("ALTER TABLE {0} {1}".format(self.name, query))
  85. return res
  86.  
  87. def add_row(self, data):
  88. query = "INSERT INTO {0} ({1}) VALUES ({2})".format(
  89. self.name, ", ".join(self.cols), " ".join([data[c] for c in self.cols]))
  90. msg = self.execute(query)
  91. new_row = Row(self.conn, self.name, data)
  92. self.rows.append(new_row)
  93. return new_row
  94.  
  95. def edit_row(self, row, field, val):
  96. setattr(row, field, val)
  97. row.save()
  98.  
  99. def delete_row(self, row):
  100. self.rows.remove(row)
  101. row.delete()
  102.  
  103. def save(self):
  104. for row in self.rows:
  105. row.save()
  106.  
  107. def _remove_row_from_mem(self, row):
  108. self.rows.remove(row)
  109.  
  110. class Row(DatabaseClass):
  111. def __init__(self, conn, tbl, data):
  112. self.conn = conn
  113. self.table = tbl
  114. self.fields = []
  115. for (field, val) in data.items():
  116. self.fields.append(field)
  117. setattr(self, field, val)
  118.  
  119. def edit(self, field, val):
  120. setattr(self, field, val)
  121. self.save()
  122.  
  123. def delete(self):
  124. query = "DELETE FROM {0} WHERE ID={1}".format(self.table, self.id)
  125. return self.execute(query)
  126.  
  127. def save(self):
  128. query = "UPDATE {0} SET ({1})".format(
  129. self.table, ", ".join(
  130. [f + " = " + getattr(self, f) for f in self.fields]
  131. )
  132. )
  133. return self.execute(query)
  134.  
  135. def __str__(self):
  136. return ", ".join([f + ": " + getattr(self, f) for f in self.fields])
  137.  
  138. def __repr__(self):
  139. string = "Table Name: {0}, Fields: {1}".format(
  140. self.table, ", ".join(
  141. [f + ": " + getattr(self, f) for f in self.fields]))
  142. return string
  143.  
  144.  
  145. class AdapterException(Exception):
  146. def __init__(self, act, msg):
  147. self.act = act
  148. self.msg = msg
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement