|
| 1 | +import asyncio |
| 2 | +import os |
| 3 | + |
| 4 | +from sqlalchemy import text |
| 5 | +from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine |
| 6 | +from sqlalchemy.orm import sessionmaker |
| 7 | +from src.insert import insert |
| 8 | +from src.last_id import get_last_id |
| 9 | + |
| 10 | +BATCH_SIZE = 1000 # Adjust as needed |
| 11 | + |
| 12 | +# Database URL format: mysql+asyncmy://user:password@host:port/database |
| 13 | +DATABASE_URL = os.getenv( |
| 14 | + "MARIADB_URL", "mysql+asyncmy://user:password@localhost:3306/database" |
| 15 | +) |
| 16 | + |
| 17 | +# Create async engine |
| 18 | +engine = create_async_engine(DATABASE_URL, echo=True) |
| 19 | + |
| 20 | +# Async session factory |
| 21 | +AsyncSessionLocal = sessionmaker( |
| 22 | + bind=engine, expire_on_commit=False, class_=AsyncSession |
| 23 | +) |
| 24 | + |
| 25 | + |
| 26 | +async def get_data(last_id): |
| 27 | + async with AsyncSessionLocal() as session: |
| 28 | + query = text( |
| 29 | + """ |
| 30 | + SELECT |
| 31 | + location_latitude AS lat, |
| 32 | + location_longitude AS lng, |
| 33 | + visit_first_action_time AS date, |
| 34 | + idvisitor AS ip, |
| 35 | + idvisit as matomo_id |
| 36 | + FROM matomo_log_visit |
| 37 | + WHERE |
| 38 | + idvisit > :last_id |
| 39 | + AND location_latitude IS NOT NULL |
| 40 | + AND location_longitude IS NOT NULL |
| 41 | + AND visit_first_action_time > '2025-07-02' |
| 42 | + LIMIT :batch_size |
| 43 | + """ |
| 44 | + ) |
| 45 | + |
| 46 | + result = await session.execute( |
| 47 | + query, {"last_id": last_id, "batch_size": BATCH_SIZE} |
| 48 | + ) |
| 49 | + rows = result.fetchall() |
| 50 | + |
| 51 | + if not rows: |
| 52 | + print("No more rows to process.") |
| 53 | + return |
| 54 | + |
| 55 | + payload = [ |
| 56 | + { |
| 57 | + "lat": float(row.lat), |
| 58 | + "lng": float(row.lng), |
| 59 | + "date": row.date, |
| 60 | + "ip": str(row.ip), |
| 61 | + "matomo_id": row.matomo_id, |
| 62 | + } |
| 63 | + for row in rows |
| 64 | + ] |
| 65 | + |
| 66 | + await insert(payload, "macrostrat") |
| 67 | + |
| 68 | + |
| 69 | +async def get_macrostrat_data(): |
| 70 | + last_id = await get_last_id("macrostrat") |
| 71 | + await get_data(last_id) |
| 72 | + print("Data fetching completed.") |
0 commit comments