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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Idempotent migration runner.
|
| 3 |
+
* Safe to run repeatedly: every statement is CREATE ... IF NOT EXISTS, and the
|
| 4 |
+
* applied set is recorded in _migrations so reruns are no-ops rather than errors.
|
| 5 |
+
*/
|
| 6 |
+
const { DatabaseSync } = require('node:sqlite');
|
| 7 |
+
const fs = require('node:fs');
|
| 8 |
+
const path = require('node:path');
|
| 9 |
+
const crypto = require('node:crypto');
|
| 10 |
+
|
| 11 |
+
const DB_PATH = process.env.DB_PATH || path.join(__dirname, 'paddock.db');
|
| 12 |
+
const id = p => p + '_' + crypto.randomBytes(6).toString('hex');
|
| 13 |
+
|
| 14 |
+
function open() {
|
| 15 |
+
const db = new DatabaseSync(DB_PATH);
|
| 16 |
+
db.exec('PRAGMA foreign_keys = ON');
|
| 17 |
+
db.exec('PRAGMA journal_mode = WAL');
|
| 18 |
+
return db;
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
function migrate(db, { quiet = false } = {}) {
|
| 22 |
+
const log = (...a) => { if (!quiet) console.log(...a); };
|
| 23 |
+
|
| 24 |
+
db.exec(`CREATE TABLE IF NOT EXISTS _migrations (
|
| 25 |
+
name TEXT PRIMARY KEY, checksum TEXT NOT NULL, applied_at TEXT NOT NULL DEFAULT (datetime('now')))`);
|
| 26 |
+
|
| 27 |
+
const file = path.join(__dirname, 'horse-racing-schema.sql');
|
| 28 |
+
const sql = fs.readFileSync(file, 'utf8');
|
| 29 |
+
const sum = crypto.createHash('sha256').update(sql).digest('hex').slice(0, 16);
|
| 30 |
+
|
| 31 |
+
const prior = db.prepare('SELECT checksum FROM _migrations WHERE name = ?').get('horse-racing-schema.sql');
|
| 32 |
+
|
| 33 |
+
if (prior && prior.checksum === sum) {
|
| 34 |
+
log(' schema already at', sum, '— nothing to do');
|
| 35 |
+
} else {
|
| 36 |
+
db.exec(sql);
|
| 37 |
+
db.prepare(`INSERT INTO _migrations (name, checksum) VALUES (?, ?)
|
| 38 |
+
ON CONFLICT(name) DO UPDATE SET checksum = excluded.checksum, applied_at = datetime('now')`)
|
| 39 |
+
.run('horse-racing-schema.sql', sum);
|
| 40 |
+
log(prior ? ' schema updated to' : ' schema applied at', sum);
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
const tables = db.prepare(
|
| 44 |
+
`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name <> '_migrations' ORDER BY name`
|
| 45 |
+
).all().map(r => r.name);
|
| 46 |
+
const idx = db.prepare(
|
| 47 |
+
`SELECT count(*) n FROM sqlite_master WHERE type='index' AND name LIKE 'ix_%'`
|
| 48 |
+
).get().n;
|
| 49 |
+
|
| 50 |
+
log(` ${tables.length} tables, ${idx} indexes`);
|
| 51 |
+
log(' ' + tables.join(', '));
|
| 52 |
+
return { tables, indexes: idx };
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
/** Demo data. Skipped entirely if an admin already exists. */
|
| 56 |
+
function seed(db, { quiet = false } = {}) {
|
| 57 |
+
const log = (...a) => { if (!quiet) console.log(...a); };
|
| 58 |
+
if (db.prepare('SELECT count(*) n FROM admins').get().n > 0) {
|
| 59 |
+
log(' already seeded — skipping');
|
| 60 |
+
return;
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
const ins = (t, row) => {
|
| 64 |
+
const cols = Object.keys(row);
|
| 65 |
+
db.prepare(`INSERT INTO ${t} (${cols.join(',')}) VALUES (${cols.map(() => '?').join(',')})`)
|
| 66 |
+
.run(...cols.map(c => row[c]));
|
| 67 |
+
};
|
| 68 |
+
const hash = pw => crypto.createHash('sha256').update(pw + '::paddock').digest('hex');
|
| 69 |
+
|
| 70 |
+
// admins ------------------------------------------------------------------
|
| 71 |
+
const SA = 'adm_super', W1 = 'adm_meridian', W2 = 'adm_kingsgate';
|
| 72 |
+
ins('admins', { id: SA, name: 'Platform Operations', email: 'ops@paddock.io',
|
| 73 |
+
password_hash: hash('super'), role: 1, parent_admin_id: null, label: 'Platform' });
|
| 74 |
+
ins('admins', { id: W1, name: 'Meridian Turf', email: 'admin@meridian.in',
|
| 75 |
+
password_hash: hash('meridian'), role: 2, parent_admin_id: SA, label: 'Meridian Turf' });
|
| 76 |
+
ins('admins', { id: W2, name: 'Kingsgate Racing', email: 'admin@kingsgate.in',
|
| 77 |
+
password_hash: hash('kingsgate'), role: 2, parent_admin_id: SA, label: 'Kingsgate Racing' });
|
| 78 |
+
|
| 79 |
+
// teams / jockeys ---------------------------------------------------------
|
| 80 |
+
const teams = [
|
| 81 |
+
['tm_poonawalla', W1, 'Poonawalla Stud', 'Emerald, gold sash', 'Pune', 412, 19.4],
|
| 82 |
+
['tm_kunigal', W1, 'Kunigal Farm', 'Royal blue, white cap','Bengaluru', 287, 16.1],
|
| 83 |
+
['tm_usha', W1, 'Usha Stud', 'Cerise, black hoops', 'Hyderabad', 198, 14.8],
|
| 84 |
+
['tm_manjri', W2, 'Manjri Horse Farm', 'Scarlet, grey sleeves','Pune', 341, 17.9],
|
| 85 |
+
['tm_nanoli', W2, 'Nanoli Stud', 'Yellow, purple star', 'Pune', 156, 12.2]
|
| 86 |
+
];
|
| 87 |
+
for (const [tid, own, name, silks, base, wins, sr] of teams)
|
| 88 |
+
ins('teams', { id: tid, owner_admin_id: own, name, silks, base,
|
| 89 |
+
stats_json: JSON.stringify({ wins, strike_rate: sr }) });
|
| 90 |
+
|
| 91 |
+
const jockeys = [
|
| 92 |
+
['jk_sandesh', W1, 'A. Sandesh', 0, 52, 1204, 246, 20.4],
|
| 93 |
+
['jk_trevor', W1, 'P. Trevor', 0, 53, 1580, 311, 19.7],
|
| 94 |
+
['jk_rawal', W1, 'Neeraj Rawal', 2, 51, 642, 88, 13.7],
|
| 95 |
+
['jk_narredu', W1, 'Suraj Narredu', 0, 52, 1712, 398, 23.2],
|
| 96 |
+
['jk_srinath', W2, 'Y.S. Srinath', 0, 54, 1388, 229, 16.5],
|
| 97 |
+
['jk_umesh', W2, 'C. Umesh', 3, 50, 411, 44, 10.7]
|
| 98 |
+
];
|
| 99 |
+
for (const [jid, own, name, claim, wt, rides, wins, sr] of jockeys)
|
| 100 |
+
ins('jockeys', { id: jid, owner_admin_id: own, name, claim_kg: claim, riding_weight: wt,
|
| 101 |
+
stats_json: JSON.stringify({ rides, wins, strike_rate: sr }) });
|
| 102 |
+
|
| 103 |
+
// race events -------------------------------------------------------------
|
| 104 |
+
const mins = m => new Date(Date.now() + m * 60000).toISOString();
|
| 105 |
+
const races = [
|
| 106 |
+
{ id: 'evt_monsoon', own: W1, name: 'The Monsoon Plate', venue: 'Mahalaxmi, Mumbai', no: 4,
|
| 107 |
+
d: 1400, going: 'Good to soft', cls: 'Class III', post: mins(9), status: 'open',
|
| 108 |
+
field: [[1,'Amber Sovereign','jk_narredu','tm_poonawalla',57,'1-2-1',2.20,2.40,0],
|
| 109 |
+
[2,'Northern Dancer','jk_sandesh','tm_kunigal', 56,'3-1-4',3.60,3.30,0],
|
| 110 |
+
[3,'Deccan Gold', 'jk_trevor', 'tm_usha', 55,'2-2-3',5.00,5.00,0],
|
| 111 |
+
[4,'Silver Stride', 'jk_rawal', 'tm_poonawalla',54,'5-3-2',7.00,6.00,0],
|
| 112 |
+
[5,'Konkan Breeze', 'jk_sandesh','tm_kunigal', 54,'4-6-5',11.0,9.50,0],
|
| 113 |
+
[6,'Midnight Ledger','jk_rawal', 'tm_usha', 53,'6-5-7',21.0,19.0,1]] },
|
| 114 |
+
{ id: 'evt_hooghly', own: W1, name: 'The Hooghly Handicap', venue: 'RCTC, Kolkata', no: 2,
|
| 115 |
+
d: 1200, going: 'Firm', cls: 'Class IV', post: mins(-14), status: 'closed',
|
| 116 |
+
field: [[1,'Steel Monsoon', 'jk_sandesh','tm_poonawalla',56,'2-1-1',1.90,2.05,0],
|
| 117 |
+
[2,'Ganges Flyer', 'jk_rawal', 'tm_usha', 55,'4-2-3',4.50,4.10,0],
|
| 118 |
+
[3,'Howrah Express','jk_trevor', 'tm_kunigal', 54,'1-5-2',3.60,3.90,0],
|
| 119 |
+
[4,'Salt Lake Star','jk_narredu','tm_poonawalla',53,'6-4-5',8.00,8.00,0]] },
|
| 120 |
+
{ id: 'evt_deccan', own: W2, name: 'The Deccan Derby Trial', venue: 'Pune', no: 3,
|
| 121 |
+
d: 1800, going: 'Good', cls: 'Class II', post: mins(24), status: 'open',
|
| 122 |
+
field: [[1,'Sahyadri Star','jk_srinath','tm_manjri',57,'1-3-2',1.80,2.10,0],
|
| 123 |
+
[2,'Mula Mutha', 'jk_umesh', 'tm_nanoli',55,'4-2-1',3.00,3.40,0],
|
| 124 |
+
[3,'Khadakwasla', 'jk_srinath','tm_manjri',54,'2-5-3',4.50,4.50,0]] }
|
| 125 |
+
];
|
| 126 |
+
|
| 127 |
+
for (const r of races) {
|
| 128 |
+
ins('race_events', { id: r.id, owner_admin_id: r.own, name: r.name, venue: r.venue,
|
| 129 |
+
race_no: r.no, distance_m: r.d, going: r.going, race_class: r.cls,
|
| 130 |
+
post_time: r.post, status: r.status, current_odds_version: 1 });
|
| 131 |
+
|
| 132 |
+
const vid = id('ver');
|
| 133 |
+
ins('odds_versions', { id: vid, event_id: r.id, version_no: 1,
|
| 134 |
+
created_by: r.own, note: 'Opening show.' });
|
| 135 |
+
|
| 136 |
+
for (const [cloth, horse, jk, tm, wt, form, odds, prev, scr] of r.field) {
|
| 137 |
+
const pid = `${r.id}_p${cloth}`;
|
| 138 |
+
ins('race_participants', { id: pid, event_id: r.id, cloth_no: cloth, horse_name: horse,
|
| 139 |
+
jockey_id: jk, team_id: tm, carried_weight: wt, recent_form: form, is_scratched: scr });
|
| 140 |
+
ins('odds_entries', { id: id('oe'), version_id: vid, participant_id: pid,
|
| 141 |
+
decimal_odds: odds, previous_odds: prev });
|
| 142 |
+
}
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
// bets --------------------------------------------------------------------
|
| 146 |
+
const bets = [
|
| 147 |
+
['evt_monsoon', W1, 'punter_4471', 'win', ['evt_monsoon_p1'], 5000, 2.40],
|
| 148 |
+
['evt_monsoon', W1, 'rajat_k', 'exacta', ['evt_monsoon_p1','evt_monsoon_p3'], 1000, null],
|
| 149 |
+
['evt_monsoon', W1, 'meena_s', 'trifecta', ['evt_monsoon_p2','evt_monsoon_p1','evt_monsoon_p4'], 500, null],
|
| 150 |
+
['evt_monsoon', W1, 'vikram_t', 'exacta', ['evt_monsoon_p2','evt_monsoon_p1'], 3000, null],
|
| 151 |
+
['evt_monsoon', W1, 'sana_m', 'exacta', ['evt_monsoon_p1','evt_monsoon_p2'], 4500, null],
|
| 152 |
+
['evt_hooghly', W1, 'arjun_bet', 'win', ['evt_hooghly_p1'], 12000, 2.05],
|
| 153 |
+
['evt_hooghly', W1, 'meena_s', 'exacta', ['evt_hooghly_p1','evt_hooghly_p3'], 2000, null],
|
| 154 |
+
['evt_hooghly', W1, 'sana_m', 'exacta', ['evt_hooghly_p3','evt_hooghly_p1'], 3500, null],
|
| 155 |
+
['evt_hooghly', W1, 'vikram_t', 'trifecta', ['evt_hooghly_p1','evt_hooghly_p3','evt_hooghly_p2'], 2200, null],
|
| 156 |
+
['evt_hooghly', W1, 'rajat_k', 'trifecta', ['evt_hooghly_p2','evt_hooghly_p1','evt_hooghly_p3'], 1800, null],
|
| 157 |
+
['evt_deccan', W2, 'kg_5512', 'win', ['evt_deccan_p1'], 4000, 2.10],
|
| 158 |
+
['evt_deccan', W2, 'kg_8890', 'exacta', ['evt_deccan_p1','evt_deccan_p2'], 1200, null]
|
| 159 |
+
];
|
| 160 |
+
for (const [ev, own, punter, type, sels, stake, odds] of bets)
|
| 161 |
+
ins('bets', { id: id('bet'), owner_admin_id: own, event_id: ev, punter_ref: punter,
|
| 162 |
+
bet_type: type, selections_json: JSON.stringify(sels), selection_count: sels.length,
|
| 163 |
+
stake, struck_odds: odds, odds_version_no: 1 });
|
| 164 |
+
|
| 165 |
+
log(` seeded 3 admins, ${teams.length} teams, ${jockeys.length} jockeys, ${races.length} races, ${bets.length} bets`);
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
if (require.main === module) {
|
| 169 |
+
const fresh = process.argv.includes('--fresh');
|
| 170 |
+
if (fresh && fs.existsSync(DB_PATH)) {
|
| 171 |
+
for (const f of [DB_PATH, DB_PATH + '-wal', DB_PATH + '-shm'])
|
| 172 |
+
if (fs.existsSync(f)) fs.unlinkSync(f);
|
| 173 |
+
console.log(' dropped existing database');
|
| 174 |
+
}
|
| 175 |
+
console.log('Running migration against', DB_PATH);
|
| 176 |
+
const db = open();
|
| 177 |
+
migrate(db);
|
| 178 |
+
seed(db);
|
| 179 |
+
db.close();
|
| 180 |
+
console.log('Done.');
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
module.exports = { open, migrate, seed, DB_PATH };
|