Skip to content

Instantly share code, notes, and snippets.

@solyard
Created March 17, 2019 20:18
Show Gist options
  • Save solyard/ae5273d2d4e61eb1da50b4c68428194e to your computer and use it in GitHub Desktop.
Save solyard/ae5273d2d4e61eb1da50b4c68428194e to your computer and use it in GitHub Desktop.
import psycopg2
import json
class Database:
@staticmethod
def insert(data):
insert_data = ''
insert_data_row = []
field_order = tuple({key for request in data for key in request.keys()})
for row in data:
values = [row.get(key) for key in field_order]
values = ['NULL' if key is None else key for key in values]
insert_data_row.append(values)
for request in insert_data_row:
insert_data += str('(' + ', '.join([repr(i) for i in request]) + '),').replace('\'NULL\'', 'NULL')
insert_data = insert_data[:-1]
request = f'INSERT INTO Feed {field_order} '.replace('\'', '') + f'VALUES {insert_data} ON CONFLICT DO NOTHING;'
return request
@staticmethod
def update(data):
result = ''
for row in data:
field_id = row.get('id')
cur.execute(f"SELECT * FROM Feed WHERE id = '{field_id}'")
if cur.fetchall():
keys = [key for key in row.keys() if key != 'id']
data = [row.get(key) for key in keys]
if len(keys) > 1:
many_items = ['(', ')']
else:
many_items = ['', '']
request = 'UPDATE Feed SET {set_keys} = {set_values} WHERE id = {field_id}'.format(
set_keys=f'{many_items[0]}' + ', '.join(keys) + f'{many_items[1]}',
set_values=f'{many_items[0]}' + ', '.join([repr(i) for i in data]) + f'{many_items[1]}',
field_id=f'{repr(field_id)};\n'
)
result += request
return result
@staticmethod
def delete(keys):
for row in keys:
return f"DELETE FROM Feed WHERE id = '{row}';"
database = Database()
def get_create_statement():
request = 'CREATE TABLE Feed ('
structure = scheme.get('fields')
for row in structure:
if not row.get('default_value'):
default = ''
else:
default = ''.join(f" DEFAULT {row.get('default_value')}")
request += f"{row.get('name')} {row.get('type')}{default},"
request = request[:-1] + ');'
return request
if __name__ == '__main__':
conn = psycopg2.connect('postgres://postgres:[email protected]:5432') #connection to database
cur = conn.cursor()
with open('./db.json') as f:
scheme = json.load(f) #reading db structure from file
print(get_create_statement())
print('-------------------------------------------------')
print(database.insert([{"id": '284e4844-be00-45b3-9631-3d05acfc0006', "news_text": 'Hello, world', 'is_read': True},
{"id": '284e4844-be00-45b3-9631-3d05acfc0007'}]))
print('-------------------------------------------------')
print(database.delete(['284e4844-be00-45b3-9631-3d05acfc0006']))
print('-------------------------------------------------')
print(database.update([
{"id": '284e4844-be00-45b3-9631-3d05acfc0006', "news_text": 'Hello, world123', 'is_read': True},
{"id": '284e4844-be00-45b3-9631-3d05acfc0007', "news_text": 'Hello, world123678'},
{"id": '284e4844-be00-45b3-9631-3d05acfc0008', "is_read": 'true'}
]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment