201 lines
No EOL
6.3 KiB
Python
Executable file
201 lines
No EOL
6.3 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
# Script to create mock events in the database
|
|
# Events will start slightly before the current date and end far in the future
|
|
# Events will be of various types: traffic, nature, weather, sport, conference, party
|
|
|
|
import os
|
|
import sys
|
|
import json
|
|
import psycopg2
|
|
import psycopg2.extras
|
|
from datetime import datetime, timedelta
|
|
import random
|
|
|
|
# Function to load environment variables from .env file
|
|
def load_env_from_file():
|
|
if os.path.exists('.env'):
|
|
print("Loading environment variables from .env file...")
|
|
with open('.env', 'r') as f:
|
|
for line in f:
|
|
line = line.strip()
|
|
if line and not line.startswith('#'):
|
|
key, value = line.split('=', 1)
|
|
os.environ[key] = value
|
|
|
|
# Load environment variables from .env file
|
|
load_env_from_file()
|
|
|
|
# Database connection parameters
|
|
DB_NAME = os.getenv("DB_NAME", "oedb")
|
|
DB_HOST = os.getenv("DB_HOST", "localhost")
|
|
DB_USER = os.getenv("DB_USER", "postgres")
|
|
DB_PASSWORD = os.getenv("POSTGRES_PASSWORD", "")
|
|
|
|
# Current date (2025-09-15 as specified in the issue)
|
|
CURRENT_DATE = datetime(2025, 9, 15, 23, 0)
|
|
|
|
# Event types
|
|
EVENT_TYPES = ["scheduled", "forecast", "unscheduled"]
|
|
|
|
# Event categories (what)
|
|
EVENT_CATEGORIES = ["traffic", "nature", "weather", "sport", "conference", "party", "community", "wildlife"]
|
|
|
|
# Sample locations (Paris, Lyon, Marseille, Toulouse, Bordeaux, Lille)
|
|
SAMPLE_LOCATIONS = [
|
|
{"name": "Paris", "lon": 2.3522, "lat": 48.8566},
|
|
{"name": "Lyon", "lon": 4.8357, "lat": 45.7640},
|
|
{"name": "Marseille", "lon": 5.3698, "lat": 43.2965},
|
|
{"name": "Toulouse", "lon": 1.4442, "lat": 43.6047},
|
|
{"name": "Bordeaux", "lon": -0.5792, "lat": 44.8378},
|
|
{"name": "Lille", "lon": 3.0573, "lat": 50.6292}
|
|
]
|
|
|
|
# Connect to the database
|
|
def db_connect():
|
|
return psycopg2.connect(
|
|
dbname=DB_NAME,
|
|
host=DB_HOST,
|
|
user=DB_USER,
|
|
password=DB_PASSWORD
|
|
)
|
|
|
|
# Create a point geometry
|
|
def create_point_geometry(lon, lat):
|
|
return {
|
|
"type": "Point",
|
|
"coordinates": [lon, lat]
|
|
}
|
|
|
|
# Insert geometry into geo table and return its hash
|
|
def insert_geometry(cur, geometry):
|
|
geometry_json = json.dumps(geometry)
|
|
|
|
# First, calculate the hash
|
|
cur.execute("""
|
|
SELECT md5(st_astext(geom)), st_astext(geom)
|
|
FROM (SELECT st_setsrid(st_geomfromgeojson(%s),4326) as geom) as g;
|
|
""", (geometry_json,))
|
|
|
|
hash_result = cur.fetchone()
|
|
if not hash_result:
|
|
raise Exception("Failed to calculate geometry hash")
|
|
|
|
geo_hash = hash_result[0]
|
|
geo_text = hash_result[1]
|
|
|
|
# Check if this hash already exists in the geo table
|
|
cur.execute("SELECT 1 FROM geo WHERE hash = %s", (geo_hash,))
|
|
exists = cur.fetchone()
|
|
|
|
if not exists:
|
|
# Insert the geometry if it doesn't exist
|
|
cur.execute("""
|
|
INSERT INTO geo (geom, hash, geom_center)
|
|
VALUES (
|
|
ST_SetSRID(ST_GeomFromText(%s), 4326),
|
|
%s,
|
|
ST_Centroid(ST_SetSRID(ST_GeomFromText(%s), 4326))
|
|
);
|
|
""", (geo_text, geo_hash, geo_text))
|
|
|
|
return geo_hash
|
|
|
|
# Create a mock event
|
|
def create_mock_event(cur, category, location, event_type):
|
|
# Generate random start date slightly before current date (0-7 days)
|
|
days_before = random.randint(0, 7)
|
|
start_date = CURRENT_DATE - timedelta(days=days_before)
|
|
|
|
# Generate random end date far in the future (30-365 days from now)
|
|
days_after = random.randint(30, 365)
|
|
end_date = CURRENT_DATE + timedelta(days=days_after)
|
|
|
|
# Format dates as ISO strings
|
|
start_date_str = start_date.isoformat()
|
|
end_date_str = end_date.isoformat()
|
|
|
|
# Create geometry
|
|
geometry = create_point_geometry(location["lon"], location["lat"])
|
|
|
|
# Insert geometry and get hash
|
|
geo_hash = insert_geometry(cur, geometry)
|
|
|
|
# Create event tags (properties)
|
|
tags = {
|
|
"name": f"{category.capitalize()} event in {location['name']}",
|
|
"description": f"Mock {category} event for testing",
|
|
"location": location["name"],
|
|
"start": start_date_str,
|
|
"stop": end_date_str
|
|
}
|
|
|
|
# Insert event
|
|
cur.execute("""
|
|
INSERT INTO events (
|
|
events_type, events_what, events_when, events_tags, events_geo
|
|
) VALUES (
|
|
%s, %s, tstzrange(%s, %s, '[)'), %s, %s
|
|
) ON CONFLICT DO NOTHING RETURNING events_id;
|
|
""", (
|
|
event_type,
|
|
category,
|
|
start_date_str,
|
|
end_date_str,
|
|
json.dumps(tags),
|
|
geo_hash
|
|
))
|
|
|
|
result = cur.fetchone()
|
|
return result[0] if result else None
|
|
|
|
def main():
|
|
print("Creating mock events...")
|
|
|
|
try:
|
|
# Connect to the database
|
|
conn = db_connect()
|
|
cur = conn.cursor()
|
|
|
|
# Create events for each category
|
|
created_events = []
|
|
|
|
for category in EVENT_CATEGORIES:
|
|
print(f"Creating events for category: {category}")
|
|
|
|
# Create 3 events for each category (one in each city)
|
|
for i in range(3):
|
|
location = random.choice(SAMPLE_LOCATIONS)
|
|
event_type = random.choice(EVENT_TYPES)
|
|
|
|
event_id = create_mock_event(cur, category, location, event_type)
|
|
if event_id:
|
|
created_events.append({
|
|
"id": event_id,
|
|
"category": category,
|
|
"location": location["name"],
|
|
"type": event_type
|
|
})
|
|
print(f" Created {category} event in {location['name']} with ID: {event_id}")
|
|
else:
|
|
print(f" Failed to create {category} event in {location['name']}")
|
|
|
|
# Commit the transaction
|
|
conn.commit()
|
|
|
|
print(f"\nSuccessfully created {len(created_events)} mock events:")
|
|
for event in created_events:
|
|
print(f" - {event['category']} event in {event['location']} (ID: {event['id']})")
|
|
|
|
except Exception as e:
|
|
print(f"Error: {e}")
|
|
if 'conn' in locals():
|
|
conn.rollback()
|
|
sys.exit(1)
|
|
finally:
|
|
if 'cur' in locals():
|
|
cur.close()
|
|
if 'conn' in locals():
|
|
conn.close()
|
|
|
|
if __name__ == "__main__":
|
|
main() |