@rebasepro/server-postgres 0.13.1-canary.gc9afce1 → 0.13.1-canary.gca63148
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/dist/PostgresBackendDriver.d.ts +48 -1
- package/dist/{src-CU6WZGYV.js → auth-users-columns-BQttUZE2.js} +587 -33
- package/dist/auth-users-columns-BQttUZE2.js.map +1 -0
- package/dist/{backup-service-CD8o_1Sl.js → backup-service-Bww-Lg0s.js} +2 -2
- package/dist/{backup-service-CD8o_1Sl.js.map → backup-service-Bww-Lg0s.js.map} +1 -1
- package/dist/{ensure-collection-policies-Bck0ky4u.js → ensure-collection-policies-C8H7ig-m.js} +2 -2
- package/dist/{ensure-collection-policies-Bck0ky4u.js.map → ensure-collection-policies-C8H7ig-m.js.map} +1 -1
- package/dist/{ensure-collection-tables-BLIIACla.js → ensure-collection-tables-CyMBc7wo.js} +78 -11
- package/dist/ensure-collection-tables-CyMBc7wo.js.map +1 -0
- package/dist/index.es.js +650 -129
- package/dist/index.es.js.map +1 -1
- package/dist/{policy-CeA1JcxP.js → policy-CPkCqVTz.js} +4 -4
- package/dist/policy-CPkCqVTz.js.map +1 -0
- package/dist/rls-bootstrap-sql-Bpv3nUZo.js +244 -0
- package/dist/rls-bootstrap-sql-Bpv3nUZo.js.map +1 -0
- package/dist/schema/auth-users-columns.d.ts +97 -0
- package/dist/schema/ensure-collection-tables.d.ts +1 -1
- package/dist/schema/rls-bootstrap-sql.d.ts +135 -0
- package/dist/schema/search-column.d.ts +192 -0
- package/dist/security/rls-enforcement.d.ts +53 -2
- package/dist/services/FetchService.d.ts +13 -0
- package/dist/{src-DoU9yPqq.js → src-C_wvdMnl.js} +91 -2
- package/dist/src-C_wvdMnl.js.map +1 -0
- package/dist/utils/drizzle-conditions.d.ts +71 -2
- package/dist/{websocket-B2LsrINK.js → websocket-D0TBU3ia.js} +3 -3
- package/dist/{websocket-B2LsrINK.js.map → websocket-D0TBU3ia.js.map} +1 -1
- package/package.json +8 -7
- package/src/PostgresBackendDriver.ts +165 -3
- package/src/PostgresBootstrapper.ts +41 -2
- package/src/auth/ensure-tables.ts +185 -86
- package/src/cli-helpers.ts +14 -7
- package/src/cli.ts +96 -30
- package/src/data-transformer.ts +18 -0
- package/src/history/ensure-history-table.ts +7 -0
- package/src/schema/auth-users-columns.ts +131 -0
- package/src/schema/ensure-collection-tables.ts +157 -18
- package/src/schema/generate-drizzle-schema-logic.ts +25 -1
- package/src/schema/generate-postgres-ddl-logic.ts +127 -8
- package/src/schema/rls-bootstrap-sql.ts +288 -0
- package/src/schema/search-column.ts +549 -0
- package/src/security/anonymous-grants.test.ts +4 -2
- package/src/security/rls-enforcement.ts +141 -3
- package/src/services/BranchService.ts +5 -0
- package/src/services/FetchService.ts +136 -15
- package/src/services/RelationService.ts +2 -1
- package/src/services/channel-history.ts +8 -0
- package/src/services/channel-presence.ts +6 -0
- package/src/utils/drizzle-conditions.ts +223 -2
- package/dist/ensure-collection-tables-BLIIACla.js.map +0 -1
- package/dist/policy-CeA1JcxP.js.map +0 -1
- package/dist/schema/auth-bootstrap-sql.d.ts +0 -24
- package/dist/src-CU6WZGYV.js.map +0 -1
- package/dist/src-DoU9yPqq.js.map +0 -1
- package/src/schema/auth-bootstrap-sql.ts +0 -47
|
@@ -2,8 +2,8 @@ import { createRequire as __createRequire } from "module";
|
|
|
2
2
|
import "process";
|
|
3
3
|
__createRequire(import.meta.url);
|
|
4
4
|
import { l as __require, s as __commonJSMin } from "./connection-BuZ97wsr.js";
|
|
5
|
-
import { a as
|
|
6
|
-
import { n as ANONYMOUS_USER_IDS, r as policy, t as ANONYMOUS_USER_ID } from "./policy-
|
|
5
|
+
import { a as rewriteLegacyRlsFunctions, c as isPostgresCollectionConfig, d as getDataSourceCapabilities, f as NULL_OPS, i as RLS_UID_SQL, l as isRelationalCollectionConfig, m as toCanonicalOp, p as REST_TO_CANONICAL, r as RLS_ROLES_SQL, s as getDeclaredSubcollections } from "./src-C_wvdMnl.js";
|
|
6
|
+
import { n as ANONYMOUS_USER_IDS, r as policy, t as ANONYMOUS_USER_ID } from "./policy-CPkCqVTz.js";
|
|
7
7
|
//#region ../types/src/types/entities.ts
|
|
8
8
|
/**
|
|
9
9
|
* Class used to create a reference to a entity in a different path
|
|
@@ -1408,6 +1408,28 @@ function legacyForeignKeyName(name) {
|
|
|
1408
1408
|
const snake = toSnakeCase(name);
|
|
1409
1409
|
return `${snake.endsWith("s") ? snake.slice(0, -1) : snake}_id`;
|
|
1410
1410
|
}
|
|
1411
|
+
/**
|
|
1412
|
+
* Truncate an identifier to what Postgres will actually store.
|
|
1413
|
+
*
|
|
1414
|
+
* Postgres silently truncates identifiers at NAMEDATALEN-1 = 63 **bytes**, so a
|
|
1415
|
+
* name generated longer than that is not the name the database ends up holding.
|
|
1416
|
+
* Anything that later looks the object up by the name it generated then misses.
|
|
1417
|
+
*
|
|
1418
|
+
* Byte length, not string length: NAMEDATALEN is a byte bound, and a multi-byte
|
|
1419
|
+
* character straddling the boundary would be cut mid-sequence by `slice(0, 63)`.
|
|
1420
|
+
*
|
|
1421
|
+
* `TextEncoder` rather than `Buffer`, which is not a matter of taste: `Buffer`
|
|
1422
|
+
* is a Node global, and this package is imported by browser-facing ones. It
|
|
1423
|
+
* typechecked only where `@types/node` happened to be in scope, so
|
|
1424
|
+
* `packages/codegen` — whose tsconfig is `lib: ["ESNext", "dom"]` — could not
|
|
1425
|
+
* compile the file at all, and both of its suites failed to run. `TextEncoder`
|
|
1426
|
+
* and `TextDecoder` are standard in both runtimes and need no ambient types.
|
|
1427
|
+
*/
|
|
1428
|
+
function toPostgresIdentifier(name) {
|
|
1429
|
+
const bytes = new TextEncoder().encode(name);
|
|
1430
|
+
if (bytes.byteLength <= 63) return name;
|
|
1431
|
+
return new TextDecoder("utf-8").decode(bytes.subarray(0, 63)).replace(/�+$/, "");
|
|
1432
|
+
}
|
|
1411
1433
|
//#endregion
|
|
1412
1434
|
//#region ../common/src/util/entities.ts
|
|
1413
1435
|
/**
|
|
@@ -1431,10 +1453,21 @@ function updateDateAutoValues({ inputValues, properties, status, timestampNowVal
|
|
|
1431
1453
|
* have `id` and `path` fields — these are relation-shaped objects from
|
|
1432
1454
|
* edge cases in the data pipeline (REST fallback, stale cache, custom data source).
|
|
1433
1455
|
*
|
|
1456
|
+
* When `targetPath` is given, also accepts a bare id. A relation column is a
|
|
1457
|
+
* foreign key, and the REST layer returns it as the scalar it is; only some
|
|
1458
|
+
* fetch paths hydrate it into an object. Which form a caller sees therefore
|
|
1459
|
+
* depends on how the row was loaded, and a caller that only accepted objects
|
|
1460
|
+
* reported half of its own data as a type error. The declared target is the
|
|
1461
|
+
* missing half: with it, an id is a relation that has not been fetched yet.
|
|
1462
|
+
*
|
|
1434
1463
|
* Returns null if the value cannot be coerced.
|
|
1435
1464
|
*/
|
|
1436
|
-
function normalizeToEntityRelation(value, propertyType) {
|
|
1465
|
+
function normalizeToEntityRelation(value, propertyType, targetPath) {
|
|
1437
1466
|
if (value instanceof EntityRelation) return value;
|
|
1467
|
+
if (targetPath && (typeof value === "string" || typeof value === "number")) {
|
|
1468
|
+
if (value === "") return null;
|
|
1469
|
+
return new EntityRelation(value, targetPath);
|
|
1470
|
+
}
|
|
1438
1471
|
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
1439
1472
|
const obj = value;
|
|
1440
1473
|
if (!(obj.__type === "relation" || obj.__type === "reference" || typeof obj.isEntityRelation === "function" && obj.isEntityRelation() || typeof obj.isEntityReference === "function" && obj.isEntityReference() || propertyType === "relation" && typeof obj.id !== "undefined" && typeof obj.path === "string")) return null;
|
|
@@ -1972,9 +2005,9 @@ function isKeywordAt(upper, i, keyword) {
|
|
|
1972
2005
|
*
|
|
1973
2006
|
* This used to be `sql.split(/ AND /i)`, which tore subqueries in half: the
|
|
1974
2007
|
* `AND` inside
|
|
1975
|
-
* `EXISTS (SELECT 1 FROM organization_members m WHERE m.org = t.org AND m.user_id =
|
|
2008
|
+
* `EXISTS (SELECT 1 FROM organization_members m WHERE m.org = t.org AND m.user_id = rebase.uid())`
|
|
1976
2009
|
* split the expression, and re-emitting the halves produced
|
|
1977
|
-
* `(EXISTS (...) AND m.user_id =
|
|
2010
|
+
* `(EXISTS (...) AND m.user_id = rebase.uid())`
|
|
1978
2011
|
* where `m` is no longer in scope — SQL that Postgres rejects outright with
|
|
1979
2012
|
* "missing FROM-clause entry for table". Returning null instead keeps such a
|
|
1980
2013
|
* clause as a `raw` expression, which round-trips verbatim.
|
|
@@ -2048,15 +2081,15 @@ function stripOuterParens(sql) {
|
|
|
2048
2081
|
}
|
|
2049
2082
|
}
|
|
2050
2083
|
function sqlToPolicy(sql) {
|
|
2051
|
-
const trimmed = stripOuterParens(sql.trim());
|
|
2084
|
+
const trimmed = stripOuterParens(rewriteLegacyRlsFunctions(sql).trim());
|
|
2052
2085
|
if (trimmed.toLowerCase() === "true") return policy.true();
|
|
2053
2086
|
if (trimmed.toLowerCase() === "false") return policy.false();
|
|
2054
|
-
const overlapMatch = trimmed.match(/^string_to_array\s*\(\s*
|
|
2087
|
+
const overlapMatch = trimmed.match(/^string_to_array\s*\(\s*rebase\.roles\(\)\s*,\s*','\s*\)\s*&&\s*ARRAY\s*\[(.+)\]$/i);
|
|
2055
2088
|
if (overlapMatch) {
|
|
2056
2089
|
const roles = overlapMatch[1].split(",").map((s) => s.trim().replace(/^'|'$/g, ""));
|
|
2057
2090
|
return policy.rolesOverlap(roles);
|
|
2058
2091
|
}
|
|
2059
|
-
const containMatch = trimmed.match(/^string_to_array\s*\(\s*
|
|
2092
|
+
const containMatch = trimmed.match(/^string_to_array\s*\(\s*rebase\.roles\(\)\s*,\s*','\s*\)\s*@>\s*ARRAY\s*\[(.+)\]$/i);
|
|
2060
2093
|
if (containMatch) {
|
|
2061
2094
|
const roles = containMatch[1].split(",").map((s) => s.trim().replace(/^'|'$/g, ""));
|
|
2062
2095
|
return policy.rolesContain(roles);
|
|
@@ -2072,10 +2105,10 @@ function sqlToPolicy(sql) {
|
|
|
2072
2105
|
const right = parseOperand(rightStr.trim());
|
|
2073
2106
|
if (left && right) return policy.compare(left, op === "=" ? "eq" : "neq", right);
|
|
2074
2107
|
}
|
|
2075
|
-
return policy.raw(
|
|
2108
|
+
return policy.raw(trimmed);
|
|
2076
2109
|
}
|
|
2077
2110
|
/**
|
|
2078
|
-
* Literals from other BaaS platforms that people compare `
|
|
2111
|
+
* Literals from other BaaS platforms that people compare `rebase.uid()` against
|
|
2079
2112
|
* out of habit. Mirrors the driver's `FOREIGN_CONVENTION_ROLES` guard on
|
|
2080
2113
|
* `pgRoles`, one surface over: the same muscle memory inside a `using:` string
|
|
2081
2114
|
* is the more dangerous spelling, because it inverts a rule instead of
|
|
@@ -2086,18 +2119,25 @@ var FOREIGN_CONVENTION_UIDS = {
|
|
|
2086
2119
|
authenticated: "Supabase",
|
|
2087
2120
|
service_role: "Supabase"
|
|
2088
2121
|
};
|
|
2089
|
-
/**
|
|
2090
|
-
|
|
2122
|
+
/**
|
|
2123
|
+
* `rebase.uid() IS NOT NULL` in raw SQL, the clause that is always true.
|
|
2124
|
+
*
|
|
2125
|
+
* Both schema spellings, because this runs over policy bodies read back from a
|
|
2126
|
+
* database, and one migrated by a pre-1.0 release still holds `auth.uid()`.
|
|
2127
|
+
* A security check that stops recognising a dangerous clause because the
|
|
2128
|
+
* framework renamed a function is a check that silently turns off.
|
|
2129
|
+
*/
|
|
2130
|
+
var UID_NOT_NULL = /\b(?:rebase|auth)\.uid\(\)\s+IS\s+NOT\s+NULL/i;
|
|
2091
2131
|
/**
|
|
2092
2132
|
* Find clauses that read as "signed-in users only" but admit anonymous callers.
|
|
2093
2133
|
*
|
|
2094
|
-
* Both spellings come from the same place — Supabase, where `auth.uid()`
|
|
2095
|
-
* is NULL for an anonymous request. Rebase substitutes
|
|
2134
|
+
* Both spellings come from the same place — Supabase, where its own `auth.uid()`
|
|
2135
|
+
* really is NULL for an anonymous request. Rebase substitutes
|
|
2096
2136
|
* {@link ANONYMOUS_USER_ID} instead (a blank id would read back as NULL, which
|
|
2097
2137
|
* is how the trusted *server* context is recognised), so:
|
|
2098
2138
|
*
|
|
2099
|
-
* - `
|
|
2100
|
-
* - `
|
|
2139
|
+
* - `rebase.uid() IS NOT NULL` is a tautology on the user path, and
|
|
2140
|
+
* - `rebase.uid() != 'anon'` excludes one spelling of anonymous and admits the
|
|
2101
2141
|
* other. This one is not hypothetical and was not only a foreign habit:
|
|
2102
2142
|
* rebase's own request path reported `'anon'` while everything that compiled
|
|
2103
2143
|
* or checked a policy used `'anonymous'`, so whichever literal an author
|
|
@@ -2129,7 +2169,7 @@ function findAnonymousGrants(expr) {
|
|
|
2129
2169
|
if (UID_NOT_NULL.test(e.sql)) found.push({
|
|
2130
2170
|
pattern: "uid-not-null",
|
|
2131
2171
|
detail: e.sql,
|
|
2132
|
-
explanation: `\`
|
|
2172
|
+
explanation: `\`rebase.uid() IS NOT NULL\` is true for every request that came from a client, including anonymous ones — they carry '${ANONYMOUS_USER_ID}', not NULL. Use \`condition: policy.authenticated()\` to mean "signed in".`
|
|
2133
2173
|
});
|
|
2134
2174
|
return;
|
|
2135
2175
|
case "compare": {
|
|
@@ -2151,7 +2191,7 @@ function findAnonymousGrants(expr) {
|
|
|
2151
2191
|
return found;
|
|
2152
2192
|
}
|
|
2153
2193
|
function parseOperand(str) {
|
|
2154
|
-
if (/current_setting\s*\(\s*'app\.(uid|user_id)'\s*\)/i.test(str) || /
|
|
2194
|
+
if (/current_setting\s*\(\s*'app\.(uid|user_id)'\s*\)/i.test(str) || /rebase\.uid\(\)/i.test(str)) return policy.authUid();
|
|
2155
2195
|
const stringMatch = str.match(/^'(.+)'$/);
|
|
2156
2196
|
if (stringMatch) return policy.literal(stringMatch[1]);
|
|
2157
2197
|
if (/^\w+$/.test(str)) return policy.field(str);
|
|
@@ -2233,12 +2273,12 @@ function compile(expr, scope) {
|
|
|
2233
2273
|
const rightSql = castForAuthUid(expr.right, operandToSql(expr.right, scope), expr.left);
|
|
2234
2274
|
return `${leftSql} ${COMPARE_SQL[expr.op]} ${rightSql}`;
|
|
2235
2275
|
}
|
|
2236
|
-
case "rolesOverlap": return `string_to_array(
|
|
2237
|
-
case "rolesContain": return `string_to_array(
|
|
2238
|
-
case "authenticated": return
|
|
2239
|
-
case "serverContext": return
|
|
2276
|
+
case "rolesOverlap": return `string_to_array(${RLS_ROLES_SQL}, ',') && ${rolesArraySql(expr.roles)}`;
|
|
2277
|
+
case "rolesContain": return `string_to_array(${RLS_ROLES_SQL}, ',') @> ${rolesArraySql(expr.roles)}`;
|
|
2278
|
+
case "authenticated": return `${RLS_UID_SQL} IS NOT NULL AND ${RLS_UID_SQL} NOT IN (${ANONYMOUS_USER_IDS.map(quoteLiteral).join(", ")})`;
|
|
2279
|
+
case "serverContext": return `${RLS_UID_SQL} IS NULL`;
|
|
2240
2280
|
case "existsIn": return compileExistsIn(expr, scope);
|
|
2241
|
-
case "raw": return expr.sql.replace(/\{(\w+)\}/g, (_, col) => `${outerQualifier(scope)}${resolveColumnName(col, scope.outerCollection)}`);
|
|
2281
|
+
case "raw": return rewriteLegacyRlsFunctions(expr.sql).replace(/\{(\w+)\}/g, (_, col) => `${outerQualifier(scope)}${resolveColumnName(col, scope.outerCollection)}`);
|
|
2242
2282
|
}
|
|
2243
2283
|
}
|
|
2244
2284
|
/**
|
|
@@ -2275,8 +2315,8 @@ function operandToSql(operand, scope) {
|
|
|
2275
2315
|
case "field": return `${scope.fieldPrefix}${resolveColumnName(operand.name, scope.fieldCollection)}`;
|
|
2276
2316
|
case "outerField": return `${scope.outerPrefix}${resolveColumnName(operand.name, scope.outerCollection)}`;
|
|
2277
2317
|
case "literal": return quoteLiteral(operand.value);
|
|
2278
|
-
case "authUid": return
|
|
2279
|
-
case "authRoles": return
|
|
2318
|
+
case "authUid": return RLS_UID_SQL;
|
|
2319
|
+
case "authRoles": return `string_to_array(${RLS_ROLES_SQL}, ',')`;
|
|
2280
2320
|
}
|
|
2281
2321
|
}
|
|
2282
2322
|
/**
|
|
@@ -2356,7 +2396,7 @@ var DEFAULT_GUARDED_OPS = [
|
|
|
2356
2396
|
"delete"
|
|
2357
2397
|
];
|
|
2358
2398
|
/** Whether a collection is flagged as an authentication collection. */
|
|
2359
|
-
function isAuthCollection(collection) {
|
|
2399
|
+
function isAuthCollection$1(collection) {
|
|
2360
2400
|
const auth = collection.auth;
|
|
2361
2401
|
return auth === true || typeof auth === "object" && auth?.enabled === true;
|
|
2362
2402
|
}
|
|
@@ -2389,7 +2429,7 @@ function getEffectiveSecurityRules(collection) {
|
|
|
2389
2429
|
condition: SERVER_OR_ADMIN_EXPR$1,
|
|
2390
2430
|
check: SERVER_OR_ADMIN_EXPR$1
|
|
2391
2431
|
});
|
|
2392
|
-
if (isAuthCollection(collection)) {
|
|
2432
|
+
if (isAuthCollection$1(collection)) {
|
|
2393
2433
|
injected.push({
|
|
2394
2434
|
name: `${tableName}_default_self_read`,
|
|
2395
2435
|
operations: ["select"],
|
|
@@ -3690,8 +3730,24 @@ var QueryBuilder = class {
|
|
|
3690
3730
|
/**
|
|
3691
3731
|
* Set a free-text search string if supported by the backend.
|
|
3692
3732
|
*/
|
|
3693
|
-
search(searchString) {
|
|
3733
|
+
search(searchString, options) {
|
|
3694
3734
|
this.params.searchString = searchString;
|
|
3735
|
+
if (options?.explain !== void 0) this.params.searchExplain = options.explain;
|
|
3736
|
+
return this;
|
|
3737
|
+
}
|
|
3738
|
+
/**
|
|
3739
|
+
* Order rows by nearest-neighbour distance to `vector`, closest first.
|
|
3740
|
+
*
|
|
3741
|
+
* Postgres only, over a property declared as `type: "vector"`. Rows come
|
|
3742
|
+
* back with a `_distance`; `where` filters before the ordering.
|
|
3743
|
+
*/
|
|
3744
|
+
vectorSearch(property, vector, options) {
|
|
3745
|
+
this.params.vectorSearch = {
|
|
3746
|
+
property,
|
|
3747
|
+
vector,
|
|
3748
|
+
...options?.distance !== void 0 && { distance: options.distance },
|
|
3749
|
+
...options?.threshold !== void 0 && { threshold: options.threshold }
|
|
3750
|
+
};
|
|
3695
3751
|
return this;
|
|
3696
3752
|
}
|
|
3697
3753
|
/**
|
|
@@ -4146,6 +4202,21 @@ function createDriverAccessor(driver, slug, getPks = () => []) {
|
|
|
4146
4202
|
values: {}
|
|
4147
4203
|
} });
|
|
4148
4204
|
},
|
|
4205
|
+
updateMany: driver.updateMany ? async (updates) => {
|
|
4206
|
+
return (await driver.updateMany({
|
|
4207
|
+
path: slug,
|
|
4208
|
+
updates: updates.map((u) => ({
|
|
4209
|
+
id: u.id,
|
|
4210
|
+
values: u.data
|
|
4211
|
+
}))
|
|
4212
|
+
})).map((row) => rowToEntity(row, slug, getPks()));
|
|
4213
|
+
} : void 0,
|
|
4214
|
+
deleteMany: driver.deleteMany ? async (ids) => {
|
|
4215
|
+
await driver.deleteMany({
|
|
4216
|
+
path: slug,
|
|
4217
|
+
ids
|
|
4218
|
+
});
|
|
4219
|
+
} : void 0,
|
|
4149
4220
|
count: driver.count ? async (params) => {
|
|
4150
4221
|
const filter = params?.where ? deserializeFilter(params.where) : void 0;
|
|
4151
4222
|
return driver.count({
|
|
@@ -4204,8 +4275,11 @@ function createDriverAccessor(driver, slug, getPks = () => []) {
|
|
|
4204
4275
|
offset(count) {
|
|
4205
4276
|
return new QueryBuilder(accessor).offset(count);
|
|
4206
4277
|
},
|
|
4207
|
-
search(searchString) {
|
|
4208
|
-
return new QueryBuilder(accessor).search(searchString);
|
|
4278
|
+
search(searchString, options) {
|
|
4279
|
+
return new QueryBuilder(accessor).search(searchString, options);
|
|
4280
|
+
},
|
|
4281
|
+
vectorSearch(property, vector, options) {
|
|
4282
|
+
return new QueryBuilder(accessor).vectorSearch(property, vector, options);
|
|
4209
4283
|
},
|
|
4210
4284
|
include(...relations) {
|
|
4211
4285
|
return new QueryBuilder(accessor).include(...relations);
|
|
@@ -4293,8 +4367,18 @@ var SdkQueryBuilder = class {
|
|
|
4293
4367
|
this.params.offset = count;
|
|
4294
4368
|
return this;
|
|
4295
4369
|
}
|
|
4296
|
-
search(searchString) {
|
|
4370
|
+
search(searchString, options) {
|
|
4297
4371
|
this.params.searchString = searchString;
|
|
4372
|
+
if (options?.explain !== void 0) this.params.searchExplain = options.explain;
|
|
4373
|
+
return this;
|
|
4374
|
+
}
|
|
4375
|
+
vectorSearch(property, vector, options) {
|
|
4376
|
+
this.params.vectorSearch = {
|
|
4377
|
+
property,
|
|
4378
|
+
vector,
|
|
4379
|
+
...options?.distance !== void 0 && { distance: options.distance },
|
|
4380
|
+
...options?.threshold !== void 0 && { threshold: options.threshold }
|
|
4381
|
+
};
|
|
4298
4382
|
return this;
|
|
4299
4383
|
}
|
|
4300
4384
|
include(...relations) {
|
|
@@ -4348,9 +4432,24 @@ function toSdkCollectionClient(snap, slug = "collection") {
|
|
|
4348
4432
|
async update(id, data) {
|
|
4349
4433
|
return entityToRow(await snap.update(id, data));
|
|
4350
4434
|
},
|
|
4435
|
+
async updateMany(updates) {
|
|
4436
|
+
if (!Array.isArray(updates)) throw new TypeError("updateMany expects an array of { id, data } entries.");
|
|
4437
|
+
if (updates.length === 0) return [];
|
|
4438
|
+
if (!snap.updateMany) throw new Error("Bulk updates are not supported by this collection's data source. Fall back to update() per record.");
|
|
4439
|
+
return (await snap.updateMany(updates.map((u) => ({
|
|
4440
|
+
id: u.id,
|
|
4441
|
+
data: u.data
|
|
4442
|
+
})))).map(entityToRow);
|
|
4443
|
+
},
|
|
4351
4444
|
delete(id) {
|
|
4352
4445
|
return snap.delete(id);
|
|
4353
4446
|
},
|
|
4447
|
+
async deleteMany(ids) {
|
|
4448
|
+
if (!Array.isArray(ids)) throw new TypeError("deleteMany expects an array of ids.");
|
|
4449
|
+
if (ids.length === 0) return;
|
|
4450
|
+
if (!snap.deleteMany) throw new Error("Bulk deletes are not supported by this collection's data source. Fall back to delete() per record.");
|
|
4451
|
+
await snap.deleteMany(ids);
|
|
4452
|
+
},
|
|
4354
4453
|
count: snap.count ? (params) => snap.count(params) : void 0,
|
|
4355
4454
|
listen: snap.listen ? (params, onUpdate, onError) => snap.listen(params, (res) => onUpdate({
|
|
4356
4455
|
data: res.data.map(entityToRow),
|
|
@@ -4366,6 +4465,7 @@ function toSdkCollectionClient(snap, slug = "collection") {
|
|
|
4366
4465
|
limit: (count) => new SdkQueryBuilder(client).limit(count),
|
|
4367
4466
|
offset: (count) => new SdkQueryBuilder(client).offset(count),
|
|
4368
4467
|
search: (searchString) => new SdkQueryBuilder(client).search(searchString),
|
|
4468
|
+
vectorSearch: (property, vector, options) => new SdkQueryBuilder(client).vectorSearch(property, vector, options),
|
|
4369
4469
|
include: (...relations) => new SdkQueryBuilder(client).include(...relations)
|
|
4370
4470
|
};
|
|
4371
4471
|
return client;
|
|
@@ -4411,6 +4511,460 @@ function buildSdkData(driver) {
|
|
|
4411
4511
|
return wrapAsSdkData(buildRebaseData(driver));
|
|
4412
4512
|
}
|
|
4413
4513
|
//#endregion
|
|
4414
|
-
|
|
4514
|
+
//#region src/schema/search-column.ts
|
|
4515
|
+
/**
|
|
4516
|
+
* The one place a collection's `search` block becomes SQL.
|
|
4517
|
+
*
|
|
4518
|
+
* Four things describe a Postgres table in this codebase — the DDL generator,
|
|
4519
|
+
* the Drizzle schema generator, the runtime table builder for BaaS mode, and
|
|
4520
|
+
* the boot-time schema ensure — and each of them has, at some point, described
|
|
4521
|
+
* a column differently from the others. The `varchar(255)` note in
|
|
4522
|
+
* `generate-postgres-ddl-logic` is one such scar: the same property produced a
|
|
4523
|
+
* capped column down one path and an uncapped one down the other, and nothing
|
|
4524
|
+
* failed until a user hit the cap.
|
|
4525
|
+
*
|
|
4526
|
+
* So the search column is not implemented four times. It is computed once,
|
|
4527
|
+
* here, and every generator renders the same {@link SearchColumnSpec}. There is
|
|
4528
|
+
* a test asserting exactly that (`search-column-contract.test.ts`); the point of
|
|
4529
|
+
* this module is that the test has something to assert *about*.
|
|
4530
|
+
*
|
|
4531
|
+
* ## Why the expressions look the way they do
|
|
4532
|
+
*
|
|
4533
|
+
* A `GENERATED ALWAYS AS … STORED` expression must be strictly IMMUTABLE, and
|
|
4534
|
+
* Postgres is stricter here than intuition. Verified against PostgreSQL 18:
|
|
4535
|
+
*
|
|
4536
|
+
* | expression | immutable |
|
|
4537
|
+
* |-----------------------------------------|-----------|
|
|
4538
|
+
* | `to_tsvector('spanish', col)` | yes |
|
|
4539
|
+
* | `to_tsvector(col)` (1-arg) | **no** — depends on `default_text_search_config` |
|
|
4540
|
+
* | `array_to_string(col, ' ')` | **no** |
|
|
4541
|
+
* | `col::text` on `text[]` | **no** |
|
|
4542
|
+
* | `to_jsonb(col)` | **no** |
|
|
4543
|
+
* | `unaccent(col)` | **no** — dictionary lookup is STABLE |
|
|
4544
|
+
* | `jsonb_to_tsvector('spanish', j, '["string"]')` | yes |
|
|
4545
|
+
* | `setweight(...) || setweight(...)` | yes |
|
|
4546
|
+
*
|
|
4547
|
+
* Three of the four things a real search column needs are therefore unavailable
|
|
4548
|
+
* directly, which is why {@link searchHelperFunctions} exists: each wraps a
|
|
4549
|
+
* stable built-in in an SQL function declared IMMUTABLE. That declaration is a
|
|
4550
|
+
* promise, and it is a true one for these three — array joining, JSON string
|
|
4551
|
+
* extraction and accent folding are all deterministic for a given input; the
|
|
4552
|
+
* built-ins are marked stable only because they must account for element types
|
|
4553
|
+
* and dictionaries in general.
|
|
4554
|
+
*
|
|
4555
|
+
* The alternative was to skip `unaccent` and text arrays entirely. That is not
|
|
4556
|
+
* a real option in an accented language: Postgres stems `auditoría` to
|
|
4557
|
+
* `auditor` and `auditoria` to `auditori` — *different lexemes* — so a query
|
|
4558
|
+
* typed without accents misses every row that carries them.
|
|
4559
|
+
*/
|
|
4560
|
+
/** Schema-qualified so a collection outside `public` still resolves them. */
|
|
4561
|
+
var HELPER_SCHEMA = "public";
|
|
4562
|
+
/**
|
|
4563
|
+
* Names of the helper functions. Frozen: they are recorded in the stored
|
|
4564
|
+
* generation expression of every search column ever created, so renaming one
|
|
4565
|
+
* orphans every table that already has a search column.
|
|
4566
|
+
*/
|
|
4567
|
+
var SEARCH_TEXT_FN = `${HELPER_SCHEMA}.rebase_search_text`;
|
|
4568
|
+
var SEARCH_UNACCENT_FN = `${HELPER_SCHEMA}.rebase_search_unaccent`;
|
|
4569
|
+
/** Raised when a `search` block names something that cannot be searched. */
|
|
4570
|
+
var SearchConfigError = class extends Error {
|
|
4571
|
+
constructor(message) {
|
|
4572
|
+
super(message);
|
|
4573
|
+
this.name = "SearchConfigError";
|
|
4574
|
+
}
|
|
4575
|
+
};
|
|
4576
|
+
/** The `search` block of a collection, or undefined when it has none. */
|
|
4577
|
+
var getSearchConfig = (collection) => isPostgresCollectionConfig(collection) ? collection.search : void 0;
|
|
4578
|
+
/**
|
|
4579
|
+
* Refuse a `search` block on a collection this engine does not store.
|
|
4580
|
+
*
|
|
4581
|
+
* The type only permits one on a `PostgresCollectionConfig`, so TypeScript
|
|
4582
|
+
* already stops the ordinary case. This catches the rest — a JS config, a cast,
|
|
4583
|
+
* a collection whose `engine` was changed after the block was written — because
|
|
4584
|
+
* the alternative is the exact failure the block exists to prevent: a developer
|
|
4585
|
+
* who declared what to index, saw no error, and got the substring fallback.
|
|
4586
|
+
*
|
|
4587
|
+
* Called with *every* collection, before the Postgres ones are filtered out.
|
|
4588
|
+
*/
|
|
4589
|
+
var assertSearchIsPostgresOnly = (collections) => {
|
|
4590
|
+
for (const collection of collections) {
|
|
4591
|
+
if (isPostgresCollectionConfig(collection)) continue;
|
|
4592
|
+
if (!collection.search) continue;
|
|
4593
|
+
const engine = collection.engine ?? "non-postgres";
|
|
4594
|
+
throw new SearchConfigError(`${collection.slug}.search: full-text search is a Postgres feature, and this collection is served by \`${engine}\`. Remove the block — it would otherwise look configured while \`.search()\` kept using the default substring match.`);
|
|
4595
|
+
}
|
|
4596
|
+
};
|
|
4597
|
+
var columnNameOf = (propName, prop) => prop && "columnName" in prop && typeof prop.columnName === "string" ? prop.columnName : toSnakeCase(propName);
|
|
4598
|
+
/**
|
|
4599
|
+
* Classify a property for search purposes.
|
|
4600
|
+
*
|
|
4601
|
+
* Deliberately narrower than `getSqlColumnType`: search only cares whether a
|
|
4602
|
+
* value reaches text, and the mapping from property to *physical* type is
|
|
4603
|
+
* asserted against `getSqlColumnType` in the contract test rather than
|
|
4604
|
+
* duplicated here.
|
|
4605
|
+
*
|
|
4606
|
+
* Returns null for anything that is not text-bearing, which the caller turns
|
|
4607
|
+
* into a boot error naming the property.
|
|
4608
|
+
*/
|
|
4609
|
+
var classify = (prop) => {
|
|
4610
|
+
switch (prop.type) {
|
|
4611
|
+
case "string": {
|
|
4612
|
+
const sp = prop;
|
|
4613
|
+
if (sp.enum) return {
|
|
4614
|
+
kind: "text",
|
|
4615
|
+
reason: "enum"
|
|
4616
|
+
};
|
|
4617
|
+
if (sp.isId === "uuid" || sp.columnType === "uuid") return {
|
|
4618
|
+
kind: "text",
|
|
4619
|
+
reason: "uuid"
|
|
4620
|
+
};
|
|
4621
|
+
return { kind: "text" };
|
|
4622
|
+
}
|
|
4623
|
+
case "map":
|
|
4624
|
+
if (prop.columnType === "json") return {
|
|
4625
|
+
kind: "jsonb",
|
|
4626
|
+
reason: "json"
|
|
4627
|
+
};
|
|
4628
|
+
return { kind: "jsonb" };
|
|
4629
|
+
case "array": {
|
|
4630
|
+
const ap = prop;
|
|
4631
|
+
let colType = ap.columnType;
|
|
4632
|
+
if (!colType && ap.of && !Array.isArray(ap.of)) {
|
|
4633
|
+
const of = ap.of;
|
|
4634
|
+
if (of.type === "string") colType = "text[]";
|
|
4635
|
+
else if (of.type === "number") colType = of.validation?.integer ? "integer[]" : "numeric[]";
|
|
4636
|
+
else if (of.type === "boolean") colType = "boolean[]";
|
|
4637
|
+
}
|
|
4638
|
+
if (colType === "text[]") return { kind: "text_array" };
|
|
4639
|
+
if (colType === "json") return {
|
|
4640
|
+
kind: "jsonb",
|
|
4641
|
+
reason: "json"
|
|
4642
|
+
};
|
|
4643
|
+
if (colType === "integer[]" || colType === "boolean[]" || colType === "numeric[]") return {
|
|
4644
|
+
kind: "text_array",
|
|
4645
|
+
reason: "non_text_array"
|
|
4646
|
+
};
|
|
4647
|
+
return { kind: "jsonb" };
|
|
4648
|
+
}
|
|
4649
|
+
default: return null;
|
|
4650
|
+
}
|
|
4651
|
+
};
|
|
4652
|
+
var normalize = (inner, unaccent) => unaccent ? `${SEARCH_UNACCENT_FN}(${inner})` : inner;
|
|
4653
|
+
/** SQL reading one field as plain text, before normalization. */
|
|
4654
|
+
var rawTextSql = (field) => {
|
|
4655
|
+
const col = `"${field.column}"`;
|
|
4656
|
+
if (field.kind === "text") return `coalesce(${col}, '')`;
|
|
4657
|
+
if (field.kind === "text_array") return `${SEARCH_TEXT_FN}(coalesce(${col}, '{}'::text[]))`;
|
|
4658
|
+
return `${SEARCH_TEXT_FN}(coalesce(${field.jsonPath.length === 0 ? col : field.jsonPath.length === 1 ? `${col} -> ${quote(field.jsonPath[0])}` : `${col} #> ${quote(`{${field.jsonPath.join(",")}}`)}`}, '{}'::jsonb))`;
|
|
4659
|
+
};
|
|
4660
|
+
var quote = (v) => `'${v.replace(/'/g, "''")}'`;
|
|
4661
|
+
/**
|
|
4662
|
+
* Resolve and validate one declared field path.
|
|
4663
|
+
*
|
|
4664
|
+
* A path that does not resolve throws. The whole point of an explicit block is
|
|
4665
|
+
* that the author knows what is indexed; a silently dropped field would make it
|
|
4666
|
+
* a guess again, and the failure — a search that returns nothing for content
|
|
4667
|
+
* that is plainly in the row — is invisible from the outside.
|
|
4668
|
+
*/
|
|
4669
|
+
var resolveField = (entry, collection, cfg) => {
|
|
4670
|
+
const path = typeof entry === "string" ? entry : entry.path;
|
|
4671
|
+
const weight = (typeof entry === "string" ? void 0 : entry.weight) ?? "B";
|
|
4672
|
+
const where = `${collection.slug}.search`;
|
|
4673
|
+
if (!path || typeof path !== "string") throw new SearchConfigError(`${where}: every entry in \`fields\` needs a property path.`);
|
|
4674
|
+
const [head, ...rest] = path.split(".");
|
|
4675
|
+
const prop = collection.properties?.[head];
|
|
4676
|
+
if (!prop) throw new SearchConfigError(`${where}: "${path}" starts at property "${head}", which this collection does not declare. Known properties: ${Object.keys(collection.properties ?? {}).join(", ")}.`);
|
|
4677
|
+
const classified = classify(prop);
|
|
4678
|
+
if (!classified) throw new SearchConfigError(`${where}: "${path}" is a \`${prop.type}\` property, which holds no text to search. Searchable kinds are \`string\`, \`string[]\` and \`map\` (or a path inside one).`);
|
|
4679
|
+
if (classified.reason === "enum") throw new SearchConfigError(`${where}: "${path}" is an enum. Enums are a fixed vocabulary — filter on them with \`where\` instead, which is exact and uses an index.`);
|
|
4680
|
+
if (classified.reason === "uuid") throw new SearchConfigError(`${where}: "${path}" is a UUID column. Look it up by id rather than searching it.`);
|
|
4681
|
+
if (classified.reason === "json") throw new SearchConfigError(`${where}: "${path}" is a \`json\` column, and the cast from \`json\` to \`jsonb\` is not immutable, so it cannot feed a generated column. Declare the property as \`jsonb\` (the default) to search it.`);
|
|
4682
|
+
if (classified.reason === "non_text_array") throw new SearchConfigError(`${where}: "${path}" is an array of numbers or booleans. Only \`string[]\` carries text to search.`);
|
|
4683
|
+
if (rest.length > 0 && classified.kind !== "jsonb") throw new SearchConfigError(`${where}: "${path}" addresses a path inside "${head}", but "${head}" is a \`${prop.type}\` property, not a \`map\`. Only map properties have paths inside them.`);
|
|
4684
|
+
const column = columnNameOf(head, prop);
|
|
4685
|
+
const textSql = normalize(rawTextSql({
|
|
4686
|
+
column,
|
|
4687
|
+
jsonPath: rest,
|
|
4688
|
+
kind: classified.kind
|
|
4689
|
+
}), cfg.unaccent === true);
|
|
4690
|
+
const language = cfg.language ?? "simple";
|
|
4691
|
+
return {
|
|
4692
|
+
path,
|
|
4693
|
+
column,
|
|
4694
|
+
jsonPath: rest,
|
|
4695
|
+
kind: classified.kind,
|
|
4696
|
+
weight,
|
|
4697
|
+
sql: `setweight(to_tsvector(${quote(language)}, ${textSql}), ${quote(weight)})`,
|
|
4698
|
+
textSql
|
|
4699
|
+
};
|
|
4700
|
+
};
|
|
4701
|
+
/**
|
|
4702
|
+
* Build the full spec for a collection, or undefined when it has not opted in.
|
|
4703
|
+
*
|
|
4704
|
+
* Throws {@link SearchConfigError} on a config that cannot be honoured. Callers
|
|
4705
|
+
* at boot surface that as a startup failure — a search block that half-works is
|
|
4706
|
+
* worse than one that refuses.
|
|
4707
|
+
*/
|
|
4708
|
+
var buildSearchColumnSpec = (collection) => {
|
|
4709
|
+
const cfg = getSearchConfig(collection);
|
|
4710
|
+
if (!cfg) return void 0;
|
|
4711
|
+
if (!Array.isArray(cfg.fields) || cfg.fields.length === 0) throw new SearchConfigError(`${collection.slug}.search: \`fields\` is empty. Name the properties to index, or remove the \`search\` block to keep the default ILIKE behaviour.`);
|
|
4712
|
+
const table = getTableName(collection);
|
|
4713
|
+
const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
|
|
4714
|
+
const column = cfg.column ?? "search_vector";
|
|
4715
|
+
if (collection.properties?.[column]) throw new SearchConfigError(`${collection.slug}.search: the generated column "${column}" collides with a declared property of the same name. Set \`search.column\` to something else.`);
|
|
4716
|
+
const fields = cfg.fields.map((entry) => resolveField(entry, collection, cfg));
|
|
4717
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4718
|
+
for (const f of fields) {
|
|
4719
|
+
if (seen.has(f.path)) throw new SearchConfigError(`${collection.slug}.search: "${f.path}" is listed twice.`);
|
|
4720
|
+
seen.add(f.path);
|
|
4721
|
+
}
|
|
4722
|
+
const extensions = [];
|
|
4723
|
+
if (cfg.unaccent) extensions.push("unaccent");
|
|
4724
|
+
if (cfg.fuzzy) extensions.push("pg_trgm");
|
|
4725
|
+
const spec = {
|
|
4726
|
+
schema,
|
|
4727
|
+
table,
|
|
4728
|
+
column,
|
|
4729
|
+
language: cfg.language ?? "simple",
|
|
4730
|
+
unaccent: cfg.unaccent === true,
|
|
4731
|
+
fields,
|
|
4732
|
+
expression: fields.map((f) => f.sql).join(" || "),
|
|
4733
|
+
indexName: toPostgresIdentifier(`${table}_${column}_gin`),
|
|
4734
|
+
extensions
|
|
4735
|
+
};
|
|
4736
|
+
if (cfg.fuzzy) {
|
|
4737
|
+
const fuzzyColumn = `${column}_text`;
|
|
4738
|
+
if (collection.properties?.[fuzzyColumn]) throw new SearchConfigError(`${collection.slug}.search: \`fuzzy\` needs the column "${fuzzyColumn}", which collides with a declared property. Set \`search.column\` to something else.`);
|
|
4739
|
+
spec.fuzzy = {
|
|
4740
|
+
column: fuzzyColumn,
|
|
4741
|
+
expression: fields.map((f) => f.textSql).join(" || ' ' || "),
|
|
4742
|
+
indexName: toPostgresIdentifier(`${table}_${fuzzyColumn}_trgm`),
|
|
4743
|
+
threshold: cfg.fuzzyThreshold ?? .3
|
|
4744
|
+
};
|
|
4745
|
+
}
|
|
4746
|
+
return spec;
|
|
4747
|
+
};
|
|
4748
|
+
/**
|
|
4749
|
+
* The IMMUTABLE wrappers the generated expressions call.
|
|
4750
|
+
*
|
|
4751
|
+
* `CREATE OR REPLACE` so a boot against an existing database is a no-op rather
|
|
4752
|
+
* than an error, and idempotent for the same reason every other boot-time DDL
|
|
4753
|
+
* statement here is.
|
|
4754
|
+
*
|
|
4755
|
+
* The bodies are stable built-ins wrapped in an immutable promise — see the
|
|
4756
|
+
* module comment for why that promise is sound. `STRICT` matters: it makes NULL
|
|
4757
|
+
* in mean NULL out without executing the body, which is what the `coalesce` at
|
|
4758
|
+
* each call site then absorbs.
|
|
4759
|
+
*/
|
|
4760
|
+
var searchHelperFunctions = (spec) => {
|
|
4761
|
+
const statements = [`CREATE OR REPLACE FUNCTION ${SEARCH_TEXT_FN}(text[]) RETURNS text\n LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\n $$ SELECT array_to_string($1, ' ') $$;`, `CREATE OR REPLACE FUNCTION ${SEARCH_TEXT_FN}(jsonb) RETURNS text\n LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\n $$ SELECT coalesce(string_agg(v, ' '), '')\n FROM jsonb_array_elements_text(jsonb_path_query_array($1, 'strict $.**?(@.type() == "string")')) AS v $$;`];
|
|
4762
|
+
if (spec.unaccent) statements.push(`CREATE OR REPLACE FUNCTION ${SEARCH_UNACCENT_FN}(text) RETURNS text\n LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\n $$ SELECT ${HELPER_SCHEMA}.unaccent('${HELPER_SCHEMA}.unaccent'::regdictionary, $1) $$;`);
|
|
4763
|
+
return statements;
|
|
4764
|
+
};
|
|
4765
|
+
/**
|
|
4766
|
+
* `CREATE EXTENSION` statements the spec's expressions depend on.
|
|
4767
|
+
*
|
|
4768
|
+
* `WITH SCHEMA public` is load-bearing, not tidiness. An unqualified
|
|
4769
|
+
* `CREATE EXTENSION` installs into the first schema on `search_path`, which
|
|
4770
|
+
* defaults to `"$user", public` — and the scaffold's database role is named
|
|
4771
|
+
* `rebase`, the same as the schema the generator creates one statement earlier.
|
|
4772
|
+
* So the moment that schema exists, `CREATE EXTENSION unaccent` puts the
|
|
4773
|
+
* dictionary in `rebase`, and every reference to `public.unaccent` below fails
|
|
4774
|
+
* with "text search dictionary does not exist". Observed, not theorised.
|
|
4775
|
+
*/
|
|
4776
|
+
var searchExtensionStatements = (spec) => spec.extensions.map((e) => `CREATE EXTENSION IF NOT EXISTS ${e} WITH SCHEMA ${HELPER_SCHEMA};`);
|
|
4777
|
+
/**
|
|
4778
|
+
* Index statements for the spec.
|
|
4779
|
+
*
|
|
4780
|
+
* `CONCURRENTLY` is deliberately *not* used here: this form runs inside the
|
|
4781
|
+
* same transaction as the `CREATE TABLE` that precedes it, where a concurrent
|
|
4782
|
+
* build is not allowed and not needed (the table is empty and unreachable).
|
|
4783
|
+
* The boot-time ensure path, which meets populated tables, uses the
|
|
4784
|
+
* concurrent form instead — see `ensureSearchColumns`.
|
|
4785
|
+
*/
|
|
4786
|
+
var searchIndexStatements = (spec) => {
|
|
4787
|
+
const statements = [`CREATE INDEX IF NOT EXISTS "${spec.indexName}" ON "${spec.schema}"."${spec.table}" USING GIN ("${spec.column}");`];
|
|
4788
|
+
if (spec.fuzzy) statements.push(`CREATE INDEX IF NOT EXISTS "${spec.fuzzy.indexName}" ON "${spec.schema}"."${spec.table}" USING GIN ("${spec.fuzzy.column}" ${HELPER_SCHEMA}.gin_trgm_ops);`);
|
|
4789
|
+
return statements;
|
|
4790
|
+
};
|
|
4791
|
+
/**
|
|
4792
|
+
* The generated column names a collection's search block adds, if any.
|
|
4793
|
+
*
|
|
4794
|
+
* These are physical columns on the table, so `SELECT *` returns them. They are
|
|
4795
|
+
* an index in column form — a list of lexeme positions, or a concatenation of
|
|
4796
|
+
* every searchable field on the row — and nothing outside the query planner has
|
|
4797
|
+
* any use for them. Left in, every list response carries a second, larger copy
|
|
4798
|
+
* of the row's text.
|
|
4799
|
+
*/
|
|
4800
|
+
var searchColumnNames = (collection) => {
|
|
4801
|
+
let spec;
|
|
4802
|
+
try {
|
|
4803
|
+
spec = buildSearchColumnSpec(collection);
|
|
4804
|
+
} catch {
|
|
4805
|
+
return [];
|
|
4806
|
+
}
|
|
4807
|
+
if (!spec) return [];
|
|
4808
|
+
return spec.fuzzy ? [spec.column, spec.fuzzy.column] : [spec.column];
|
|
4809
|
+
};
|
|
4810
|
+
/**
|
|
4811
|
+
* True for a column whose type only ever holds a search index.
|
|
4812
|
+
*
|
|
4813
|
+
* Independent of any collection config on purpose: an introspected database
|
|
4814
|
+
* (BaaS mode) can carry a `tsvector` column this framework never created —
|
|
4815
|
+
* Pagila's `film.fulltext` is the canonical one — and it should not be returned
|
|
4816
|
+
* to callers either. `isDerivedIndexColumn` already keeps such a column out of
|
|
4817
|
+
* the *properties*; this keeps it out of the *rows*.
|
|
4818
|
+
*/
|
|
4819
|
+
var isSearchIndexColumn = (column) => {
|
|
4820
|
+
const sqlType = typeof column?.getSQLType === "function" ? column.getSQLType().toLowerCase() : "";
|
|
4821
|
+
return sqlType === "tsvector" || sqlType === "tsquery";
|
|
4822
|
+
};
|
|
4823
|
+
/**
|
|
4824
|
+
* A drizzle select projection over `table` with the search columns dropped.
|
|
4825
|
+
*
|
|
4826
|
+
* Returns undefined when nothing needs dropping, so the common case keeps using
|
|
4827
|
+
* a plain `select()` and this stays invisible in the generated SQL.
|
|
4828
|
+
*/
|
|
4829
|
+
var visibleColumnProjection = (tableColumns, collection) => {
|
|
4830
|
+
const excluded = excludedColumnNames(tableColumns, collection);
|
|
4831
|
+
if (!tableColumns || excluded.length === 0) return void 0;
|
|
4832
|
+
const projection = {};
|
|
4833
|
+
for (const [name, column] of Object.entries(tableColumns)) if (!excluded.includes(name)) projection[name] = column;
|
|
4834
|
+
return projection;
|
|
4835
|
+
};
|
|
4836
|
+
/** The same exclusion as a drizzle `db.query` `columns` denylist. */
|
|
4837
|
+
var hiddenColumnsOption = (tableColumns, collection) => {
|
|
4838
|
+
const excluded = excludedColumnNames(tableColumns, collection);
|
|
4839
|
+
if (excluded.length === 0) return void 0;
|
|
4840
|
+
return Object.fromEntries(excluded.map((name) => [name, false]));
|
|
4841
|
+
};
|
|
4842
|
+
/**
|
|
4843
|
+
* The columns to keep out of a response, by name.
|
|
4844
|
+
*
|
|
4845
|
+
* `tableColumns` is whatever `getTableColumns` returned, which is `undefined`
|
|
4846
|
+
* for anything that is not a real drizzle table — a stub in a test, a derived
|
|
4847
|
+
* or nested path with no table behind it. Nothing to exclude is the right
|
|
4848
|
+
* answer there, and it has to be an answer rather than a throw: this runs on
|
|
4849
|
+
* the read path of every collection, opted in or not.
|
|
4850
|
+
*/
|
|
4851
|
+
var excludedColumnNames = (tableColumns, collection) => {
|
|
4852
|
+
if (!tableColumns || typeof tableColumns !== "object") return [];
|
|
4853
|
+
const byName = new Set(collection ? searchColumnNames(collection) : []);
|
|
4854
|
+
return Object.keys(tableColumns).filter((name) => byName.has(name) || isSearchIndexColumn(tableColumns[name]));
|
|
4855
|
+
};
|
|
4856
|
+
//#endregion
|
|
4857
|
+
//#region src/schema/auth-users-columns.ts
|
|
4858
|
+
/**
|
|
4859
|
+
* `email` is NOT NULL on purpose, and the anonymous sign-in route depends on it
|
|
4860
|
+
* — it synthesizes `anon_<32 hex>@anonymous.local` rather than inserting NULL.
|
|
4861
|
+
* The 320-char bound (RFC 5321) is a CHECK rather than a `VARCHAR(n)`, added
|
|
4862
|
+
* separately by `ensureAuthTablesExist` so it can be `NOT VALID` on an adopted
|
|
4863
|
+
* table that already holds a longer row.
|
|
4864
|
+
*/
|
|
4865
|
+
var AUTH_USERS_COLUMNS = [
|
|
4866
|
+
{
|
|
4867
|
+
column: "email",
|
|
4868
|
+
type: "TEXT",
|
|
4869
|
+
notNull: true
|
|
4870
|
+
},
|
|
4871
|
+
{
|
|
4872
|
+
column: "display_name",
|
|
4873
|
+
type: "TEXT"
|
|
4874
|
+
},
|
|
4875
|
+
{
|
|
4876
|
+
column: "photo_url",
|
|
4877
|
+
type: "TEXT"
|
|
4878
|
+
},
|
|
4879
|
+
{
|
|
4880
|
+
column: "roles",
|
|
4881
|
+
type: "TEXT[]",
|
|
4882
|
+
default: "'{}'",
|
|
4883
|
+
notNull: true
|
|
4884
|
+
},
|
|
4885
|
+
{
|
|
4886
|
+
column: "password_hash",
|
|
4887
|
+
type: "TEXT"
|
|
4888
|
+
},
|
|
4889
|
+
{
|
|
4890
|
+
column: "email_verified",
|
|
4891
|
+
type: "BOOLEAN",
|
|
4892
|
+
default: "FALSE",
|
|
4893
|
+
notNull: true
|
|
4894
|
+
},
|
|
4895
|
+
{
|
|
4896
|
+
column: "email_verification_token",
|
|
4897
|
+
type: "TEXT"
|
|
4898
|
+
},
|
|
4899
|
+
{
|
|
4900
|
+
column: "email_verification_sent_at",
|
|
4901
|
+
type: "TIMESTAMP WITH TIME ZONE"
|
|
4902
|
+
},
|
|
4903
|
+
{
|
|
4904
|
+
column: "is_anonymous",
|
|
4905
|
+
type: "BOOLEAN",
|
|
4906
|
+
default: "FALSE",
|
|
4907
|
+
notNull: true
|
|
4908
|
+
},
|
|
4909
|
+
{
|
|
4910
|
+
column: "metadata",
|
|
4911
|
+
type: "JSONB",
|
|
4912
|
+
default: "'{}'",
|
|
4913
|
+
notNull: true
|
|
4914
|
+
},
|
|
4915
|
+
{
|
|
4916
|
+
column: "tokens_valid_after",
|
|
4917
|
+
type: "TIMESTAMP WITH TIME ZONE"
|
|
4918
|
+
},
|
|
4919
|
+
{
|
|
4920
|
+
column: "created_at",
|
|
4921
|
+
type: "TIMESTAMP WITH TIME ZONE",
|
|
4922
|
+
default: "NOW()",
|
|
4923
|
+
notNull: true
|
|
4924
|
+
},
|
|
4925
|
+
{
|
|
4926
|
+
column: "updated_at",
|
|
4927
|
+
type: "TIMESTAMP WITH TIME ZONE",
|
|
4928
|
+
default: "NOW()",
|
|
4929
|
+
notNull: true
|
|
4930
|
+
}
|
|
4931
|
+
];
|
|
4932
|
+
var BY_COLUMN = new Map(AUTH_USERS_COLUMNS.map((c) => [c.column, c]));
|
|
4933
|
+
/** Type + inline constraints, as they appear after the column name. */
|
|
4934
|
+
function authUsersColumnSql(spec) {
|
|
4935
|
+
return [
|
|
4936
|
+
spec.type,
|
|
4937
|
+
spec.default !== void 0 ? `DEFAULT ${spec.default}` : "",
|
|
4938
|
+
spec.notNull ? "NOT NULL" : ""
|
|
4939
|
+
].filter(Boolean).join(" ");
|
|
4940
|
+
}
|
|
4941
|
+
/**
|
|
4942
|
+
* The auth-owned definition for a physical column name, or `undefined` when
|
|
4943
|
+
* auth does not own it.
|
|
4944
|
+
*
|
|
4945
|
+
* Callers pass the RESOLVED column name (after `columnName` mapping), because
|
|
4946
|
+
* that is the only name the three creators agree on: the scaffold's users
|
|
4947
|
+
* collection spells the property `displayName` and the column `display_name`.
|
|
4948
|
+
*/
|
|
4949
|
+
function authUsersColumnDefinition(column) {
|
|
4950
|
+
const spec = BY_COLUMN.get(column);
|
|
4951
|
+
return spec ? authUsersColumnSql(spec) : void 0;
|
|
4952
|
+
}
|
|
4953
|
+
/**
|
|
4954
|
+
* Whether a collection is an auth collection, i.e. whether the definitions in
|
|
4955
|
+
* this module apply to its table at all.
|
|
4956
|
+
*
|
|
4957
|
+
* Duplicated in shape from `@rebasepro/common`'s policy defaults on purpose:
|
|
4958
|
+
* that one takes a `CollectionConfig`, this one is called from DDL code paths
|
|
4959
|
+
* that hold looser objects, and both spellings must accept `auth: true` as well
|
|
4960
|
+
* as `auth: { enabled: true }`.
|
|
4961
|
+
*/
|
|
4962
|
+
function isAuthCollection(collection) {
|
|
4963
|
+
const auth = collection?.auth;
|
|
4964
|
+
if (auth === true) return true;
|
|
4965
|
+
return typeof auth === "object" && auth !== null && auth.enabled === true;
|
|
4966
|
+
}
|
|
4967
|
+
//#endregion
|
|
4968
|
+
export { resolveCollectionRelations as A, legacyForeignKeyName as B, securityRuleToConditions as C, getEnumVarName as D, getColumnName as E, createRelationRef as F, camelCase as G, getPolicyNamesForRule as H, createRelationRefWithData as I, DEFAULT_ONE_OF_VALUE as J, toSnakeCase as K, normalizeToEntityRelation as L, getDeclaredPrimaryKeys as M, isAddressableId as N, getTableName as O, parseIdValues as P, Vector as Q, updateDateAutoValues as R, policyToPostgres as S, findRelation as T, isPrototypePollutingKey as U, toPostgresIdentifier as V, mergeDeep as W, hasForeignKeyOnTarget as X, resolveClientListLimit as Y, isManyToMany as Z, resolveStringColumnLength as _, SEARCH_TEXT_FN as a, resolveJunctionSpecs as b, buildSearchColumnSpec as c, searchHelperFunctions as d, searchIndexStatements as f, relationalCollections as g, CollectionRegistry as h, isAuthCollection as i, buildCompositeId as j, getTableVarName as k, hiddenColumnsOption as l, buildSdkData as m, authUsersColumnDefinition as n, SEARCH_UNACCENT_FN as o, visibleColumnProjection as p, DEFAULT_ONE_OF_TYPE as q, authUsersColumnSql as r, assertSearchIsPostgresOnly as s, AUTH_USERS_COLUMNS as t, searchExtensionStatements as u, getJunctionCollectionConfig as v, findAnonymousGrants as w, getEffectiveSecurityRules as x, getJunctionSecurityRules as y, generateForeignKeyName as z };
|
|
4415
4969
|
|
|
4416
|
-
//# sourceMappingURL=
|
|
4970
|
+
//# sourceMappingURL=auth-users-columns-BQttUZE2.js.map
|