feat(go): bootstrap minimal identity schema

This commit is contained in:
lingniu
2026-07-02 20:06:38 +08:00
parent 593dc08870
commit 3c9678491a
4 changed files with 87 additions and 6 deletions

View File

@@ -58,6 +58,59 @@ func NewMySQLResolverWithOptions(db *sql.DB, table string, opts MySQLResolverOpt
}
}
func (r *MySQLResolver) EnsureSchema(ctx context.Context) error {
if _, err := r.db.ExecContext(ctx, identityBindingTableSQL(r.table)); err != nil {
return err
}
_, err := r.db.ExecContext(ctx, jt808RegistrationTableSQL)
return err
}
func identityBindingTableSQL(table string) string {
if table == "" || !safeIdentifier(table) {
table = "vehicle_identity_binding"
}
return `CREATE TABLE IF NOT EXISTS ` + table + ` (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
vin VARCHAR(32) NOT NULL,
plate VARCHAR(32) NULL,
phone VARCHAR(32) NULL,
device_id VARCHAR(64) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uk_identity_plate (plate),
UNIQUE KEY uk_identity_phone (phone),
UNIQUE KEY uk_identity_device (device_id),
KEY idx_identity_vin (vin)
)`
}
const jt808RegistrationTableSQL = `CREATE TABLE IF NOT EXISTS jt808_registration (
phone VARCHAR(32) PRIMARY KEY,
device_id VARCHAR(64) NULL,
plate VARCHAR(32) NULL,
vin VARCHAR(32) NULL DEFAULT 'unknown',
province VARCHAR(16) NULL,
city VARCHAR(16) NULL,
manufacturer VARCHAR(64) NULL,
device_type VARCHAR(64) NULL,
plate_color VARCHAR(16) NULL,
auth_token VARCHAR(128) NULL,
auth_imei VARCHAR(64) NULL,
auth_software_version VARCHAR(64) NULL,
source_endpoint VARCHAR(64) NULL,
first_registered_at DATETIME NULL,
latest_registered_at DATETIME NULL,
latest_authenticated_at DATETIME NULL,
latest_seen_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY idx_jt808_registration_device (device_id),
KEY idx_jt808_registration_plate (plate),
KEY idx_jt808_registration_vin (vin),
KEY idx_jt808_registration_seen (latest_seen_at)
)`
func safeIdentifier(value string) bool {
if value == "" {
return false