aboutsummaryrefslogtreecommitdiff
path: root/app/app_database.py
diff options
context:
space:
mode:
authorpacien2021-07-25 21:53:59 +0200
committerpacien2021-07-25 21:53:59 +0200
commit7f11aa00673b0f77523db44969699c54289ace5b (patch)
tree77ed092b04460e263532d76843945a05a1229d58 /app/app_database.py
parent1a74f19cd68e3b7264621e7231475c6b25505e6d (diff)
downloaduge_l2_rdbms_python_proto-7f11aa00673b0f77523db44969699c54289ace5b.tar.gz
app: working web prototype
Diffstat (limited to 'app/app_database.py')
-rw-r--r--app/app_database.py43
1 files changed, 43 insertions, 0 deletions
diff --git a/app/app_database.py b/app/app_database.py
new file mode 100644
index 0000000..77f092a
--- /dev/null
+++ b/app/app_database.py
@@ -0,0 +1,43 @@
1# UGE / L2 / Intro to relational databases / Python project prototype
2# Author: Pacien TRAN-GIRARD
3# Licence: EUPL-1.2
4
5from os import environ
6from functools import partial
7from contextlib import contextmanager
8
9import psycopg2
10from psycopg2.extras import NamedTupleCursor
11from psycopg2.extensions import ISOLATION_LEVEL_READ_COMMITTED
12
13import embrace
14from embrace import pool
15
16
17# Connection to the PostgreSQL database server.
18# Using a cursor which exposes result rows as named tuples for convenience.
19# TODO: switch to psycopg3 and use asynchronous queries in handlers.
20db_connect = partial(
21 psycopg2.connect,
22 environ['DATABASE_URL'],
23 cursor_factory=NamedTupleCursor)
24
25db_pool = pool.ConnectionPool(db_connect, limit=4)
26
27
28# Turn our annotated SQL queries into Python functions.
29queries = embrace.module('./sql/', auto_reload=True)
30
31
32@contextmanager
33def db_transaction(isolation_level=ISOLATION_LEVEL_READ_COMMITTED):
34 """
35 Get a connection from the connection pool and begin a transaction with the
36 given isolation level. The transaction is automatically rolled back if an
37 uncaught exception escapes the current context. Otherwise, it is
38 automatically committed when finishing with no error.
39 """
40 with db_pool.connect() as conn:
41 conn.set_isolation_level(isolation_level)
42 with queries.transaction(conn) as tx:
43 yield tx