-
Notifications
You must be signed in to change notification settings - Fork 0
/
etl.py
73 lines (62 loc) · 2.27 KB
/
etl.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
import configparser
import psycopg2
from psycopg2 import Error
from sql_queries import copy_table_queries, insert_table_queries
import logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
def fetch_table_names(cur):
try:
cur.execute("SELECT table_name \
FROM information_schema.tables \
WHERE table_schema='public'")
table_names = [row[0] for row in cur.fetchall()]
return table_names
except Error as e:
logging.error("Error occurred while fetching table names")
logging.error(e)
def load_staging_tables(cur, conn):
for query in copy_table_queries:
try:
cur.execute(query)
conn.commit()
logging.info(f"Executed load staging table query: {query}")
except Error as e:
logging.error(f"Error occurred while executing query: {query}")
logging.error(e)
conn.rollback()
def insert_tables(cur, conn):
for query in insert_table_queries:
try:
cur.execute(query)
conn.commit()
logging.info(f"Executed insert table query: {query}")
except Error as e:
logging.error(f"Error occurred while executing query: {query}")
logging.error(e)
conn.rollback()
def count_rows(cur, conn):
table_names = fetch_table_names(cur)
for table in table_names:
try:
cur.execute(f"SELECT COUNT(*) FROM {table}")
result = cur.fetchone()
count = result[0]
logging.info(f"Row count for {table}: {count}")
except Error as e:
logging.error(f"Error occurred while counting rows for {table}")
logging.error(e)
def main():
config = configparser.ConfigParser()
config.read('dwh.cfg')
try:
with psycopg2.connect("host={} dbname={} user={} password={} port={}"
.format(*config['CLUSTER'].values())) as conn:
cur = conn.cursor()
load_staging_tables(cur, conn)
insert_tables(cur, conn)
count_rows(cur, conn)
except Error as e:
logging.error(f"Error occurred while connecting to the database")
logging.error(e)
if __name__ == "__main__":
main()