Syntrex commited on
Commit
f06437c
·
verified ·
1 Parent(s): fd6db19

Update SQL

Browse files
Files changed (1) hide show
  1. SQL +20 -250
SQL CHANGED
@@ -1,257 +1,27 @@
1
- Here is Claude's plan: ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ DB Cutover — DuckDB → CockroachDB (Full Runtime)
2
-
3
- Context
4
 
5
- All active app tables (recommendation_logs, recommendation_outcomes, upcoming_hr_props,
6
- game_outcomes, batter_prop_outcomes, bets) currently persist to a local DuckDB file
7
- (data/wbc.duckdb). This resets on every container/HF Space rebuild, meaning no data
8
- survives between sessions. CockroachDB is already in use for zone/pitcher/family-zone
9
- stores (via database/remote_db.py + SQLAlchemy).
10
 
11
- This batch cuts over ALL active runtime paths to CockroachDB. No simulator logic changes.
12
- Batch 13 and Batch 12.5 follow-up remain deferred and untouched.
 
13
 
14
- ---
15
- Audit Report
 
16
 
17
- Active DuckDB paths (ALL must migrate)
 
 
18
 
19
- ┌────────────────────────────────────┬────────────────────────────────────────────────────┬─────────────────────────────────────┐
20
- │ Location │ What │ Table(s) │
21
- ├────────────────────────────────────┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
22
- │ app.py:388 │ conn = get_connection() — module-level DuckDB conn │ all tables │
23
- ├────────────────────────────────────┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
24
- │ app.py:2006 │ insert_recommendation_logs() │ recommendation_logs │
25
- ├────────────────────────────────────┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
26
- │ app.py:2012 │ insert_recommendation_outcomes() │ recommendation_outcomes │
27
- ├────────────────────────────────────┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
28
- │ app.py:2386 │ insert_game_outcomes() (debug button) │ game_outcomes │
29
- ├─────────────────────────────────��──┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
30
- │ app.py:2397 │ insert_batter_prop_outcomes() (debug button) │ batter_prop_outcomes │
31
- ├────────────────────────────────────┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
32
- │ app.py:2414 │ replace_batter_prop_outcomes() (debug button) │ batter_prop_outcomes │
33
- ├────────────────────────────────────┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
34
- │ app.py:2392 │ read_recommendation_audit_view() │ rec_logs + rec_outcomes │
35
- ├────────────────────────────────────┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
36
- │ app.py:2403 │ read_batter_prop_outcomes() │ batter_prop_outcomes │
37
- ├────────────────────────────────────┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
38
- │ app.py:2671,2681 │ read_game_outcomes(), read_batter_prop_outcomes() │ game_outcomes, batter_prop_outcomes │
39
- ├────────────────────────────────────┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
40
- │ app.py:2880 │ pitcher_store_conn = get_connection() (debug read) │ pitcher_inning_first_seed_events │
41
- ├────────────────────────────────────┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
42
- │ app.py:2948 │ batter_store_conn = get_connection() (debug read) │ batter_zone_events │
43
- ├────────────────────────────────────┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
44
- │ app.py:3516,3545,3556,3588 │ multiple read_* in debug sections │ rec_logs, rec_outcomes │
45
- ├────────────────────────────────────┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
46
- │ app.py:3882,3916 │ insert_bet(), update_bet_result() (Bet Tracker) │ bets │
47
- ├────────────────────────────────────┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
48
- │ app.py:3898,3919 │ read_table(conn, "bets") │ bets │
49
- ├────────────────────────────────────┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
50
- │ visualization/props_page.py:96-97 │ insert_upcoming_hr_props(conn, ...) │ upcoming_hr_props │
51
- ├────────────────────────────────────┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
52
- │ evaluation/xgb_hr_evaluation.py:53 │ conn.execute(query).df() │ rec_logs + rec_outcomes │
53
- ├────────────────────────────────────┼────────────────────────────────────────────────────┼─────────────────────────────────────┤
54
- │ database/db.py │ All table management, all DuckDB-specific APIs │ all │
55
- └────────────────────────────────────┴────────────────────────────────────────────────────┴─────────────────────────────────────┘
56
 
