@venturekit/data 0.0.37 → 0.0.39

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.
Files changed (45) hide show
  1. package/README.md +62 -0
  2. package/dist/files/postgres.d.ts.map +1 -1
  3. package/dist/files/postgres.js +10 -5
  4. package/dist/files/postgres.js.map +1 -1
  5. package/dist/flags/flags.d.ts +153 -0
  6. package/dist/flags/flags.d.ts.map +1 -0
  7. package/dist/flags/flags.js +266 -0
  8. package/dist/flags/flags.js.map +1 -0
  9. package/dist/flags/index.d.ts +3 -0
  10. package/dist/flags/index.d.ts.map +1 -0
  11. package/dist/flags/index.js +2 -0
  12. package/dist/flags/index.js.map +1 -0
  13. package/dist/idempotency/postgres.d.ts.map +1 -1
  14. package/dist/idempotency/postgres.js +2 -2
  15. package/dist/idempotency/postgres.js.map +1 -1
  16. package/dist/internal/identifier.d.ts +15 -1
  17. package/dist/internal/identifier.d.ts.map +1 -1
  18. package/dist/internal/identifier.js +14 -1
  19. package/dist/internal/identifier.js.map +1 -1
  20. package/dist/jobs/postgres.d.ts.map +1 -1
  21. package/dist/jobs/postgres.js +3 -3
  22. package/dist/jobs/postgres.js.map +1 -1
  23. package/dist/migrations/runners/custom.js +4 -2
  24. package/dist/migrations/runners/custom.js.map +1 -1
  25. package/dist/outbox/postgres.d.ts.map +1 -1
  26. package/dist/outbox/postgres.js +2 -2
  27. package/dist/outbox/postgres.js.map +1 -1
  28. package/dist/query/pool.d.ts +23 -1
  29. package/dist/query/pool.d.ts.map +1 -1
  30. package/dist/query/pool.js +32 -2
  31. package/dist/query/pool.js.map +1 -1
  32. package/dist/query/transaction.d.ts +8 -0
  33. package/dist/query/transaction.d.ts.map +1 -1
  34. package/dist/query/transaction.js +54 -15
  35. package/dist/query/transaction.js.map +1 -1
  36. package/dist/search/index.d.ts +3 -0
  37. package/dist/search/index.d.ts.map +1 -0
  38. package/dist/search/index.js +2 -0
  39. package/dist/search/index.js.map +1 -0
  40. package/dist/search/search.d.ts +122 -0
  41. package/dist/search/search.d.ts.map +1 -0
  42. package/dist/search/search.js +164 -0
  43. package/dist/search/search.js.map +1 -0
  44. package/package.json +10 -2
  45. package/src/sql/vk_data_005_flags_settings.sql +53 -0
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Search helpers — the SQL-building half of "search my tables", kept pure so
3
+ * it is unit-testable and works with `query()` / `tx.query` alike.
4
+ *
5
+ * Three tools, from cheapest to most capable:
6
+ *
7
+ * - **LIKE / ILIKE** for short, prefix-ish lookups (names, slugs):
8
+ * {@link containsPattern} / {@link prefixPattern} escape `%`, `_` and the
9
+ * escape character itself, so a member typing `100%` matches the literal
10
+ * text instead of everything. Pair with a `pg_trgm` GIN index
11
+ * ({@link trigramIndexSql}) once the table grows.
12
+ * - **Full-text search** for prose (posts, descriptions):
13
+ * {@link toWebSearchQuery} normalizes user input for
14
+ * `websearch_to_tsquery` (never throws on odd input, unlike
15
+ * `to_tsquery`), and {@link ftsColumnSql} / {@link ftsIndexSql} generate
16
+ * the migration lines for a generated, indexed `tsvector` column.
17
+ * {@link ftsWhereSql} / {@link ftsRankSql} / {@link ftsHeadlineSql} are
18
+ * the query-side fragments.
19
+ * - **Keyset pagination** for any ordered listing:
20
+ * {@link encodeCursor} / {@link decodeCursor} carry `(sortValue, id)`
21
+ * opaquely and tamper-evidently enough for a URL.
22
+ *
23
+ * Nothing here executes SQL; every fragment takes the `$n` parameter index
24
+ * you will bind, so the helpers compose with the rest of your statement.
25
+ */
26
+ /** Escape character the patterns use; add `ESCAPE '\\'` only if you changed `standard_conforming_strings`. */
27
+ export declare const LIKE_ESCAPE = "\\";
28
+ /** Escape `%`, `_` and the escape character so `term` matches literally inside a LIKE pattern. */
29
+ export declare function escapeLike(term: string): string;
30
+ /** `%term%` with the term escaped — `WHERE name ILIKE $1`. */
31
+ export declare function containsPattern(term: string): string;
32
+ /** `term%` with the term escaped — `WHERE slug LIKE $1` (index-friendly with `text_pattern_ops`). */
33
+ export declare function prefixPattern(term: string): string;
34
+ /**
35
+ * Migration line for a trigram index that accelerates `ILIKE '%term%'`.
36
+ * Requires `CREATE EXTENSION IF NOT EXISTS pg_trgm;` once per database.
37
+ */
38
+ export declare function trigramIndexSql(table: string, column: string): string;
39
+ /** Text-search configurations Postgres ships with; anything else must exist in the database. */
40
+ export type TextSearchConfig = 'simple' | 'english' | 'french' | 'arabic' | 'spanish' | 'german' | 'portuguese' | 'italian' | 'dutch' | (string & {});
41
+ /**
42
+ * Normalize raw user input for `websearch_to_tsquery($cfg, $1)`:
43
+ * trims, collapses whitespace, strips control characters and caps length
44
+ * (a 10 kB query is never a search). Returns `''` when nothing searchable
45
+ * remains — callers skip the FTS predicate in that case.
46
+ *
47
+ * `websearch_to_tsquery` itself tolerates unbalanced quotes and stray
48
+ * operators, so no operator escaping is needed; this only bounds the input.
49
+ */
50
+ export declare function toWebSearchQuery(input: string | null | undefined, options?: {
51
+ maxLength?: number;
52
+ }): string;
53
+ export interface FtsColumnOptions {
54
+ /** Name of the generated column. Default `search_vector`. */
55
+ column?: string;
56
+ /** Text-search configuration. Default `simple` (no stemming — safe for mixed-language content). */
57
+ config?: TextSearchConfig;
58
+ /**
59
+ * Source columns with their weight (`A` highest … `D`). Order is
60
+ * significant only for readability.
61
+ */
62
+ sources: Array<{
63
+ column: string;
64
+ weight?: 'A' | 'B' | 'C' | 'D';
65
+ }>;
66
+ }
67
+ /**
68
+ * Migration line adding a STORED generated `tsvector` column — kept in sync
69
+ * by Postgres on every write, no trigger, no application code:
70
+ *
71
+ * ```sql
72
+ * ALTER TABLE posts ADD COLUMN IF NOT EXISTS search_vector tsvector
73
+ * GENERATED ALWAYS AS (
74
+ * setweight(to_tsvector('simple', coalesce(title, '')), 'A') ||
75
+ * setweight(to_tsvector('simple', coalesce(body, '')), 'B')
76
+ * ) STORED;
77
+ * ```
78
+ */
79
+ export declare function ftsColumnSql(table: string, options: FtsColumnOptions): string;
80
+ /** Migration line for the GIN index the FTS predicate needs. */
81
+ export declare function ftsIndexSql(table: string, column?: string): string;
82
+ /** `search_vector @@ websearch_to_tsquery('simple', $1)` — bind the normalized query at `paramIndex`. */
83
+ export declare function ftsWhereSql(paramIndex: number, options?: {
84
+ column?: string;
85
+ config?: TextSearchConfig;
86
+ }): string;
87
+ /** `ts_rank_cd(search_vector, websearch_to_tsquery(...))` for `ORDER BY … DESC`. */
88
+ export declare function ftsRankSql(paramIndex: number, options?: {
89
+ column?: string;
90
+ config?: TextSearchConfig;
91
+ }): string;
92
+ /**
93
+ * `ts_headline(...)` — a snippet with the matches wrapped in `<mark>` … `</mark>`.
94
+ * The source column is HTML-escaped by Postgres only for the markers, so
95
+ * escape `textColumn`'s content client-side if it may contain markup.
96
+ */
97
+ export declare function ftsHeadlineSql(textColumn: string, paramIndex: number, options?: {
98
+ config?: TextSearchConfig;
99
+ maxWords?: number;
100
+ minWords?: number;
101
+ }): string;
102
+ export interface KeysetCursor {
103
+ /** The sort column's value of the last row (ISO string for dates, number, or string). */
104
+ value: string | number;
105
+ /** Tie-breaker: the last row's id. */
106
+ id: string;
107
+ }
108
+ /** Opaque, URL-safe cursor. */
109
+ export declare function encodeCursor(cursor: KeysetCursor): string;
110
+ /** `null` for anything that is not a cursor this module produced. */
111
+ export declare function decodeCursor(token: string | null | undefined): KeysetCursor | null;
112
+ /**
113
+ * `(created_at, id) < ($n, $n+1)` — the row-value comparison for the NEXT
114
+ * page of a `ORDER BY created_at DESC, id DESC` listing (`direction: 'desc'`,
115
+ * the default) or `>` for ascending. Bind `cursor.value` at `paramIndex`
116
+ * and `cursor.id` at `paramIndex + 1`.
117
+ */
118
+ export declare function keysetWhereSql(sortColumn: string, paramIndex: number, options?: {
119
+ idColumn?: string;
120
+ direction?: 'asc' | 'desc';
121
+ }): string;
122
+ //# sourceMappingURL=search.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../src/search/search.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;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kept pure so
3
+ * it is unit-testable and works with `query()` / `tx.query` alike.
4
+ *
5
+ * Three tools, from cheapest to most capable:
6
+ *
7
+ * - **LIKE / ILIKE** for short, prefix-ish lookups (names, slugs):
8
+ * {@link containsPattern} / {@link prefixPattern} escape `%`, `_` and the
9
+ * escape character itself, so a member typing `100%` matches the literal
10
+ * text instead of everything. Pair with a `pg_trgm` GIN index
11
+ * ({@link trigramIndexSql}) once the table grows.
12
+ * - **Full-text search** for prose (posts, descriptions):
13
+ * {@link toWebSearchQuery} normalizes user input for
14
+ * `websearch_to_tsquery` (never throws on odd input, unlike
15
+ * `to_tsquery`), and {@link ftsColumnSql} / {@link ftsIndexSql} generate
16
+ * the migration lines for a generated, indexed `tsvector` column.
17
+ * {@link ftsWhereSql} / {@link ftsRankSql} / {@link ftsHeadlineSql} are
18
+ * the query-side fragments.
19
+ * - **Keyset pagination** for any ordered listing:
20
+ * {@link encodeCursor} / {@link decodeCursor} carry `(sortValue, id)`
21
+ * opaquely and tamper-evidently enough for a URL.
22
+ *
23
+ * Nothing here executes SQL; every fragment takes the `$n` parameter index
24
+ * you will bind, so the helpers compose with the rest of your statement.
25
+ */
26
+ import { assertSqlIdentifier } from '../internal/identifier.js';
27
+ // ---------------------------------------------------------------------------
28
+ // LIKE
29
+ // ---------------------------------------------------------------------------
30
+ /** Escape character the patterns use; add `ESCAPE '\\'` only if you changed `standard_conforming_strings`. */
31
+ export const LIKE_ESCAPE = '\\';
32
+ /** Escape `%`, `_` and the escape character so `term` matches literally inside a LIKE pattern. */
33
+ export function escapeLike(term) {
34
+ return term.replace(/[\\%_]/g, (c) => `${LIKE_ESCAPE}${c}`);
35
+ }
36
+ /** `%term%` with the term escaped — `WHERE name ILIKE $1`. */
37
+ export function containsPattern(term) {
38
+ return `%${escapeLike(term.trim())}%`;
39
+ }
40
+ /** `term%` with the term escaped — `WHERE slug LIKE $1` (index-friendly with `text_pattern_ops`). */
41
+ export function prefixPattern(term) {
42
+ return `${escapeLike(term.trim())}%`;
43
+ }
44
+ /**
45
+ * Migration line for a trigram index that accelerates `ILIKE '%term%'`.
46
+ * Requires `CREATE EXTENSION IF NOT EXISTS pg_trgm;` once per database.
47
+ */
48
+ export function trigramIndexSql(table, column) {
49
+ assertSqlIdentifier(table, 'trigram index table');
50
+ assertSqlIdentifier(column, 'trigram index column');
51
+ return `CREATE INDEX IF NOT EXISTS ${table}_${column}_trgm_idx ON ${table} USING gin (${column} gin_trgm_ops);`;
52
+ }
53
+ /**
54
+ * Normalize raw user input for `websearch_to_tsquery($cfg, $1)`:
55
+ * trims, collapses whitespace, strips control characters and caps length
56
+ * (a 10 kB query is never a search). Returns `''` when nothing searchable
57
+ * remains — callers skip the FTS predicate in that case.
58
+ *
59
+ * `websearch_to_tsquery` itself tolerates unbalanced quotes and stray
60
+ * operators, so no operator escaping is needed; this only bounds the input.
61
+ */
62
+ export function toWebSearchQuery(input, options = {}) {
63
+ if (!input)
64
+ return '';
65
+ const max = options.maxLength ?? 200;
66
+ const cleaned = input.replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim();
67
+ return cleaned.length > max ? cleaned.slice(0, max).trim() : cleaned;
68
+ }
69
+ /**
70
+ * Migration line adding a STORED generated `tsvector` column — kept in sync
71
+ * by Postgres on every write, no trigger, no application code:
72
+ *
73
+ * ```sql
74
+ * ALTER TABLE posts ADD COLUMN IF NOT EXISTS search_vector tsvector
75
+ * GENERATED ALWAYS AS (
76
+ * setweight(to_tsvector('simple', coalesce(title, '')), 'A') ||
77
+ * setweight(to_tsvector('simple', coalesce(body, '')), 'B')
78
+ * ) STORED;
79
+ * ```
80
+ */
81
+ export function ftsColumnSql(table, options) {
82
+ assertSqlIdentifier(table, 'fts table');
83
+ const column = options.column ?? 'search_vector';
84
+ assertSqlIdentifier(column, 'fts column');
85
+ const config = assertConfig(options.config ?? 'simple');
86
+ if (options.sources.length === 0)
87
+ throw new Error('[venturekit/data] ftsColumnSql: at least one source column is required');
88
+ const parts = options.sources.map((s) => {
89
+ assertSqlIdentifier(s.column, 'fts source column');
90
+ return `setweight(to_tsvector('${config}', coalesce(${s.column}, '')), '${s.weight ?? 'D'}')`;
91
+ });
92
+ return `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${column} tsvector GENERATED ALWAYS AS (${parts.join(' || ')}) STORED;`;
93
+ }
94
+ /** Migration line for the GIN index the FTS predicate needs. */
95
+ export function ftsIndexSql(table, column = 'search_vector') {
96
+ assertSqlIdentifier(table, 'fts index table');
97
+ assertSqlIdentifier(column, 'fts index column');
98
+ return `CREATE INDEX IF NOT EXISTS ${table}_${column}_idx ON ${table} USING gin (${column});`;
99
+ }
100
+ /** `search_vector @@ websearch_to_tsquery('simple', $1)` — bind the normalized query at `paramIndex`. */
101
+ export function ftsWhereSql(paramIndex, options = {}) {
102
+ const column = options.column ?? 'search_vector';
103
+ assertSqlIdentifier(column, 'fts column');
104
+ return `${column} @@ websearch_to_tsquery('${assertConfig(options.config ?? 'simple')}', $${paramIndex})`;
105
+ }
106
+ /** `ts_rank_cd(search_vector, websearch_to_tsquery(...))` for `ORDER BY … DESC`. */
107
+ export function ftsRankSql(paramIndex, options = {}) {
108
+ const column = options.column ?? 'search_vector';
109
+ assertSqlIdentifier(column, 'fts column');
110
+ return `ts_rank_cd(${column}, websearch_to_tsquery('${assertConfig(options.config ?? 'simple')}', $${paramIndex}))`;
111
+ }
112
+ /**
113
+ * `ts_headline(...)` — a snippet with the matches wrapped in `<mark>` … `</mark>`.
114
+ * The source column is HTML-escaped by Postgres only for the markers, so
115
+ * escape `textColumn`'s content client-side if it may contain markup.
116
+ */
117
+ export function ftsHeadlineSql(textColumn, paramIndex, options = {}) {
118
+ assertSqlIdentifier(textColumn, 'fts headline column');
119
+ const maxWords = Math.max(1, Math.floor(options.maxWords ?? 35));
120
+ const minWords = Math.max(1, Math.min(maxWords, Math.floor(options.minWords ?? 15)));
121
+ return (`ts_headline('${assertConfig(options.config ?? 'simple')}', ${textColumn}, websearch_to_tsquery('${assertConfig(options.config ?? 'simple')}', $${paramIndex}), ` +
122
+ `'StartSel=<mark>, StopSel=</mark>, MaxWords=${maxWords}, MinWords=${minWords}')`);
123
+ }
124
+ function assertConfig(config) {
125
+ if (!/^[a-z_]{1,32}$/.test(config)) {
126
+ throw new Error(`[venturekit/data] invalid text-search configuration: ${JSON.stringify(config)}`);
127
+ }
128
+ return config;
129
+ }
130
+ /** Opaque, URL-safe cursor. */
131
+ export function encodeCursor(cursor) {
132
+ return Buffer.from(JSON.stringify([cursor.value, cursor.id]), 'utf8').toString('base64url');
133
+ }
134
+ /** `null` for anything that is not a cursor this module produced. */
135
+ export function decodeCursor(token) {
136
+ if (!token)
137
+ return null;
138
+ try {
139
+ const parsed = JSON.parse(Buffer.from(token, 'base64url').toString('utf8'));
140
+ if (!Array.isArray(parsed) || parsed.length !== 2)
141
+ return null;
142
+ const [value, id] = parsed;
143
+ if ((typeof value !== 'string' && typeof value !== 'number') || typeof id !== 'string')
144
+ return null;
145
+ return { value, id };
146
+ }
147
+ catch {
148
+ return null;
149
+ }
150
+ }
151
+ /**
152
+ * `(created_at, id) < ($n, $n+1)` — the row-value comparison for the NEXT
153
+ * page of a `ORDER BY created_at DESC, id DESC` listing (`direction: 'desc'`,
154
+ * the default) or `>` for ascending. Bind `cursor.value` at `paramIndex`
155
+ * and `cursor.id` at `paramIndex + 1`.
156
+ */
157
+ export function keysetWhereSql(sortColumn, paramIndex, options = {}) {
158
+ assertSqlIdentifier(sortColumn, 'keyset sort column');
159
+ const idColumn = options.idColumn ?? 'id';
160
+ assertSqlIdentifier(idColumn, 'keyset id column');
161
+ const op = (options.direction ?? 'desc') === 'desc' ? '<' : '>';
162
+ return `(${sortColumn}, ${idColumn}) ${op} ($${paramIndex}, $${paramIndex + 1})`;
163
+ }
164
+ //# sourceMappingURL=search.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search.js","sourceRoot":"","sources":["../../src/search/search.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;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MAAM,UAAU,cAAc,CAC5B,UAAkB,EAClB,UAAkB,EAClB,UAA6D,EAAE;IAE/D,mBAAmB,CAAC,UAAU,EAAE,oBAAoB,CAAC,CAAC;IACtD,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,IAAI,CAAC;IAC1C,mBAAmB,CAAC,QAAQ,EAAE,kBAAkB,CAAC,CAAC;IAClD,MAAM,EAAE,GAAG,CAAC,OAAO,CAAC,SAAS,IAAI,MAAM,CAAC,KAAK,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;IAChE,OAAO,IAAI,UAAU,KAAK,QAAQ,KAAK,EAAE,MAAM,UAAU,MAAM,UAAU,GAAG,CAAC,GAAG,CAAC;AACnF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venturekit/data",
3
- "version": "0.0.37",
3
+ "version": "0.0.39",
4
4
  "description": "Database and data layer for VentureKit",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -46,11 +46,19 @@
