@xixixao/convex-migrations 0.3.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.
Files changed (57) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +523 -0
  3. package/dist/client/index.d.ts +383 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +528 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/log.d.ts +8 -0
  8. package/dist/client/log.d.ts.map +1 -0
  9. package/dist/client/log.js +74 -0
  10. package/dist/client/log.js.map +1 -0
  11. package/dist/component/_generated/api.d.ts +34 -0
  12. package/dist/component/_generated/api.d.ts.map +1 -0
  13. package/dist/component/_generated/api.js +31 -0
  14. package/dist/component/_generated/api.js.map +1 -0
  15. package/dist/component/_generated/component.d.ts +95 -0
  16. package/dist/component/_generated/component.d.ts.map +1 -0
  17. package/dist/component/_generated/component.js +11 -0
  18. package/dist/component/_generated/component.js.map +1 -0
  19. package/dist/component/_generated/dataModel.d.ts +46 -0
  20. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  21. package/dist/component/_generated/dataModel.js +11 -0
  22. package/dist/component/_generated/dataModel.js.map +1 -0
  23. package/dist/component/_generated/server.d.ts +121 -0
  24. package/dist/component/_generated/server.d.ts.map +1 -0
  25. package/dist/component/_generated/server.js +78 -0
  26. package/dist/component/_generated/server.js.map +1 -0
  27. package/dist/component/convex.config.d.ts +3 -0
  28. package/dist/component/convex.config.d.ts.map +1 -0
  29. package/dist/component/convex.config.js +3 -0
  30. package/dist/component/convex.config.js.map +1 -0
  31. package/dist/component/lib.d.ts +74 -0
  32. package/dist/component/lib.d.ts.map +1 -0
  33. package/dist/component/lib.js +290 -0
  34. package/dist/component/lib.js.map +1 -0
  35. package/dist/component/schema.d.ts +28 -0
  36. package/dist/component/schema.d.ts.map +1 -0
  37. package/dist/component/schema.js +20 -0
  38. package/dist/component/schema.js.map +1 -0
  39. package/dist/shared.d.ts +40 -0
  40. package/dist/shared.d.ts.map +1 -0
  41. package/dist/shared.js +22 -0
  42. package/dist/shared.js.map +1 -0
  43. package/package.json +95 -0
  44. package/src/client/index.test.ts +16 -0
  45. package/src/client/index.ts +748 -0
  46. package/src/client/log.ts +76 -0
  47. package/src/component/_generated/api.ts +50 -0
  48. package/src/component/_generated/component.ts +116 -0
  49. package/src/component/_generated/dataModel.ts +60 -0
  50. package/src/component/_generated/server.ts +161 -0
  51. package/src/component/convex.config.ts +3 -0
  52. package/src/component/lib.test.ts +110 -0
  53. package/src/component/lib.ts +356 -0
  54. package/src/component/schema.ts +20 -0
  55. package/src/component/setup.test.ts +5 -0
  56. package/src/shared.ts +37 -0
  57. package/src/test.ts +18 -0
