Skip to content

Commit 24cc61f

Browse files
fix(driver-sql): distinct and aggregate group keys present a text boolean as find() does (#35332)
Fixes #34974 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么**:SQLite 上布尔/开关字段在 `distinct()` 和聚合分组键里,存储的文本 `'0'` / `'false'` 现在显示为 `false`,`'1'` / `'true'` 显示为 `true`,与记录读取(`find()`)完全一致;用的是记录读取同一个函数,不是另写一套规则。 - **为什么改**:此前这两个出口用 `Boolean(value)`,文本 `'0'` 会被当成 `true`。对于由文本字段改成布尔字段的列(SQLite 保留 TEXT 亲和性),所有未勾选的行在仪表盘分组里都会算进 `true` 桶,`distinct` 也只答 `[true]`。 - **风险与回滚**:只影响 SQLite / MySQL / Oracle 上布尔字段的 distinct 和分组键显示;数字与布尔值的显示不变,其他文本照旧。回滚即还原一行代码,无数据改动。 - **先看**:`packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts`(`presentReadValue` 的 `'boolean'` 分支)、`packages/drivers/driver-sql/src/sql-driver-sqlite-serialisation.ts`(`presentStoredBoolean` 改为导出)、`packages/drivers/driver-sql/src/sql-driver-34974-boolean-read-presenter.test.ts`。 - **两分钟验证**:`pnpm --filter @objectstack/driver-sql exec vitest run src/sql-driver-34974-boolean-read-presenter.test.ts`,预期 10 个测试全部通过。 - **需要你做的**:无,席位落地。 ## What changes - `sql-driver-filter-helpers.ts`: `presentReadValue`'s `'boolean'` arm calls `presentStoredBoolean`, the function `formatOutput` applies to a `find()` row (#34916). `0` / `'0'` / `'false'` / `false` present as `false`; `1` / `'1'` / `'true'` / `true` as `true`; any other value keeps the `Boolean(value)` reading it had. This makes the class docblock's contract true again: one presenter per kind, the function `formatOutput` itself calls, never a re-derivation. - `sql-driver-sqlite-serialisation.ts`: `presentStoredBoolean` gains `export` and one docblock sentence naming its second caller. Nothing else in the file moves. - Both doors are covered: `distinct()` presents through `presentReadValue` directly, and `aggregate()` group keys (plain and aliased) through `presentReadColumns`, which calls `presentReadValue`. `min` / `max` / `sum` / `avg` over a boolean still skip the boolean kind and answer a number, as the #11635 ruling says. - `sql-driver-34916-boolean-text-read.test.ts`: the `[#34973]` groupBy pin's "before the convergence" half asserted the defect this card fixes (the text `'false'` group presenting as `true`). It now asserts that group presents as `false`. The after-convergence half is unchanged. - Root changeset, `@objectstack/driver-sql` patch. ## Tests New file `packages/drivers/driver-sql/src/sql-driver-34974-boolean-read-presenter.test.ts`, 10 tests on two columns: - **INTEGER column** (created by the driver, legacy text `'true'` / `'false'` written past the driver, not yet converged): fixture storage types, `find()` as the reference, `distinct()` answers `[false, true]`, group key and aliased group key present the text `'false'` as `false`. - **TEXT-affinity column** (raw `flag text` column, legacy `'false'` / `'true'` plus a `'0'`, then a boot): the fixture shows the boot leaves every cell as the text `'0'` / `'1'`; `find()` as the reference; `distinct()` answers `[false, true]`; group key and aliased group key count `[[false, 3], [true, 1]]`. <details><summary>Reading first: the TEXT-affinity case live on SQLite, before the fix (origin/main de8d549)</summary> The new file run against the unfixed presenter: 6 failed, 4 passed. The fixture and `find()` pins pass, and every `distinct` / group-key pin fails: ``` TEXT-affinity distinct(): expected [ true ] to deeply equal [ false, true ] TEXT-affinity group key: expected [ [ true, 3 ], [ true, 1 ] ] to deeply equal [ [ false, 3 ], [ true, 1 ] ] INTEGER distinct(): expected [ true ] to deeply equal [ false, true ] INTEGER group key: expected [ [ true, 1 ], [ true, 1 ], …(1) ] to deeply equal [ [ false, 1 ], [ true, 1 ], …(1) ] ``` </details> <details><summary>Ablation (one, on the committed fix)</summary> `node scripts/ablation-replace.mjs` swapped `return presentStoredBoolean(value);` back to `return Boolean(value);` in `sql-driver-filter-helpers.ts`: anchor x1 to x0, blob `6ec738601bee` to `77d0e0a57de7`. Result: the new file goes 6 failed / 4 passed, the same six pins as the reading above. Restore: blob back to `6ec738601bee`, equal to HEAD, and `git diff HEAD` empty. The test imports `./sql-driver.js` from `src`, so no `dist` rebuild was involved. </details> <details><summary>Package suite</summary> - `pnpm --filter @objectstack/driver-sql test`: Test Files 264 passed, 13 skipped (277); Tests 4397 passed, 257 skipped (4654). - `pnpm --filter @objectstack/driver-sql typecheck`: exit 0. `tsc --listFiles` includes the new test file (1 hit). </details> ## Acceptance notes - **Premise check:** `readPresentationKind` already returned `'boolean'` for a declared boolean on SQLite / MySQL / Oracle, so the card body's "no boolean kind" was stale. The live defect was the `Boolean(value)` arm, as the triage widening said. - **Boot convergence (#35076) does not remove the case.** On a TEXT-affinity column the convergence writes `0` / `1` for a legacy `'false'` / `'true'`, and the affinity stores that as the text `'0'` / `'1'`. It leaves the text `'0'` / `'1'` in place on purpose, because those already read correctly on a row. So a TEXT-affinity column holds `'0'` after every boot. - **Separate finding, not fixed here:** on SQLite, a field retyped from `text` to `boolean` keeps its `TEXT` column after the boot (`pragma_table_info` reads `TEXT` before and after). The driver's own `create(…, { flag: false })` then stores the text `'0.0'` (better-sqlite3 binds the number as REAL), and `find()` presents it as `true`, along with `distinct()` and group keys. The same column also misses `'0'` rows on `flag = false`. This is out of this card's scope: fixing it means either reading `'0.0'` / `'1.0'` as booleans in the shared presenter, which changes `find()` and adds a new truthiness rule, or converging or rebuilding the column's storage. That is a design choice, so it goes to the seat in the report. ## Verification Local gates and CI check-runs are cited in the os-dev report on the card. `node scripts/pm/overlap-check.mjs --branch=HEAD`: clean, exit 0. --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3819afe commit 24cc61f

5 files changed

Lines changed: 169 additions & 4 deletions
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/driver-sql': patch
3+
---
4+
5+
fix(driver-sql): `distinct()` and aggregate group keys read a stored text `'0'` / `'false'` boolean as `false`, as `find()` does
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A declared `Field.boolean` / `Field.toggle` column can hold the text `'0'`, `'1'`, `'true'` or `'false'` on SQLite: a column whose type changed to boolean without a rebuild keeps TEXT affinity, and rows a boot has not converged yet still hold the legacy text. Record reads presented those values as their boolean, but `distinct()` and an `aggregate()` group key presented them as `Boolean(value)`, so a stored `'0'` or `'false'` showed as `true`. A group-by over a yes/no field then counted un-ticked rows in a `true` bucket, and `distinct()` could answer `[true]` for a column with no ticked row.
11+
12+
Both doors now present a boolean through the same function the record read uses: `0`, `'0'` and `'false'` read as `false`; `1`, `'1'` and `'true'` read as `true`. Any other value reads as it did. Postgres is unchanged, since it stores a real boolean. `min` / `max` / `sum` / `avg` over a boolean still answer a number, as before. No metadata key, value or default changes.

‎packages/drivers/driver-sql/src/sql-driver-34916-boolean-text-read.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,8 +194,9 @@ describe('[#34973] driver-sql — boot converges legacy text booleans to 1 / 0 (
194194
} as DriverQuery)) as Array<{ flag: unknown; n: number }>;
195195
return rows.map((r) => [r.flag, Number(r.n)]).sort((a, b) => String(a[0]).localeCompare(String(b[0])));
196196
};
197-
// Before: four groups, and the text 'false' group presents as true.
198-
expect(await groups()).toEqual([[false, 1], [null, 1], [true, 1], [true, 1], [true, 1]]);
197+
// Before: SQL groups the raw cells apart (five groups); since #34974 each
198+
// presents as find() does, so the text 'false' group reads as false.
199+
expect(await groups()).toEqual([[false, 1], [false, 1], [null, 1], [true, 1], [true, 1]]);
199200
await driver.initObjects([CONV_OBJECT]);
200201
expect(await groups()).toEqual([[false, 2], [null, 1], [true, 2]]);
201202
});
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#34974] `distinct()` and an `aggregate()` group key present a declared
5+
* `Field.boolean` the way `find()` presents it: the stored `0` / `'0'` /
6+
* `'false'` read as `false`, and `1` / `'1'` / `'true'` as `true`.
7+
*
8+
* `presentReadValue`'s `'boolean'` arm was `Boolean(value)`, while the row read
9+
* (`formatOutput`) has read the text spellings as their boolean since #34916.
10+
* On a column with TEXT affinity (one whose type changed to boolean without a
11+
* rebuild) the boot's storage convergence rewrites a legacy `'false'` to `0`,
12+
* which the affinity stores as the text `'0'`, and it leaves a `'0'` alone
13+
* because it already reads as `false` on a row. `Boolean('0')` is `true`, so
14+
* `distinct()` answered `[true]` for a column of un-ticked rows and a group-by
15+
* put every row in a `true` bucket.
16+
*
17+
* Two columns: an INTEGER-form boolean column the driver creates (with the
18+
* pre-#34916 text `'true'` / `'false'` written past the driver, the form a
19+
* boot that has not converged it yet still holds), and a TEXT-affinity column
20+
* after a boot.
21+
*/
22+
23+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
24+
import type { DriverQuery } from '@objectstack/spec/contracts';
25+
import { SqlDriver } from './sql-driver.js';
26+
27+
const INT_TABLE = 'bool_presenter_int_34974';
28+
const TXT_TABLE = 'bool_presenter_txt_34974';
29+
30+
function sqliteDriver(): SqlDriver {
31+
return new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any);
32+
}
33+
34+
/** The group-by answer as `[flag, count]` pairs, sorted by the flag's text. */
35+
async function groupCounts(driver: SqlDriver, table: string, groupBy: DriverQuery['groupBy'], key: string): Promise<Array<[unknown, number]>> {
36+
const rows = (await driver.aggregate(table, {
37+
groupBy,
38+
aggregations: [{ function: 'count', field: 'id', alias: 'n' }],
39+
} as DriverQuery)) as Array<Record<string, unknown>>;
40+
return rows
41+
.map((r): [unknown, number] => [r[key], Number(r.n)])
42+
.sort((a, b) => String(a[0]).localeCompare(String(b[0])));
43+
}
44+
45+
describe('[#34974] driver-sql — distinct and aggregate present an INTEGER boolean column as find() does (sqlite)', () => {
46+
let driver: SqlDriver;
47+
48+
beforeAll(async () => {
49+
driver = sqliteDriver();
50+
await driver.initObjects([{ name: INT_TABLE, fields: { label: { type: 'string' }, flag: { type: 'boolean' } } }]);
51+
const knex = (driver as any).knex;
52+
// Written past the driver, after the table was created: the convergence
53+
// has not seen these rows, so the text spellings are still text.
54+
await knex(INT_TABLE).insert([
55+
{ id: 'int_one', label: 'int_one', flag: 1 },
56+
{ id: 'text_true', label: 'text_true', flag: 'true' },
57+
{ id: 'text_false', label: 'text_false', flag: 'false' },
58+
]);
59+
});
60+
61+
afterAll(async () => {
62+
await driver.disconnect();
63+
});
64+
65+
it('the fixture: the column holds the integer 1 and the text true / false', async () => {
66+
const rows = await (driver as any).knex.raw(`select id, typeof(flag) as t from ${INT_TABLE} order by id`);
67+
expect(Object.fromEntries(rows.map((r: any) => [r.id, r.t]))).toEqual({ int_one: 'integer', text_false: 'text', text_true: 'text' });
68+
});
69+
70+
it('find() is the reference: the text false reads as false', async () => {
71+
const rows = (await driver.find(INT_TABLE, { orderBy: [{ field: 'id', order: 'asc' }] } as DriverQuery)) as any[];
72+
expect(rows.map((r) => [r.id, r.flag])).toEqual([['int_one', true], ['text_false', false], ['text_true', true]]);
73+
});
74+
75+
it('distinct() answers false and true, not true alone', async () => {
76+
const values = await driver.distinct(INT_TABLE, 'flag');
77+
expect([...values].sort()).toEqual([false, true]);
78+
});
79+
80+
it('an aggregate group key presents the text false as false', async () => {
81+
// The stored values stay three groups (SQL groups the raw cells); each presents as find() does.
82+
expect(await groupCounts(driver, INT_TABLE, ['flag'], 'flag')).toEqual([[false, 1], [true, 1], [true, 1]]);
83+
});
84+
85+
it('an aliased group key presents the same way', async () => {
86+
expect(await groupCounts(driver, INT_TABLE, [{ field: 'flag', alias: 'ticked' }] as any, 'ticked'))
87+
.toEqual([[false, 1], [true, 1], [true, 1]]);
88+
});
89+
});
90+
91+
describe('[#34974] driver-sql — distinct and aggregate present a TEXT-affinity boolean column as find() does (sqlite)', () => {
92+
let driver: SqlDriver;
93+
94+
beforeAll(async () => {
95+
driver = sqliteDriver();
96+
const knex = (driver as any).knex;
97+
// A column whose type changed to boolean without a rebuild keeps TEXT
98+
// affinity (a `text` field retyped to `boolean` boots onto the same column).
99+
await knex.raw(`create table ${TXT_TABLE} (id varchar(255) primary key, label varchar(255), flag text)`);
100+
await knex(TXT_TABLE).insert([
101+
{ id: 'canon_zero', label: 'canon_zero', flag: '0' },
102+
{ id: 'legacy_false_a', label: 'legacy_false_a', flag: 'false' },
103+
{ id: 'legacy_false_b', label: 'legacy_false_b', flag: 'false' },
104+
{ id: 'legacy_true', label: 'legacy_true', flag: 'true' },
105+
]);
106+
// The boot: the storage convergence rewrites the legacy text to `1` / `0`,
107+
// which this affinity stores as the text '1' / '0'.
108+
await driver.initObjects([{ name: TXT_TABLE, fields: { label: { type: 'string' }, flag: { type: 'boolean' } } }]);
109+
});
110+
111+
afterAll(async () => {
112+
await driver.disconnect();
113+
});
114+
115+
it('the fixture: after the boot, every cell is the text 0 or 1', async () => {
116+
const rows = await (driver as any).knex.raw(`select id, flag, typeof(flag) as t from ${TXT_TABLE} order by id`);
117+
expect(rows.map((r: any) => [r.id, r.flag, r.t])).toEqual([
118+
['canon_zero', '0', 'text'],
119+
['legacy_false_a', '0', 'text'],
120+
['legacy_false_b', '0', 'text'],
121+
['legacy_true', '1', 'text'],
122+
]);
123+
});
124+
125+
it('find() is the reference: the text 0 reads as false', async () => {
126+
const rows = (await driver.find(TXT_TABLE, { orderBy: [{ field: 'id', order: 'asc' }] } as DriverQuery)) as any[];
127+
expect(rows.map((r) => [r.id, r.flag])).toEqual([
128+
['canon_zero', false], ['legacy_false_a', false], ['legacy_false_b', false], ['legacy_true', true],
129+
]);
130+
});
131+
132+
it('distinct() answers false and true, not true alone', async () => {
133+
const values = await driver.distinct(TXT_TABLE, 'flag');
134+
expect([...values].sort()).toEqual([false, true]);
135+
});
136+
137+
it('an aggregate group key counts three false and one true', async () => {
138+
expect(await groupCounts(driver, TXT_TABLE, ['flag'], 'flag')).toEqual([[false, 3], [true, 1]]);
139+
});
140+
141+
it('an aliased group key presents the same way', async () => {
142+
expect(await groupCounts(driver, TXT_TABLE, [{ field: 'flag', alias: 'ticked' }] as any, 'ticked'))
143+
.toEqual([[false, 3], [true, 1]]);
144+
});
145+
});

