-
Notifications
You must be signed in to change notification settings - Fork 5
feat(autonumber): date, {field} & per-scope counter reset for autonumber formats #2043
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
3d55c55
feat(autonumber): date, {field} and per-scope counter reset for formats
baozhoutao 0f8786c
fix(autonumber): drop backtracking lookahead in seed scan (ReDoS)
baozhoutao 6b695fd
fix(autonumber): guard {field} interpolation footguns
os-zhuang 9813c42
fix(autonumber): hash-keyed sequence table; clarify scope & width sem…
os-zhuang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| --- | ||
| "@objectstack/spec": minor | ||
| "@objectstack/objectql": minor | ||
| "@objectstack/driver-sql": minor | ||
| --- | ||
|
|
||
| feat(autonumber): date, {field} and per-scope counter reset for autonumber formats | ||
|
|
||
| `autonumberFormat` previously only understood a single `{0000}` sequence slot — | ||
| everything else was a fixed literal prefix on one global counter. Real MES/eHR | ||
| record numbers need three more token classes, so the format is now tokenized by a | ||
| shared pure renderer in `@objectstack/spec` (`parseAutonumberFormat` / | ||
| `renderAutonumber`) that the engine fallback and the SQL driver both call, so they | ||
| emit byte-identical numbers (#1603 parity): | ||
|
|
||
| - **Date tokens** — `{YYYY}` `{YY}` `{MM}` `{DD}` `{YYYYMMDD}` resolve the calendar | ||
| day in the request's **business timezone** (`ExecutionContext.timezone`, ADR-0053; | ||
| UTC fallback), threaded through the new `DriverOptions.timezone`. | ||
| - **`{field}` interpolation** — `{section}{island_zone}{000}` substitutes record | ||
| field values into the prefix. | ||
| - **Per-scope counter reset** — the counter's scope is the rendered prefix *before* | ||
| the sequence slot, so `AD{YYYYMMDD}{0000}` resets daily, `{section}{island_zone}{000}` | ||
| numbers per group, and `{plan_no}{000}` numbers per parent — all from one | ||
| mechanism, no separate reset config. | ||
|
|
||
| Fixed-prefix formats like `CASE-{0000}` render an empty scope and keep their single | ||
| global counter, so existing sequences are unchanged. The persistent | ||
| `_objectstack_sequences` table gains a `scope` column (PK widened to | ||
| `object, tenant_id, field, scope`); deployments with the legacy 3-column table are | ||
| migrated in place on first use, carrying existing counters to `scope=''`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
165 changes: 165 additions & 0 deletions
165
packages/plugins/driver-sql/src/sql-driver-autonumber-tokens.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,165 @@ | ||
| // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. | ||
|
|
||
| import { describe, it, expect, beforeEach, afterEach } from 'vitest'; | ||
| import { SqlDriver } from '../src/index.js'; | ||
|
|
||
| /** | ||
| * Auto-number format tokens — date interpolation, {field} interpolation, and | ||
| * per-scope counter reset. These are the MES/eHR record-number shapes | ||
| * (`AD{YYYYMMDD}{0000}`, `{section}{island_zone}{000}`, `{plan_no}{000}`) that | ||
| * the persistent `_objectstack_sequences` table now backs natively. | ||
| */ | ||
|
|
||
| /** Today's date in UTC as YYYYMMDD — matches the driver's renderer with tz=UTC. */ | ||
| function utcYmd(): string { | ||
| const p = new Intl.DateTimeFormat('en-CA', { | ||
| timeZone: 'UTC', | ||
| year: 'numeric', | ||
| month: '2-digit', | ||
| day: '2-digit', | ||
| }).formatToParts(new Date()); | ||
| const y = p.find((x) => x.type === 'year')!.value; | ||
| const m = p.find((x) => x.type === 'month')!.value; | ||
| const d = p.find((x) => x.type === 'day')!.value; | ||
| return `${y}${m}${d}`; | ||
| } | ||
|
|
||
| describe('SqlDriver auto_number format tokens', () => { | ||
| let driver: SqlDriver; | ||
|
|
||
| beforeEach(() => { | ||
| driver = new SqlDriver({ | ||
| client: 'better-sqlite3', | ||
| connection: { filename: ':memory:' }, | ||
| useNullAsDefault: true, | ||
| }); | ||
| }); | ||
|
|
||
| afterEach(async () => { | ||
| await driver.disconnect(); | ||
| }); | ||
|
|
||
| it('renders {YYYYMMDD} date tokens in the business timezone', async () => { | ||
| await driver.initObjects([ | ||
| { name: 'andon', fields: { andon_no: { type: 'autonumber', format: 'AD{YYYYMMDD}{0000}' } } }, | ||
| ]); | ||
| const r1 = await driver.create('andon', {}, { timezone: 'UTC' } as any); | ||
| const r2 = await driver.create('andon', {}, { timezone: 'UTC' } as any); | ||
| expect(r1.andon_no).toBe(`AD${utcYmd()}0001`); | ||
| expect(r2.andon_no).toBe(`AD${utcYmd()}0002`); | ||
| }); | ||
|
|
||
| it('resets the counter per day (prior-day rows do not bleed into today)', async () => { | ||
| await driver.initObjects([ | ||
| { name: 'andon', fields: { andon_no: { type: 'autonumber', format: 'AD{YYYYMMDD}{0000}' } } }, | ||
| ]); | ||
| // A row from a long-past day sits at 0099. Today's counter must ignore it. | ||
| const k = (driver as any).knex; | ||
| await k('andon').insert({ id: 'old', andon_no: 'AD202001010099' }); | ||
|
|
||
| const r = await driver.create('andon', {}, { timezone: 'UTC' } as any); | ||
| expect(r.andon_no).toBe(`AD${utcYmd()}0001`); // fresh scope, not 0100 | ||
| }); | ||
|
|
||
| it('interpolates {field} values and counts independently per group', async () => { | ||
| await driver.initObjects([ | ||
| { | ||
| name: 'task', | ||
| fields: { | ||
| section: { type: 'string' }, | ||
| island_zone: { type: 'string' }, | ||
| task_no: { type: 'autonumber', format: '{section}{island_zone}{000}' }, | ||
| }, | ||
| }, | ||
| ]); | ||
| const a1 = await driver.create('task', { section: 'JYG', island_zone: '1A' }); | ||
| const b1 = await driver.create('task', { section: 'JYG', island_zone: '2B' }); | ||
| const a2 = await driver.create('task', { section: 'JYG', island_zone: '1A' }); | ||
| const b2 = await driver.create('task', { section: 'JYG', island_zone: '2B' }); | ||
|
|
||
| expect(a1.task_no).toBe('JYG1A001'); | ||
| expect(a2.task_no).toBe('JYG1A002'); | ||
| expect(b1.task_no).toBe('JYG2B001'); // a different island resets to 001 | ||
| expect(b2.task_no).toBe('JYG2B002'); | ||
| }); | ||
|
|
||
| it('numbers child records per parent (dispatch order under a plan)', async () => { | ||
| await driver.initObjects([ | ||
| { | ||
| name: 'dispatch_order', | ||
| fields: { | ||
| plan_no: { type: 'string' }, | ||
| order_no: { type: 'autonumber', format: '{plan_no}{000}' }, | ||
| }, | ||
| }, | ||
| ]); | ||
| const p1a = await driver.create('dispatch_order', { plan_no: 'JYG1A1PROD20260617001' }); | ||
| const p2a = await driver.create('dispatch_order', { plan_no: 'JYG1A1PROD20260617002' }); | ||
| const p1b = await driver.create('dispatch_order', { plan_no: 'JYG1A1PROD20260617001' }); | ||
|
|
||
| expect(p1a.order_no).toBe('JYG1A1PROD20260617001001'); | ||
| expect(p1b.order_no).toBe('JYG1A1PROD20260617001002'); | ||
| expect(p2a.order_no).toBe('JYG1A1PROD20260617002001'); | ||
| }); | ||
|
|
||
| it('combines field + date tokens and stays tenant-isolated', async () => { | ||
| await driver.initObjects([ | ||
| { | ||
| name: 'plan', | ||
| fields: { | ||
| organization_id: { type: 'string' }, | ||
| line: { type: 'string' }, | ||
| plan_no: { type: 'autonumber', format: '{line}{YYYYMMDD}{000}' }, | ||
| }, | ||
| }, | ||
| ]); | ||
| const a = await driver.create('plan', { organization_id: 'orgA', line: 'PROD' }, { timezone: 'UTC' } as any); | ||
| const b = await driver.create('plan', { organization_id: 'orgB', line: 'PROD' }, { timezone: 'UTC' } as any); | ||
| const a2 = await driver.create('plan', { organization_id: 'orgA', line: 'PROD' }, { timezone: 'UTC' } as any); | ||
|
|
||
| expect(a.plan_no).toBe(`PROD${utcYmd()}001`); | ||
| expect(a2.plan_no).toBe(`PROD${utcYmd()}002`); | ||
| // Same scope string, different tenant → independent counter. | ||
| expect(b.plan_no).toBe(`PROD${utcYmd()}001`); | ||
| }); | ||
|
|
||
| it('leaves fixed-prefix formats on a single global counter (backward compatible)', async () => { | ||
| await driver.initObjects([ | ||
| { name: 'invoice', fields: { invoice_number: { type: 'autonumber', format: 'INV-{0000}' } } }, | ||
| ]); | ||
| const r1 = await driver.create('invoice', {}); | ||
| const r2 = await driver.create('invoice', {}); | ||
| expect(r1.invoice_number).toBe('INV-0001'); | ||
| expect(r2.invoice_number).toBe('INV-0002'); | ||
| }); | ||
|
|
||
| it('migrates a legacy 3-column _objectstack_sequences table by adding scope', async () => { | ||
| const k = (driver as any).knex; | ||
| // Simulate a deployment whose sequence table predates the `scope` column. | ||
| await k.schema.createTable('_objectstack_sequences', (t: any) => { | ||
| t.string('object').notNullable(); | ||
| t.string('tenant_id').notNullable(); | ||
| t.string('field').notNullable(); | ||
| t.bigInteger('last_value').notNullable().defaultTo(0); | ||
| t.timestamp('updated_at').defaultTo(k.fn.now()); | ||
| t.primary(['object', 'tenant_id', 'field']); | ||
| }); | ||
| await k('_objectstack_sequences').insert({ | ||
| object: 'invoice', | ||
| tenant_id: '__global__', | ||
| field: 'invoice_number', | ||
| last_value: 41, | ||
| }); | ||
|
|
||
| await driver.initObjects([ | ||
| { name: 'invoice', fields: { invoice_number: { type: 'autonumber', format: 'INV-{0000}' } } }, | ||
| ]); | ||
| // First create triggers the lazy table-ensure → in-place migration. | ||
| const r = await driver.create('invoice', {}); | ||
|
|
||
| const cols = await k('_objectstack_sequences').columnInfo(); | ||
| expect(Object.keys(cols)).toContain('scope'); | ||
| // The legacy counter continued rather than restarting. | ||
| expect(r.invoice_number).toBe('INV-0042'); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.