57
- Already CockroachDB-backed (no changes needed)
58
 
59
- ┌─────────────────────────────────────┬──────────────────────────────────┬────────────────────────────────────┐
60
- │ File │ Tables │ Notes │
61
- ├─────────────────────────────────────┼──────────────────────────────────┼────────────────────────────────────┤
62
- │ models/pitcher_baseline_store.py │ pitcher_inning_first_seed_events │ Uses remote_db.get_connection() ✅ │
63
- ├─────────────────────────────────────┼──────────────────────────────────┼────────────────────────────────────┤
64
- │ models/batter_zone_store.py │ batter_zone_events │ Uses remote_db.get_connection() ✅ │
65
- ├─────────────────────────────────────┼──────────────────────────────────┼────────────────────────────────────┤
66
- │ models/family_zone_profile_store.py │ family_zone_profiles │ Uses remote_db.get_connection() ✅ │
67
- └─────────────────────────────────────┴──────────────────────────────────┴────────────────────────────────────┘
68
-
69
- Dead / cache-only (report, don't migrate)
70
-
71
- ┌──────────────────────────────────┬─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
72
- ��� Table │ Status │
73
- ├──────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
74
- │ cached_schedule, cached_odds, │ Created in initialize_schema() but no active INSERT paths found. Schema artifacts from earlier version. Will be created │
75
- │ cached_weather │ in CockroachDB via initialize_schema() as part of migration — harmless. │
76
- └──────────────────────────────────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
77
-
78
- ---
79
- Implementation — 3 Files Only
80
-
81
- All callers import from database.db — public API stays identical. Only implementations change.
82
-
83
- ---
84
- File 1 — database/remote_db.py (MODIFY — lazy init)
85
-
86
- Problem: Engine is created at module import time. RuntimeError fires if DATABASE_URL not set.
87
- This blocks importing db.py after migration.
88
-
89
- Fix: Make engine lazy — only built on first get_connection() call.
90
-
91
- from __future__ import annotations
92
- import os
93
- from sqlalchemy import create_engine
94
-
95
- _engine = None
96
-
97
- def _get_engine():
98
- global _engine
99
- if _engine is not None:
100
- return _engine
101
- database_url = os.getenv("DATABASE_URL", "").strip()
102
- if not database_url:
103
- raise RuntimeError("DATABASE_URL is not set")
104
- if database_url.startswith("postgresql://"):
105
- database_url = "cockroachdb://" + database_url[len("postgresql://"):]
106
- _engine = create_engine(database_url, pool_pre_ping=True, pool_recycle=300)
107
- return _engine
108
-
109
- def get_connection():
110
- return _get_engine().connect()
111
-
112
- Backward compatible — all stores that import get_connection continue to work exactly as before.
113
-
114
- ---
115
- File 2 — database/db.py (REWRITE — same public API, CockroachDB backend)
116
-
117
- Connection: Replace duckdb.connect() with remote_db.get_connection() using AUTOCOMMIT
118
- isolation level. Autocommit matches DuckDB's default behavior — no explicit conn.commit() needed.
119
-
120
- from database import remote_db
121
-
122
- def get_connection():
123
- conn = remote_db.get_connection().execution_options(isolation_level="AUTOCOMMIT")
124
- initialize_schema(conn)
125
- return conn
126
-
127
- DDL changes:
128
- - DOUBLE → DOUBLE PRECISION (PostgreSQL doesn't accept bare DOUBLE)
129
- - bets.created_at TIMESTAMP → TEXT (consistent with all other tables; avoids implicit cast issues)
130
- - All other types unchanged: TEXT, INTEGER, BIGINT, BOOLEAN are compatible
131
-
132
- DuckDB-specific API translations:
133
-
134
- ┌────────────────────────────────────────────────────────────────────────────────────┬────────────────────────────────────────────────────────────┐
135
- │ DuckDB pattern │ Replacement │
136
- ├────────────────────────────────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
137
- │ import duckdb │ from sqlalchemy import text │
138
- ├────────────────────────────────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
139
- │ conn.register(name, df) + INSERT INTO t SELECT * FROM name + conn.unregister(name) │ _bulk_insert(conn, table, df) helper (see below) │
140
- ├────────────────────────────────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
141
- │ conn.execute(sql).df() │ pd.read_sql(text(sql), conn) │
142
- ├────────────────────────────────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
143
- │ conn.execute(sql, [p1, p2, ...]) with ? placeholders │ conn.execute(text(sql_with_named_params), {"p1": v1, ...}) │
144
- ├────────────────────────────────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
145
- │ conn.execute(sql).fetchone()[0] │ conn.execute(text(sql)).scalar() │
146
- ├────────────────────────────────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
147
- │ conn.execute(f"DELETE FROM {t}") │ conn.execute(text(f"DELETE FROM {t}")) │
148
- ├────────────────────────────────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
149
- │ conn.execute(f"ALTER TABLE t ADD COLUMN c TYPE") │ conn.execute(text(...)) — same try/except pattern │
150
- └────────────────────────────────────────────────────────────────────────────────────┴────────────────────────────────────────────────────────────┘
151
-
152
- _bulk_insert private helper (eliminates all register/unregister boilerplate):
153
- def _bulk_insert(conn, table: str, df: pd.DataFrame) -> None:
154
- if df is None or df.empty:
155
- return
156
- cols = list(df.columns)
157
- col_list = ", ".join(cols)
158
- placeholders = ", ".join(f":{c}" for c in cols)
159
- sql = f"INSERT INTO {table} ({col_list}) VALUES ({placeholders})"
160
- records = df.where(df.notna(), other=None).to_dict("records")
161
- if records:
162
- conn.execute(text(sql), records)
163
-
164
- initialize_schema: Wrap all DDL strings in text(). Remove duckdb.DuckDBPyConnection type hints.
165
-
166
- insert_bet: Convert ? positional params to :name named params.
167
- conn.execute(text("INSERT INTO bets (...) VALUES (:bet_id, :created_at, ...)"), {"bet_id": bet_id, ...})
168
-
169
- update_bet_result: Same conversion.
170
- conn.execute(text("UPDATE bets SET result = :result, profit = :profit WHERE bet_id = :bet_id"), {...})
171
-
172
- next_bet_id:
173
- return int(conn.execute(text("SELECT COALESCE(MAX(bet_id), 0) + 1 FROM bets")).scalar())
174
-
175
- read_table:
176
- return pd.read_sql(text(f"SELECT * FROM {table_name}"), conn)
177
-
178
- read_recommendation_audit_view: Replace conn.execute(query).df() with pd.read_sql(text(query), conn).
179
-
180
- All insert_* / replace_* functions: Replace register/unregister/SELECT * FROM with _bulk_insert().
181
-
182
- All read_* functions: Replace .execute(sql).df() with pd.read_sql(text(sql), conn).
183
-
184
- All ensure_* functions: Wrap DDL strings in text(). Keep try/except migration blocks as-is.
185
-
186
- upsert_dataframe: Replace .register()/DuckDB idiom with DELETE + _bulk_insert().
187
-
188
- ---
189
- File 3 — evaluation/xgb_hr_evaluation.py (MODIFY — fix .df() call)
190
-
191
- _load_evaluation_df(conn) uses conn.execute(query).df() — DuckDB-specific.
192
-
193
- Fix:
194
- from sqlalchemy import text
195
- import pandas as pd
196
-
197
- def _load_evaluation_df(conn) -> pd.DataFrame:
198
- query = """...""" # unchanged
199
- try:
200
- return pd.read_sql(text(query), conn)
201
- except Exception:
202
- return pd.DataFrame()
203
-
204
- Note: WHERE rl.xgb_shadow_active = true — PostgreSQL/CockroachDB BOOLEAN comparison
205
- accepts lowercase true ✅. No change needed to query text.
206
-
207
- ---
208
- What Does NOT Change
209
-
210
- - app.py — zero changes. conn = get_connection() still works; now returns CockroachDB conn.
211
- - pitcher_store_conn and batter_store_conn debug reads will now correctly see
212
- CockroachDB tables (since db.get_connection() now returns the same CockroachDB).
213
- - visualization/props_page.py — no changes; conn parameter still works.
214
- - analytics/props_mapper.py — no changes; doesn't touch DB.
215
- - All simulator / model code — untouched.
216
- - models/pitcher_baseline_store.py, batter_zone_store.py, family_zone_profile_store.py — already Cockroach ✅.
217
-
218
- ---
219
- Schema Compatibility Notes
220
-
221
- CockroachDB-specific behavior to be aware of:
222
- 1. CREATE TABLE IF NOT EXISTS — supported ✅
223
- 2. ALTER TABLE ... ADD COLUMN — supported; try/except for already-exists error still works ✅
224
- 3. ON CONFLICT — supported ✅ (used in pitcher store, not in db.py)
225
- 4. BOOLEAN — supported; Python True/False maps correctly ✅
226
- 5. DOUBLE PRECISION — required instead of DOUBLE ✅ (updated in DDL)
227
- 6. TEXT for timestamps — consistent with existing data format ✅
228
- 7. Autocommit mode — supported via SQLAlchemy isolation_level="AUTOCOMMIT" ✅
229
-
230
- ---
231
- Roadmap Preservation
232
-
233
- - Batch 13 (post-evaluation grading, multi-market) → deferred, untouched
234
- - Batch 12.5 follow-up (audit view legacy join, lineup_slot backfill) → deferred, untouched
235
- - This batch is infrastructure only — no model or feature changes
236
-
237
- ---
238
- Verification
239
-
240
- After implementation:
241
- 1. python -c "from database.db import get_connection; print(type(get_connection()))" — should show SQLAlchemy connection type
242
- 2. App loads without error — conn = get_connection() succeeds with DATABASE_URL set
243
- 3. Navigate to Dashboard: trigger a recommendation → verify recommendation_logs row appears in CockroachDB
244
- 4. Navigate to Props: verify upcoming_hr_props row appears in CockroachDB
245
- 5. Debug buttons: click "Grade Final Game Outcomes" → verify game_outcomes row in CockroachDB
246
- 6. Bet Tracker: log a test bet → verify bets row in CockroachDB
247
- 7. App restart → data is still present (not reset)
248
- 8. from evaluation.xgb_hr_evaluation import _load_evaluation_df — imports cleanly
249
- 9. No import duckdb remains in database/db.py
250
- ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
251
-
252
- Claude has written up a plan and is ready to execute. Would you like to proceed?
253
-
254
- ❯ 1. Yes, clear context (79% used) and auto-accept edits
255
- 2. Yes, auto-accept edits
256
- 3. Yes, manually approve edits
257
- 4. Type here to tell Claude what to change
 
1
+ Before executing, apply the following critical adjustments:
 
 
2
 
3
+ 1. Bulk insert safety
4
+ - Ensure _bulk_insert uses batched inserts (e.g. chunks of 500–1000 rows)
5
+ - Prevent partial insert issues in CockroachDB
6
+ - Do not rely on a single large execute call for large DataFrames
 
7
 
8
+ 2. Insert performance
9
+ - Ensure inserts use efficient executemany-style execution
10
+ - Avoid per-row execution loops
11
 
12
+ 3. Connection lifecycle
13
+ - Ensure no connection leaks
14
+ - Connections must be safely reused or closed appropriately within Streamlit runtime
15
 
16
+ 4. Behavioral compatibility
17
+ - If any existing logic implicitly relied on DuckDB behavior (ordering, temp handling, etc),
18
+ preserve that behavior in the Cockroach implementation
19
 
20
+ 5. Future schema safety
21
+ - Do NOT introduce primary keys yet
22
+ - But ensure schema and insert logic do not prevent adding keys later
23
+ - Maintain consistency of identifying fields (game_pk, batter_name, lineup_slot, timestamps)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ Do not change overall architecture — only strengthen implementation robustness.
26
 
27
+ Then proceed with execution.