-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.py
More file actions
66 lines (54 loc) · 2.44 KB
/
schema.py
File metadata and controls
66 lines (54 loc) · 2.44 KB
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
from typing import Optional, TYPE_CHECKING
import psycopg2
import roadgraphtool.db
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."""
db = roadgraphtool.db.db
try:
with db.get_new_psycopg2_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 roadgraphtool.db.db.get_new_psycopg2_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."""
with roadgraphtool.db.db.get_new_psycopg2_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