-
Notifications
You must be signed in to change notification settings - Fork 0
/
tammy-test-queries-orm.py
104 lines (89 loc) · 3.06 KB
/
tammy-test-queries-orm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import json
import os
from sqlalchemy import create_engine, insert, inspect, select
from sqlalchemy import Column, ForeignKey, Integer, MetaData, String, Table
rds_proxy_host = os.environ.get('RDS_PROXY_HOST')
db_name = os.environ.get('DB_NAME')
user_name = os.environ.get('USER_NAME')
pword = os.environ.get('PASSWORD')
db_engine = create_engine(f"postgresql://{user_name}:{pword}@{rds_proxy_host}")
class MyDB:
def __init__(self):
self.md = MetaData()
self.author_table = Table(
"author",
self.md,
Column("author_id", Integer, primary_key=True),
Column("name", String, nullable=False),
)
self.book_table = Table(
"book",
self.md,
Column('book_id', Integer, primary_key=True),
Column('author_id', Integer, ForeignKey("author.author_id"), nullable=False),
Column('title', String),
Column('summary', String),
)
def select_author(self, author_name):
rows = None
with db_engine.connect() as conn:
rows = conn.execute(
select(self.author_table).where(
self.author_table.c.name == author_name
)
)
return str(rows.first())
def insert_author(self, author_name):
with db_engine.connect() as conn:
result = conn.execute(
insert(self.author_table),
[
{"name": author_name}
]
)
conn.commit()
def select_book_by_title(self, book_title):
rows = None
with db_engine.connect() as conn:
rows = conn.execute(
select(self.book_table).where(
self.book_table.c.title == book_title
)
)
return str(rows.first())
def select_books_by_author(self, book_author_id):
rows = None
with db_engine.connect() as conn:
rows = conn.execute(
select(self.book_table).where(
self.book_table.c.author_id == book_author_id
)
)
return str(rows.all())
def insert_book(self, author_id, title, summary):
with db_engine.connect() as conn:
result = conn.execute(
insert(self.book_table),
[
{
"author_id": author_id,
"title": title,
"summary": summary,
}
]
)
conn.commit()
def lambda_handler(event, context):
inspection = inspect(db_engine)
table_names = inspection.get_table_names()
my_db = MyDB()
# my_db.insert_author("Isaac Asimov")
# my_db.insert_book(2, "The Foundation", "Nerds are exiled to Terminus, what next?")
author = my_db.select_author("Frank Herbert")
books = my_db.select_books_by_author(1)
return {
'statusCode': 200,
'table_names': table_names,
'author': author,
'books': books,
}