46
46
  "./files": {
47
47
  "types": "./dist/files/index.d.ts",
48
48
  "import": "./dist/files/index.js"
49
+ },
50
+ "./flags": {
51
+ "types": "./dist/flags/index.d.ts",
52
+ "import": "./dist/flags/index.js"
53
+ },
54
+ "./search": {
55
+ "types": "./dist/search/index.d.ts",
56
+ "import": "./dist/search/index.js"
49
57
  }
50
58
  },
51
59
  "dependencies": {
52
60
  "@aws-sdk/client-secrets-manager": "^3.1126.0",
53
- "@venturekit/core": "0.0.37",
61
+ "@venturekit/core": "0.0.39",
54
62
  "pg": "^8.12.0"
55
63
  },
56
64
  "devDependencies": {
@@ -0,0 +1,53 @@
1
+ -- @venturekit/data — feature flags + tenant settings.
2
+ --
3
+ -- Tables created by this migration:
4
+ -- vk_feature_flags — one row per flag: global default + rollout
5
+ -- vk_feature_flag_overrides — per-tenant / per-user pins
6
+ -- vk_tenant_settings — one JSONB document per tenant
7
+ --
8
+ -- Backs `@venturekit/data/flags` (`createFlags()`, `getTenantSettings()`).
9
+ -- Additive for existing projects: nothing reads these tables until an app
10
+ -- calls the helpers.
11
+ --
12
+ -- Flags are evaluated in memory from a periodically refreshed snapshot of
13
+ -- BOTH flag tables (one query each per refresh), so a request costs no
14
+ -- round-trip; edits propagate within the evaluator's TTL.
15
+
16
+ CREATE TABLE IF NOT EXISTS vk_feature_flags (
17
+ key TEXT PRIMARY KEY,
18
+ description TEXT,
19
+ -- Global default when no override / rollout decides.
20
+ enabled BOOLEAN NOT NULL DEFAULT FALSE,
21
+ -- 0..100. With `enabled = false`, this share of subjects (hashed by
22
+ -- key + subject id, so a subject is stable across evaluations) gets the
23
+ -- flag ON — the gradual rollout. Ignored when `enabled = true`.
24
+ rollout_percent INTEGER NOT NULL DEFAULT 0
25
+ CHECK (rollout_percent BETWEEN 0 AND 100),
26
+ -- Free-form: owner, ticket, planned removal date.
27
+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
28
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
29
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
30
+ );
31
+
32
+ CREATE TABLE IF NOT EXISTS vk_feature_flag_overrides (
33
+ flag_key TEXT NOT NULL REFERENCES vk_feature_flags (key) ON DELETE CASCADE,
34
+ -- 'tenant' or 'user'. A user pin beats a tenant pin beats the flag.
35
+ scope TEXT NOT NULL CHECK (scope IN ('tenant', 'user')),
36
+ scope_id TEXT NOT NULL,
37
+ enabled BOOLEAN NOT NULL,
38
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
39
+ PRIMARY KEY (flag_key, scope, scope_id)
40
+ );
41
+
42
+ CREATE TABLE IF NOT EXISTS vk_tenant_settings (
43
+ tenant_id TEXT PRIMARY KEY,
44
+ settings JSONB NOT NULL DEFAULT '{}'::jsonb,
45
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
46
+ );
47
+
48
+ COMMENT ON TABLE vk_feature_flags IS
49
+ 'Feature flags: global default + percentage rollout. Owned by @venturekit/data (flags helpers).';
50
+ COMMENT ON TABLE vk_feature_flag_overrides IS
51
+ 'Per-tenant / per-user feature-flag pins. user > tenant > flag.';
52
+ COMMENT ON TABLE vk_tenant_settings IS
53
+ 'One JSONB settings document per tenant, merged on write by @venturekit/data setTenantSettings().';