@@ -0,0 +1,76 @@
1
+ import type { MigrationStatus } from "../shared.js";
2
+
3
+ export function logStatusAndInstructions(
4
+ name: string,
5
+ status: MigrationStatus,
6
+ args: {
7
+ fn?: string;
8
+ cursor?: string | null;
9
+ batchSize?: number;
10
+ dryRun?: boolean;
11
+ },
12
+ ) {
13
+ const output: Record<string, unknown> = {};
14
+ if (status.isDone) {
15
+ if (status.latestEnd! < Date.now()) {
16
+ output["Status"] = "Migration already done.";
17
+ } else if (status.latestStart === status.latestEnd) {
18
+ output["Status"] = "Migration was started and finished in one batch.";
19
+ } else {
20
+ output["Status"] = "Migration completed with this batch.";
21
+ }
22
+ } else {
23
+ if (status.state === "failed") {
24
+ output["Status"] = `Migration failed: ${status.error}`;
25
+ } else if (status.state === "canceled") {
26
+ output["Status"] = "Migration canceled.";
27
+ } else if (status.latestStart >= Date.now()) {
28
+ output["Status"] = "Migration started.";
29
+ } else {
30
+ output["Status"] = "Migration running.";
31
+ }
32
+ }
33
+ if (args.dryRun) {
34
+ output["DryRun"] = "No changes were committed.";
35
+ output["Status"] = "DRY RUN: " + output["Status"];
36
+ }
37
+ output["Name"] = name;
38
+ output["lastStarted"] = new Date(status.latestStart).toISOString();
39
+ if (status.latestEnd) {
40
+ output["lastFinished"] = new Date(status.latestEnd).toISOString();
41
+ }
42
+ output["processed"] = status.processed;
43
+ if (status.next?.length) {
44
+ if (status.isDone) {
45
+ output["nowUp"] = status.next;
46
+ } else {
47
+ output["nextUp"] = status.next;
48
+ }
49
+ }
50
+ const nextArgs = (status.next || []).map((n) => `"${n}"`).join(", ");
51
+ const run = `npx convex run --component migrations`;
52
+ if (!args.dryRun) {
53
+ if (status.state === "inProgress") {
54
+ output["toCancel"] = {
55
+ cmd: `${run} lib:cancel`,
56
+ args: `{"name": "${name}"}`,
57
+ prod: `--prod`,
58
+ };
59
+ output["toMonitorStatus"] = {
60
+ cmd: `${run} --watch lib:getStatus`,
61
+ args: `{"names": ["${name}"${status.next?.length ? ", " + nextArgs : ""}]}`,
62
+ prod: `--prod`,
63
+ };
64
+ } else {
65
+ output["toStartOver"] = JSON.stringify({ ...args, cursor: null });
66
+ if (status.next?.length) {
67
+ output["toMonitorStatus"] = {
68
+ cmd: `${run} --watch lib:getStatus`,
69
+ args: `{"names": [${nextArgs}]}`,
70
+ prod: `--prod`,
71
+ };
72
+ }
73
+ }
74
+ }
75
+ return output;
76
+ }
@@ -0,0 +1,50 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated `api` utility.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type * as lib from "../lib.js";
12
+
13
+ import type {
14
+ ApiFromModules,
15
+ FilterApi,
16
+ FunctionReference,
17
+ } from "convex/server";
18
+ import { anyApi, componentsGeneric } from "convex/server";
19
+
20
+ const fullApi: ApiFromModules<{
21
+ lib: typeof lib;
22
+ }> = anyApi as any;
23
+
24
+ /**
25
+ * A utility for referencing Convex functions in your app's public API.
26
+ *
27
+ * Usage:
28
+ * ```js
29
+ * const myFunctionReference = api.myModule.myFunction;
30
+ * ```
31
+ */
32
+ export const api: FilterApi<
33
+ typeof fullApi,
34
+ FunctionReference<any, "public">
35
+ > = anyApi as any;
36
+
37
+ /**
38
+ * A utility for referencing Convex functions in your app's internal API.
39
+ *
40
+ * Usage:
41
+ * ```js
42
+ * const myFunctionReference = internal.myModule.myFunction;
43
+ * ```
44
+ */
45
+ export const internal: FilterApi<
46
+ typeof fullApi,
47
+ FunctionReference<any, "internal">
48
+ > = anyApi as any;
49
+
50
+ export const components = componentsGeneric() as unknown as {};
@@ -0,0 +1,116 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated `ComponentApi` utility.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type { FunctionReference } from "convex/server";
12
+
13
+ /**
14
+ * A utility for referencing a Convex component's exposed API.
15
+ *
16
+ * Useful when expecting a parameter like `components.myComponent`.
17
+ * Usage:
18
+ * ```ts
19
+ * async function myFunction(ctx: QueryCtx, component: ComponentApi) {
20
+ * return ctx.runQuery(component.someFile.someQuery, { ...args });
21
+ * }
22
+ * ```
23
+ */
24
+ export type ComponentApi<Name extends string | undefined = string | undefined> =
25
+ {
26
+ lib: {
27
+ cancel: FunctionReference<
28
+ "mutation",
29
+ "internal",
30
+ { name: string },
31
+ {
32
+ batchSize?: number;
33
+ cursor?: string | null;
34
+ error?: string;
35
+ isDone: boolean;
36
+ latestEnd?: number;
37
+ latestStart: number;
38
+ name: string;
39
+ next?: Array<string>;
40
+ processed: number;
41
+ state: "inProgress" | "success" | "failed" | "canceled" | "unknown";
42
+ },
43
+ Name
44
+ >;
45
+ cancelAll: FunctionReference<
46
+ "mutation",
47
+ "internal",
48
+ { sinceTs?: number },
49
+ Array<{
50
+ batchSize?: number;
51
+ cursor?: string | null;
52
+ error?: string;
53
+ isDone: boolean;
54
+ latestEnd?: number;
55
+ latestStart: number;
56
+ name: string;
57
+ next?: Array<string>;
58
+ processed: number;
59
+ state: "inProgress" | "success" | "failed" | "canceled" | "unknown";
60
+ }>,
61
+ Name
62
+ >;
63
+ clearAll: FunctionReference<
64
+ "mutation",
65
+ "internal",
66
+ { before?: number },
67
+ null,
68
+ Name
69
+ >;
70
+ getStatus: FunctionReference<
71
+ "query",
72
+ "internal",
73
+ { limit?: number; names?: Array<string> },
74
+ Array<{
75
+ batchSize?: number;
76
+ cursor?: string | null;
77
+ error?: string;
78
+ isDone: boolean;
79
+ latestEnd?: number;
80
+ latestStart: number;
81
+ name: string;
82
+ next?: Array<string>;
83
+ processed: number;
84
+ state: "inProgress" | "success" | "failed" | "canceled" | "unknown";
85
+ }>,
86
+ Name
87
+ >;
88
+ migrate: FunctionReference<
89
+ "mutation",
90
+ "internal",
91
+ {
92
+ args?: any;
93
+ batchSize?: number;
94
+ cursor?: string | null;
95
+ dryRun: boolean;
96
+ fnHandle: string;
97
+ name: string;
98
+ next?: Array<{ fnHandle: string; name: string }>;
99
+ oneBatchOnly?: boolean;
100
+ },
101
+ {
102
+ batchSize?: number;
103
+ cursor?: string | null;
104
+ error?: string;
105
+ isDone: boolean;
106
+ latestEnd?: number;
107
+ latestStart: number;
108
+ name: string;
109
+ next?: Array<string>;
110
+ processed: number;
111
+ state: "inProgress" | "success" | "failed" | "canceled" | "unknown";
112
+ },
113
+ Name
114
+ >;
115
+ };
116
+ };
@@ -0,0 +1,60 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated data model types.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ DataModelFromSchemaDefinition,
13
+ DocumentByName,
14
+ TableNamesInDataModel,
15
+ SystemTableNames,
16
+ } from "convex/server";
17
+ import type { GenericId } from "convex/values";
18
+ import schema from "../schema.js";
19
+
20
+ /**
21
+ * The names of all of your Convex tables.
22
+ */
23
+ export type TableNames = TableNamesInDataModel<DataModel>;
24
+
25
+ /**
26
+ * The type of a document stored in Convex.
27
+ *
28
+ * @typeParam TableName - A string literal type of the table name (like "users").
29
+ */
30
+ export type Doc<TableName extends TableNames> = DocumentByName<
31
+ DataModel,
32
+ TableName
33
+ >;
34
+
35
+ /**
36
+ * An identifier for a document in Convex.
37
+ *
38
+ * Convex documents are uniquely identified by their `Id`, which is accessible
39
+ * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
40
+ *
41
+ * Documents can be loaded using `db.get(id)` in query and mutation functions.
42
+ *
43
+ * IDs are just strings at runtime, but this type can be used to distinguish them from other
44
+ * strings when type checking.
45
+ *
46
+ * @typeParam TableName - A string literal type of the table name (like "users").
47
+ */
48
+ export type Id<TableName extends TableNames | SystemTableNames> =
49
+ GenericId<TableName>;
50
+
51
+ /**
52
+ * A type describing your Convex data model.
53
+ *
54
+ * This type includes information about what tables you have, the type of
55
+ * documents stored in those tables, and the indexes defined on them.
56
+ *
57
+ * This type is used to parameterize methods like `queryGeneric` and
58
+ * `mutationGeneric` to make them type-safe.
59
+ */
60
+ export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
@@ -0,0 +1,161 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated utilities for implementing server-side Convex query and mutation functions.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ ActionBuilder,
13
+ HttpActionBuilder,
14
+ MutationBuilder,
15
+ QueryBuilder,
16
+ GenericActionCtx,
17
+ GenericMutationCtx,
18
+ GenericQueryCtx,
19
+ GenericDatabaseReader,
20
+ GenericDatabaseWriter,
21
+ } from "convex/server";
22
+ import {
23
+ actionGeneric,
24
+ httpActionGeneric,
25
+ queryGeneric,
26
+ mutationGeneric,
27
+ internalActionGeneric,
28
+ internalMutationGeneric,
29
+ internalQueryGeneric,
30
+ } from "convex/server";
31
+ import type { DataModel } from "./dataModel.js";
32
+
33
+ /**
34
+ * Define a query in this Convex app's public API.
35
+ *
36
+ * This function will be allowed to read your Convex database and will be accessible from the client.
37
+ *
38
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
39
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
40
+ */
41
+ export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
42
+
43
+ /**
44
+ * Define a query that is only accessible from other Convex functions (but not from the client).
45
+ *
46
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
47
+ *
48
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
49
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
50
+ */
51
+ export const internalQuery: QueryBuilder<DataModel, "internal"> =
52
+ internalQueryGeneric;
53
+
54
+ /**
55
+ * Define a mutation in this Convex app's public API.
56
+ *
57
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
58
+ *
59
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
60
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
61
+ */
62
+ export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
63
+
64
+ /**
65
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
66
+ *
67
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
68
+ *
69
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
70
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
71
+ */
72
+ export const internalMutation: MutationBuilder<DataModel, "internal"> =
73
+ internalMutationGeneric;
74
+
75
+ /**
76
+ * Define an action in this Convex app's public API.
77
+ *
78
+ * An action is a function which can execute any JavaScript code, including non-deterministic
79
+ * code and code with side-effects, like calling third-party services.
80
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
81
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
82
+ *
83
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
84
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
85
+ */
86
+ export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
87
+
88
+ /**
89
+ * Define an action that is only accessible from other Convex functions (but not from the client).
90
+ *
91
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
92
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
93
+ */
94
+ export const internalAction: ActionBuilder<DataModel, "internal"> =
95
+ internalActionGeneric;
96
+
97
+ /**
98
+ * Define an HTTP action.
99
+ *
100
+ * The wrapped function will be used to respond to HTTP requests received
101
+ * by a Convex deployment if the requests matches the path and method where
102
+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.
103
+ *
104
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument
105
+ * and a Fetch API `Request` object as its second.
106
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
107
+ */
108
+ export const httpAction: HttpActionBuilder = httpActionGeneric;
109
+
110
+ type GenericCtx =
111
+ | GenericActionCtx<DataModel>
112
+ | GenericMutationCtx<DataModel>
113
+ | GenericQueryCtx<DataModel>;
114
+
115
+ /**
116
+ * A set of services for use within Convex query functions.
117
+ *
118
+ * The query context is passed as the first argument to any Convex query
119
+ * function run on the server.
120
+ *
121
+ * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
122
+ */
123
+ export type QueryCtx = GenericQueryCtx<DataModel>;
124
+
125
+ /**
126
+ * A set of services for use within Convex mutation functions.
127
+ *
128
+ * The mutation context is passed as the first argument to any Convex mutation
129
+ * function run on the server.
130
+ *
131
+ * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
132
+ */
133
+ export type MutationCtx = GenericMutationCtx<DataModel>;
134
+
135
+ /**
136
+ * A set of services for use within Convex action functions.
137
+ *
138
+ * The action context is passed as the first argument to any Convex action
139
+ * function run on the server.
140
+ */
141
+ export type ActionCtx = GenericActionCtx<DataModel>;
142
+
143
+ /**
144
+ * An interface to read from the database within Convex query functions.
145
+ *
146
+ * The two entry points are {@link DatabaseReader.get}, which fetches a single
147
+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
148
+ * building a query.
149
+ */
150
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
151
+
152
+ /**
153
+ * An interface to read from and write to the database within Convex mutation
154
+ * functions.
155
+ *
156
+ * Convex guarantees that all writes within a single mutation are
157
+ * executed atomically, so you never have to worry about partial writes leaving
158
+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
159
+ * for the guarantees Convex provides your functions.
160
+ */
161
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
@@ -0,0 +1,3 @@
1
+ import { defineComponent } from "convex/server";
2
+
3
+ export default defineComponent("migrations");
@@ -0,0 +1,110 @@
1
+ import { describe, test, expect } from "vitest";
2
+ import {
3
+ type ApiFromModules,
4
+ anyApi,
5
+ createFunctionHandle,
6
+ } from "convex/server";
7
+ import { convexTest } from "convex-test";
8
+ import { modules } from "./setup.test.js";
9
+ import { api } from "./_generated/api.js";
10
+ import type { MigrationArgs, MigrationResult } from "../client/index.js";
11
+ import { mutation } from "./_generated/server.js";
12
+ import schema from "./schema.js";
13
+
14
+ export const doneMigration = mutation({
15
+ handler: async (_, _args: MigrationArgs): Promise<MigrationResult> => {
16
+ return {
17
+ isDone: true,
18
+ continueCursor: "foo",
19
+ processed: 1,
20
+ };
21
+ },
22
+ });
23
+
24
+ const testApi: ApiFromModules<{
25
+ fns: { doneMigration: typeof doneMigration };
26
+ }>["fns"] = anyApi["lib.test"] as any;
27
+
28
+ describe("migrate", () => {
29
+ test("runs a simple migration in one go", async () => {
30
+ const t = convexTest(schema, modules);
31
+ const fnHandle = await createFunctionHandle(testApi.doneMigration);
32
+ const result = await t.mutation(api.lib.migrate, {
33
+ name: "testMigration",
34
+ fnHandle: fnHandle,
35
+ dryRun: false,
36
+ });
37
+ expect(result.isDone).toBe(true);
38
+ expect(result.cursor).toBe("foo");
39
+ expect(result.processed).toBe(1);
40
+ expect(result.error).toBeUndefined();
41
+ expect(result.batchSize).toBeUndefined();
42
+ expect(result.next).toBeUndefined();
43
+ expect(result.latestEnd).toBeTypeOf("number");
44
+ expect(result.state).toBe("success");
45
+ });
46
+
47
+ test("throws error for batchSize <= 0", async () => {
48
+ const args = {
49
+ name: "testMigration",
50
+ fnHandle: "function://dummy",
51
+ cursor: null,
52
+ batchSize: 0,
53
+ next: [],
54
+ dryRun: false,
55
+ };
56
+ const t = convexTest(schema, modules);
57
+ // Assumes testApi has shape matching api.lib – adjust per actual ConvexTest usage
58
+ await expect(t.mutation(api.lib.migrate, args)).rejects.toThrow(
59
+ "Batch size must be greater than 0",
60
+ );
61
+ });
62
+
63
+ test("throws error for invalid fnHandle", async () => {
64
+ const args = {
65
+ name: "testMigration",
66
+ fnHandle: "invalid_handle",
67
+ cursor: null,
68
+ batchSize: 10,
69
+ next: [],
70
+ dryRun: false,
71
+ };
72
+ const t = convexTest(schema, modules);
73
+ await expect(t.mutation(api.lib.migrate, args)).rejects.toThrow(
74
+ "Invalid fnHandle",
75
+ );
76
+ });
77
+ });
78
+
79
+ describe("cancel", () => {
80
+ test("throws error if migration not found", async () => {
81
+ // For cancel, ConvexTest-like patterns would be similar – this code demonstrates minimal direct call
82
+ const t = convexTest(schema, modules);
83
+ await expect(
84
+ t.mutation(api.lib.cancel, { name: "nonexistent" }),
85
+ ).rejects.toThrow();
86
+ });
87
+ });
88
+
89
+ describe("It doesn't attempt a migration if it's already done", () => {
90
+ test("runs a simple migration in one go", async () => {
91
+ const t = convexTest(schema, modules);
92
+ const fnHandle = "function://invalid";
93
+ await t.run((ctx) =>
94
+ ctx.db.insert("migrations", {
95
+ name: "testMigration",
96
+ latestStart: Date.now(),
97
+ isDone: true,
98
+ cursor: "foo",
99
+ processed: 1,
100
+ }),
101
+ );
102
+ // It'd throw if it tried to run the migration.
103
+ const result = await t.mutation(api.lib.migrate, {
104
+ name: "testMigration",
105
+ fnHandle: fnHandle,
106
+ dryRun: false,
107
+ });
108
+ expect(result.isDone).toBe(true);
109
+ });
110
+ });