kitcn 0.31.0 → 0.31.1

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.
@@ -1,7 +1,7 @@
1
- import { t as DirectAggregate } from "../../runtime-BcvcfaP8.js";
1
+ import { t as DirectAggregate } from "../../runtime-B-8HKSIE.js";
2
2
  import { n as Columns } from "../../symbols-DDNAddkd.js";
3
3
  import { d as INTERNAL_CREATION_TIME_FIELD, f as PUBLIC_CREATED_AT_FIELD, m as usesSystemCreatedAtAlias } from "../../index-utils-C1DyktHe.js";
4
- import { Q as normalizeTemporalComparableValue, a as AGGREGATE_STATE_TABLE, c as getAggregateIndexDefinitions, d as COUNT_ERROR, ht as mapWithConcurrency, i as AGGREGATE_RANK_TREE_TABLE, l as getRankIndexDefinitions, m as createError, n as AGGREGATE_EXTREMA_TABLE, r as AGGREGATE_MEMBER_TABLE, s as rankAggregateName, t as AGGREGATE_BUCKET_TABLE, u as AGGREGATE_ERROR } from "../../schema-hL2FWCE7.js";
4
+ import { Q as normalizeTemporalComparableValue, a as AGGREGATE_STATE_TABLE, c as getAggregateIndexDefinitions, d as COUNT_ERROR, ht as mapWithConcurrency, i as AGGREGATE_RANK_TREE_TABLE, l as getRankIndexDefinitions, m as createError, n as AGGREGATE_EXTREMA_TABLE, r as AGGREGATE_MEMBER_TABLE, s as rankAggregateName, t as AGGREGATE_BUCKET_TABLE, u as AGGREGATE_ERROR } from "../../schema-DbPcDW-N.js";
5
5
 
6
6
  //#region src/orm/transaction-cache.ts
7
7
  /**
@@ -1411,23 +1411,21 @@ const setCountStateError = async (db, tableName, indexName, error, kind = AGGREG
1411
1411
  * reports whether anything is left. Callers drive it to completion across
1412
1412
  * transactions, so clearing a large index never has to fit in one mutation.
1413
1413
  *
1414
- * Members are removed through the normal delta machinery rather than raw
1415
- * deletes, so buckets and extrema stay consistent with the members that remain
1416
- * at every intermediate step. That keeps concurrent writers correct while the
1417
- * clear drains. Residual bucket/extrema rows (drift with no member behind them)
1418
- * are swept only once no members are left, and the loop re-checks members
1419
- * afterwards.
1414
+ * Member rows are deleted outright rather than run back through the delta
1415
+ * machinery. The bucket and extrema branches below drop every row this index
1416
+ * owns whatever it holds, so folding a removal delta into a bucket first would
1417
+ * only rewrite a document this same clear is about to delete.
1418
+ *
1419
+ * Branch order is load-bearing: buckets and extrema are swept only once no
1420
+ * members are left, and the loop re-checks members afterwards. The intermediate
1421
+ * "members gone, buckets still populated" state is safe because `setCountState`
1422
+ * refuses to leave CLEARING while a bucket or extrema row survives, and the
1423
+ * CLEARING write barrier keeps concurrent writers out of the index.
1420
1424
  */
