create_tables.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import configparser
  2. import psycopg2
  3. from sql_queries import create_table_queries, drop_table_queries
  4. def drop_tables(cur, conn):
  5. """Drop all tables before recreating them;
  6. Parameter: cur, a cursor object used to execute commands;
  7. Parameter: conn, a database connection object."""
  8. for query in drop_table_queries:
  9. cur.execute(query)
  10. conn.commit()
  11. def create_tables(cur, conn):
  12. """Create all tables that are needed;
  13. Parameter: cur, a cursor object used to execute commands;
  14. Parameter: conn, a database connection object."""
  15. for query in create_table_queries:
  16. cur.execute(query)
  17. conn.commit()
  18. def main():
  19. # Obtain configuration information
  20. config = configparser.ConfigParser()
  21. config.read('dwh.cfg')
  22. # Get a connection object to AWS Redshift Cluster
  23. conn = psycopg2.connect("host={} dbname={} user={} password={} port={}".format(*config['CLUSTER'].values()))
  24. cur = conn.cursor()
  25. # Drop tables before creating
  26. drop_tables(cur, conn)
  27. # Create tables
  28. create_tables(cur, conn)
  29. conn.close()
  30. if __name__ == "__main__":
  31. main()