-
Notifications
You must be signed in to change notification settings - Fork 0
/
schema.py
63 lines (56 loc) · 2.51 KB
/
schema.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
from typing import Optional, TYPE_CHECKING
import psycopg2
from roadgraphtool.credentials_config import CREDENTIALS as config
if TYPE_CHECKING:
from psycopg2 import connection
TABLES = ["nodes", "ways"]
def get_connection() -> Optional['connection']:
"""Establishes a connection to the database and returns the connection object."""
try:
connection = psycopg2.connect(
dbname=config.db_name,
user=config.username,
password=config.db_password,
host=config.db_host,
port=config.db_server_port
)
return connection
except psycopg2.DatabaseError as error:
raise Exception(f"Error connecting to the database: {str(error)}")
def create_schema(schema: str):
"""Creates a new schema in the database."""
try:
with get_connection() as conn:
with conn.cursor() as cur:
query = f'CREATE SCHEMA if not exists "{schema}";'
cur.execute(query)
except (psycopg2.DatabaseError, Exception) as error:
raise Exception(f"Error: {str(error)}")
def add_postgis_extension(schema: str):
"""Adds the PostGIS extension to the specified schema."""
try:
with get_connection() as conn:
with conn.cursor() as cur:
query = f'CREATE EXTENSION if not exists postgis SCHEMA "{schema}";'
cur.execute(query)
except (psycopg2.DatabaseError, Exception) as error:
raise Exception(f"Error: {str(error)}")
def check_empty_or_nonexistent_tables(schema: str, tables: list = TABLES) -> bool:
"""Returns True, if all tables from TABLES are non-existent or empty.
Returns False if at least one isn't empty."""
try:
with get_connection() as conn:
with conn.cursor() as cur:
for t in tables:
query = f"SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = '{schema}' AND table_name = '{t}');"
cur.execute(query)
exists = cur.fetchone()[0]
if exists:
query = f"SELECT EXISTS (SELECT * FROM {schema}.{t} limit 1) as has_data;"
cur.execute(query)
has_data = cur.fetchone()[0]
if has_data: # at least one table from TABLES exists and isn't empty
return False
return True
except (psycopg2.DatabaseError, Exception) as error:
raise Exception(f"Error: {str(error)}")