File size: 2,642 Bytes
e0560d9 | 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 | import random
from faker import Faker
from datetime import datetime, timedelta
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from create_db import (
Base,
Customer,
Product,
Employee,
Order,
OrderItem
)
fake = Faker()
engine = create_engine("sqlite:///ecommerce.db")
Session = sessionmaker(bind=engine)
session = Session()
customers = []
for _ in range(100):
customer = Customer(
name=fake.name(),
email=fake.unique.email(),
city=fake.city(),
signup_date=fake.date_between(start_date="-2y", end_date="today")
)
customers.append(customer)
session.add_all(customers)
session.commit()
print(" Customers inserted")
categories = [
"Electronics",
"Clothing",
"Books",
"Home",
"Sports"
]
products = []
for _ in range(50):
product = Product(
product_name=fake.word().capitalize() + " Product",
category=random.choice(categories),
price=round(random.uniform(10, 1000), 2),
stock=random.randint(10, 500)
)
products.append(product)
session.add_all(products)
session.commit()
print(" Products inserted")
departments = [
"Sales",
"Support",
"Operations",
"HR"
]
employees = []
for _ in range(10):
employee = Employee(
employee_name=fake.name(),
department=random.choice(departments)
)
employees.append(employee)
session.add_all(employees)
session.commit()
print(" Employees inserted")
orders = []
for _ in range(500):
customer = random.choice(customers)
employee = random.choice(employees)
order = Order(
customer_id=customer.customer_id,
employee_id=employee.employee_id,
order_date=fake.date_between(start_date="-1y", end_date="today"),
total_amount=0
)
session.add(order)
session.flush()
total_amount = 0
# Each order gets 1-5 products
for _ in range(random.randint(1, 5)):
product = random.choice(products)
quantity = random.randint(1, 5)
order_item = OrderItem(
order_id=order.order_id,
product_id=product.product_id,
quantity=quantity
)
session.add(order_item)
total_amount += product.price * quantity
order.total_amount = round(total_amount, 2)
orders.append(order)
session.commit()
print(" Orders and order items inserted")
print("\n🎉 Database successfully populated with synthetic data!") |