‎packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import { JSON_COLUMN_INCOMPATIBLE_OPERATORS, findMisplacedReadableIds, presentAs
4545
import type { JsonColumnFieldClass } from '@objectstack/core';
4646
import { StorageNameMapping } from '@objectstack/spec/system';
4747
import { emitBalancedGroup } from './sql-driver-balanced-group.js';
48+
import { presentStoredBoolean } from './sql-driver-sqlite-serialisation.js';
4849
import type { Knex } from 'knex';
4950
import {
5051
AUDIT_TIMESTAMP_COLUMNS, CROSS_FIELD_COMPARISON_OPERATORS, SQLITE_TIME_EXPR_REFS, TEXT_OPERATORS,
@@ -331,7 +332,10 @@ export class FilterHelpersFacet {
331332
// `distinct()` — the divergence the conformance file's §D pins closed.
332333
return presentAuditTimestampOutput(value);
333334
case 'boolean':
334-
return Boolean(value);
335+
// [#34974] The presenter `formatOutput` applies to a `find()` row, so
336+
// the text `'0'` / `'false'` a TEXT-affinity or unconverted column
337+
// holds presents as `false` here too, never `Boolean('0')`.
338+
return presentStoredBoolean(value);
335339
case 'number':
336340
// [#20889] The presenter lives in `@objectstack/core`, beside
337341
// `AGGREGATE_ANSWER_KIND`, so the analytics native-SQL face presents

‎packages/drivers/driver-sql/src/sql-driver-sqlite-serialisation.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,11 @@ import { isDateOnInstantColumn, utcMidnightOfDay } from './date-on-instant-colum
5353
* that arm admits reached a SQLite column as text (the console's inline grid
5454
* sent them), and `Boolean('false')` presented an un-ticked row as `true`.
5555
* Any other string keeps the `Boolean(value)` reading it had.
56+
*
57+
* [#34974] `presentReadValue`'s `'boolean'` arm calls this same function, so
58+
* `distinct()` and an `aggregate()` group key read a stored value as `find()` does.
5659
*/
57-
function presentStoredBoolean(value: unknown): boolean {
60+
export function presentStoredBoolean(value: unknown): boolean {
5861
if (value === 'false' || value === '0') return false;
5962
if (value === 'true' || value === '1') return true;
6063
return Boolean(value);

0 commit comments

Comments
 (0)