1421
1425
  const clearCountIndexChunk = async (db, tableName, indexName, batchSize) => {
1422
1426
  const members = await takeMembersForIndex(db, tableName, indexName, batchSize);
1423
1427
  if (members.length > 0) {
1424
- await flushAggregateMembershipDeltas(db, tableName, indexName, members.map((member) => computeMembershipDelta(member, {
1425
- tableName,
1426
- indexName,
1427
- docId: member.docId,
1428
- keyParts: null,
1429
- metricValues: null
1430
- })));
1428
+ for (const member of members) await db.delete(AGGREGATE_MEMBER_TABLE, member._id);
1431
1429
  return {
1432
1430
  done: false,
1433
1431
  processed: members.length
@@ -1593,36 +1591,35 @@ const rankCtx = (db) => ({
1593
1591
  db,
1594
1592
  orm: void 0
1595
1593
  });
1596
- /** Trees dropped per invocation once every rank member has been removed. */
1597
- const RANK_TREE_DROP_BATCH = 16;
1598
1594
  /**
1599
- * Removes at most `batchSize` rank members and reports whether anything is
1600
- * left. Each member is removed from the btree before its row is dropped, so the
1601
- * tree stays consistent with the members that remain and a partially drained
1602
- * clear can safely resume in a later mutation.
1595
+ * Removes at most `batchSize` documents of a rank index's stored state and
1596
+ * reports whether anything is left. Callers drive it to completion across
1597
+ * transactions, so clearing a large index never has to fit in one mutation.
1598
+ *
1599
+ * Member rows are dropped without touching the btree. The tree branch below
1600
+ * deletes every node whatever it contains, so removing a member key first would
1601
+ * only buy a root-to-leaf descent plus an aggregate patch per level on nodes
1602
+ * this same clear is about to delete.
1603
+ *
1604
+ * Branch order is load-bearing: a member delete recreates the tree it lands on,
1605
+ * so the members must be gone before the first node is dropped. The
1606
+ * intermediate "members gone, tree still full" state is safe because
1607
+ * `setCountState` refuses to leave CLEARING while a tree row survives, and the
1608
+ * CLEARING write barrier keeps concurrent writers out of the index.
1603
1609
  */
1604
1610
  const clearRankIndexChunk = async (db, tableName, indexName, batchSize) => {
1605
- const aggregate = rankAggregate(tableName, indexName);
1606
- const ctx = rankCtx(db);
1607
1611
  const members = await takeRankMembers(db, tableName, indexName, batchSize);
1608
1612
  if (members.length > 0) {
1609
- for (const member of members) {
1610
- if (member.rankKey !== void 0) await aggregate.deleteIfExists(ctx, {
1611
- id: member.docId,
1612
- key: member.rankKey,
1613
- namespace: member.rankNamespace
1614
- });
1615
- await db.delete(AGGREGATE_MEMBER_TABLE, member._id);
1616
- }
1613
+ for (const member of members) await db.delete(AGGREGATE_MEMBER_TABLE, member._id);
1617
1614
  return {
1618
1615
  done: false,
1619
1616
  processed: members.length
1620
1617
  };
1621
1618
  }
1622
- const done = await aggregate.deleteTrees(ctx, RANK_TREE_DROP_BATCH);
1619
+ const { documents, done } = await rankAggregate(tableName, indexName).deleteTrees(rankCtx(db), batchSize);
1623
1620
  return {
1624
1621
  done,
1625
- processed: done ? 0 : RANK_TREE_DROP_BATCH
1622
+ processed: documents
1626
1623
  };
1627
1624
  };
1628
1625
  const reconcileRankMembership = async (db, params) => {
@@ -1,5 +1,5 @@
1
- import { $n as TableName, $t as OrmLifecycleChange, An as ConvexCheckBuilder, At as UpdateSet, Bn as ConvexTextBuilder, Br as IsPrimaryKey, Bt as RelationsBuilderColumnBase, C as MigrationStep, Cn as ConvexVectorIndexConfig, Cr as not, Ct as OrderByClause, D as defineMigration, Dn as searchIndex, Dr as startsWith, Dt as ReturningAll, E as buildMigrationPlan, En as rankIndex, Er as or, Et as PredicateWhereIndexConfig, Fn as ConvexUniqueConstraintBuilderOn, Fr as ColumnBuilderTypeConfig, Ft as ExtractTablesFromSchema, Gn as Columns, Gt as TablesRelationalConfig, H as RlsMode, Hn as text, Hr as NotNull, In as ConvexUniqueConstraintConfig, Ir as ColumnBuilderWithTableName, It as ExtractTablesWithRelations, Jn as OrmSchemaExtensionTables, Jt as ConvexDeletionBuilder, Kt as defineRelations, Ln as check, Lr as ColumnDataType, Lt as ManyConfig, M as DatabaseWithQuery, Mn as ConvexForeignKeyBuilder, Mr as ColumnBuilder, Mt as VectorSearchProvider, N as OrmReader$1, Nn as ConvexForeignKeyConfig, Nr as ColumnBuilderBaseConfig, Nt as unsetToken, O as defineMigrationSet, On as uniqueIndex, Ot as ReturningResult, P as OrmWriter$1, Pn as ConvexUniqueConstraintBuilder, Pr as ColumnBuilderRuntimeConfig, Qn as OrmSchemaTriggers, Qt as DiscriminatorBuilderConfig, Rn as foreignKey, Rr as DrizzleEntity, Rt as OneConfig, S as MigrationStateMap, Sn as ConvexVectorIndexBuilderOn, Sr as ne, St as MutationRunMode, T as MigrationWriteMode, Tn as index, Tr as notInArray, Tt as PaginatedResult, U as EdgeMetadata, V as RlsContext, Vn as ConvexTextBuilderInitial, Vr as IsUnique, Vt as RelationsBuilderColumnConfig, W as extractRelationsConfig, Wn as Brand, Wt as TableRelationalConfig, Xn as OrmSchemaExtensions, Xt as ConvexTable, Yt as ConvexDeletionConfig, Zn as OrmSchemaRelations, Zt as ConvexTableWithColumns, _ as MigrationManifestEntry, _n as ConvexRankIndexBuilderOn, _r as isNotNull, _t as MutationExecutionMode, an as RlsPolicy, ar as UnaryExpression, at as BuildRelationResult, b as MigrationRunStatus, bn as ConvexSearchIndexConfig, br as lt, bt as MutationResult, cn as rlsPolicy, cr as contains, ct as DBQueryConfig, d as MigrationAppliedState, dn as rlsRole, dr as fieldRef, dt as InferInsertModel, en as OrmLifecycleOperation, er as BinaryExpression, f as MigrationDefinition, fn as ConvexAggregateIndexBuilder, fr as gt, ft as InferModelFromColumns, g as MigrationDriftIssue, gn as ConvexRankIndexBuilder, gr as isFieldReference, gt as MutationExecuteResult, h as MigrationDocContext, hn as ConvexIndexBuilderOn, hr as inArray, ht as MutationExecuteConfig, i as OrmMigrationCapability, in as discriminator, ir as LogicalExpression, it as BuildQueryResult, j as DatabaseWithMutations, jn as ConvexCheckConfig, jr as AnyColumn, jt as VectorQueryConfig, k as detectMigrationDrift, kn as vectorIndex, kr as SystemFields, kt as ReturningSelection, ln as RlsRole, lr as endsWith, lt as FilterOperators, m as MigrationDoc, mn as ConvexIndexBuilder, mr as ilike, mt as InsertValue, n as OrmCapabilities, nn as convexTable, nr as FieldReference, nt as AggregateFieldValue, on as RlsPolicyConfig, or as and, ot as CountConfig, p as MigrationDirection, pn as ConvexAggregateIndexBuilderOn, pr as gte, pt as InferSelectModel, qt as defineRelationsPart, r as OrmCapability, rn as deletion, rr as FilterExpression, rt as AggregateResult, sn as RlsPolicyToOption, sr as between, st as CountResult, t as OrmAggregateCapability, tn as TableConfig, tr as ExpressionVisitor, tt as AggregateConfig, un as RlsRoleConfig, ur as eq, ut as GetColumnData, v as MigrationMigrateOne, vn as ConvexSearchIndexBuilder, vr as isNull, vt as MutationPaginateConfig, w as MigrationTableName, wn as aggregateIndex, wr as notBetween, wt as OrderDirection, x as MigrationSet, xn as ConvexVectorIndexBuilder, xr as lte, xt as MutationReturning, y as MigrationPlan, yn as ConvexSearchIndexBuilderOn, yr as like, yt as MutationPaginatedResult, zn as unique, zr as HasDefault, zt as RelationsBuilder } from "../capabilities-DPB-JKlm.js";
2
- import { $ as OrmClientWithApi$1, A as ConvexDateMode, B as ConvexBytesBuilderInitial, C as ConvexNumberBuilderInitial, D as id, E as ConvexIdBuilderInitial, F as custom, G as ConvexBigIntBuilder, H as ConvexBooleanBuilder, I as json, J as CreateOrmOptions, K as ConvexBigIntBuilderInitial, L as objectOf, M as ConvexCustomBuilder, N as ConvexCustomBuilderInitial, O as ConvexDateBuilder, P as arrayOf, Q as OrmClientBase$1, R as unionOf, S as ConvexNumberBuilder, St as defineTriggers, T as ConvexIdBuilder, U as ConvexBooleanBuilderInitial, V as bytes, W as boolean, X as GenericOrmCtx$1, Y as GenericOrm$1, Z as OrmApiResult, _ as ConvexTimestampMode, _t as OrmBeforeResult, a as requireSchemaRelations, at as ScheduledMutationBatchArgs, b as ConvexTextEnumBuilderInitial, bt as OrmTriggerContext, c as TableConfigResult, ct as scheduledDeleteFactory, d as OrmNotFoundError, et as OrmFunctions, f as ConvexVectorBuilder, g as ConvexTimestampBuilderInitial, gt as defineSchemaExtension, h as ConvexTimestampBuilder, ht as SchemaExtension, i as getSchemaTriggers, it as createOrm, j as date, k as ConvexDateBuilderInitial, l as getTableColumns, m as vector, n as defineSchema, nt as OrmWriterCtx, o as asc, ot as scheduledMutationBatchFactory, p as ConvexVectorBuilderInitial, q as bigint, r as getSchemaRelations, rt as ResolveOrmSchema, s as desc, st as ScheduledDeleteArgs, t as WhereClauseResult, tt as OrmReaderCtx, u as getTableConfig, v as timestamp, vt as OrmTableTriggers, w as integer, x as textEnum, xt as OrmTriggers, y as ConvexTextEnumBuilder, yt as OrmTriggerChange, z as ConvexBytesBuilder } from "../where-clause-compiler-Dddhscyy.js";
1
+ import { $n as TableName, $t as OrmLifecycleChange, An as ConvexCheckBuilder, At as UpdateSet, Bn as ConvexTextBuilder, Br as IsPrimaryKey, Bt as RelationsBuilderColumnBase, C as MigrationStep, Cn as ConvexVectorIndexConfig, Cr as not, Ct as OrderByClause, D as defineMigration, Dn as searchIndex, Dr as startsWith, Dt as ReturningAll, E as buildMigrationPlan, En as rankIndex, Er as or, Et as PredicateWhereIndexConfig, Fn as ConvexUniqueConstraintBuilderOn, Fr as ColumnBuilderTypeConfig, Ft as ExtractTablesFromSchema, Gn as Columns, Gt as TablesRelationalConfig, H as RlsMode, Hn as text, Hr as NotNull, In as ConvexUniqueConstraintConfig, Ir as ColumnBuilderWithTableName, It as ExtractTablesWithRelations, Jn as OrmSchemaExtensionTables, Jt as ConvexDeletionBuilder, Kt as defineRelations, Ln as check, Lr as ColumnDataType, Lt as ManyConfig, M as DatabaseWithQuery, Mn as ConvexForeignKeyBuilder, Mr as ColumnBuilder, Mt as VectorSearchProvider, N as OrmReader$1, Nn as ConvexForeignKeyConfig, Nr as ColumnBuilderBaseConfig, Nt as unsetToken, O as defineMigrationSet, On as uniqueIndex, Ot as ReturningResult, P as OrmWriter$1, Pn as ConvexUniqueConstraintBuilder, Pr as ColumnBuilderRuntimeConfig, Qn as OrmSchemaTriggers, Qt as DiscriminatorBuilderConfig, Rn as foreignKey, Rr as DrizzleEntity, Rt as OneConfig, S as MigrationStateMap, Sn as ConvexVectorIndexBuilderOn, Sr as ne, St as MutationRunMode, T as MigrationWriteMode, Tn as index, Tr as notInArray, Tt as PaginatedResult, U as EdgeMetadata, V as RlsContext, Vn as ConvexTextBuilderInitial, Vr as IsUnique, Vt as RelationsBuilderColumnConfig, W as extractRelationsConfig, Wn as Brand, Wt as TableRelationalConfig, Xn as OrmSchemaExtensions, Xt as ConvexTable, Yt as ConvexDeletionConfig, Zn as OrmSchemaRelations, Zt as ConvexTableWithColumns, _ as MigrationManifestEntry, _n as ConvexRankIndexBuilderOn, _r as isNotNull, _t as MutationExecutionMode, an as RlsPolicy, ar as UnaryExpression, at as BuildRelationResult, b as MigrationRunStatus, bn as ConvexSearchIndexConfig, br as lt, bt as MutationResult, cn as rlsPolicy, cr as contains, ct as DBQueryConfig, d as MigrationAppliedState, dn as rlsRole, dr as fieldRef, dt as InferInsertModel, en as OrmLifecycleOperation, er as BinaryExpression, f as MigrationDefinition, fn as ConvexAggregateIndexBuilder, fr as gt, ft as InferModelFromColumns, g as MigrationDriftIssue, gn as ConvexRankIndexBuilder, gr as isFieldReference, gt as MutationExecuteResult, h as MigrationDocContext, hn as ConvexIndexBuilderOn, hr as inArray, ht as MutationExecuteConfig, i as OrmMigrationCapability, in as discriminator, ir as LogicalExpression, it as BuildQueryResult, j as DatabaseWithMutations, jn as ConvexCheckConfig, jr as AnyColumn, jt as VectorQueryConfig, k as detectMigrationDrift, kn as vectorIndex, kr as SystemFields, kt as ReturningSelection, ln as RlsRole, lr as endsWith, lt as FilterOperators, m as MigrationDoc, mn as ConvexIndexBuilder, mr as ilike, mt as InsertValue, n as OrmCapabilities, nn as convexTable, nr as FieldReference, nt as AggregateFieldValue, on as RlsPolicyConfig, or as and, ot as CountConfig, p as MigrationDirection, pn as ConvexAggregateIndexBuilderOn, pr as gte, pt as InferSelectModel, qt as defineRelationsPart, r as OrmCapability, rn as deletion, rr as FilterExpression, rt as AggregateResult, sn as RlsPolicyToOption, sr as between, st as CountResult, t as OrmAggregateCapability, tn as TableConfig, tr as ExpressionVisitor, tt as AggregateConfig, un as RlsRoleConfig, ur as eq, ut as GetColumnData, v as MigrationMigrateOne, vn as ConvexSearchIndexBuilder, vr as isNull, vt as MutationPaginateConfig, w as MigrationTableName, wn as aggregateIndex, wr as notBetween, wt as OrderDirection, x as MigrationSet, xn as ConvexVectorIndexBuilder, xr as lte, xt as MutationReturning, y as MigrationPlan, yn as ConvexSearchIndexBuilderOn, yr as like, yt as MutationPaginatedResult, zn as unique, zr as HasDefault, zt as RelationsBuilder } from "../capabilities-CG-oIMyR.js";
2
+ import { $ as OrmClientWithApi$1, A as ConvexDateMode, B as ConvexBytesBuilderInitial, C as ConvexNumberBuilderInitial, D as id, E as ConvexIdBuilderInitial, F as custom, G as ConvexBigIntBuilder, H as ConvexBooleanBuilder, I as json, J as CreateOrmOptions, K as ConvexBigIntBuilderInitial, L as objectOf, M as ConvexCustomBuilder, N as ConvexCustomBuilderInitial, O as ConvexDateBuilder, P as arrayOf, Q as OrmClientBase$1, R as unionOf, S as ConvexNumberBuilder, St as defineTriggers, T as ConvexIdBuilder, U as ConvexBooleanBuilderInitial, V as bytes, W as boolean, X as GenericOrmCtx$1, Y as GenericOrm$1, Z as OrmApiResult, _ as ConvexTimestampMode, _t as OrmBeforeResult, a as requireSchemaRelations, at as ScheduledMutationBatchArgs, b as ConvexTextEnumBuilderInitial, bt as OrmTriggerContext, c as TableConfigResult, ct as scheduledDeleteFactory, d as OrmNotFoundError, et as OrmFunctions, f as ConvexVectorBuilder, g as ConvexTimestampBuilderInitial, gt as defineSchemaExtension, h as ConvexTimestampBuilder, ht as SchemaExtension, i as getSchemaTriggers, it as createOrm, j as date, k as ConvexDateBuilderInitial, l as getTableColumns, m as vector, n as defineSchema, nt as OrmWriterCtx, o as asc, ot as scheduledMutationBatchFactory, p as ConvexVectorBuilderInitial, q as bigint, r as getSchemaRelations, rt as ResolveOrmSchema, s as desc, st as ScheduledDeleteArgs, t as WhereClauseResult, tt as OrmReaderCtx, u as getTableConfig, v as timestamp, vt as OrmTableTriggers, w as integer, x as textEnum, xt as OrmTriggers, y as ConvexTextEnumBuilder, yt as OrmTriggerChange, z as ConvexBytesBuilder } from "../where-clause-compiler-Bgkzm3Y-.js";
3
3
  import { i as pretendRequired, n as deprecated, r as pretend } from "../validators-0I-Ik1EN.js";
4
4
  import { a as QueryCtxWithPreferredOrmQueryTable, i as QueryCtxWithOrmQueryTable, n as LookupByIdResultByCtx, o as getByIdWithOrmQueryFallback, r as QueryCtxWithOptionalOrmQueryTable, t as DocByCtx } from "../query-context-BkNjkDCk.js";
5
5
  import { DefineSchemaOptions, GenericDatabaseReader, GenericDatabaseWriter, GenericSchema, SchemaDefinition } from "convex/server";
package/dist/orm/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { _ as json, a as rlsPolicy, b as ConvexColumnBuilder, c as rankIndex, d as vectorIndex, f as text, g as custom, h as arrayOf, i as RlsPolicy, l as searchIndex, m as integer, n as deletion, o as aggregateIndex, p as createSystemFields, r as discriminator, s as index, t as convexTable, u as uniqueIndex, v as objectOf, x as entityKind, y as unionOf } from "../table-d9o_n4R3.js";
2
2
  import { d as boolean, i as detectMigrationDrift, l as migrationExtension, n as defineMigration, r as defineMigrationSet, t as buildMigrationPlan } from "../definitions-3PX4ywR-.js";
3
3
  import { a as pretendRequired, i as pretend, n as deprecated } from "../validators-CIoUYCqO.js";
4
- import { t as id } from "../id-BVdWER1U.js";
4
+ import { o as id } from "../schema-BFP_awgP.js";
5
5
  import { a as OrmSchemaDefinition, c as OrmSchemaExtensionTriggers, d as OrmSchemaRelations, f as OrmSchemaTriggers, g as TablePolymorphic, h as TableName, i as OrmContext, l as OrmSchemaExtensions, n as Columns, o as OrmSchemaExtensionRelations, p as RlsPolicies, r as EnableRLS, s as OrmSchemaExtensionTables, t as Brand, u as OrmSchemaOptions } from "../symbols-DDNAddkd.js";
6
6
  import { A as inArray, B as notBetween, C as eq, D as gt, E as filterValuesEqual, F as lt, G as startsWith, H as notInArray, I as lte, L as matchLikePattern, M as isNotNull, N as isNull, O as gte, P as like, R as ne, S as endsWith, T as filterValueInList, U as notLike, V as notIlike, W as or, _ as arrayContains, a as findVectorIndexByName, b as column, c as getRankIndexes, d as INTERNAL_CREATION_TIME_FIELD, f as PUBLIC_CREATED_AT_FIELD, g as arrayContained, h as and, i as findSearchIndexByName, j as isFieldReference, k as ilike, l as resolveIndexOrderPushdown, m as usesSystemCreatedAtAlias, n as findIndexForColumns, o as getAggregateIndexes, r as findRelationIndex, s as getIndexes, t as findExactIndexForColumns, u as CREATED_AT_MIGRATION_MESSAGE, v as arrayOverlaps, w as fieldRef, x as contains, y as between, z as not } from "../index-utils-C1DyktHe.js";
7
7
  import { a as indexKeyWithinBounds, c as streamIndexRange, i as getIndexFields, l as isUnsetToken, n as EmptyStream, o as mergedStream, r as QueryStream, s as stream, t as getByIdWithOrmQueryFallback, u as unsetToken } from "../query-context-DdSg3fuk.js";
8
- import { $ as patchReferencingRows, A as enforcePolymorphicWrite, B as getForeignKeys, C as collectPrimaryIdLookupRows, D as encodeUndefinedDeep, E as deserializeFilterExpression, F as evaluateCheckConstraintTriState, G as getTableColumns$2, H as getMutationCollectionLimits, I as evaluateFilter, J as getUniqueIndexes, K as getTableDeleteConfig, L as extractPrimaryIdLookup, M as ensureDefaultColumns, N as ensureNonNullValues, O as enforceCheckConstraints, P as ensureNullableColumns, Q as normalizeTemporalComparableValue, R as getChecks, S as collectMutationRowsBounded, T as decodeUndefinedDeep, U as getMutationExecutionMode, V as getMutationAsyncDelayMs, W as getOrmContext, X as hydrateDateFieldsForRead, Y as hardDeleteRow, Z as normalizeDateFieldsForWrite, _ as applyDefaults, at as splitReturningSelection, b as buildForeignKeyGraph, c as getAggregateIndexDefinitions, ct as toConvexFilter, d as COUNT_ERROR, dt as markLifecycleHookedTables, et as resolveOrmRuntimeDefaults, f as createAggregateError, ft as compileConvexFilter, g as ensureCountAllowedForRls, h as ensureAggregateAllowedForRls, ht as mapWithConcurrency, it as softDeleteRow, j as enforceUniqueIndexes, k as enforceForeignKeys, l as getRankIndexDefinitions, lt as unsetFieldsOf, mt as isConvexEnforceableFilter, nt as selectReturningRowWithHydration, o as aggregateExtension, ot as stripUnsetFields, p as createCountError, pt as convexAnd, q as getTableName, rt as serializeFilterExpression, st as takeRowsWithinByteBudget, tt as returningSelectionReadsCreationTime, u as AGGREGATE_ERROR, ut as hasLifecycleHooks, v as applyIncomingForeignKeyActionsOnDelete, w as createForeignKeyProbeMemo, x as canUsePrimaryIdLookupCursor, y as applyIncomingForeignKeyActionsOnUpdate, z as getColumnName$1 } from "../schema-hL2FWCE7.js";
8
+ import { $ as patchReferencingRows, A as enforcePolymorphicWrite, B as getForeignKeys, C as collectPrimaryIdLookupRows, D as encodeUndefinedDeep, E as deserializeFilterExpression, F as evaluateCheckConstraintTriState, G as getTableColumns$2, H as getMutationCollectionLimits, I as evaluateFilter, J as getUniqueIndexes, K as getTableDeleteConfig, L as extractPrimaryIdLookup, M as ensureDefaultColumns, N as ensureNonNullValues, O as enforceCheckConstraints, P as ensureNullableColumns, Q as normalizeTemporalComparableValue, R as getChecks, S as collectMutationRowsBounded, T as decodeUndefinedDeep, U as getMutationExecutionMode, V as getMutationAsyncDelayMs, W as getOrmContext, X as hydrateDateFieldsForRead, Y as hardDeleteRow, Z as normalizeDateFieldsForWrite, _ as applyDefaults, at as splitReturningSelection, b as buildForeignKeyGraph, c as getAggregateIndexDefinitions, ct as toConvexFilter, d as COUNT_ERROR, dt as markLifecycleHookedTables, et as resolveOrmRuntimeDefaults, f as createAggregateError, ft as compileConvexFilter, g as ensureCountAllowedForRls, h as ensureAggregateAllowedForRls, ht as mapWithConcurrency, it as softDeleteRow, j as enforceUniqueIndexes, k as enforceForeignKeys, l as getRankIndexDefinitions, lt as unsetFieldsOf, mt as isConvexEnforceableFilter, nt as selectReturningRowWithHydration, o as aggregateExtension, ot as stripUnsetFields, p as createCountError, pt as convexAnd, q as getTableName, rt as serializeFilterExpression, st as takeRowsWithinByteBudget, tt as returningSelectionReadsCreationTime, u as AGGREGATE_ERROR, ut as hasLifecycleHooks, v as applyIncomingForeignKeyActionsOnDelete, w as createForeignKeyProbeMemo, x as canUsePrimaryIdLookupCursor, y as applyIncomingForeignKeyActionsOnUpdate, z as getColumnName$1 } from "../schema-DbPcDW-N.js";
9
9
  import { t as defineSchemaExtension } from "../extensions-Bp0XHanR.js";
10
10
  import { compareValues, convexToJson, jsonToConvex, v } from "convex/values";
11
11
  import { defineSchema as defineSchema$1, internalActionGeneric, internalMutationGeneric, internalQueryGeneric } from "convex/server";
@@ -1,3 +1,3 @@
1
- import { C as MigrationStep, D as defineMigration, E as buildMigrationPlan, O as defineMigrationSet, S as MigrationStateMap, T as MigrationWriteMode, _ as MigrationManifestEntry, a as MAX_STATUS_RUN_LIMIT, b as MigrationRunStatus, c as MigrationRunChunkArgs, d as MigrationAppliedState, f as MigrationDefinition, g as MigrationDriftIssue, h as MigrationDocContext, k as detectMigrationDrift, l as MigrationStatusArgs, m as MigrationDoc, o as MigrationCancelArgs, p as MigrationDirection, s as MigrationRunArgs, u as createMigrationHandlers, v as MigrationMigrateOne, w as MigrationTableName, x as MigrationSet, y as MigrationPlan } from "../../capabilities-DPB-JKlm.js";
2
- import { Ct as migrationCapability, dt as MIGRATION_STORAGE_TABLE_NAMES, ft as injectMigrationStorageTables, lt as MIGRATION_RUN_TABLE, mt as migrationStorageTables, pt as migrationExtension, ut as MIGRATION_STATE_TABLE } from "../../where-clause-compiler-Dddhscyy.js";
1
+ import { C as MigrationStep, D as defineMigration, E as buildMigrationPlan, O as defineMigrationSet, S as MigrationStateMap, T as MigrationWriteMode, _ as MigrationManifestEntry, a as MAX_STATUS_RUN_LIMIT, b as MigrationRunStatus, c as MigrationRunChunkArgs, d as MigrationAppliedState, f as MigrationDefinition, g as MigrationDriftIssue, h as MigrationDocContext, k as detectMigrationDrift, l as MigrationStatusArgs, m as MigrationDoc, o as MigrationCancelArgs, p as MigrationDirection, s as MigrationRunArgs, u as createMigrationHandlers, v as MigrationMigrateOne, w as MigrationTableName, x as MigrationSet, y as MigrationPlan } from "../../capabilities-CG-oIMyR.js";
2
+ import { Ct as migrationCapability, dt as MIGRATION_STORAGE_TABLE_NAMES, ft as injectMigrationStorageTables, lt as MIGRATION_RUN_TABLE, mt as migrationStorageTables, pt as migrationExtension, ut as MIGRATION_STATE_TABLE } from "../../where-clause-compiler-Bgkzm3Y-.js";
3
3
  export { MAX_STATUS_RUN_LIMIT, MIGRATION_RUN_TABLE, MIGRATION_STATE_TABLE, MIGRATION_STORAGE_TABLE_NAMES, type MigrationAppliedState, type MigrationCancelArgs, type MigrationDefinition, type MigrationDirection, type MigrationDoc, type MigrationDocContext, type MigrationDriftIssue, type MigrationManifestEntry, type MigrationMigrateOne, type MigrationPlan, type MigrationRunArgs, type MigrationRunChunkArgs, type MigrationRunStatus, type MigrationSet, type MigrationStateMap, type MigrationStatusArgs, type MigrationStep, type MigrationTableName, type MigrationWriteMode, buildMigrationPlan, createMigrationHandlers, defineMigration, defineMigrationSet, detectMigrationDrift, injectMigrationStorageTables, migrationCapability, migrationExtension, migrationStorageTables };
@@ -1,6 +1,5 @@
1
- import { f as text, g as custom, m as integer, s as index, t as convexTable } from "./table-d9o_n4R3.js";
2
- import { t as id } from "./id-BVdWER1U.js";
3
- import { ConvexError, convexToJson, jsonToConvex, v } from "convex/values";
1
+ import { n as AGGREGATE_TREE_TABLE, t as AGGREGATE_NODE_TABLE } from "./schema-BFP_awgP.js";
2
+ import { ConvexError, convexToJson, jsonToConvex } from "convex/values";
4
3
 
5
4
  //#region src/aggregate-core/compare.ts
6
5
  function isCommitTsPlaceholder(value) {
@@ -44,36 +43,6 @@ function makeComparable(v) {
44
43
  return [8, keys.map((k) => [k, record[k]]).map(makeComparable)];
45
44
  }
46
45
 
47
- //#endregion
48
- //#region src/aggregate-core/schema.ts
49
- const AGGREGATE_TREE_TABLE = "aggregate_rank_tree";
50
- const AGGREGATE_NODE_TABLE = "aggregate_rank_node";
51
- const aggregateCounterValidator = v.object({
52
- count: v.number(),
53
- sum: v.number()
54
- });
55
- const aggregateItemValidator = v.object({
56
- k: v.any(),
57
- v: v.any(),
58
- s: v.number()
59
- });
60
- const aggregateTreeTable = convexTable(AGGREGATE_TREE_TABLE, {
61
- aggregateName: text().notNull(),
62
- deletionStack: custom(v.array(v.id(AGGREGATE_NODE_TABLE))),
63
- maxNodeSize: integer().notNull(),
64
- namespace: custom(v.any()),
65
- root: id(AGGREGATE_NODE_TABLE).notNull()
66
- }, (tree) => [index("by_namespace").on(tree.namespace), index("by_aggregate_name").on(tree.aggregateName)]);
67
- const aggregateNodeTable = convexTable(AGGREGATE_NODE_TABLE, {
68
- aggregate: custom(aggregateCounterValidator),
69
- items: custom(v.array(aggregateItemValidator)).notNull(),
70
- subtrees: custom(v.array(v.string())).notNull()
71
- });
72
- const aggregateStorageTables = {
73
- [AGGREGATE_NODE_TABLE]: aggregateNodeTable,
74
- [AGGREGATE_TREE_TABLE]: aggregateTreeTable
75
- };
76
-
77
46
  //#endregion
78
47
  //#region src/aggregate-core/btree.ts
79
48
  const DEFAULT_MAX_NODE_SIZE = 16;
@@ -525,14 +494,21 @@ async function deleteTreeNodes(db, node) {
525
494
  }
526
495
  /**
527
496
  * Deletes up to `limit` nodes from one namespace tree belonging to an
528
- * aggregate, returning true once none are left. The traversal stack lives on
497
+ * aggregate, reporting `done` once none are left. The traversal stack lives on
529
498
  * the tree document so a large tree resumes across transactions.
499
+ *
500
+ * Nodes are dropped whatever they contain, so a caller clearing an aggregate
501
+ * never has to empty the tree key by key first.
530
502
  */
531
503
  async function deleteTreesHandler(ctx, args) {
532
504
  const tree = (await ctx.db.query(AGGREGATE_TREE_TABLE).withIndex("by_aggregate_name", (q) => q.eq("aggregateName", args.aggregateName)).take(1))[0];
533
- if (!tree) return true;
505
+ if (!tree) return {
506
+ done: true,
507
+ documents: 0
508
+ };
534
509
  const stack = [...tree.deletionStack ?? [tree.root]];
535
510
  let remaining = Math.max(1, Math.floor(args.limit));
511
+ let documents = 0;
536
512
  while (stack.length > 0 && remaining > 0) {
537
513
  const nodeId = stack.pop();
538
514
  const node = await ctx.db.get(nodeId);
@@ -540,10 +516,14 @@ async function deleteTreesHandler(ctx, args) {
540
516
  if (!node) continue;
541
517
  stack.push(...node.subtrees);
542
518
  await ctx.db.delete(nodeId);
519
+ documents += 1;
543
520
  }
544
521
  if (stack.length > 0) await ctx.db.patch(tree._id, { deletionStack: stack });
545
522
  else await ctx.db.delete(tree._id);
546
- return false;
523
+ return {
524
+ done: false,
525
+ documents: documents + 1
526
+ };
547
527
  }
548
528
  async function clearTree(db, args) {
549
529
  const tree = await getTree(db, args.namespace);
@@ -935,9 +915,10 @@ var Aggregate = class {
935
915
  });
936
916
  }
937
917
  /**
938
- * Deletes up to `limit` namespace trees without recreating them. Returns true
939
- * once this aggregate owns no trees, so callers can drain every namespace
940
- * across several mutations instead of walking them all in one.
918
+ * Deletes up to `limit` nodes from one namespace tree without recreating it,
919
+ * reporting `done` once this aggregate owns no trees and how many documents
920
+ * the call wrote. Callers drain every namespace across several mutations
921
+ * instead of walking them all in one, and charge their budget by `documents`.
941
922
  */
942
923
  async deleteTrees(ctx, limit) {
943
924
  return deleteTreesHandler({ db: ctx.db }, {
@@ -1077,4 +1058,4 @@ function namespaceFromOpts(opts) {
1077
1058
  }
1078
1059
 
1079
1060
  //#endregion
1080
- export { TableAggregate as n, aggregateStorageTables as r, DirectAggregate as t };
1061
+ export { TableAggregate as n, DirectAggregate as t };
@@ -0,0 +1,67 @@
1
+ import { b as ConvexColumnBuilder, f as text, g as custom, m as integer, s as index, t as convexTable, x as entityKind } from "./table-d9o_n4R3.js";
2
+ import { v } from "convex/values";
3
+
4
+ //#region src/orm/builders/id.ts
5
+ /**
6
+ * ID column builder class
7
+ * Compiles to v.id(tableName) or v.optional(v.id(tableName))
8
+ */
9
+ var ConvexIdBuilder = class extends ConvexColumnBuilder {
10
+ static [entityKind] = "ConvexIdBuilder";
11
+ constructor(name, tableName) {
12
+ super(name, "string", "ConvexId");
13
+ this.tableName = tableName;
14
+ this.config.referenceTable = tableName;
15
+ }
16
+ /**
17
+ * Expose Convex validator for schema integration
18
+ */
19
+ get convexValidator() {
20
+ if (this.config.notNull) return v.id(this.tableName);
21
+ return v.optional(v.union(v.null(), v.id(this.tableName)));
22
+ }
23
+ /**
24
+ * Compile to Convex validator
25
+ * .notNull() → v.id(tableName)
26
+ * nullable → v.optional(v.id(tableName))
27
+ */
28
+ build() {
29
+ return this.convexValidator;
30
+ }
31
+ };
32
+ function id(tableName) {
33
+ return new ConvexIdBuilder("", tableName);
34
+ }
35
+
36
+ //#endregion
37
+ //#region src/aggregate-core/schema.ts
38
+ const AGGREGATE_TREE_TABLE = "aggregate_rank_tree";
39
+ const AGGREGATE_NODE_TABLE = "aggregate_rank_node";
40
+ const aggregateCounterValidator = v.object({
41
+ count: v.number(),
42
+ sum: v.number()
43
+ });
44
+ const aggregateItemValidator = v.object({
45
+ k: v.any(),
46
+ v: v.any(),
47
+ s: v.number()
48
+ });
49
+ const aggregateTreeTable = convexTable(AGGREGATE_TREE_TABLE, {
50
+ aggregateName: text().notNull(),
51
+ deletionStack: custom(v.array(v.id(AGGREGATE_NODE_TABLE))),
52
+ maxNodeSize: integer().notNull(),
53
+ namespace: custom(v.any()),
54
+ root: id(AGGREGATE_NODE_TABLE).notNull()
55
+ }, (tree) => [index("by_namespace").on(tree.namespace), index("by_aggregate_name").on(tree.aggregateName)]);
56
+ const aggregateNodeTable = convexTable(AGGREGATE_NODE_TABLE, {
57
+ aggregate: custom(aggregateCounterValidator),
58
+ items: custom(v.array(aggregateItemValidator)).notNull(),
59
+ subtrees: custom(v.array(v.string())).notNull()
60
+ });
61
+ const aggregateStorageTables = {
62
+ [AGGREGATE_NODE_TABLE]: aggregateNodeTable,
63
+ [AGGREGATE_TREE_TABLE]: aggregateTreeTable
64
+ };
65
+
66
+ //#endregion
67
+ export { aggregateTreeTable as a, aggregateStorageTables as i, AGGREGATE_TREE_TABLE as n, id as o, aggregateNodeTable as r, AGGREGATE_NODE_TABLE as t };
@@ -1,5 +1,5 @@
1
1
  import { _ as json, f as text, h as arrayOf, m as integer, s as index, t as convexTable, v as objectOf } from "./table-d9o_n4R3.js";
2
- import { t as id } from "./id-BVdWER1U.js";
2
+ import { a as aggregateTreeTable, n as AGGREGATE_TREE_TABLE, r as aggregateNodeTable, t as AGGREGATE_NODE_TABLE } from "./schema-BFP_awgP.js";
3
3
  import { g as TablePolymorphic, h as TableName, i as OrmContext, m as TableDeleteConfig, n as Columns } from "./symbols-DDNAddkd.js";
4
4
  import { E as filterValuesEqual, L as matchLikePattern, T as filterValueInList, d as INTERNAL_CREATION_TIME_FIELD, f as PUBLIC_CREATED_AT_FIELD, j as isFieldReference, m as usesSystemCreatedAtAlias, n as findIndexForColumns, p as hasUserCreatedAtColumn, s as getIndexes, t as findExactIndexForColumns, u as CREATED_AT_MIGRATION_MESSAGE, w as fieldRef } from "./index-utils-C1DyktHe.js";
5
5
  import { t as defineSchemaExtension } from "./extensions-Bp0XHanR.js";
@@ -1344,9 +1344,11 @@ const getRankIndexDefinitions = (tableConfig) => {
1344
1344
  const AGGREGATE_BUCKET_TABLE = "aggregate_bucket";
1345
1345
  const AGGREGATE_MEMBER_TABLE = "aggregate_member";
1346
1346
  const AGGREGATE_EXTREMA_TABLE = "aggregate_extrema";
1347
- const AGGREGATE_RANK_TREE_TABLE = "aggregate_rank_tree";
1348
- const AGGREGATE_RANK_NODE_TABLE = "aggregate_rank_node";
1349
1347
  const AGGREGATE_STATE_TABLE = "aggregate_state";
1348
+ const AGGREGATE_RANK_TREE_TABLE = AGGREGATE_TREE_TABLE;
1349
+ const AGGREGATE_RANK_NODE_TABLE = AGGREGATE_NODE_TABLE;
1350
+ const rankTreeTable = aggregateTreeTable;
1351
+ const rankNodeTable = aggregateNodeTable;
1350
1352
  /**
1351
1353
  * Partition key a rank index's btree rows are stored under. Lives next to the
1352
1354
  * table names because it is how `AGGREGATE_RANK_TREE_TABLE` is addressed, and
@@ -1411,24 +1413,6 @@ const countStateTable = convexTable(AGGREGATE_STATE_TABLE, {
1411
1413
  index("by_kind_status").on(t.kind, t.status),
1412
1414
  index("by_table_status").on(t.tableKey, t.status)
1413
1415
  ]);
1414
- const rankTreeTable = convexTable(AGGREGATE_RANK_TREE_TABLE, {
1415
- aggregateName: text().notNull(),
1416
- maxNodeSize: integer().notNull(),
1417
- namespace: json(),
1418
- root: id(AGGREGATE_RANK_NODE_TABLE).notNull()
1419
- }, (tree) => [index("by_namespace").on(tree.namespace), index("by_aggregate_name").on(tree.aggregateName)]);
1420
- const rankNodeTable = convexTable(AGGREGATE_RANK_NODE_TABLE, {
1421
- aggregate: objectOf({
1422
- count: integer().notNull(),
1423
- sum: integer().notNull()
1424
- }),
1425
- items: arrayOf(objectOf({
1426
- k: json(),
1427
- v: json(),
1428
- s: integer().notNull()
1429
- })).notNull(),
1430
- subtrees: arrayOf(text().notNull()).notNull()
1431
- });
1432
1416
  const aggregateStorageTables = {
1433
1417
  [AGGREGATE_BUCKET_TABLE]: countBucketTable,
1434
1418
  [AGGREGATE_MEMBER_TABLE]: countMemberTable,
package/dist/watcher.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as generateMeta, d as PARSE_SNAPSHOT_SUFFIX, i as resolveConfiguredBackend, n as withLocalCodegenEnv, o as getConvexConfig, r as loadCliConfig, u as logger } from "./local-env-DGSkmXQk.mjs";
2
+ import { a as generateMeta, d as PARSE_SNAPSHOT_SUFFIX, i as resolveConfiguredBackend, n as withLocalCodegenEnv, o as getConvexConfig, r as loadCliConfig, u as logger } from "./local-env-CYYSNf_o.mjs";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5