@openreachtech/hora-skills-ort-renchan 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.ja.md +135 -0
- package/README.md +135 -0
- package/dist/skills/hor-agent-loop/SKILL.md +123 -0
- package/dist/skills/hor-agent-loop/references/core.md +485 -0
- package/dist/skills/hor-agent-loop/references/graphql-integration.md +178 -0
- package/dist/skills/hor-agent-loop/references/renchan-job-integration.md +368 -0
- package/dist/skills/hor-agent-loop/references/testing.md +492 -0
- package/dist/skills/hor-ai-agent-structure/SKILL.md +403 -0
- package/dist/skills/hor-ai-agent-structure/references/loop-and-actions.md +100 -0
- package/dist/skills/hor-ai-prompt-document-store/SKILL.md +220 -0
- package/dist/skills/hor-ai-prompt-document-store/references/models-and-composition.md +156 -0
- package/dist/skills/hor-backend-testing/SKILL.md +118 -0
- package/dist/skills/hor-backend-testing/references/placement-and-ordering.md +89 -0
- package/dist/skills/hor-backend-testing/references/purity-and-mocks.md +82 -0
- package/dist/skills/hor-backend-testing/references/running-tests.md +186 -0
- package/dist/skills/hor-bank-id/SKILL.md +91 -0
- package/dist/skills/hor-build-e2e-test-environment/SKILL.md +609 -0
- package/dist/skills/hor-build-e2e-test-environment/references/compose-definition.md +368 -0
- package/dist/skills/hor-build-e2e-test-environment/references/edge-and-proxy.md +287 -0
- package/dist/skills/hor-build-e2e-test-environment/references/environment-and-ports.md +201 -0
- package/dist/skills/hor-build-e2e-test-environment/references/runner-and-lifecycle.md +330 -0
- package/dist/skills/hor-build-e2e-test-environment/references/seed-data.md +145 -0
- package/dist/skills/hor-build-e2e-test-environment/references/windows-runner.md +146 -0
- package/dist/skills/hor-constant-definition/SKILL.md +139 -0
- package/dist/skills/hor-cookie-authentication/SKILL.md +33 -0
- package/dist/skills/hor-cookie-authentication/references/auth-filter.md +55 -0
- package/dist/skills/hor-cookie-authentication/references/cookie-context.md +53 -0
- package/dist/skills/hor-cookie-authentication/references/dev-login-seeder.md +22 -0
- package/dist/skills/hor-cookie-authentication/references/environment.md +64 -0
- package/dist/skills/hor-cookie-authentication/references/error-codes.md +24 -0
- package/dist/skills/hor-cookie-authentication/references/migrations.md +18 -0
- package/dist/skills/hor-cookie-authentication/references/resolvers.md +97 -0
- package/dist/skills/hor-cookie-authentication/references/session-clerk.md +41 -0
- package/dist/skills/hor-cookie-authentication/references/token-models.md +125 -0
- package/dist/skills/hor-database-design/SKILL.md +54 -0
- package/dist/skills/hor-database-design/references/column-types.md +92 -0
- package/dist/skills/hor-database-design/references/datetimes.md +88 -0
- package/dist/skills/hor-database-design/references/master-tables.md +117 -0
- package/dist/skills/hor-database-design/references/normalization.md +40 -0
- package/dist/skills/hor-database-design/references/update-history.md +35 -0
- package/dist/skills/hor-execution-placement-pattern/SKILL.md +216 -0
- package/dist/skills/hor-external-api-client/SKILL.md +99 -0
- package/dist/skills/hor-external-api-client/references/architecture.md +127 -0
- package/dist/skills/hor-external-api-client/references/authorization.md +105 -0
- package/dist/skills/hor-external-api-client/references/capsule.md +130 -0
- package/dist/skills/hor-external-api-client/references/conventions.md +68 -0
- package/dist/skills/hor-external-api-client/references/launcher.md +138 -0
- package/dist/skills/hor-external-api-client/references/payload.md +176 -0
- package/dist/skills/hor-external-api-client/references/sdk-wrapper.md +291 -0
- package/dist/skills/hor-external-api-client/references/testing.md +130 -0
- package/dist/skills/hor-external-api-client/references/usage.md +152 -0
- package/dist/skills/hor-graphql-schema/SKILL.md +360 -0
- package/dist/skills/hor-graphql-server-engine/SKILL.md +356 -0
- package/dist/skills/hor-light-rag/SKILL.md +242 -0
- package/dist/skills/hor-light-rag/references/retrieval-internals.md +143 -0
- package/dist/skills/hor-multi-llm-provider/SKILL.md +288 -0
- package/dist/skills/hor-multi-llm-provider/references/provider-internals.md +153 -0
- package/dist/skills/hor-mutation-resolver/SKILL.md +360 -0
- package/dist/skills/hor-mutation-resolver/references/dependency-injection.md +148 -0
- package/dist/skills/hor-mutation-resolver/references/errors.md +120 -0
- package/dist/skills/hor-mutation-resolver/references/resolve-flow.md +275 -0
- package/dist/skills/hor-mutation-resolver/references/testing.md +125 -0
- package/dist/skills/hor-mutation-resolver/references/transaction.md +197 -0
- package/dist/skills/hor-post-worker/SKILL.md +320 -0
- package/dist/skills/hor-query-resolver/SKILL.md +246 -0
- package/dist/skills/hor-query-resolver/references/anatomy.md +384 -0
- package/dist/skills/hor-query-resolver/references/data-access.md +248 -0
- package/dist/skills/hor-query-resolver/references/errors-and-context.md +172 -0
- package/dist/skills/hor-query-resolver/references/testing.md +241 -0
- package/dist/skills/hor-renchan-job-bullmq/SKILL.md +178 -0
- package/dist/skills/hor-renchan-job-bullmq/references/daemon-and-scheduler.md +182 -0
- package/dist/skills/hor-renchan-job-bullmq/references/engine-and-infra.md +106 -0
- package/dist/skills/hor-renchan-job-bullmq/references/job-triple.md +189 -0
- package/dist/skills/hor-renchan-job-bullmq/references/queues.md +74 -0
- package/dist/skills/hor-renchan-job-bullmq/references/subscriptions.md +113 -0
- package/dist/skills/hor-resolver-share/SKILL.md +262 -0
- package/dist/skills/hor-resolver-validator/SKILL.md +194 -0
- package/dist/skills/hor-resolver-validator/references/inspector-api.md +115 -0
- package/dist/skills/hor-resolver-validator/references/validator-pattern.md +281 -0
- package/dist/skills/hor-restfulapi-architecture/SKILL.md +275 -0
- package/dist/skills/hor-restfulapi-architecture/references/engine-and-context.md +192 -0
- package/dist/skills/hor-restfulapi-architecture/references/renderers.md +204 -0
- package/dist/skills/hor-restfulapi-architecture/references/response-and-flusher.md +118 -0
- package/dist/skills/hor-restfulapi-architecture/references/validation.md +229 -0
- package/dist/skills/hor-security-audit/SKILL.md +110 -0
- package/dist/skills/hor-security-audit/references/application-surface.md +90 -0
- package/dist/skills/hor-security-audit/references/auth-and-transport.md +147 -0
- package/dist/skills/hor-security-audit/references/code-safety.md +74 -0
- package/dist/skills/hor-security-audit/references/dependencies.md +72 -0
- package/dist/skills/hor-security-audit/references/network-and-logging.md +56 -0
- package/dist/skills/hor-security-audit/references/secrets.md +95 -0
- package/dist/skills/hor-sequelize-migration/SKILL.md +336 -0
- package/dist/skills/hor-sequelize-migration/references/alter-table.md +147 -0
- package/dist/skills/hor-sequelize-migration/references/foreign-keys.md +107 -0
- package/dist/skills/hor-sequelize-migration/references/indexes.md +149 -0
- package/dist/skills/hor-sequelize-migration/references/notation.md +215 -0
- package/dist/skills/hor-sequelize-model/SKILL.md +69 -0
- package/dist/skills/hor-sequelize-model/references/associations.md +218 -0
- package/dist/skills/hor-sequelize-model/references/default-methods.md +244 -0
- package/dist/skills/hor-sequelize-model/references/mixins.md +247 -0
- package/dist/skills/hor-sequelize-model/references/notation.md +225 -0
- package/dist/skills/hor-sequelize-model/references/timestamps.md +74 -0
- package/dist/skills/hor-sequelize-seeder/SKILL.md +275 -0
- package/dist/skills/hor-sequelize-seeder/references/development-coverage.md +74 -0
- package/dist/skills/hor-sequelize-seeder/references/directory-structure.md +113 -0
- package/dist/skills/hor-sequelize-seeder/references/id-numbering.md +133 -0
- package/dist/skills/hor-sequelize-seeder/references/naming.md +59 -0
- package/dist/skills/hor-sequelize-seeder/references/notation.md +170 -0
- package/dist/skills/hor-sequelize-subquery/SKILL.md +369 -0
- package/dist/skills/hor-strategy-pattern/SKILL.md +371 -0
- package/dist/skills/hor-stub-api/SKILL.md +330 -0
- package/dist/skills/hor-subscription-resolver/SKILL.md +105 -0
- package/dist/skills/hor-subscription-resolver/references/authentication.md +99 -0
- package/dist/skills/hor-subscription-resolver/references/basic-notation.md +116 -0
- package/dist/skills/hor-subscription-resolver/references/design-philosophy.md +68 -0
- package/dist/skills/hor-type-interface/SKILL.md +200 -0
- package/docs/skills.ja.md +40 -0
- package/docs/skills.md +40 -0
- package/lib/equip/CommandLineArguments.js +178 -0
- package/lib/equip/HoraSkillsCli.js +590 -0
- package/lib/equip/SkillsInstaller.js +443 -0
- package/lib/equip/SkillsManifestFile.js +260 -0
- package/lib/equip/constants/CLI_COMMAND.js +8 -0
- package/lib/equip/hora-skills-ort-renchan.js +8 -0
- package/package.json +51 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Error codes
|
|
2
|
+
|
|
3
|
+
Two codes make the cookie flow legible to the frontend ([[hof-cookie-authentication]]), on top of the engine's standard hash. Codes follow the dotted `<class>.<id>.<seq>` convention, spread over `super.errorCodeHash` in the resolver.
|
|
4
|
+
|
|
5
|
+
```js
|
|
6
|
+
// RenewAccessTokenMutationResolver
|
|
7
|
+
static get errorCodeHash () {
|
|
8
|
+
return {
|
|
9
|
+
...super.errorCodeHash,
|
|
10
|
+
|
|
11
|
+
// This op skips filtering, so it raises Unauthenticated itself — reusing the engine's own
|
|
12
|
+
// code so the client sees the same "sign in again" signal.
|
|
13
|
+
Unauthenticated: '102.X000.001',
|
|
14
|
+
|
|
15
|
+
RefreshTokenReused: '205.M003.001',
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
- **`Unauthenticated` = `102.X000.001`** — the engine's standard code. Header-guarded operations get it from the filter ([auth-filter](./auth-filter.md)); `renewAccessToken` skips the filter, so it raises the same code itself when the refresh cookie is missing, expired, or unavailable.
|
|
21
|
+
- **`RefreshTokenReused` = `205.M003.001`** — a spent refresh token was presented again (a leak). `renewAccessToken` revokes the whole series and throws this; the frontend treats it as a hard sign-out, no retry.
|
|
22
|
+
- **`IncorrectSecret` = `202.M002.001`** — `signIn` throws this for a wrong email *or* password, one code for both so it never reveals which was wrong.
|
|
23
|
+
|
|
24
|
+
The engine's `standardErrorCodeHash` owns `Unauthenticated` / `Unauthorized` / `DeniedSchemaPermission` (all `102.X000.*`); the filter throws those for header-guarded operations, so the auth resolvers only add what is theirs.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# Migrations
|
|
2
|
+
|
|
3
|
+
One create-table migration per credential / token table, written with the standard migration shape (`MigrationAttributeFactory`, a `COLUMN_NAME` map, snake_case `field:`, `addIndex`). See the migration convention for the skeleton; this reference is only the auth-specific columns and indexes.
|
|
4
|
+
|
|
5
|
+
Tables, per actor (`<Actor>` shown):
|
|
6
|
+
|
|
7
|
+
- `<actor>_password_hashes` (+ `<actor>_password_hashes_bk` backup) — `<actor>_id`, `password_hash`, `saved_at`.
|
|
8
|
+
- `<actor>_access_tokens` — `<actor>_id`, `access_token`, `session_key`, `generated_at`, `expired_at`.
|
|
9
|
+
- `<actor>_refresh_tokens` — `<actor>_id`, `token_hash`, `session_key`, `used_at`, `revoked_at`, `generated_at`, `expired_at`.
|
|
10
|
+
|
|
11
|
+
Auth-specific points:
|
|
12
|
+
|
|
13
|
+
- **Unique index on the token digest** (`token_hash`) and on `access_token` — each is the lookup key, and the unique index makes a duplicate impossible.
|
|
14
|
+
- **Index `session_key`** on both token tables — rotation and revocation query by series.
|
|
15
|
+
- Foreign keys (`<actor>_id`) are plain `BIGINT` columns with an index and **no** DB-level `references` constraint — the renchan convention.
|
|
16
|
+
- The `_bk` backup table mirrors the source columns; it pairs with the password-hash model's backup mixin ([token-models](./token-models.md)).
|
|
17
|
+
|
|
18
|
+
The columns map one-to-one to the model attributes ([token-models](./token-models.md)) — camelCase attribute ↔ snake_case column via `underscored: true`. Add or change a column in the migration and the model together.
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# Auth resolvers
|
|
2
|
+
|
|
3
|
+
Four mutations, all thin: each wires `SessionClerk` ([session-clerk](./session-clerk.md)) and `RefreshTokenExpressCookieClerk` ([cookie-context](./cookie-context.md)). Write them with [[hor-mutation-resolver]]; this reference is only the auth wiring. Both clerks are reached through getter seams (`SessionClerkCtor`, `RefreshTokenExpressCookieClerkCtor`) so tests substitute them.
|
|
4
|
+
|
|
5
|
+
## signIn
|
|
6
|
+
|
|
7
|
+
Verify the password, start a session, set the cookie **after** the write commits, return only the access token.
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
const passwordHashEntity = await this.findPasswordHashByEmail({ email })
|
|
11
|
+
|
|
12
|
+
if (!passwordHashEntity) {
|
|
13
|
+
throw this.errorHash.IncorrectSecret.create()
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const isValidPassword = await passwordHashEntity.verifiesPassword({ password })
|
|
17
|
+
|
|
18
|
+
if (!isValidPassword) {
|
|
19
|
+
throw this.errorHash.IncorrectSecret.create() // same code for wrong email or password
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const result = await this.createSessionClerk()
|
|
23
|
+
.saveSession({
|
|
24
|
+
userId: passwordHashEntity.<Actor>Id,
|
|
25
|
+
now: context.now,
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
if (result.hasError()) {
|
|
29
|
+
throw new Error(result.extractErrorMessage())
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Only after the transaction committed — a cookie for a rolled-back session would leave the
|
|
33
|
+
// client holding a refresh token no row backs.
|
|
34
|
+
this.createCookieClerk({ context })
|
|
35
|
+
.saveRefreshTokenCookie({ refreshToken: result.credentialPair.refreshToken })
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
accessToken: result.credentialPair.accessTokenEntity.accessToken,
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## renewAccessToken
|
|
43
|
+
|
|
44
|
+
Authenticate from the **cookie** (the access token is usually expired when this runs, so the op skips filtering — [auth-filter](./auth-filter.md)). Rotate; a **used** token presented again is a leak → revoke the series and report reuse.
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
const refreshTokenEntity = await sessionClerk.findRefreshToken({
|
|
48
|
+
refreshToken: cookieClerk.extractRefreshToken(),
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
if (!refreshTokenEntity) {
|
|
52
|
+
cookieClerk.clearRefreshTokenCookie()
|
|
53
|
+
|
|
54
|
+
throw this.errorHash.Unauthenticated.create()
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (refreshTokenEntity.isUsed()) {
|
|
58
|
+
return this.handleReusedToken({ context, refreshTokenEntity }) // revoke series + RefreshTokenReused
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (!refreshTokenEntity.isAvailable({ pointsAt: context.now })) {
|
|
62
|
+
cookieClerk.clearRefreshTokenCookie()
|
|
63
|
+
|
|
64
|
+
throw this.errorHash.Unauthenticated.create()
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const result = await sessionClerk.rotateSession({ refreshTokenEntity, now: context.now })
|
|
68
|
+
// ... on success: set the new cookie, return the fresh accessToken
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## signOut
|
|
72
|
+
|
|
73
|
+
Authenticate from the cookie, revoke the whole series, clear the cookie. **Idempotent** — a missing or unmatched cookie still clears the cookie and returns success, because signing out is never an error.
|
|
74
|
+
|
|
75
|
+
```js
|
|
76
|
+
const refreshTokenEntity = await sessionClerk.findRefreshToken({
|
|
77
|
+
refreshToken: cookieClerk.extractRefreshToken(),
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
const result = await this.revokeSeries({ context, refreshTokenEntity }) // null when nothing matched
|
|
81
|
+
|
|
82
|
+
if (result?.hasError()) {
|
|
83
|
+
throw new Error(result.extractErrorMessage())
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
cookieClerk.clearRefreshTokenCookie()
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
isSignedOut: true,
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## signUp
|
|
94
|
+
|
|
95
|
+
Creates the actor together with its secret (email) and password hash. The profile fields are the app's own design; the auth-specific part is enciphering the password into the password-hash table (the same enciphering `verifiesPassword` compares against — [token-models](./token-models.md)). It may start a session like `signIn`, or leave the actor to sign in afterward.
|
|
96
|
+
|
|
97
|
+
All four operations are public — they are listed in `schemasToSkipFiltering` ([auth-filter](./auth-filter.md)).
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Session clerk
|
|
2
|
+
|
|
3
|
+
`app/session/SessionClerk.js` is the single window over the token tables — every find / save / update / delete across the access and refresh token tables. Resolvers depend only on it and never touch the tables. The **token models are injected**, so both audiences share one implementation.
|
|
4
|
+
|
|
5
|
+
```js
|
|
6
|
+
const sessionClerk = SessionClerk.create({
|
|
7
|
+
AccessTokenModel: <Actor>AccessToken,
|
|
8
|
+
RefreshTokenModel: <Actor>RefreshToken,
|
|
9
|
+
})
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Throwable-save, result objects
|
|
13
|
+
|
|
14
|
+
Each public write self-resolves a transaction and returns a **result object** rather than throwing — a throw rolls the transaction back and comes back as `result.error`. Naming the error is left to the resolver.
|
|
15
|
+
|
|
16
|
+
- `saveSession({ userId, now })` → `SavingSessionResult` — starts a new series (access + refresh pair). `result.credentialPair` is `{ accessTokenEntity, refreshTokenEntity, refreshToken }`, where `refreshToken` is the plaintext for the cookie.
|
|
17
|
+
- `rotateSession({ refreshTokenEntity, now })` → `SavingSessionResult` — spends the presented refresh row (`usedAt`) and issues the next pair in the same `sessionKey`.
|
|
18
|
+
- `revokeSession({ sessionKey, now })` → `RevokingSessionResult` — revokes every refresh token in the series and deletes its access tokens.
|
|
19
|
+
- `findRefreshToken({ refreshToken })` → the row, looked up by digest, or `null`.
|
|
20
|
+
|
|
21
|
+
```js
|
|
22
|
+
const result = await sessionClerk.saveSession({
|
|
23
|
+
userId,
|
|
24
|
+
now: context.now,
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
if (result.hasError()) {
|
|
28
|
+
throw new Error(result.extractErrorMessage())
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// result.credentialPair.refreshToken → hand to the cookie clerk
|
|
32
|
+
// result.credentialPair.accessTokenEntity.accessToken → the response body
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Rotation detects reuse
|
|
36
|
+
|
|
37
|
+
Rotation spends the presented row guarded on `usedAt: null`, so presenting a spent row again updates nothing. The resolver reads `refreshTokenEntity.isUsed()` and treats a used row as a leak ([resolvers](./resolvers.md)). Revocation is keyed on `sessionKey`, so it takes down the whole series at once.
|
|
38
|
+
|
|
39
|
+
## Transactions and seams
|
|
40
|
+
|
|
41
|
+
Every write takes an optional `transaction`: pass one to join an outer transaction (the caller then decides rollback via `result.hasError()`), or omit it to self-resolve one here. The clerk builds tokens through a `SessionCredentialGenerator` (token, digest, session-key) defaulted in its factory — real callers get real behavior; tests substitute the injected models and the generator seam.
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
# Token & credential models
|
|
2
|
+
|
|
3
|
+
An authenticated actor's credential and session live in a small cluster of tables, kept apart from the actor's profile. For an actor `<Actor>`:
|
|
4
|
+
|
|
5
|
+
- `<Actor>` — the entity (its profile fields are the app's own design; see [[hor-database-design]]).
|
|
6
|
+
- `<Actor>Secret` — the sign-in identifier (`email`), kept apart from the profile.
|
|
7
|
+
- `<Actor>PasswordHash` — the password digest; verifies a candidate password.
|
|
8
|
+
- `<Actor>AccessToken` — the short-lived token (15 min), sent on the `x-renchan-access-token` header.
|
|
9
|
+
- `<Actor>RefreshToken` — the long-lived token; stored only as a digest, delivered as an `HttpOnly` cookie.
|
|
10
|
+
|
|
11
|
+
Each is a normal renchan model ([[hor-sequelize-model]]); this reference is only the auth-specific shape.
|
|
12
|
+
|
|
13
|
+
## The rotation columns (refresh token)
|
|
14
|
+
|
|
15
|
+
`sessionKey` is the **series**; `usedAt` / `revokedAt` / `expiredAt` drive rotation and reuse detection. Only the **digest** is stored (`tokenHash`, unique) — a dump of the table is not a set of usable sessions.
|
|
16
|
+
|
|
17
|
+
```js
|
|
18
|
+
// <Actor>RefreshToken.createAttributes — the auth-specific columns
|
|
19
|
+
<Actor>Id: {
|
|
20
|
+
type: DataTypes.BIGINT,
|
|
21
|
+
allowNull: false,
|
|
22
|
+
},
|
|
23
|
+
tokenHash: {
|
|
24
|
+
type: DataTypes.STRING(191),
|
|
25
|
+
allowNull: false,
|
|
26
|
+
unique: true, // the digest, never the token; the lookup key
|
|
27
|
+
},
|
|
28
|
+
sessionKey: {
|
|
29
|
+
type: DataTypes.STRING(191),
|
|
30
|
+
allowNull: false, // the series a rotation keeps
|
|
31
|
+
},
|
|
32
|
+
usedAt: {
|
|
33
|
+
type: DataTypes.DATE,
|
|
34
|
+
allowNull: true, // set when spent on rotation
|
|
35
|
+
},
|
|
36
|
+
revokedAt: {
|
|
37
|
+
type: DataTypes.DATE,
|
|
38
|
+
allowNull: true, // set on sign-out or reuse
|
|
39
|
+
},
|
|
40
|
+
generatedAt: {
|
|
41
|
+
type: DataTypes.DATE,
|
|
42
|
+
allowNull: false,
|
|
43
|
+
},
|
|
44
|
+
expiredAt: {
|
|
45
|
+
type: DataTypes.DATE,
|
|
46
|
+
allowNull: false,
|
|
47
|
+
},
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`<Actor>AccessToken` mirrors this but has no `usedAt` / `revokedAt` (an access token is deleted, not flagged) and carries the `accessToken` value (unique) plus the same `sessionKey`.
|
|
51
|
+
|
|
52
|
+
## Store the digest, hand back the plaintext
|
|
53
|
+
|
|
54
|
+
The token models never store the plain token. `buildWithGeneratedAttributes` takes the plain refresh token and stores only its digest through `hashToken`; the plaintext is returned by the clerk for the cookie.
|
|
55
|
+
|
|
56
|
+
```js
|
|
57
|
+
static buildWithGeneratedAttributes ({
|
|
58
|
+
userId,
|
|
59
|
+
sessionKey,
|
|
60
|
+
refreshToken,
|
|
61
|
+
generatedAt,
|
|
62
|
+
expiredAt = this.createExpiredAt({ generatedAt }),
|
|
63
|
+
}) {
|
|
64
|
+
return this.build({
|
|
65
|
+
<Actor>Id: userId,
|
|
66
|
+
sessionKey,
|
|
67
|
+
tokenHash: this.hashToken({ token: refreshToken }), // only the digest is persisted
|
|
68
|
+
generatedAt,
|
|
69
|
+
expiredAt,
|
|
70
|
+
usedAt: null,
|
|
71
|
+
revokedAt: null,
|
|
72
|
+
})
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## State reads live on the model
|
|
77
|
+
|
|
78
|
+
Availability and reuse are model methods, so a resolver never re-implements the rules:
|
|
79
|
+
|
|
80
|
+
```js
|
|
81
|
+
isUsed () {
|
|
82
|
+
return this.get('usedAt') !== null // presented again after this ⇒ reuse
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
isAvailable ({ pointsAt }) {
|
|
86
|
+
return !this.isUsed()
|
|
87
|
+
&& !this.isRevoked()
|
|
88
|
+
&& !this.isExpired({ pointsAt })
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Audience-neutral foreign-key read
|
|
93
|
+
|
|
94
|
+
The shared `SessionClerk` ([session-clerk](./session-clerk.md)) holds the token model without knowing the actor, so expose the concrete foreign key through `extractUserId()`:
|
|
95
|
+
|
|
96
|
+
```js
|
|
97
|
+
extractUserId () {
|
|
98
|
+
return this.get('<Actor>Id') // the Admin model returns AdminId
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Password hash
|
|
103
|
+
|
|
104
|
+
`<Actor>PasswordHash` stores `passwordHash`, uses the backup mixin (history), and verifies a candidate through the enciphered compare — never a plain equality:
|
|
105
|
+
|
|
106
|
+
```js
|
|
107
|
+
static get Mixins () {
|
|
108
|
+
return [BackupMixinModel]
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
static get BackupModel () {
|
|
112
|
+
return this._.<Actor>PasswordHashesBk
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async verifiesPassword ({ password }) {
|
|
116
|
+
const passwordHash = this.get('passwordHash')
|
|
117
|
+
|
|
118
|
+
if (!passwordHash) {
|
|
119
|
+
return false
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return Encipher.create()
|
|
123
|
+
.compare(password, passwordHash)
|
|
124
|
+
}
|
|
125
|
+
```
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hor-database-design
|
|
3
|
+
description: >
|
|
4
|
+
Decide the logical shape of a renchan database schema — the design choices made before writing a
|
|
5
|
+
migration or model. Use this skill whenever the user asks how to model a table, whether to
|
|
6
|
+
normalize or denormalize, how to represent a status or category, which column type to pick, how
|
|
7
|
+
to store times, how to scale reads as data grows, how to version a master table, or how to keep
|
|
8
|
+
a table's update history. Writing the migration and the model are separate conventions.
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# Database Design
|
|
12
|
+
|
|
13
|
+
A skill for the **schema-design decisions** that come *before* the mechanics: what tables and
|
|
14
|
+
columns should exist, how they relate, and what each column's type and meaning is. The physical
|
|
15
|
+
declaration (migration files, DataTypes, indexes) is written by `hor-sequelize-migration`; the logical
|
|
16
|
+
declaration on top (model attributes, associations) by `hor-sequelize-model`. This skill decides
|
|
17
|
+
**what** to put in them and **why**. The individual conventions are split across the detail files
|
|
18
|
+
below — consult them as needed.
|
|
19
|
+
|
|
20
|
+
## Grand principle: the database holds canonical, normalized truth
|
|
21
|
+
|
|
22
|
+
The database is the **single source of truth**, and it stores that truth in its **canonical,
|
|
23
|
+
non-redundant** form. Anything that is *derived* (aggregates, search indexes), *presentational*
|
|
24
|
+
(timezone, human-readable labels), or *volatile / large* (files, dynamic blobs) is kept **out of
|
|
25
|
+
the normalized core** and lives in a separate structure or in another layer. Every rule in the
|
|
26
|
+
detail files is this principle applied to one kind of data.
|
|
27
|
+
|
|
28
|
+
- **Why**: when the canonical tables stay minimal and non-redundant, each fact lives in exactly one
|
|
29
|
+
place, so responsibility boundaries are clear and the structure stays flexible as requirements
|
|
30
|
+
change — which keeps the schema stable over the project's long life. The moment derived or
|
|
31
|
+
presentational data leaks into the core, that data drifts out of sync, makes the schema rigid,
|
|
32
|
+
and every later change has to reconcile duplicates.
|
|
33
|
+
- **When a rule and performance conflict, do not compromise the core** — add a separate, additive,
|
|
34
|
+
rebuildable structure (a summary table, a search DB) beside it. Never fix a query-speed concern
|
|
35
|
+
by corrupting the write model.
|
|
36
|
+
|
|
37
|
+
This skill is design-level. Whenever a decision needs to be *written*, cross to `hor-sequelize-migration`
|
|
38
|
+
(column types, `DATE(3)`, `TEXT('medium')`, `JSON`, no DB foreign-key constraint, indexes) and
|
|
39
|
+
`hor-sequelize-model` (attributes, timestamps, and the Mixins that implement versioning and archiving).
|
|
40
|
+
Code comments in the examples are English, matching those sibling skills.
|
|
41
|
+
|
|
42
|
+
## Detail files
|
|
43
|
+
|
|
44
|
+
- [normalization.md](./references/normalization.md) — normalize to 3NF; when reads grow, add a
|
|
45
|
+
`summary_` table or a search DB instead of denormalizing the core
|
|
46
|
+
- [datetimes.md](./references/datetimes.md) — separate business datetimes from the ORM's audit
|
|
47
|
+
timestamps; store every datetime as UTC at millisecond precision (`DATE(3)`)
|
|
48
|
+
- [master-tables.md](./references/master-tables.md) — model a status / category as a master table +
|
|
49
|
+
key column (not free strings, rarely `ENUM`); version a master table (a price list) by splitting
|
|
50
|
+
the version table from its rows
|
|
51
|
+
- [column-types.md](./references/column-types.md) — pick a column's type from the shape of its data
|
|
52
|
+
(`JSON` / `TEXT` / `TEXT('medium')`); keep files in external storage and store only a reference
|
|
53
|
+
- [update-history.md](./references/update-history.md) — retain a table's update log with the archive
|
|
54
|
+
pattern (`BackupMixinModel` + a `*_bk` table)
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# Column types (choosing a type, and where files go)
|
|
2
|
+
|
|
3
|
+
Choosing a column's type from the shape of the data it holds, and why file bytes never live in the
|
|
4
|
+
database. Referenced from [SKILL.md](../SKILL.md). The concrete DataTypes and how to write them
|
|
5
|
+
belong to `hor-sequelize-migration`.
|
|
6
|
+
|
|
7
|
+
## Pick the column type from the shape of the data
|
|
8
|
+
|
|
9
|
+
Type each column to what it actually holds:
|
|
10
|
+
|
|
11
|
+
| Data | Type | Note |
|
|
12
|
+
| --- | --- | --- |
|
|
13
|
+
| Genuinely dynamic / schemaless values | `JSON` | only for values never queried or joined relationally |
|
|
14
|
+
| URL | `TEXT` | not `STRING(n)` — real URLs have no reliable length bound |
|
|
15
|
+
| Long content (article body, description) | `TEXT('medium')` (MEDIUMTEXT) | size the column to the content |
|
|
16
|
+
| Datetime | `DATE(3)` (UTC) | [datetimes.md](./datetimes.md) |
|
|
17
|
+
| Status / category | master-table key column | [master-tables.md](./master-tables.md) |
|
|
18
|
+
|
|
19
|
+
- **Why `JSON` only for truly dynamic data**: `JSON` is the right home for a value whose structure
|
|
20
|
+
varies per row and is never the target of a relational query (a settings blob, a captured
|
|
21
|
+
third-party payload). It is the **wrong** home for data that has a fixed shape and relationships —
|
|
22
|
+
stuffing normalizable rows into a `JSON` column hides them from joins, indexes, and constraints
|
|
23
|
+
and directly violates the
|
|
24
|
+
[grand principle](../SKILL.md#grand-principle-the-database-holds-canonical-normalized-truth).
|
|
25
|
+
Normalize relational facts into tables; reserve `JSON` for the genuinely schemaless.
|
|
26
|
+
- **Why URL as `TEXT`**: URLs (signed storage links, tracking-laden redirects) routinely exceed any
|
|
27
|
+
`STRING(n)` you would guess, and a too-short limit truncates silently and corrupts the reference.
|
|
28
|
+
`TEXT` removes the guess.
|
|
29
|
+
- **Why long content as `TEXT('medium')`**: plain `TEXT` can be too small for real article bodies;
|
|
30
|
+
choose the width from the expected content rather than discovering the ceiling in production.
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
-- Good: type matches the data's shape
|
|
34
|
+
settings_json JSON -- per-row dynamic structure, never queried relationally
|
|
35
|
+
avatar_url TEXT -- unbounded in practice
|
|
36
|
+
body TEXT('medium') -- long article content
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
-- Avoid: normalizable relations hidden inside JSON, and a length-capped URL
|
|
41
|
+
tags_json JSON -- should be a tags table + join (queryable, constrained)
|
|
42
|
+
avatar_url STRING(255) -- silently truncates a long signed URL
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Default integer columns to INTEGER / BIGINT; use SMALLINT only with a specific reason
|
|
46
|
+
|
|
47
|
+
For an integer column, default to `INTEGER` (and `BIGINT` for ids and anything that accumulates over
|
|
48
|
+
the table's life). Do **not** reach for `SMALLINT` (or `TINYINT`) to "save space" unless there is a
|
|
49
|
+
**specific, permanent bound** on the value that guarantees it can never outgrow the narrow range.
|
|
50
|
+
|
|
51
|
+
- **Why**: the storage a narrower integer saves is negligible (a few bytes per row), but the
|
|
52
|
+
overflow it invites is not. A column sized to today's guessed range silently caps out when the
|
|
53
|
+
data grows past it (`SMALLINT` tops out at 32767 signed), and widening it afterwards is an
|
|
54
|
+
`ALTER TABLE` on a live table. Ranges almost always grow beyond the original estimate — the same
|
|
55
|
+
reasoning that discourages `ENUM` in [master-tables.md](./master-tables.md). Defaulting to
|
|
56
|
+
`INTEGER` removes the guess; `BIGINT` is already the id convention (`hor-sequelize-migration`).
|
|
57
|
+
- **Exception**: use `SMALLINT` only when the domain is **inherently and permanently bounded** (a
|
|
58
|
+
value that is by definition 0–100, a fixed small code set) *and* the narrower type usefully
|
|
59
|
+
documents that bound. That is a reason, not a micro-optimization — the default remains `INTEGER`.
|
|
60
|
+
|
|
61
|
+
```
|
|
62
|
+
-- Good: default width; ids and counters never run out of range
|
|
63
|
+
quantity INTEGER
|
|
64
|
+
CustomerId BIGINT -- id convention
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
```
|
|
68
|
+
-- Avoid: narrowed "to save space" — overflows once the count passes 32767
|
|
69
|
+
view_count SMALLINT -- silently caps; widening later is an ALTER on a live table
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Keep files out of the database; store a reference
|
|
73
|
+
|
|
74
|
+
Never store a file's bytes in the database. Put the file in **external object storage** (S3, GCS,
|
|
75
|
+
etc.) and keep only a **reference** in the DB — the storage key or URL, as `TEXT` (above).
|
|
76
|
+
|
|
77
|
+
- **Why**: file bytes are large and volatile and are not relational truth (the
|
|
78
|
+
[grand principle](../SKILL.md#grand-principle-the-database-holds-canonical-normalized-truth)).
|
|
79
|
+
Storing them in a column bloats the table, slows every backup / replication / dump, and pushes
|
|
80
|
+
binary delivery through the app tier. A reference keeps the canonical tables small and lets the
|
|
81
|
+
storage service (and a CDN) do what it is good at; the DB stays the index of *where* the file is,
|
|
82
|
+
not the file.
|
|
83
|
+
|
|
84
|
+
```
|
|
85
|
+
-- Good: the DB records where the file lives, not the file
|
|
86
|
+
documents (id, OwnerId, storage_key TEXT, content_type, byte_size, uploaded_at)
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
```
|
|
90
|
+
-- Avoid: binary content in the row
|
|
91
|
+
documents (id, OwnerId, file_blob BLOB) -- bloats backups, slows replication, wrong tier for delivery
|
|
92
|
+
```
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Datetimes (business time vs audit time, UTC, precision)
|
|
2
|
+
|
|
3
|
+
How to model time columns: which datetimes are the framework's and which are the business's, and
|
|
4
|
+
how every datetime is stored. Referenced from [SKILL.md](../SKILL.md). The physical `DATE(3)` column
|
|
5
|
+
is written per `hor-sequelize-migration`; the model side per `hor-sequelize-model`.
|
|
6
|
+
|
|
7
|
+
## Separate business datetimes from the ORM's audit timestamps
|
|
8
|
+
|
|
9
|
+
`created_at` / `updated_at` / `deleted_at` are **audit columns managed by the ORM** — the
|
|
10
|
+
application does **not** read or write them. When business logic needs a creation / update /
|
|
11
|
+
registration time to display or to reason about, add a **dedicated, well-named column**:
|
|
12
|
+
`generated_at`, `modified_at`, `registered_at`, etc. (`DATE(3)`, per the UTC rule below, named per
|
|
13
|
+
the `_at` / `_on` rule below).
|
|
14
|
+
|
|
15
|
+
- **Why**: the audit columns' timing is not an operational guarantee — a data backfill during a
|
|
16
|
+
migration rewrites `updated_at` without any business event happening, and the framework, not your
|
|
17
|
+
code, supplies their values. Depending on them for business meaning couples your logic to
|
|
18
|
+
framework operations and breaks silently on the next migration. A dedicated column states its
|
|
19
|
+
intent in its name and is safe to read, write, sort, and expose.
|
|
20
|
+
- This is the same split enforced from the schema side by `hor-sequelize-model` (do not put timestamp
|
|
21
|
+
columns in model attributes) and `hor-sequelize-migration` (timestamps come from the shared
|
|
22
|
+
`...factory.TIMESTAMPS` preset). This skill decides *whether you need a business time column at
|
|
23
|
+
all*; those skills declare it.
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
-- Good: audit columns are the framework's; business time is its own named column
|
|
27
|
+
articles (id, title, registered_at, created_at, updated_at)
|
|
28
|
+
-- ^ business: when the author registered it (app reads/writes)
|
|
29
|
+
-- ^ audit: framework-managed (app never touches)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
-- Avoid: reusing created_at as "registered at" for display
|
|
34
|
+
articles (id, title, created_at) -- a migration backfill silently changes the displayed date
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Suffix a datetime column `_at`, a date-only column `_on`
|
|
38
|
+
|
|
39
|
+
A column that carries a **time of day** ends with `_at` (`modified_at`, `trashed_at`,
|
|
40
|
+
`expired_at`). A column whose meaning stops at the **calendar date** ends with `_on` (`billed_on`,
|
|
41
|
+
`due_on`). A value that has a range is **two columns**, each keeping the suffix — `modified_at_from`
|
|
42
|
+
and `modified_at_to`, never one column carrying both ends.
|
|
43
|
+
|
|
44
|
+
- **Why**: the suffix is the only place a column states its granularity. Without it (`modified_from`)
|
|
45
|
+
every reader must open the migration to learn whether a time component exists, and a date-only
|
|
46
|
+
value compared against an instant is off by up to a day — a bug that only surfaces near midnight.
|
|
47
|
+
The same name travels unchanged into the model attribute and the SDL field, so one rename covers
|
|
48
|
+
all three layers.
|
|
49
|
+
- `_from` / `_to` mark **the two ends of a range**. A single column meaning "in effect from this
|
|
50
|
+
moment" is not a range end: name it for the instant it holds — `effective_at`, not
|
|
51
|
+
`effective_from`.
|
|
52
|
+
- This is the column-side form of the shared naming convention's `At` / `On` rule; the model
|
|
53
|
+
attribute and the GraphQL field carry the camelCase form of the same name.
|
|
54
|
+
|
|
55
|
+
```
|
|
56
|
+
-- Good: granularity is in the name; a range is two columns
|
|
57
|
+
files (id, modified_at, trashed_at, ...) -- instants
|
|
58
|
+
invoices (id, billed_on, due_on, ...) -- calendar dates
|
|
59
|
+
-- a search filter over modified_at spans two columns / two inputs:
|
|
60
|
+
-- modified_at_from, modified_at_to
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
```
|
|
64
|
+
-- Avoid: granularity unstated, or a single instant named as a range end
|
|
65
|
+
files (id, modified, ...) -- date or instant? open the migration to find out
|
|
66
|
+
invoices (id, billed_at, ...) -- carries a time of day the business never means
|
|
67
|
+
price_tables (id, effective_from, ...) -- one instant wearing a range-end suffix
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Store datetimes as UTC with millisecond precision
|
|
71
|
+
|
|
72
|
+
Every datetime column is **UTC** and typed `DATETIME(3)` (Sequelize `DATE(3)`, written per
|
|
73
|
+
`hor-sequelize-migration`), which keeps time to the **millisecond**. Timezone conversion is the
|
|
74
|
+
**application layer's** responsibility, never the database's.
|
|
75
|
+
|
|
76
|
+
- **Why (UTC)**: a timezone is a *presentational* concern (the
|
|
77
|
+
[grand principle](../SKILL.md#grand-principle-the-database-holds-canonical-normalized-truth)), so
|
|
78
|
+
it does not belong in the canonical store. One unambiguous instant per row means comparisons,
|
|
79
|
+
sorting, and range queries are always correct, and the data survives being served to clients in
|
|
80
|
+
any region or migrated across environments (dev SQLite / staging MySQL / live MariaDB). Mixing
|
|
81
|
+
local times in the DB makes every `ORDER BY time` and `BETWEEN` subtly wrong.
|
|
82
|
+
- **Why (ms precision)**: high-frequency writes within the same second must still order
|
|
83
|
+
deterministically; second precision collapses them and makes "latest row" ambiguous.
|
|
84
|
+
|
|
85
|
+
```
|
|
86
|
+
-- Good: UTC instant, millisecond precision; the app renders it in the user's timezone
|
|
87
|
+
DataTypes.DATE(3) // stored as UTC DATETIME(3)
|
|
88
|
+
```
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# Master tables (status / category sets, and versioned masters)
|
|
2
|
+
|
|
3
|
+
How to model a fixed-ish set of reference values (statuses, categories) as data, and how to version
|
|
4
|
+
a master table that changes over time (a price list). Referenced from [SKILL.md](../SKILL.md). The
|
|
5
|
+
entity's key column is written per `hor-sequelize-migration`; the versioning mixin per `hor-sequelize-model`.
|
|
6
|
+
|
|
7
|
+
## Model status / category with a master table + a key column, not free strings
|
|
8
|
+
|
|
9
|
+
Do not store a status or category as a free-form string on the entity. Create a **master table**
|
|
10
|
+
(`order_statuses`) that defines the set, and give the entity a **key column** that maps to it
|
|
11
|
+
(the FK-like `OrderStatusId`, or a stable string key resolved against the master). Reserve `ENUM`
|
|
12
|
+
for sets that are **clearly closed and small**.
|
|
13
|
+
|
|
14
|
+
- **Why (not strings)**: free strings drift — `'active'`, `'Active'`, `'ACTIVE'` all appear, and a
|
|
15
|
+
status carries no metadata (display label, sort order, an "is active" flag). A master table makes
|
|
16
|
+
the set **queryable, extendable, and consistent**: adding a status is one row, and each status can
|
|
17
|
+
carry the metadata the app needs — a system key, a display name, a display order, an active flag
|
|
18
|
+
([the standard columns below](#give-every-reference-master-table-the-standard-columns)). The status
|
|
19
|
+
is *config data*, presentational and operational — exactly what the
|
|
20
|
+
[grand principle](../SKILL.md#grand-principle-the-database-holds-canonical-normalized-truth) keeps
|
|
21
|
+
out of ad-hoc columns.
|
|
22
|
+
- **Why (ENUM discouraged)**: statuses and categories almost always grow as the project runs, and
|
|
23
|
+
adding an `ENUM` value requires an `ALTER TABLE` migration and still cannot hold metadata. `ENUM`
|
|
24
|
+
is acceptable **only** when the set is genuinely fixed and tiny (a value that will not grow), and
|
|
25
|
+
the metadata of a master table would be overkill. When unsure, use the master table — it is the
|
|
26
|
+
reversible choice.
|
|
27
|
+
- The entity's key column is an **FK-like column** (uppercase-initial `OrderStatusId`, **no DB
|
|
28
|
+
foreign-key constraint**); follow the FK-like-column rule in `hor-sequelize-migration`.
|
|
29
|
+
- **Name the master table for the classification it holds, in the plural: `*_statuses` for a status
|
|
30
|
+
set, `*_categories` for a classification set — never `*_types`.** The entity's key column follows
|
|
31
|
+
the table (`OrderStatusId`, `GranteeCategoryId`; not `GranteeTypeId`). `type` is prohibited as a
|
|
32
|
+
suffix because it collides with the JSDoc type annotation, so a reader cannot tell whether the
|
|
33
|
+
name means a JavaScript type or a business classification; the shared naming convention states
|
|
34
|
+
the rule and its one exception (a word borrowed verbatim from an external standard, such as
|
|
35
|
+
`mimeType`). The name chosen here propagates to the model, the FK-like column, and the GraphQL
|
|
36
|
+
field, so getting it wrong is a three-layer rename later.
|
|
37
|
+
|
|
38
|
+
```
|
|
39
|
+
-- Good: the set of statuses is data in a master table; the entity references it by key
|
|
40
|
+
order_statuses (id, name, display_name, display_order, is_active) -- e.g. (1, 'ordered', 'Ordered', 1, true)
|
|
41
|
+
orders (id, OrderStatusId, ...) -- maps to a master row; add a status = one row
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
```
|
|
45
|
+
-- Avoid: a free string that drifts and carries no metadata
|
|
46
|
+
orders (id, status VARCHAR(32), ...) -- 'active' / 'Active' / 'ACTIVE' accumulate; unqueryable set
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Give every reference master table the standard columns
|
|
50
|
+
|
|
51
|
+
A status / category master table (the enumerable set of reference values from the previous section)
|
|
52
|
+
carries a fixed set of columns beyond `id`: the **system key**, a **user-facing label**, a
|
|
53
|
+
**display order**, and an **active flag**.
|
|
54
|
+
|
|
55
|
+
| Column | Role |
|
|
56
|
+
| --- | --- |
|
|
57
|
+
| `id` | primary key — what the entity's FK-like key column references |
|
|
58
|
+
| `name` | **system key**: the stable identifier the application binds to (`'ordered'`). Machine-facing, unique, never renamed once referenced |
|
|
59
|
+
| `display_name` | **user-facing label** shown in the UI (`'Ordered'`). Free to reword or localize without touching logic |
|
|
60
|
+
| `display_order` | the order in which to present the set in the UI |
|
|
61
|
+
| `is_active` | whether the entry is currently selectable / in use |
|
|
62
|
+
|
|
63
|
+
- **Why split `name` from `display_name`**: application logic must key off a value that never
|
|
64
|
+
changes — the system key `name`. The label users see (`display_name`) is presentational and
|
|
65
|
+
changes often (wording, localization). If code keys off the display label, every rename or
|
|
66
|
+
translation silently breaks a lookup; keeping the two separate lets the UI text move freely while
|
|
67
|
+
logic stays pinned to the stable key. This is the metadata the master-table pattern in the
|
|
68
|
+
previous section exists to hold.
|
|
69
|
+
- **Why `display_order` is a column, not code**: presentation order is data. A column lets the set
|
|
70
|
+
be reordered without a deploy; hardcoding the order in the app couples a presentation tweak to a
|
|
71
|
+
release.
|
|
72
|
+
- **Why `is_active` instead of deleting a row**: retiring a value by flag keeps the row — and
|
|
73
|
+
therefore every historical reference to it (an order pointing at a now-discontinued status) —
|
|
74
|
+
valid. Deleting the master row would orphan those references (there is no DB foreign-key
|
|
75
|
+
constraint to stop it; integrity is the app's job, per `hor-sequelize-migration`). Filter to
|
|
76
|
+
`is_active = true` when offering choices, and keep inactive rows for history.
|
|
77
|
+
- Put a UNIQUE index on `name` — it is the real key of the set; see `hor-sequelize-migration`.
|
|
78
|
+
|
|
79
|
+
```
|
|
80
|
+
-- Good: system key, display label, order, and active flag are all columns
|
|
81
|
+
order_statuses (id, name, display_name, display_order, is_active)
|
|
82
|
+
-- (1, 'ordered', 'Ordered', 1, true)
|
|
83
|
+
-- (2, 'cancelled', 'Cancelled', 2, false) -- retired: kept for history, no longer offered
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Version a master table by splitting the version from its rows
|
|
87
|
+
|
|
88
|
+
A master table that manages **many records as one unit that changes over time** — a price list, a
|
|
89
|
+
rate table, a fee schedule — should be **versioned**. Model it as **two separate tables**: a
|
|
90
|
+
**version table** (one row per published version, carrying the version key, e.g. an
|
|
91
|
+
`effective_at` datetime — the instant the version takes effect, so it is `_at`, not `_from`) and
|
|
92
|
+
the **master-rows table** (the actual records, each belonging to a version). Read the version
|
|
93
|
+
effective at a given time; never edit a published version's rows in
|
|
94
|
+
place — publish a new version instead. This is the versioned form of the master-table idea above.
|
|
95
|
+
|
|
96
|
+
- **Why**: a price list is not one record, it is a *snapshot of many records that must change
|
|
97
|
+
together and stay auditable*. Editing the rows in place destroys the history — you can no longer
|
|
98
|
+
answer "what was the price on date X", and an order placed last month that refers to "the price
|
|
99
|
+
list" silently starts reading this month's numbers. Splitting the **immutable rows of each
|
|
100
|
+
version** from the **"which version applies" axis** keeps every published version intact and makes
|
|
101
|
+
activating a new one a single, reversible act. It is the
|
|
102
|
+
[grand principle](../SKILL.md#grand-principle-the-database-holds-canonical-normalized-truth)
|
|
103
|
+
again: the canonical rows are immutable truth; the current-version selection is a separate concern.
|
|
104
|
+
- **Mechanics**: renchan implements exactly this with `SuiteVersionMixinModel` — the version table
|
|
105
|
+
`hasMany` the master ("suite") rows, `versionKey` (e.g. `effectiveAt`) selects the version in
|
|
106
|
+
effect, and `findCurrentSuite()` reads it. See the mixin catalog in `hor-sequelize-model`.
|
|
107
|
+
|
|
108
|
+
```
|
|
109
|
+
-- Good: the version and its rows are separate tables; a new version is a new set of rows
|
|
110
|
+
price_tables (id, effective_at, ...) -- version table (one row per version)
|
|
111
|
+
price_table_rows (id, PriceTableId, product_key, amount, ...) -- master rows, immutable per version
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
```
|
|
115
|
+
-- Avoid: one flat table edited in place
|
|
116
|
+
price_list (id, product_key, amount) -- no history; "which price applied when" is unanswerable
|
|
117
|
+
```
|