Spaces:
Paused

File size: 5,148 Bytes
4a91ea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pymysql
import random
from datetime import datetime, timedelta

# Database configuration
DB_HOST = "49.233.26.60"
DB_PORT = 3306
DB_USER = "root"
DB_PASSWORD = "dianyue"
DB_NAME = "sales_test_db"

def create_sales_db():
    print(f"Connecting to {DB_HOST}...")
    try:
        connection = pymysql.connect(
            host=DB_HOST,
            port=DB_PORT,
            user=DB_USER,
            password=DB_PASSWORD,
            cursorclass=pymysql.cursors.DictCursor
        )
        
        with connection:
            with connection.cursor() as cursor:
                # Create Database
                print(f"Creating database {DB_NAME}...")
                cursor.execute(f"CREATE DATABASE IF NOT EXISTS {DB_NAME} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;")
                cursor.execute(f"USE {DB_NAME};")
                
                # Create Tables
                print("Creating tables...")
                
                # Products Table
                cursor.execute("""
                CREATE TABLE IF NOT EXISTS products (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    name VARCHAR(100) NOT NULL,
                    category VARCHAR(50),
                    price DECIMAL(10, 2)
                );
                """)
                
                # Regions Table
                cursor.execute("""
                CREATE TABLE IF NOT EXISTS regions (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    name VARCHAR(50) NOT NULL,
                    manager VARCHAR(50)
                );
                """)
                
                # Sales Table
                cursor.execute("""
                CREATE TABLE IF NOT EXISTS sales (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    product_id INT,
                    region_id INT,
                    amount DECIMAL(10, 2),
                    quantity INT,
                    sale_date DATE,
                    FOREIGN KEY (product_id) REFERENCES products(id),
                    FOREIGN KEY (region_id) REFERENCES regions(id)
                );
                """)
                
                # Insert Data
                print("Inserting sample data...")
                
                # Products
                products = [
                    ("Smartphone X", "Electronics", 699.00),
                    ("Laptop Pro", "Electronics", 1299.00),
                    ("Wireless Earbuds", "Electronics", 149.00),
                    ("Coffee Maker", "Home", 89.00),
                    ("Office Chair", "Furniture", 199.00),
                    ("Running Shoes", "Apparel", 79.00),
                    ("Desk Lamp", "Home", 35.00),
                    ("Bluetooth Speaker", "Electronics", 59.00)
                ]
                cursor.executemany("INSERT INTO products (name, category, price) VALUES (%s, %s, %s)", products)
                
                # Regions
                regions = [
                    ("North America", "John Doe"),
                    ("Europe", "Jane Smith"),
                    ("Asia Pacific", "Bob Johnson"),
                    ("Latin America", "Maria Garcia")
                ]
                cursor.executemany("INSERT INTO regions (name, manager) VALUES (%s, %s)", regions)
                
                connection.commit()
                
                # Get IDs
                cursor.execute("SELECT id, price FROM products")
                product_rows = cursor.fetchall()
                product_ids = {row['id']: row['price'] for row in product_rows}
                
                cursor.execute("SELECT id FROM regions")
                region_rows = cursor.fetchall()
                region_ids = [row['id'] for row in region_rows]
                
                # Generate Sales
                sales_data = []
                start_date = datetime(2024, 1, 1)
                
                for _ in range(200):  # Generate 200 sales records
                    prod_id = random.choice(list(product_ids.keys()))
                    region_id = random.choice(region_ids)
                    qty = random.randint(1, 10)
                    price = product_ids[prod_id]
                    amount = price * qty
                    
                    # Random date within last 365 days
                    day_offset = random.randint(0, 365)
                    sale_date = start_date + timedelta(days=day_offset)
                    
                    sales_data.append((prod_id, region_id, amount, qty, sale_date))
                
                cursor.executemany(
                    "INSERT INTO sales (product_id, region_id, amount, quantity, sale_date) VALUES (%s, %s, %s, %s, %s)",
                    sales_data
                )
                
                connection.commit()
                print(f"Successfully inserted {len(products)} products, {len(regions)} regions, and {len(sales_data)} sales records.")
                
    except Exception as e:
        print(f"Failed to create sales data: {e}")

if __name__ == "__main__":
    create_sales_db()