//go:build mysql // +build mysql package mysql import ( "errors" mysqldriver "github.com/go-sql-driver/mysql" ) func ensureIMRegistrationInviteControlTables(exec sqlExecutor) error { statements := []string{ `CREATE TABLE IF NOT EXISTS im_registration_invite_batches( id BIGINT NOT NULL, tenant_id BIGINT NOT NULL, quantity INT UNSIGNED NOT NULL, idempotency_key VARCHAR(128) NOT NULL, expires_at DATETIME(3) NOT NULL, created_by BIGINT NOT NULL, remark VARCHAR(255) NOT NULL DEFAULT '', created_at DATETIME(3) NOT NULL, updated_at DATETIME(3) NOT NULL, PRIMARY KEY(id), UNIQUE INDEX uk_im_registration_invite_batch_tenant_idempotency(tenant_id,idempotency_key), INDEX idx_im_registration_invite_batch_tenant_created(tenant_id,created_at) )`, `CREATE TABLE IF NOT EXISTS im_registration_invite_codes( id BIGINT NOT NULL, tenant_id BIGINT NOT NULL, batch_id BIGINT, code CHAR(5) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, status VARCHAR(16) NOT NULL, expires_at DATETIME(3) NOT NULL, usage_count INT UNSIGNED NOT NULL DEFAULT 0, last_used_at DATETIME(3) NULL, created_by BIGINT NOT NULL, remark VARCHAR(255) NOT NULL DEFAULT '', created_at DATETIME(3) NOT NULL, updated_at DATETIME(3) NOT NULL, PRIMARY KEY(id), UNIQUE INDEX uk_im_registration_invite_code_tenant(tenant_id,code), INDEX idx_im_registration_invite_tenant_status_expires(tenant_id,status,expires_at), INDEX idx_im_registration_invite_tenant_batch(tenant_id,batch_id), INDEX idx_im_registration_invite_tenant_created(tenant_id,created_at) )`, } for _, stmt := range statements { if _, err := exec.Exec(stmt); err != nil { return err } } return nil } func ensureIMRegistrationInviteUseTable(exec sqlExecutor) error { if _, err := exec.Exec(`CREATE TABLE IF NOT EXISTS im_registration_invite_uses( id BIGINT NOT NULL, invite_code_id BIGINT NOT NULL, user_id BIGINT NOT NULL, request_id VARCHAR(64) NOT NULL, used_at DATETIME(3) NOT NULL, PRIMARY KEY(id), INDEX idx_im_registration_invite_use_code(invite_code_id), UNIQUE INDEX uk_im_registration_invite_use_user(user_id), INDEX idx_im_registration_invite_use_request(request_id) )`); err != nil { return err } for _, migration := range []struct { statement string ignored uint16 }{ {`ALTER TABLE im_registration_invite_uses DROP INDEX uk_im_registration_invite_use_code`, 1091}, {`ALTER TABLE im_registration_invite_uses ADD INDEX idx_im_registration_invite_use_code(invite_code_id)`, 1061}, } { if _, err := exec.Exec(migration.statement); err != nil && !isMySQLErrorNumber(err, migration.ignored) { return err } } return nil } func isMySQLErrorNumber(err error, number uint16) bool { var mysqlErr *mysqldriver.MySQLError return errors.As(err, &mysqlErr) && mysqlErr.Number == number }