-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_data.py
More file actions
322 lines (239 loc) · 8.41 KB
/
Copy pathgenerate_data.py
File metadata and controls
322 lines (239 loc) · 8.41 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import random
import uuid
import argparse
import sys
from datetime import timedelta
import psycopg2
from faker import Faker
fake = Faker()
genres = [
"Fiction",
"Fantasy",
"Mystery",
"Sci-Fi",
"Romance",
"History",
"Biography",
"Non-fiction",
"Thriller",
"Classic",
]
def unique_email():
return f"{fake.first_name().lower()}.{uuid.uuid4().hex[:12]}@example.com"
def unique_isbn():
return f"978-{uuid.uuid4().hex[:12]}"
def generate_book_title():
words = fake.words(nb=random.randint(2, 4))
words = [word.capitalize() for word in words]
title = " ".join(words)
if random.random() < 0.4:
title = "The " + title
return title
def connect():
return psycopg2.connect(
user="postgres",
dbname="library",
)
def insert_authors(cur, n):
for _ in range(n):
cur.execute(
"INSERT INTO authors (name, country) VALUES (%s, %s)",
(fake.name(), fake.country()),
)
def insert_members(cur, n):
for _ in range(n):
cur.execute(
"INSERT INTO members (name, email, joined_at) VALUES (%s, %s, %s)",
(
fake.name(),
unique_email(),
fake.date_time_between(start_date="-5y", end_date="now"),
),
)
def insert_books(cur, n):
cur.execute("SELECT id FROM authors")
author_ids = [row[0] for row in cur.fetchall()]
if not author_ids:
raise RuntimeError("No authors found. Insert authors before inserting books.")
total_copies = 0
for _ in range(n):
cur.execute(
"""
INSERT INTO books (title, author_id, genre, published_year, isbn, description)
VALUES (%s, %s, %s, %s, %s, %s)
RETURNING id
""",
(
generate_book_title(),
random.choice(author_ids),
random.choice(genres),
random.randint(1900, 2025),
unique_isbn(),
fake.text(max_nb_chars=random.randint(500, 1500)),
),
)
book_id = cur.fetchone()[0]
total_copies += insert_copies_for_book(cur, book_id)
return total_copies
def insert_copies_for_book(cur, book_id):
used_shelves = set()
copy_count = 0
for _ in range(random.randint(1, 6)):
while True:
shelf = f"{random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ')}{random.randint(1, 80)}"
if shelf not in used_shelves:
used_shelves.add(shelf)
break
cur.execute(
"""
INSERT INTO copies (book_id, shelf_location, status)
VALUES (%s, %s, %s)
""",
(
book_id,
shelf,
random.choice(["available", "available", "available", "borrowed", "reserved"]),
),
)
copy_count += 1
return copy_count
def insert_loans_bulk(cur, n, batch_size=5000):
cur.execute("SELECT id FROM members")
member_ids = [row[0] for row in cur.fetchall()]
cur.execute("SELECT id FROM copies")
copy_ids = [row[0] for row in cur.fetchall()]
if not member_ids:
raise RuntimeError("No members found. Insert members before inserting loans.")
if not copy_ids:
raise RuntimeError("No copies found. Insert books/copies before inserting loans.")
inserted = 0
while inserted < n:
rows = []
current_batch = min(batch_size, n - inserted)
for _ in range(current_batch):
loan_date = fake.date_time_between(start_date="-5y", end_date="now")
due_date = loan_date + timedelta(days=random.choice([14, 21, 30]))
if random.random() < 0.12:
return_date = None
else:
return_date = loan_date + timedelta(days=random.randint(1, 60))
rows.append((
random.choice(member_ids),
random.choice(copy_ids),
loan_date,
due_date,
return_date,
))
cur.executemany(
"""
INSERT INTO loans (member_id, copy_id, loan_date, due_date, return_date)
VALUES (%s, %s, %s, %s, %s)
""",
rows,
)
inserted += current_batch
return inserted
def insert_reservations(cur, n, batch_size=5000):
cur.execute("SELECT id FROM books")
book_ids = [row[0] for row in cur.fetchall()]
cur.execute("SELECT id FROM members")
member_ids = [row[0] for row in cur.fetchall()]
if not book_ids:
raise RuntimeError("No books found. Insert books before inserting reservations.")
if not member_ids:
raise RuntimeError("No members found. Insert members before inserting reservations.")
inserted = 0
while inserted < n:
rows = []
current_batch = min(batch_size, n - inserted)
for _ in range(current_batch):
rows.append((
random.choice(member_ids),
random.choice(book_ids),
fake.date_time_between(start_date="-3y", end_date="now"),
random.choice(["active", "cancelled", "fulfilled", "fulfilled", "fulfilled"]),
))
cur.executemany(
"""
INSERT INTO reservations (member_id, book_id, reserved_at, status)
VALUES (%s, %s, %s, %s)
""",
rows,
)
inserted += current_batch
return inserted
def insert_reviews(cur, n, batch_size=5000):
cur.execute("SELECT id FROM books")
book_ids = [row[0] for row in cur.fetchall()]
cur.execute("SELECT id FROM members")
member_ids = [row[0] for row in cur.fetchall()]
if not book_ids:
raise RuntimeError("No books found. Insert books before inserting reviews.")
if not member_ids:
raise RuntimeError("No members found. Insert members before inserting reviews.")
inserted = 0
while inserted < n:
rows = []
current_batch = min(batch_size, n - inserted)
for _ in range(current_batch):
rows.append((
random.choice(member_ids),
random.choice(book_ids),
random.randint(1, 5),
fake.sentence(nb_words=random.randint(6, 14)),
fake.date_time_between(start_date="-4y", end_date="now"),
fake.text(max_nb_chars=random.randint(100, 800)),
))
cur.executemany(
"""
INSERT INTO reviews (member_id, book_id, rating, comment, created_at, review_text)
VALUES (%s, %s, %s, %s, %s, %s)
""",
rows,
)
inserted += current_batch
return inserted
def main(authors, members, books, loans, reservations, reviews):
conn = None
try:
conn = connect()
cur = conn.cursor()
insert_authors(cur, authors)
print(f"Added {authors} authors")
insert_members(cur, members)
print(f"Added {members} members")
total_copies = insert_books(cur, books)
print(f"Added {books} books and {total_copies} copies")
inserted_loans = insert_loans_bulk(cur, loans)
print(f"Added {inserted_loans} loans")
inserted_reservations = insert_reservations(cur, reservations)
print(f"Added {inserted_reservations} reservations")
inserted_reviews = insert_reviews(cur, reviews)
print(f"Added {inserted_reviews} reviews")
conn.commit()
cur.close()
conn.close()
print("Data generation completed successfully!")
except Exception as e:
if conn:
conn.rollback()
conn.close()
print(f"Error: {e}")
sys.exit(1)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Generate realistic demo data for the library database.")
parser.add_argument("--authors", type=int, default=500)
parser.add_argument("--members", type=int, default=5000)
parser.add_argument("--books", type=int, default=10000)
parser.add_argument("--loans", type=int, default=100000)
parser.add_argument("--reservations", type=int, default=50000)
parser.add_argument("--reviews", type=int, default=50000)
args = parser.parse_args()
main(
authors=args.authors,
members=args.members,
books=args.books,
loans=args.loans,
reservations=args.reservations,
reviews=args.reviews,
)