dynamo-bao 0.4.2 → 0.6.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/README.md +5 -4
- package/bin/bao-rebuild-search-text.js +62 -0
- package/bin/codegen.js +5 -31
- package/bin/dynamo-bao-update-table.js +37 -0
- package/bin/generators/model.js +21 -3
- package/bin/lib/create-table-params.js +5 -0
- package/bin/lib/process-models.js +133 -0
- package/package.json +3 -2
- package/src/constants.js +16 -1
- package/src/filter-expression.js +45 -5
- package/src/mixins/mutation-mixin.js +17 -0
- package/src/mixins/validation-mixin.js +34 -0
- package/src/model-manager.js +11 -0
- package/src/model.js +561 -14
- package/src/utils/search-text.js +419 -0
package/README.md
CHANGED
|
@@ -24,6 +24,7 @@ DynamoBao is the tool I wish I had when I started.
|
|
|
24
24
|
- Return total read/write consumed capacity (even when multiple operations were performed)
|
|
25
25
|
- Request-scoped capacity aggregation for usage metering and billing
|
|
26
26
|
- Easily iterate over all items in a model for batch processing or migrations
|
|
27
|
+
- Declarative substring search across iterable models with parallel cross-bucket fan-out (`searchAll`/`searchBucket`)
|
|
27
28
|
- ESM (ECMAScript Modules) support for modern JavaScript projects
|
|
28
29
|
- StringSetField for storing sets of strings with efficient diffing on save
|
|
29
30
|
|
|
@@ -319,7 +320,7 @@ app.use(async (req, res, next) => {
|
|
|
319
320
|
|
|
320
321
|
DynamoBao makes it easy to iterate over all items in a model, which is useful for tasks like data migration, backfills, or reporting.
|
|
321
322
|
|
|
322
|
-
|
|
323
|
+
Iteration is **opt-in** — set `iterable: true` in the model's YAML to enable the dedicated index that backs `iterateAll()`. Iteration adds one GSI write per row mutation, so leaving it off is the safer default; turn it on when you actually need to scan the model.
|
|
323
324
|
|
|
324
325
|
#### Basic Usage
|
|
325
326
|
|
|
@@ -410,15 +411,15 @@ This convenience comes at a cost: every `create`, `update`, or `delete` operatio
|
|
|
410
411
|
|
|
411
412
|
To prevent "hot partitions" on large models, the iteration index is automatically split into 10 "buckets" or partitions. The `iterateAll()` method handles fetching from all buckets seamlessly.
|
|
412
413
|
|
|
413
|
-
**
|
|
414
|
+
**Default**
|
|
414
415
|
|
|
415
|
-
|
|
416
|
+
`iterable` defaults to `false`. To opt in, set it explicitly in the YAML — high-volume models like logging tables can leave it off; models you'll need to scan should set `iterable: true`:
|
|
416
417
|
|
|
417
418
|
```yaml
|
|
418
419
|
models:
|
|
419
420
|
AnalyticsEvent:
|
|
420
421
|
modelPrefix: "ae"
|
|
421
|
-
iterable
|
|
422
|
+
# iterable defaults to false — leave it off for write-heavy logs
|
|
422
423
|
fields:
|
|
423
424
|
# ...
|
|
424
425
|
```
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// Walks every row of a searchable model via iterateAll and re-saves with
|
|
4
|
+
// forceReindex: true so the save-time _searchText computation runs and the
|
|
5
|
+
// row's _searchText attribute is populated. Use after turning a model
|
|
6
|
+
// `searchable: true` on a model with existing data.
|
|
7
|
+
|
|
8
|
+
const resolve = require("./lib/resolve");
|
|
9
|
+
const { initModels, runWithBatchContext } = resolve("src/index.js");
|
|
10
|
+
const { initConfig } = resolve("src/config.js");
|
|
11
|
+
|
|
12
|
+
const modelName = process.argv[2];
|
|
13
|
+
if (!modelName) {
|
|
14
|
+
console.error("Usage: bao-rebuild-search-text <ModelName>");
|
|
15
|
+
process.exit(1);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
(async () => {
|
|
19
|
+
const config = await initConfig();
|
|
20
|
+
const manager = initModels(config);
|
|
21
|
+
let ModelClass;
|
|
22
|
+
try {
|
|
23
|
+
ModelClass = manager.getModel(modelName);
|
|
24
|
+
} catch (err) {
|
|
25
|
+
console.error(`Model "${modelName}" not found.`);
|
|
26
|
+
process.exit(1);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if (!ModelClass.searchable || !ModelClass.searchConfig) {
|
|
30
|
+
console.error(
|
|
31
|
+
`Model "${modelName}" is not configured as searchable. Add a ` +
|
|
32
|
+
`searchable: { fields: [...] } block in YAML and run codegen first.`,
|
|
33
|
+
);
|
|
34
|
+
process.exit(1);
|
|
35
|
+
}
|
|
36
|
+
if (!ModelClass.iterable) {
|
|
37
|
+
console.error(
|
|
38
|
+
`Model "${modelName}" is not iterable. Cannot bulk-rebuild via iterateAll.`,
|
|
39
|
+
);
|
|
40
|
+
process.exit(1);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
console.log(`Rebuilding _searchText for ${modelName}...`);
|
|
44
|
+
let total = 0;
|
|
45
|
+
|
|
46
|
+
await runWithBatchContext(async () => {
|
|
47
|
+
for await (const batch of ModelClass.iterateAll({ batchSize: 50 })) {
|
|
48
|
+
for (const item of batch) {
|
|
49
|
+
await item.save({ forceReindex: true });
|
|
50
|
+
total++;
|
|
51
|
+
if (total % 100 === 0) {
|
|
52
|
+
console.log(` rebuilt ${total} so far...`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
console.log(`Done. Rebuilt _searchText on ${total} ${modelName} item(s).`);
|
|
59
|
+
})().catch((err) => {
|
|
60
|
+
console.error("Error:", err);
|
|
61
|
+
process.exit(1);
|
|
62
|
+
});
|
package/bin/codegen.js
CHANGED
|
@@ -9,6 +9,7 @@ const { createLogger } = require("./utils/scriptLogger");
|
|
|
9
9
|
const resolve = require("./lib/resolve");
|
|
10
10
|
const FieldResolver = resolve("src/fieldResolver");
|
|
11
11
|
const { initConfig } = resolve("src/config");
|
|
12
|
+
const { applyModelDefaults } = require("./lib/process-models");
|
|
12
13
|
|
|
13
14
|
// const __dirname = __dirname;
|
|
14
15
|
|
|
@@ -50,38 +51,11 @@ async function loadModelDefinitions(definitionsPath, fieldResolver) {
|
|
|
50
51
|
}
|
|
51
52
|
}
|
|
52
53
|
|
|
53
|
-
//
|
|
54
|
-
|
|
55
|
-
// Default 'iterable' based on tableType
|
|
56
|
-
if (modelDef.iterable === undefined) {
|
|
57
|
-
if (modelDef.tableType === "mapping") {
|
|
58
|
-
logger.debug(
|
|
59
|
-
`Model "${modelName}" is a mapping table, defaulting 'iterable' to false.`,
|
|
60
|
-
);
|
|
61
|
-
modelDef.iterable = false;
|
|
62
|
-
} else {
|
|
63
|
-
logger.debug(
|
|
64
|
-
`Model "${modelName}" is a standard table, defaulting 'iterable' to true.`,
|
|
65
|
-
);
|
|
66
|
-
modelDef.iterable = true;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
// Default 'iterationBuckets'
|
|
71
|
-
if (modelDef.iterationBuckets === undefined) {
|
|
72
|
-
if (modelDef.iterable) {
|
|
73
|
-
logger.debug(
|
|
74
|
-
`Model "${modelName}" is iterable, defaulting 'iterationBuckets' to 10.`,
|
|
75
|
-
);
|
|
76
|
-
modelDef.iterationBuckets = 10;
|
|
77
|
-
} else {
|
|
78
|
-
logger.debug(
|
|
79
|
-
`Model "${modelName}" is not iterable, defaulting 'iterationBuckets' to 0.`,
|
|
80
|
-
);
|
|
81
|
-
modelDef.iterationBuckets = 0;
|
|
82
|
-
}
|
|
83
|
-
}
|
|
54
|
+
// Apply iterable/iterationBuckets/searchable defaults and validation.
|
|
55
|
+
applyModelDefaults(models);
|
|
84
56
|
|
|
57
|
+
// Handle mapping-table specific shape after defaults are applied.
|
|
58
|
+
for (const [modelName, modelDef] of Object.entries(models)) {
|
|
85
59
|
if (modelDef.mapping) {
|
|
86
60
|
// For mapping tables, merge mapping properties with regular model properties
|
|
87
61
|
models[modelName] = {
|
|
@@ -53,6 +53,8 @@ const EXPECTED_GSIS = [
|
|
|
53
53
|
Projection: { ProjectionType: "ALL" },
|
|
54
54
|
},
|
|
55
55
|
{
|
|
56
|
+
// Legacy iteration index — KEYS_ONLY. The package default still reads
|
|
57
|
+
// through this; existing tables keep working without changes.
|
|
56
58
|
IndexName: "iter_index",
|
|
57
59
|
KeySchema: [
|
|
58
60
|
{ AttributeName: "_iter_pk", KeyType: "HASH" },
|
|
@@ -60,6 +62,22 @@ const EXPECTED_GSIS = [
|
|
|
60
62
|
],
|
|
61
63
|
Projection: { ProjectionType: "KEYS_ONLY" },
|
|
62
64
|
},
|
|
65
|
+
{
|
|
66
|
+
// New search-capable iteration index. INCLUDEs _searchText so
|
|
67
|
+
// searchAll/searchBucket can filter on the GSI without a base read.
|
|
68
|
+
// Adding this index is non-destructive: it costs an extra GSI write per
|
|
69
|
+
// save, but iterateAll continues to use iter_index until the user opts
|
|
70
|
+
// in via `db.iterationIndexName: "iter_search_index"`.
|
|
71
|
+
IndexName: "iter_search_index",
|
|
72
|
+
KeySchema: [
|
|
73
|
+
{ AttributeName: "_iter_pk", KeyType: "HASH" },
|
|
74
|
+
{ AttributeName: "_iter_sk", KeyType: "RANGE" },
|
|
75
|
+
],
|
|
76
|
+
Projection: {
|
|
77
|
+
ProjectionType: "INCLUDE",
|
|
78
|
+
NonKeyAttributes: ["_searchText"],
|
|
79
|
+
},
|
|
80
|
+
},
|
|
63
81
|
];
|
|
64
82
|
|
|
65
83
|
// All attribute definitions that GSIs may reference
|
|
@@ -210,6 +228,25 @@ async function main() {
|
|
|
210
228
|
console.log("Checking GSIs...");
|
|
211
229
|
await checkAndAddMissingGSIs(tableName);
|
|
212
230
|
|
|
231
|
+
// Print next steps for users who just added iter_search_index for the
|
|
232
|
+
// first time. The package default keeps reading through iter_index, so
|
|
233
|
+
// adding the new GSI alone doesn't change runtime behavior — they need to
|
|
234
|
+
// flip the config.
|
|
235
|
+
const desc = await client.send(
|
|
236
|
+
new DescribeTableCommand({ TableName: tableName }),
|
|
237
|
+
);
|
|
238
|
+
const existingIndexNames = (desc.Table.GlobalSecondaryIndexes || []).map(
|
|
239
|
+
(g) => g.IndexName,
|
|
240
|
+
);
|
|
241
|
+
if (existingIndexNames.includes("iter_search_index")) {
|
|
242
|
+
console.log(
|
|
243
|
+
"\nTo enable search:\n" +
|
|
244
|
+
" 1) Set 'db.iterationIndexName: \"iter_search_index\"' in your config.\n" +
|
|
245
|
+
" 2) (If your model has existing rows) run 'bao-rebuild-search-text <ModelName>'.\n" +
|
|
246
|
+
" 3) (Optional, after verification) drop the legacy 'iter_index' GSI.",
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
|
|
213
250
|
// Check and enable TTL
|
|
214
251
|
console.log("\nChecking TTL...");
|
|
215
252
|
await checkAndEnableTTL(tableName);
|
package/bin/generators/model.js
CHANGED
|
@@ -119,9 +119,25 @@ function generateModelClass(
|
|
|
119
119
|
.join("\n")
|
|
120
120
|
: "";
|
|
121
121
|
|
|
122
|
-
// Handle iteration configuration
|
|
122
|
+
// Handle iteration configuration. `??` (not `||`) so a deliberate 0
|
|
123
|
+
// from applyModelDefaults (non-iterable models get iterationBuckets=0)
|
|
124
|
+
// isn't silently bumped back to 100.
|
|
123
125
|
const iterable = modelConfig.iterable === true;
|
|
124
|
-
const iterationBuckets =
|
|
126
|
+
const iterationBuckets =
|
|
127
|
+
modelConfig.iterationBuckets !== undefined &&
|
|
128
|
+
modelConfig.iterationBuckets !== null
|
|
129
|
+
? modelConfig.iterationBuckets
|
|
130
|
+
: 100;
|
|
131
|
+
|
|
132
|
+
// Handle searchable configuration. modelConfig.searchable is either `false`
|
|
133
|
+
// or a fully-validated object (validated by applyModelDefaults in
|
|
134
|
+
// bin/lib/process-models.js).
|
|
135
|
+
const searchable = !!(
|
|
136
|
+
modelConfig.searchable && typeof modelConfig.searchable === "object"
|
|
137
|
+
);
|
|
138
|
+
const searchConfigLiteral = searchable
|
|
139
|
+
? JSON.stringify(modelConfig.searchable)
|
|
140
|
+
: "null";
|
|
125
141
|
|
|
126
142
|
// Always need these
|
|
127
143
|
baseImports.add("PrimaryKeyConfig");
|
|
@@ -231,7 +247,9 @@ class ${modelName} extends BaoModel {
|
|
|
231
247
|
static modelPrefix = '${modelConfig.modelPrefix}';
|
|
232
248
|
static iterable = ${iterable};
|
|
233
249
|
static iterationBuckets = ${iterationBuckets};
|
|
234
|
-
|
|
250
|
+
static searchable = ${searchable};
|
|
251
|
+
static searchConfig = ${searchConfigLiteral};
|
|
252
|
+
|
|
235
253
|
static fields = {
|
|
236
254
|
${fields}
|
|
237
255
|
};
|
|
@@ -62,6 +62,11 @@ const TABLE_PARAMS = {
|
|
|
62
62
|
Projection: { ProjectionType: "ALL" },
|
|
63
63
|
},
|
|
64
64
|
{
|
|
65
|
+
// Legacy iteration index (KEYS_ONLY). To enable search, run
|
|
66
|
+
// `bao-update-table` after package upgrade — it will add
|
|
67
|
+
// `iter_search_index` (INCLUDE projection on _searchText) alongside
|
|
68
|
+
// this one. Then set `db.iterationIndexName: "iter_search_index"` in
|
|
69
|
+
// your config to start using it.
|
|
65
70
|
IndexName: "iter_index",
|
|
66
71
|
KeySchema: [
|
|
67
72
|
{ AttributeName: "_iter_pk", KeyType: "HASH" },
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// Pure function for normalizing and validating parsed model definitions
|
|
2
|
+
// before they hit codegen. Keeps validation testable in isolation and
|
|
3
|
+
// produces clear, model-scoped error messages.
|
|
4
|
+
|
|
5
|
+
const SEARCHABLE_KNOWN_OPTIONS = new Set([
|
|
6
|
+
"fields",
|
|
7
|
+
"caseSensitive",
|
|
8
|
+
"minTermLength",
|
|
9
|
+
"dedupe",
|
|
10
|
+
]);
|
|
11
|
+
|
|
12
|
+
function applyIterableDefaults(modelDef) {
|
|
13
|
+
// Default `iterable` to false. Iteration adds a per-row write to the
|
|
14
|
+
// iter_search_index GSI on every save, doubling write cost — opt-in is
|
|
15
|
+
// safer than opt-out. Mapping tables default to false either way.
|
|
16
|
+
if (modelDef.iterable === undefined) {
|
|
17
|
+
modelDef.iterable = false;
|
|
18
|
+
}
|
|
19
|
+
if (modelDef.iterationBuckets === undefined) {
|
|
20
|
+
modelDef.iterationBuckets = modelDef.iterable ? 10 : 0;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function validateSearchable(modelName, modelDef) {
|
|
25
|
+
const raw = modelDef.searchable;
|
|
26
|
+
|
|
27
|
+
if (raw === undefined || raw === false) {
|
|
28
|
+
modelDef.searchable = false;
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (raw === true) {
|
|
33
|
+
throw new Error(
|
|
34
|
+
`Model "${modelName}": \`searchable: true\` is not supported. ` +
|
|
35
|
+
`Provide an object with \`fields\` listing the StringField names to index, ` +
|
|
36
|
+
`e.g. \`searchable: { fields: [title, body] }\`.`,
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (typeof raw !== "object" || Array.isArray(raw)) {
|
|
41
|
+
throw new Error(
|
|
42
|
+
`Model "${modelName}": \`searchable\` must be either a boolean or an object. Got ${typeof raw}.`,
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
for (const key of Object.keys(raw)) {
|
|
47
|
+
if (!SEARCHABLE_KNOWN_OPTIONS.has(key)) {
|
|
48
|
+
throw new Error(
|
|
49
|
+
`Model "${modelName}": \`searchable\` has unknown option "${key}". ` +
|
|
50
|
+
`Known options: ${Array.from(SEARCHABLE_KNOWN_OPTIONS).join(", ")}.`,
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (!Array.isArray(raw.fields) || raw.fields.length === 0) {
|
|
56
|
+
throw new Error(
|
|
57
|
+
`Model "${modelName}": \`searchable.fields\` must be a non-empty array of field names.`,
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
for (const fieldName of raw.fields) {
|
|
62
|
+
if (typeof fieldName !== "string") {
|
|
63
|
+
throw new Error(
|
|
64
|
+
`Model "${modelName}": \`searchable.fields\` entries must be strings. Got ${typeof fieldName}.`,
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
const fieldDef = modelDef.fields && modelDef.fields[fieldName];
|
|
68
|
+
if (!fieldDef) {
|
|
69
|
+
throw new Error(
|
|
70
|
+
`Model "${modelName}": \`searchable.fields\` references "${fieldName}" but that field is not defined on the model.`,
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
if (fieldDef.type !== "StringField") {
|
|
74
|
+
throw new Error(
|
|
75
|
+
`Model "${modelName}": \`searchable.fields\` entry "${fieldName}" must be a StringField, got ${fieldDef.type}.`,
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (raw.caseSensitive !== undefined && typeof raw.caseSensitive !== "boolean") {
|
|
81
|
+
throw new Error(
|
|
82
|
+
`Model "${modelName}": \`searchable.caseSensitive\` must be a boolean.`,
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (raw.dedupe !== undefined && typeof raw.dedupe !== "boolean") {
|
|
87
|
+
throw new Error(
|
|
88
|
+
`Model "${modelName}": \`searchable.dedupe\` must be a boolean.`,
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (raw.minTermLength !== undefined) {
|
|
93
|
+
const n = raw.minTermLength;
|
|
94
|
+
if (typeof n !== "number" || !Number.isInteger(n) || n < 1) {
|
|
95
|
+
throw new Error(
|
|
96
|
+
`Model "${modelName}": \`searchable.minTermLength\` must be a positive integer.`,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
modelDef.searchable = {
|
|
102
|
+
fields: raw.fields.slice(),
|
|
103
|
+
caseSensitive: raw.caseSensitive === true,
|
|
104
|
+
minTermLength: raw.minTermLength === undefined ? 1 : raw.minTermLength,
|
|
105
|
+
dedupe: raw.dedupe === true,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function applyModelDefaults(models) {
|
|
110
|
+
for (const [modelName, modelDef] of Object.entries(models)) {
|
|
111
|
+
applyIterableDefaults(modelDef);
|
|
112
|
+
validateSearchable(modelName, modelDef);
|
|
113
|
+
// searchable on a non-iterable model is a supported combination
|
|
114
|
+
// (partition-scoped _searchText filtering), but searchAll/searchBucket
|
|
115
|
+
// require iteration buckets and will throw at runtime. Warn so users
|
|
116
|
+
// who forgot to opt into iteration find out at codegen, not in prod.
|
|
117
|
+
if (
|
|
118
|
+
modelDef.searchable &&
|
|
119
|
+
typeof modelDef.searchable === "object" &&
|
|
120
|
+
!modelDef.iterable
|
|
121
|
+
) {
|
|
122
|
+
console.warn(
|
|
123
|
+
`[dynamo-bao] Model "${modelName}" has \`searchable\` configured but ` +
|
|
124
|
+
`\`iterable\` is false. _searchText will populate and filter on it ` +
|
|
125
|
+
`via the standard query API works, but searchAll/searchBucket will ` +
|
|
126
|
+
`throw. Set \`iterable: true\` to enable cross-bucket parallel search.`,
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return models;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
module.exports = { applyModelDefaults };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dynamo-bao",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"exports": {
|
|
@@ -58,6 +58,7 @@
|
|
|
58
58
|
"bao-codegen": "./bin/codegen.js",
|
|
59
59
|
"bao-watch": "./bin/watch.js",
|
|
60
60
|
"bao-update-table": "./bin/dynamo-bao-update-table.js",
|
|
61
|
-
"bao-delete": "./bin/dynamo-bao-delete-table.js"
|
|
61
|
+
"bao-delete": "./bin/dynamo-bao-delete-table.js",
|
|
62
|
+
"bao-rebuild-search-text": "./bin/bao-rebuild-search-text.js"
|
|
62
63
|
}
|
|
63
64
|
}
|
package/src/constants.js
CHANGED
|
@@ -5,10 +5,21 @@ const GSI_INDEX_ID3 = "gsi3";
|
|
|
5
5
|
const GSI_INDEX_ID4 = "gsi4";
|
|
6
6
|
const GSI_INDEX_ID5 = "gsi5";
|
|
7
7
|
|
|
8
|
-
// Constants for iteration index
|
|
8
|
+
// Constants for iteration index. The package default is `iter_index` (the
|
|
9
|
+
// legacy KEYS_ONLY GSI) so an upgrade doesn't break iteration on tables that
|
|
10
|
+
// haven't been migrated yet. To enable search, users add the new
|
|
11
|
+
// `iter_search_index` GSI (via bao-update-table) and set
|
|
12
|
+
// `db.iterationIndexName: "iter_search_index"` in their config — see
|
|
13
|
+
// SEARCH_INDEX_NAME below.
|
|
9
14
|
const ITERATION_INDEX_NAME = "iter_index";
|
|
15
|
+
const SEARCH_INDEX_NAME = "iter_search_index";
|
|
10
16
|
const ITERATION_PK_FIELD = "_iter_pk";
|
|
11
17
|
const ITERATION_SK_FIELD = "_iter_sk";
|
|
18
|
+
const SEARCH_TEXT_FIELD = "_searchText";
|
|
19
|
+
|
|
20
|
+
// Backwards-compatibility alias so older code that imported the legacy name
|
|
21
|
+
// keeps working. Same value as ITERATION_INDEX_NAME.
|
|
22
|
+
const LEGACY_ITERATION_INDEX_NAME = ITERATION_INDEX_NAME;
|
|
12
23
|
|
|
13
24
|
// Constants for unique constraints
|
|
14
25
|
const UNIQUE_CONSTRAINT_ID1 = "_uc1";
|
|
@@ -31,6 +42,7 @@ const SYSTEM_FIELDS = [
|
|
|
31
42
|
"_gsi5_sk",
|
|
32
43
|
"_iter_pk",
|
|
33
44
|
"_iter_sk",
|
|
45
|
+
"_searchText",
|
|
34
46
|
];
|
|
35
47
|
|
|
36
48
|
const UNIQUE_CONSTRAINT_KEY = "_raft_uc";
|
|
@@ -42,8 +54,11 @@ module.exports = {
|
|
|
42
54
|
GSI_INDEX_ID4,
|
|
43
55
|
GSI_INDEX_ID5,
|
|
44
56
|
ITERATION_INDEX_NAME,
|
|
57
|
+
SEARCH_INDEX_NAME,
|
|
45
58
|
ITERATION_PK_FIELD,
|
|
46
59
|
ITERATION_SK_FIELD,
|
|
60
|
+
SEARCH_TEXT_FIELD,
|
|
61
|
+
LEGACY_ITERATION_INDEX_NAME,
|
|
47
62
|
UNIQUE_CONSTRAINT_ID1,
|
|
48
63
|
UNIQUE_CONSTRAINT_ID2,
|
|
49
64
|
UNIQUE_CONSTRAINT_ID3,
|
package/src/filter-expression.js
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
const { defaultLogger: logger } = require("./utils/logger");
|
|
2
2
|
const { QueryError, ValidationError } = require("./exceptions");
|
|
3
|
+
const { SEARCH_TEXT_FIELD } = require("./constants");
|
|
4
|
+
|
|
5
|
+
// System fields that don't appear in `model.fields` but are still allowed
|
|
6
|
+
// targets for FilterExpressions. _searchText is the auto-populated search
|
|
7
|
+
// column on `searchable` models — see src/utils/search-text.js. The values
|
|
8
|
+
// here describe how to convert the user-supplied filter value into the
|
|
9
|
+
// shape stored on the row, since system fields don't have a Field instance
|
|
10
|
+
// with `.toDy()` to do that for us.
|
|
11
|
+
const SYSTEM_FILTERABLE_FIELDS = {
|
|
12
|
+
[SEARCH_TEXT_FIELD]: {
|
|
13
|
+
convertValue(value, model) {
|
|
14
|
+
// Mirror the write-time normalization so user input matches what's
|
|
15
|
+
// stored. `normalizeSearchTerm` is idempotent so callers who already
|
|
16
|
+
// normalized the value pay no penalty for re-running it. Falls back
|
|
17
|
+
// to a plain String() when the model has no searchConfig (e.g. the
|
|
18
|
+
// model is non-searchable but its rows happen to carry the attribute).
|
|
19
|
+
if (model.searchConfig) {
|
|
20
|
+
const { normalizeSearchTerm } = require("./utils/search-text");
|
|
21
|
+
return normalizeSearchTerm(String(value), model.searchConfig);
|
|
22
|
+
}
|
|
23
|
+
return String(value);
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
};
|
|
3
27
|
|
|
4
28
|
/**
|
|
5
29
|
* Supporting class for building DynamoDB filter expressions.
|
|
@@ -34,6 +58,10 @@ class FilterExpressionBuilder {
|
|
|
34
58
|
|
|
35
59
|
// Simplified value conversion - let the field handle it
|
|
36
60
|
convertValue(value, model, fieldName) {
|
|
61
|
+
const systemField = SYSTEM_FILTERABLE_FIELDS[fieldName];
|
|
62
|
+
if (systemField) {
|
|
63
|
+
return systemField.convertValue(value, model);
|
|
64
|
+
}
|
|
37
65
|
const field = model.fields[fieldName];
|
|
38
66
|
return field.toDy(value);
|
|
39
67
|
}
|
|
@@ -65,7 +93,12 @@ class FilterExpressionBuilder {
|
|
|
65
93
|
if (!Array.isArray(value)) {
|
|
66
94
|
throw new ValidationError("$in operator requires an array value");
|
|
67
95
|
}
|
|
68
|
-
|
|
96
|
+
// Run each element through convertValue (same as $eq does) so
|
|
97
|
+
// system fields like _searchText auto-normalize their values and
|
|
98
|
+
// user fields with meaningful toDy() (dates, etc.) get coerced.
|
|
99
|
+
const valueKeys = value.map((v) =>
|
|
100
|
+
this.generateValue(this.convertValue(v, model, fieldName)),
|
|
101
|
+
);
|
|
69
102
|
return `${nameKey} IN (${valueKeys.join(", ")})`;
|
|
70
103
|
case "$exists":
|
|
71
104
|
if (typeof value !== "boolean") {
|
|
@@ -262,10 +295,17 @@ class FilterExpressionBuilder {
|
|
|
262
295
|
continue;
|
|
263
296
|
}
|
|
264
297
|
|
|
265
|
-
//
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
298
|
+
// Allow whitelisted system fields (e.g., _searchText) without
|
|
299
|
+
// requiring a matching entry in model.fields. Operator validation
|
|
300
|
+
// below still runs so bad operators are rejected the same way.
|
|
301
|
+
const isSystemField = !!SYSTEM_FILTERABLE_FIELDS[key];
|
|
302
|
+
|
|
303
|
+
if (!isSystemField) {
|
|
304
|
+
// Validate field exists in model
|
|
305
|
+
const field = model.fields[key];
|
|
306
|
+
if (!field) {
|
|
307
|
+
throw new QueryError(`Unknown field in filter: ${key}`);
|
|
308
|
+
}
|
|
269
309
|
}
|
|
270
310
|
|
|
271
311
|
// Recursively validate nested conditions
|
|
@@ -13,6 +13,8 @@ const {
|
|
|
13
13
|
ConditionalError,
|
|
14
14
|
ValidationError,
|
|
15
15
|
} = require("../exceptions");
|
|
16
|
+
const { computeSearchTextUpdate } = require("../utils/search-text");
|
|
17
|
+
const { SEARCH_TEXT_FIELD } = require("../constants");
|
|
16
18
|
|
|
17
19
|
const MutationMethods = {
|
|
18
20
|
/**
|
|
@@ -480,6 +482,21 @@ const MutationMethods = {
|
|
|
480
482
|
Object.assign(dyUpdatesToSave, iterationKeys);
|
|
481
483
|
}
|
|
482
484
|
|
|
485
|
+
// Compute _searchText if the model is searchable. Returns undefined to
|
|
486
|
+
// skip the write entirely, null to REMOVE, or a string to SET.
|
|
487
|
+
if (this.searchable && this.searchConfig) {
|
|
488
|
+
const searchTextValue = computeSearchTextUpdate({
|
|
489
|
+
searchConfig: this.searchConfig,
|
|
490
|
+
dyUpdatesToSave,
|
|
491
|
+
currentItem,
|
|
492
|
+
isNew,
|
|
493
|
+
forceReindex,
|
|
494
|
+
});
|
|
495
|
+
if (searchTextValue !== undefined) {
|
|
496
|
+
dyUpdatesToSave[SEARCH_TEXT_FIELD] = searchTextValue;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
483
500
|
// Build the update expression first
|
|
484
501
|
const { updateExpression, names, values } = this._buildUpdateExpression(
|
|
485
502
|
dyUpdatesToSave,
|
|
@@ -190,6 +190,40 @@ const ValidationMethods = {
|
|
|
190
190
|
this.iterable = false;
|
|
191
191
|
}
|
|
192
192
|
|
|
193
|
+
// Validate searchable configuration. Catches the case where a model has
|
|
194
|
+
// `searchable: true` but no `searchConfig` (e.g., hand-written class or
|
|
195
|
+
// partially-regenerated codebase) — better to fail loudly at registration
|
|
196
|
+
// than silently skip _searchText computation on every save.
|
|
197
|
+
if (this.searchable === true) {
|
|
198
|
+
if (!this.searchConfig || typeof this.searchConfig !== "object") {
|
|
199
|
+
throw new ConfigurationError(
|
|
200
|
+
`${this.name} has \`searchable: true\` but no \`searchConfig\`. ` +
|
|
201
|
+
`Re-run codegen, or set \`static searchConfig = { fields: [...] }\` ` +
|
|
202
|
+
`on the class.`,
|
|
203
|
+
this.name,
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
if (
|
|
207
|
+
!Array.isArray(this.searchConfig.fields) ||
|
|
208
|
+
this.searchConfig.fields.length === 0
|
|
209
|
+
) {
|
|
210
|
+
throw new ConfigurationError(
|
|
211
|
+
`${this.name} \`searchConfig.fields\` must be a non-empty array.`,
|
|
212
|
+
this.name,
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
for (const fieldName of this.searchConfig.fields) {
|
|
216
|
+
const fieldDef = this.fields[fieldName];
|
|
217
|
+
if (!fieldDef) {
|
|
218
|
+
throw new ConfigurationError(
|
|
219
|
+
`${this.name} \`searchConfig.fields\` references "${fieldName}" but ` +
|
|
220
|
+
`that field is not defined on the model.`,
|
|
221
|
+
this.name,
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
193
227
|
// Validate unique constraints
|
|
194
228
|
const validConstraintIds = [
|
|
195
229
|
UNIQUE_CONSTRAINT_ID1,
|
package/src/model-manager.js
CHANGED
|
@@ -113,6 +113,17 @@ class ModelManager {
|
|
|
113
113
|
return this._tenantId;
|
|
114
114
|
}
|
|
115
115
|
|
|
116
|
+
// Resolved iteration index name. Defaults to "iter_search_index"; users
|
|
117
|
+
// mid-migration can override via config.db.iterationIndexName: "iter_index"
|
|
118
|
+
// to keep iteration on the legacy index. searchAll/searchBucket guard against
|
|
119
|
+
// the legacy value.
|
|
120
|
+
getIterationIndexName() {
|
|
121
|
+
return (
|
|
122
|
+
this._config?.db?.iterationIndexName ||
|
|
123
|
+
require("./constants").ITERATION_INDEX_NAME
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
|
|
116
127
|
// Backward compatibility
|
|
117
128
|
getTestId() {
|
|
118
129
|
return this._tenantId;
|