-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimport.py
60 lines (43 loc) · 1.83 KB
/
import.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
import os
import csv
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
#----------------------------------------------------------------------------------------------
if not os.getenv("DATABASE_URL"):
raise RuntimeError("DATABASE_URL is not set")
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
#----------------------------------------------------------------------------------------------
def main():
f = open("books.csv")
reader = csv.reader(f)
# Populating the "authors" table.
first_line = True
for isbn, title, author, year in reader:
if first_line:
first_line = False
continue
if db.execute("SELECT * FROM authors WHERE name = :name", {"name": author}).fetchone() == None:
db.execute("INSERT INTO authors (name) VALUES (:name)", {"name": author})
print(f"Added author '{author}' to table 'authors'.")
else:
print(f"DBInsertError: Author '{author}' is already on the table 'authors'.")
db.commit()
# Populating the "books" table.
first_line = True
for isbn, title, author, year in reader:
if first_line:
first_line = False
continue
if db.execute("SELECT * FROM books WHERE isbn = :isbn", {"isbn": isbn}).fetchone() == None:
author_id = db.execute("SELECT id FROM authors WHERE name = :name",
{"name": author}).fetchone()[0]
db.execute("INSERT INTO books (isbn, title, author_id, year) VALUES (:isbn, :title, :author_id, :year)",
{"isbn": isbn, "title": title, "author_id": author_id, "year": year})
print(f"Added book 'ISBN: {isbn} | {title}' to table 'books'.")
else:
print(f"DBInsertError: ISBN '{isbn}' is already on the table 'books'.")
db.commit()
#----------------------------------------------------------------------------------------------
if __name__ == "__main__":
main()