peta-migrate 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.d.mts +4 -0
- package/dist/cli.mjs +74 -0
- package/dist/index.d.mts +434 -0
- package/dist/index.mjs +2 -0
- package/dist/runner-DOQsuaSQ.mjs +180 -0
- package/package.json +46 -0
package/dist/cli.d.mts
ADDED
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { a as loadMigrationFiles, i as loadConfig, n as createMigrationGenerator, t as createMigrationRunner } from "./runner-DOQsuaSQ.mjs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
4
|
+
import cac from "cac";
|
|
5
|
+
import ora from "ora";
|
|
6
|
+
//#region src/cli.ts
|
|
7
|
+
async function run() {
|
|
8
|
+
const cli = cac("peta");
|
|
9
|
+
cli.command("migrate:init", "Create migrations directory and tracking table").action(async () => {
|
|
10
|
+
const config = await loadConfig();
|
|
11
|
+
const spinner = ora("Setting up migrations...").start();
|
|
12
|
+
mkdirSync(config.migrationsDir, { recursive: true });
|
|
13
|
+
await createMigrationRunner(config.getKysely()).ensureTable();
|
|
14
|
+
spinner.succeed(`Migrations directory created at ${config.migrationsDir}`);
|
|
15
|
+
});
|
|
16
|
+
cli.command("migrate:generate [name]", "Generate initial migration from models").action(async (name) => {
|
|
17
|
+
const config = await loadConfig();
|
|
18
|
+
const spinner = ora("Generating migration...").start();
|
|
19
|
+
const code = createMigrationGenerator().generateInitialMigration(/* @__PURE__ */ new Map(), { name: name ?? "Initial" });
|
|
20
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T.Z]/g, "").slice(0, 14);
|
|
21
|
+
const safeName = (name ?? "initial").replace(/[^a-zA-Z0-9_]/g, "_");
|
|
22
|
+
const filename = resolve(config.migrationsDir, `${timestamp}_${safeName}.ts`);
|
|
23
|
+
mkdirSync(config.migrationsDir, { recursive: true });
|
|
24
|
+
writeFileSync(filename, code);
|
|
25
|
+
spinner.succeed(`Created ${filename}`);
|
|
26
|
+
});
|
|
27
|
+
cli.command("migrate:up", "Apply pending migrations").action(async () => {
|
|
28
|
+
const config = await loadConfig();
|
|
29
|
+
const migrations = await loadMigrationFiles(config.migrationsDir);
|
|
30
|
+
if (migrations.length === 0) {
|
|
31
|
+
console.log("No migration files found.");
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const runner = createMigrationRunner(config.getKysely());
|
|
35
|
+
const status = await runner.status(migrations);
|
|
36
|
+
if (status.pending.length === 0) {
|
|
37
|
+
console.log("All migrations have been applied.");
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
const spinner = ora(`Running ${status.pending.length} migration(s)...`).start();
|
|
41
|
+
await runner.up(migrations);
|
|
42
|
+
spinner.succeed(`Applied ${(await runner.getCompleted()).length} migration(s)`);
|
|
43
|
+
});
|
|
44
|
+
cli.command("migrate:down", "Rollback last batch").action(async () => {
|
|
45
|
+
const config = await loadConfig();
|
|
46
|
+
const migrations = await loadMigrationFiles(config.migrationsDir);
|
|
47
|
+
if (migrations.length === 0) {
|
|
48
|
+
console.log("No migration files found.");
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
const runner = createMigrationRunner(config.getKysely());
|
|
52
|
+
if ((await runner.getCompleted()).length === 0) {
|
|
53
|
+
console.log("Nothing to rollback.");
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
const spinner = ora("Rolling back...").start();
|
|
57
|
+
await runner.down(migrations);
|
|
58
|
+
spinner.succeed("Rolled back");
|
|
59
|
+
});
|
|
60
|
+
cli.command("migrate:status", "Show migration status").action(async () => {
|
|
61
|
+
const config = await loadConfig();
|
|
62
|
+
const migrations = await loadMigrationFiles(config.migrationsDir);
|
|
63
|
+
const { completed, pending } = await createMigrationRunner(config.getKysely()).status(migrations);
|
|
64
|
+
console.log(`\n Completed: ${completed.length}`);
|
|
65
|
+
for (const m of completed) console.log(` ✓ ${m.name}`);
|
|
66
|
+
console.log(`\n Pending: ${pending.length}`);
|
|
67
|
+
for (const m of pending) console.log(` · ${m.name}`);
|
|
68
|
+
console.log();
|
|
69
|
+
});
|
|
70
|
+
cli.help();
|
|
71
|
+
cli.parse();
|
|
72
|
+
}
|
|
73
|
+
//#endregion
|
|
74
|
+
export { run };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
import { Kysely } from "kysely";
|
|
2
|
+
|
|
3
|
+
//#region src/types.d.ts
|
|
4
|
+
interface MigrationFile {
|
|
5
|
+
name: string;
|
|
6
|
+
up: (db: Kysely<unknown>) => Promise<void>;
|
|
7
|
+
down: (db: Kysely<unknown>) => Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
interface MigrationRecord {
|
|
10
|
+
name: string;
|
|
11
|
+
appliedAt: string;
|
|
12
|
+
}
|
|
13
|
+
interface MigrationStatus {
|
|
14
|
+
completed: MigrationRecord[];
|
|
15
|
+
pending: MigrationFile[];
|
|
16
|
+
}
|
|
17
|
+
interface PetaMigrateConfig {
|
|
18
|
+
migrationsDir: string;
|
|
19
|
+
models: string[] | string;
|
|
20
|
+
getKysely: () => Kysely<unknown>;
|
|
21
|
+
}
|
|
22
|
+
interface ResolvedConfig {
|
|
23
|
+
migrationsDir: string;
|
|
24
|
+
models: string[] | string;
|
|
25
|
+
getKysely: () => Kysely<unknown>;
|
|
26
|
+
}
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region src/config.d.ts
|
|
29
|
+
declare function defineConfig(config: PetaMigrateConfig): PetaMigrateConfig;
|
|
30
|
+
declare function loadConfig(): Promise<ResolvedConfig>;
|
|
31
|
+
declare function loadMigrationFiles(dir: string): Promise<MigrationFile[]>;
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region ../orm/src/lib/kysely.d.ts
|
|
34
|
+
type Database = Kysely<Record<string, never>>;
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region ../orm/src/pagination/index.d.ts
|
|
37
|
+
interface Paginator {
|
|
38
|
+
readonly data: Collection;
|
|
39
|
+
readonly total: number;
|
|
40
|
+
readonly perPage: number;
|
|
41
|
+
readonly currentPage: number;
|
|
42
|
+
readonly lastPage: number;
|
|
43
|
+
readonly hasMorePages: boolean;
|
|
44
|
+
readonly hasPages: boolean;
|
|
45
|
+
readonly firstItem: number;
|
|
46
|
+
readonly lastItem: number;
|
|
47
|
+
readonly onFirstPage: boolean;
|
|
48
|
+
readonly onLastPage: boolean;
|
|
49
|
+
readonly count: number;
|
|
50
|
+
map<T>(fn: (item: ModelInstance) => T): T[];
|
|
51
|
+
toJSON(): PaginatorJson;
|
|
52
|
+
}
|
|
53
|
+
interface PaginatorJson {
|
|
54
|
+
data: Record<string, unknown>[];
|
|
55
|
+
total: number;
|
|
56
|
+
perPage: number;
|
|
57
|
+
currentPage: number;
|
|
58
|
+
lastPage: number;
|
|
59
|
+
hasMorePages: boolean;
|
|
60
|
+
hasPages: boolean;
|
|
61
|
+
firstItem: number | null;
|
|
62
|
+
lastItem: number | null;
|
|
63
|
+
onFirstPage: boolean;
|
|
64
|
+
onLastPage: boolean;
|
|
65
|
+
}
|
|
66
|
+
//#endregion
|
|
67
|
+
//#region ../orm/src/relations/base.d.ts
|
|
68
|
+
type RelationType = "hasMany" | "belongsTo" | "hasOne" | "manyToMany" | "hasManyThrough";
|
|
69
|
+
interface Relation {
|
|
70
|
+
readonly type: RelationType;
|
|
71
|
+
readonly relatedModelClass: ModelDefinition;
|
|
72
|
+
readonly foreignKey: string;
|
|
73
|
+
readonly localKey: string;
|
|
74
|
+
readonly throughTable?: string;
|
|
75
|
+
readonly foreignPivotKey?: string;
|
|
76
|
+
readonly relatedPivotKey?: string;
|
|
77
|
+
readonly throughForeignKey?: string;
|
|
78
|
+
readonly throughLocalKey?: string;
|
|
79
|
+
_morphMap?: Record<string, () => ModelDefinition>;
|
|
80
|
+
_morphType?: string;
|
|
81
|
+
_morphId?: string;
|
|
82
|
+
_morphTypeValue?: string;
|
|
83
|
+
query(parent: ModelInstance): QueryBuilder;
|
|
84
|
+
addEagerConstraints(query: QueryBuilder, models: ModelInstance[]): void;
|
|
85
|
+
match(models: ModelInstance[], results: ModelInstance[], relationName: string): void;
|
|
86
|
+
getResults(parent: ModelInstance): Promise<ModelInstance | ModelInstance[] | null>;
|
|
87
|
+
loadEager(models: ModelInstance[], relationName: string, constraints?: ((qb: QueryBuilder) => void) | null): Promise<void>;
|
|
88
|
+
}
|
|
89
|
+
//#endregion
|
|
90
|
+
//#region ../orm/src/relations/graph/types.d.ts
|
|
91
|
+
interface InsertGraphOptions {
|
|
92
|
+
/** Allow `#id` / `#ref` special properties in the graph */
|
|
93
|
+
allowRefs?: boolean;
|
|
94
|
+
/**
|
|
95
|
+
* If `true`, objects with an `id` property get related (pivot row / FK set)
|
|
96
|
+
* instead of inserted. Can be an array of relation names to scope.
|
|
97
|
+
*/
|
|
98
|
+
relate?: boolean | string[];
|
|
99
|
+
/**
|
|
100
|
+
* Whitelist of relation paths allowed for this graph operation.
|
|
101
|
+
* Accepts an array of dotted paths or a Set. If not set, all relations are allowed.
|
|
102
|
+
* When used via the query builder, the QB's `allowGraph()` set is forwarded automatically.
|
|
103
|
+
*/
|
|
104
|
+
allowGraph?: string[] | Set<string>;
|
|
105
|
+
}
|
|
106
|
+
interface UpsertGraphOptions extends InsertGraphOptions {
|
|
107
|
+
/** Unrelate (set FK null / remove pivot) instead of deleting missing items */
|
|
108
|
+
unrelate?: boolean | string[];
|
|
109
|
+
/** Prevent deletion for all or specific relation paths */
|
|
110
|
+
noDelete?: boolean | string[];
|
|
111
|
+
/** Prevent insertion for all or specific relation paths */
|
|
112
|
+
noInsert?: boolean | string[];
|
|
113
|
+
/** Prevent update for all or specific relation paths */
|
|
114
|
+
noUpdate?: boolean | string[];
|
|
115
|
+
}
|
|
116
|
+
//#endregion
|
|
117
|
+
//#region ../orm/src/query/types.d.ts
|
|
118
|
+
interface QueryBuilder extends PromiseLike<ModelInstance[]> {
|
|
119
|
+
execute(): Promise<ModelInstance[]>;
|
|
120
|
+
collect(): Promise<Collection>;
|
|
121
|
+
executeTakeFirst(): Promise<ModelInstance | undefined>;
|
|
122
|
+
executeTakeFirstOrThrow(): Promise<ModelInstance>;
|
|
123
|
+
find(id: number | string): Promise<ModelInstance | undefined>;
|
|
124
|
+
findOrFail(id: number | string): Promise<ModelInstance>;
|
|
125
|
+
first(): Promise<ModelInstance | undefined>;
|
|
126
|
+
toSQL(): {
|
|
127
|
+
sql: string;
|
|
128
|
+
parameters: readonly unknown[];
|
|
129
|
+
};
|
|
130
|
+
count(): Promise<number>;
|
|
131
|
+
sum(column: string): Promise<number>;
|
|
132
|
+
avg(column: string): Promise<number>;
|
|
133
|
+
min(column: string): Promise<number>;
|
|
134
|
+
max(column: string): Promise<number>;
|
|
135
|
+
withCount(relation: string): QueryBuilder;
|
|
136
|
+
withSum(relation: string, column: string): QueryBuilder;
|
|
137
|
+
withAvg(relation: string, column: string): QueryBuilder;
|
|
138
|
+
withMin(relation: string, column: string): QueryBuilder;
|
|
139
|
+
withMax(relation: string, column: string): QueryBuilder;
|
|
140
|
+
withExists(relation: string): QueryBuilder;
|
|
141
|
+
chunk(size: number, callback: (chunk: ModelInstance[]) => Promise<void>): Promise<void>;
|
|
142
|
+
paginate(page: number, perPage?: number): Promise<Paginator>;
|
|
143
|
+
insertGraph(data: Record<string, unknown> | Record<string, unknown>[], options?: InsertGraphOptions): Promise<any>;
|
|
144
|
+
upsertGraph(data: Record<string, unknown> | Record<string, unknown>[], options?: UpsertGraphOptions): Promise<any>;
|
|
145
|
+
with(...relations: (string | Record<string, (qb: QueryBuilder) => void>)[]): QueryBuilder;
|
|
146
|
+
/**
|
|
147
|
+
* Whitelist allowed relations (and nested paths) for eager loading.
|
|
148
|
+
* Throws if a relation path is not in the allow list.
|
|
149
|
+
*
|
|
150
|
+
* Supports dotted paths for granular control:
|
|
151
|
+
* - `allowGraph("posts")` allows `posts`, `posts.author`, `posts.author.profile`, etc.
|
|
152
|
+
* - `allowGraph("posts.author")` allows `posts.author` and `posts.author.profile`,
|
|
153
|
+
* but NOT bare `posts` or `posts.comments`.
|
|
154
|
+
*
|
|
155
|
+
* Multiple arguments are merged: `allowGraph("posts", "profile")`
|
|
156
|
+
*/
|
|
157
|
+
allowGraph(...expressions: string[]): QueryBuilder;
|
|
158
|
+
updateMany(data: Record<string, unknown>): Promise<number>;
|
|
159
|
+
deleteMany(): Promise<number>;
|
|
160
|
+
withTrashed(): QueryBuilder;
|
|
161
|
+
onlyTrashed(): QueryBuilder;
|
|
162
|
+
whereIn(column: string, values: unknown[]): QueryBuilder;
|
|
163
|
+
whereInPivot(column: string, values: unknown[]): QueryBuilder;
|
|
164
|
+
has(relationName: string): QueryBuilder;
|
|
165
|
+
whereHas(relationName: string, callback?: (qb: QueryBuilder) => void): QueryBuilder;
|
|
166
|
+
whereDoesntHave(relationName: string, callback?: (qb: QueryBuilder) => void): QueryBuilder;
|
|
167
|
+
where(column: string, operator: unknown, value?: unknown): QueryBuilder;
|
|
168
|
+
whereRef(col1: string, operator: string, col2: string): QueryBuilder;
|
|
169
|
+
orWhere(column: string, operator: unknown, value?: unknown): QueryBuilder;
|
|
170
|
+
orderBy(column: string, direction?: "asc" | "desc"): QueryBuilder;
|
|
171
|
+
limit(n: number): QueryBuilder;
|
|
172
|
+
offset(n: number): QueryBuilder;
|
|
173
|
+
select(...columns: string[]): QueryBuilder;
|
|
174
|
+
selectAll(table?: string): QueryBuilder;
|
|
175
|
+
innerJoin(table: string, lhs: string, rhs: string): QueryBuilder;
|
|
176
|
+
leftJoin(table: string, lhs: string, rhs: string): QueryBuilder;
|
|
177
|
+
groupBy(...columns: string[]): QueryBuilder;
|
|
178
|
+
having(column: string, operator: string, value: unknown): QueryBuilder;
|
|
179
|
+
withoutGlobalScope(name: string): QueryBuilder;
|
|
180
|
+
all(): QueryBuilder;
|
|
181
|
+
/** @internal Access underlying Kysely builder for raw SQL operations */
|
|
182
|
+
_getKyselyQb(): any;
|
|
183
|
+
/** @internal Replace the underlying Kysely builder */
|
|
184
|
+
_replaceKyselyQb(newQb: any): void;
|
|
185
|
+
when(condition: unknown, callback: (q: QueryBuilder) => QueryBuilder): QueryBuilder;
|
|
186
|
+
unless(condition: unknown, callback: (q: QueryBuilder) => QueryBuilder): QueryBuilder;
|
|
187
|
+
}
|
|
188
|
+
//#endregion
|
|
189
|
+
//#region ../orm/src/relations/related-query.d.ts
|
|
190
|
+
interface RelationQuery extends QueryBuilder {
|
|
191
|
+
/** Attach related model(s) for many-to-many relations. */
|
|
192
|
+
attach(ids: number | number[] | string | string[], pivotData?: Record<string, unknown>): Promise<void>;
|
|
193
|
+
/** Detach related model(s) for many-to-many relations. */
|
|
194
|
+
detach(ids?: number | number[] | string | string[]): Promise<void>;
|
|
195
|
+
/** Sync related models: attaches new IDs, detaches missing ones. */
|
|
196
|
+
sync(ids: (number | string)[] | Record<number | string, Record<string, unknown>>): Promise<void>;
|
|
197
|
+
/** Sync without detaching existing IDs. */
|
|
198
|
+
syncWithoutDetaching(ids: (number | string)[]): Promise<void>;
|
|
199
|
+
/** Update pivot data for a specific related model. */
|
|
200
|
+
updateExistingPivot(id: number | string, data: Record<string, unknown>): Promise<void>;
|
|
201
|
+
}
|
|
202
|
+
//#endregion
|
|
203
|
+
//#region ../orm/src/plugins/index.d.ts
|
|
204
|
+
/**
|
|
205
|
+
* A plugin is a function that receives a model definition and can
|
|
206
|
+
* modify it by adding hooks, scopes, columns, or methods.
|
|
207
|
+
*
|
|
208
|
+
* ```ts
|
|
209
|
+
* const myPlugin = (options?: MyOptions): Plugin =>
|
|
210
|
+
* (def) => {
|
|
211
|
+
* def.addGlobalScope?.('active', (q) => q.where('active', true))
|
|
212
|
+
* return def
|
|
213
|
+
* }
|
|
214
|
+
* ```
|
|
215
|
+
*/
|
|
216
|
+
type Plugin = (def: ModelDefinition) => undefined | ModelDefinition;
|
|
217
|
+
//#endregion
|
|
218
|
+
//#region ../orm/src/columns/schema.d.ts
|
|
219
|
+
interface Constraint {
|
|
220
|
+
type: string;
|
|
221
|
+
args: unknown[];
|
|
222
|
+
}
|
|
223
|
+
//#endregion
|
|
224
|
+
//#region ../orm/src/columns/column.d.ts
|
|
225
|
+
interface Column<out T = unknown> {
|
|
226
|
+
readonly arkType: unknown;
|
|
227
|
+
readonly dataType: string;
|
|
228
|
+
readonly args: readonly unknown[];
|
|
229
|
+
readonly constraints: readonly Constraint[];
|
|
230
|
+
readonly isNullable: boolean;
|
|
231
|
+
readonly isPrimaryKey: boolean;
|
|
232
|
+
readonly isUnique: boolean;
|
|
233
|
+
readonly defaultValue: unknown;
|
|
234
|
+
hasConstraint(type: string): boolean;
|
|
235
|
+
parse(value: unknown): T;
|
|
236
|
+
assert(value: unknown): T;
|
|
237
|
+
primaryKey(): Column<T>;
|
|
238
|
+
nullable(): Column<T | null>;
|
|
239
|
+
default<V>(value: V): Column<T>;
|
|
240
|
+
unique(): Column<T>;
|
|
241
|
+
index(): Column<T>;
|
|
242
|
+
min(n: number): Column<T>;
|
|
243
|
+
max(n: number): Column<T>;
|
|
244
|
+
email(): Column<T>;
|
|
245
|
+
url(): Column<T>;
|
|
246
|
+
pattern(regex: RegExp | string): Column<T>;
|
|
247
|
+
references(table: () => unknown, columns: string[]): Column<T>;
|
|
248
|
+
}
|
|
249
|
+
type ColumnShape = Record<string, Column>;
|
|
250
|
+
//#endregion
|
|
251
|
+
//#region ../orm/src/types.d.ts
|
|
252
|
+
interface ModelLike {
|
|
253
|
+
get<T = unknown>(key: string): T;
|
|
254
|
+
set(key: string, value: unknown): void;
|
|
255
|
+
}
|
|
256
|
+
interface ORMLike {
|
|
257
|
+
readonly kysely: Database;
|
|
258
|
+
register(model: ModelDefinition$1<any>): void;
|
|
259
|
+
registerAll(...models: (ModelDefinition$1<any> | ModelDefinition$1<any>[])[]): void;
|
|
260
|
+
destroy(): Promise<void>;
|
|
261
|
+
transaction<T>(fn: (trx: import("kysely").Kysely<Record<string, never>>) => Promise<T>): Promise<T>;
|
|
262
|
+
readonly models: ReadonlyMap<string, ModelDefinition$1<any>>;
|
|
263
|
+
getModel<T extends ColumnShape = ColumnShape>(name: string): ModelDefinition$1<T> | undefined;
|
|
264
|
+
}
|
|
265
|
+
interface ModelDefinition$1<TColumns extends ColumnShape = ColumnShape> {
|
|
266
|
+
readonly table: string;
|
|
267
|
+
readonly columns: TColumns;
|
|
268
|
+
readonly relations: Record<string, Relation>;
|
|
269
|
+
readonly name: string;
|
|
270
|
+
_orm: ORMLike | null;
|
|
271
|
+
query(): QueryBuilder;
|
|
272
|
+
find(id: number | string): Promise<ModelInstance | undefined>;
|
|
273
|
+
findOrFail(id: number | string): Promise<ModelInstance>;
|
|
274
|
+
first(): Promise<ModelInstance | undefined>;
|
|
275
|
+
create(data: Record<string, unknown>): Promise<ModelInstance>;
|
|
276
|
+
insert(data: Record<string, unknown>): Promise<ModelInstance>;
|
|
277
|
+
insertMany(dataArray: Record<string, unknown>[]): Promise<ModelInstance[]>;
|
|
278
|
+
update(id: number | string, data: Record<string, unknown>): Promise<ModelInstance>;
|
|
279
|
+
delete(id: number | string): Promise<void>;
|
|
280
|
+
hydrate(row: Record<string, unknown>): ModelInstance;
|
|
281
|
+
on(event: string, callback: (model: ModelInstance) => void | Promise<void>): () => void;
|
|
282
|
+
getHooks(): HookManager;
|
|
283
|
+
addGlobalScope(name: string, callback: (qb: QueryBuilder) => void): void;
|
|
284
|
+
removeGlobalScope(name: string): void;
|
|
285
|
+
getGlobalScopes(): Map<string, (qb: QueryBuilder) => void> | undefined;
|
|
286
|
+
_init(orm: ORMLike): void;
|
|
287
|
+
}
|
|
288
|
+
//#endregion
|
|
289
|
+
//#region ../orm/src/hooks/index.d.ts
|
|
290
|
+
type LifecycleEvent = "beforeCreate" | "afterCreate" | "beforeUpdate" | "afterUpdate" | "beforeSave" | "afterSave" | "beforeDelete" | "afterDelete" | "beforeRestore" | "afterRestore" | "beforeForceDelete" | "afterForceDelete";
|
|
291
|
+
type HookCallback = (model: ModelLike) => void | Promise<void>;
|
|
292
|
+
interface HookManager {
|
|
293
|
+
on(event: LifecycleEvent, callback: HookCallback): () => void;
|
|
294
|
+
off(event: LifecycleEvent, callback: HookCallback): void;
|
|
295
|
+
trigger(event: LifecycleEvent, model: ModelLike): Promise<void>;
|
|
296
|
+
clone(): HookManager;
|
|
297
|
+
}
|
|
298
|
+
//#endregion
|
|
299
|
+
//#region ../orm/src/hooks/static.d.ts
|
|
300
|
+
interface StaticHookArgs {
|
|
301
|
+
/** Transform the mutating query into a SELECT to preview affected rows */
|
|
302
|
+
asFindQuery(): QueryBuilder;
|
|
303
|
+
/** Cancel the mutation and return a custom result */
|
|
304
|
+
cancelQuery(result: unknown): void;
|
|
305
|
+
/** The column data being inserted/updated (for create/update hooks) */
|
|
306
|
+
inputItems?: Record<string, unknown>[];
|
|
307
|
+
}
|
|
308
|
+
type StaticHookCallback = (args: StaticHookArgs) => void | Promise<void>;
|
|
309
|
+
//#endregion
|
|
310
|
+
//#region ../orm/src/model/types.d.ts
|
|
311
|
+
interface ModelInstance {
|
|
312
|
+
readonly exists: boolean;
|
|
313
|
+
readonly attributes: Record<string, unknown>;
|
|
314
|
+
readonly dirtyAttributes: Record<string, unknown>;
|
|
315
|
+
isDirty(key?: string): boolean;
|
|
316
|
+
get<T = unknown>(key: string): T;
|
|
317
|
+
set(key: string, value: unknown): void;
|
|
318
|
+
fill(data: Record<string, unknown>): void;
|
|
319
|
+
reset(): void;
|
|
320
|
+
$getRelation<T = unknown>(name: string): T;
|
|
321
|
+
$setRelation(name: string, value: unknown): void;
|
|
322
|
+
$hasRelation(name: string): boolean;
|
|
323
|
+
$relationData(): Record<string, unknown>;
|
|
324
|
+
$load(...relations: string[]): Promise<void>;
|
|
325
|
+
$related(name: string): RelationQuery;
|
|
326
|
+
$save(): Promise<this>;
|
|
327
|
+
$delete(): Promise<void>;
|
|
328
|
+
$forceDelete(): Promise<void>;
|
|
329
|
+
$restore(): Promise<void>;
|
|
330
|
+
$trashed(): boolean;
|
|
331
|
+
$reload(): Promise<void>;
|
|
332
|
+
$toJSON(): Record<string, unknown>;
|
|
333
|
+
toJSON(): Record<string, unknown>;
|
|
334
|
+
}
|
|
335
|
+
interface ModelDefinition<TColumns extends ColumnShape = ColumnShape> {
|
|
336
|
+
readonly table: string;
|
|
337
|
+
readonly columns: TColumns;
|
|
338
|
+
readonly relations: Record<string, Relation>;
|
|
339
|
+
readonly name: string;
|
|
340
|
+
_orm: ORMLike | null;
|
|
341
|
+
query(): QueryBuilder;
|
|
342
|
+
find(id: number | string): Promise<ModelInstance | undefined>;
|
|
343
|
+
findOrFail(id: number | string): Promise<ModelInstance>;
|
|
344
|
+
first(): Promise<ModelInstance | undefined>;
|
|
345
|
+
create(data: Record<string, unknown>): Promise<ModelInstance>;
|
|
346
|
+
insert(data: Record<string, unknown>): Promise<ModelInstance>;
|
|
347
|
+
insertMany(dataArray: Record<string, unknown>[]): Promise<ModelInstance[]>;
|
|
348
|
+
update(id: number | string, data: Record<string, unknown>): Promise<ModelInstance>;
|
|
349
|
+
delete(id: number | string): Promise<void>;
|
|
350
|
+
insertGraph(data: Record<string, unknown> | Record<string, unknown>[], options?: InsertGraphOptions): Promise<any>;
|
|
351
|
+
upsertGraph(data: Record<string, unknown> | Record<string, unknown>[], options?: UpsertGraphOptions): Promise<any>;
|
|
352
|
+
hydrate(row: Record<string, unknown>): ModelInstance;
|
|
353
|
+
use(plugin: Plugin): ModelDefinition;
|
|
354
|
+
makeHelper<A extends any[], R>(fn: (qb: QueryBuilder, ...args: A) => R): (...args: A) => R;
|
|
355
|
+
on(event: string, callback: (model: ModelInstance) => void | Promise<void>): () => void;
|
|
356
|
+
getHooks(): HookManager;
|
|
357
|
+
beforeDelete(callback: StaticHookCallback): () => void;
|
|
358
|
+
afterDelete(callback: StaticHookCallback): () => void;
|
|
359
|
+
beforeUpdate(callback: StaticHookCallback): () => void;
|
|
360
|
+
afterUpdate(callback: StaticHookCallback): () => void;
|
|
361
|
+
beforeCreate(callback: StaticHookCallback): () => void;
|
|
362
|
+
afterCreate(callback: StaticHookCallback): () => void;
|
|
363
|
+
beforeFind(callback: StaticHookCallback): () => void;
|
|
364
|
+
afterFind(callback: StaticHookCallback): () => void;
|
|
365
|
+
addGlobalScope(name: string, callback: (qb: QueryBuilder) => void): void;
|
|
366
|
+
removeGlobalScope(name: string): void;
|
|
367
|
+
getGlobalScopes(): Map<string, (qb: QueryBuilder) => void> | undefined;
|
|
368
|
+
registerTimestamps?(createdAtCol?: string, updatedAtCol?: string): void;
|
|
369
|
+
registerSoftDeletes?(deletedAtCol?: string): void;
|
|
370
|
+
discover?(): Promise<never>;
|
|
371
|
+
_init(orm: ORMLike): void;
|
|
372
|
+
}
|
|
373
|
+
//#endregion
|
|
374
|
+
//#region ../orm/src/collection/index.d.ts
|
|
375
|
+
interface Collection {
|
|
376
|
+
readonly length: number;
|
|
377
|
+
[Symbol.iterator](): Iterator<ModelInstance>;
|
|
378
|
+
at(index: number): ModelInstance | undefined;
|
|
379
|
+
first(): ModelInstance | undefined;
|
|
380
|
+
last(): ModelInstance | undefined;
|
|
381
|
+
all(): ModelInstance[];
|
|
382
|
+
findBy(id: number | string): ModelInstance | undefined;
|
|
383
|
+
find(callback: (item: ModelInstance, index: number) => boolean): ModelInstance | undefined;
|
|
384
|
+
some(callback: (item: ModelInstance, index: number) => boolean): boolean;
|
|
385
|
+
includes(item: ModelInstance): boolean;
|
|
386
|
+
isEmpty(): boolean;
|
|
387
|
+
isNotEmpty(): boolean;
|
|
388
|
+
get(key: string): unknown[];
|
|
389
|
+
pluck(key: string): unknown[];
|
|
390
|
+
groupBy(key: string): Record<string, ModelInstance[]>;
|
|
391
|
+
keyBy(key: string): Record<string, ModelInstance>;
|
|
392
|
+
map<T>(fn: (item: ModelInstance, index: number) => T): T[];
|
|
393
|
+
filter(fn: (item: ModelInstance, index: number) => boolean): Collection;
|
|
394
|
+
reduce<T>(fn: (acc: T, item: ModelInstance, index: number) => T, initial: T): T;
|
|
395
|
+
forEach(fn: (item: ModelInstance, index: number) => void): void;
|
|
396
|
+
each(fn: (item: ModelInstance, index: number) => void): Collection;
|
|
397
|
+
unique(key?: string): Collection;
|
|
398
|
+
sortBy(key: string, direction?: "asc" | "desc"): Collection;
|
|
399
|
+
shuffle(): Collection;
|
|
400
|
+
take(n: number): Collection;
|
|
401
|
+
skip(n: number): Collection;
|
|
402
|
+
chunk(size: number): Collection[];
|
|
403
|
+
sum(key: string): number;
|
|
404
|
+
avg(key: string): number;
|
|
405
|
+
min(key: string): number;
|
|
406
|
+
max(key: string): number;
|
|
407
|
+
diff(other: Collection): Collection;
|
|
408
|
+
intersect(other: Collection): Collection;
|
|
409
|
+
concat(other: Collection): Collection;
|
|
410
|
+
push(...items: ModelInstance[]): void;
|
|
411
|
+
load(...relations: string[]): Promise<Collection>;
|
|
412
|
+
toJSON(): Record<string, unknown>[];
|
|
413
|
+
}
|
|
414
|
+
//#endregion
|
|
415
|
+
//#region src/generator.d.ts
|
|
416
|
+
interface GeneratorOptions {
|
|
417
|
+
name?: string;
|
|
418
|
+
}
|
|
419
|
+
interface MigrationGenerator {
|
|
420
|
+
generateInitialMigration(models: Map<string, ModelDefinition>, options?: GeneratorOptions): string;
|
|
421
|
+
}
|
|
422
|
+
declare function createMigrationGenerator(): MigrationGenerator;
|
|
423
|
+
//#endregion
|
|
424
|
+
//#region src/runner.d.ts
|
|
425
|
+
interface MigrationRunner {
|
|
426
|
+
ensureTable(): Promise<void>;
|
|
427
|
+
getCompleted(): Promise<MigrationRecord[]>;
|
|
428
|
+
up(migrations: MigrationFile[]): Promise<void>;
|
|
429
|
+
down(migrations: MigrationFile[]): Promise<void>;
|
|
430
|
+
status(migrations: MigrationFile[]): Promise<MigrationStatus>;
|
|
431
|
+
}
|
|
432
|
+
declare function createMigrationRunner(db: Kysely<Record<string, never>>, table?: string): MigrationRunner;
|
|
433
|
+
//#endregion
|
|
434
|
+
export { type GeneratorOptions, type MigrationFile, type MigrationGenerator, type MigrationRecord, type MigrationRunner, type MigrationStatus, type PetaMigrateConfig, type ResolvedConfig, createMigrationGenerator, createMigrationRunner, defineConfig, loadConfig, loadMigrationFiles };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
//#region src/config.ts
|
|
4
|
+
function defineConfig(config) {
|
|
5
|
+
return config;
|
|
6
|
+
}
|
|
7
|
+
async function loadConfig() {
|
|
8
|
+
const candidates = [
|
|
9
|
+
"peta.config.ts",
|
|
10
|
+
"peta.config.js",
|
|
11
|
+
"peta.config.mjs"
|
|
12
|
+
];
|
|
13
|
+
let mod = null;
|
|
14
|
+
for (const file of candidates) try {
|
|
15
|
+
mod = await import(resolve(process.cwd(), file));
|
|
16
|
+
break;
|
|
17
|
+
} catch {}
|
|
18
|
+
if (!mod) throw new Error("No peta.config.ts found. Create one in your project root.");
|
|
19
|
+
const config = mod.default ?? mod;
|
|
20
|
+
return {
|
|
21
|
+
migrationsDir: config.migrationsDir,
|
|
22
|
+
models: config.models,
|
|
23
|
+
getKysely: config.getKysely
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
async function loadMigrationFiles(dir) {
|
|
27
|
+
const { readdirSync } = await import("node:fs");
|
|
28
|
+
const files = readdirSync(dir).filter((f) => f.endsWith(".ts") || f.endsWith(".js")).sort();
|
|
29
|
+
const migrations = [];
|
|
30
|
+
for (const file of files) {
|
|
31
|
+
const mod = await import(resolve(dir, file));
|
|
32
|
+
if (mod.up) migrations.push({
|
|
33
|
+
name: file.replace(/\.(ts|js)$/, ""),
|
|
34
|
+
up: mod.up,
|
|
35
|
+
down: mod.down ?? (async () => {})
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return migrations;
|
|
39
|
+
}
|
|
40
|
+
//#endregion
|
|
41
|
+
//#region src/generator.ts
|
|
42
|
+
function createMigrationGenerator() {
|
|
43
|
+
function generateInitialMigration(models, options = {}) {
|
|
44
|
+
options.name;
|
|
45
|
+
const parts = [];
|
|
46
|
+
const indexParts = [];
|
|
47
|
+
const warnings = [];
|
|
48
|
+
const registeredTables = new Set([...models.values()].map((m) => m.table).filter(Boolean));
|
|
49
|
+
for (const [, modelDef] of models) {
|
|
50
|
+
const table = modelDef.table;
|
|
51
|
+
if (!table) continue;
|
|
52
|
+
parts.push(generateCreateTable(table, modelDef.columns));
|
|
53
|
+
for (const [colName, col] of Object.entries(modelDef.columns)) if (col.hasConstraint("index") && !col.isPrimaryKey && !col.isUnique) indexParts.push(generateCreateIndex(table, colName));
|
|
54
|
+
for (const [, rel] of Object.entries(modelDef.relations ?? {})) if (rel.type === "manyToMany") {
|
|
55
|
+
const through = rel.throughTable;
|
|
56
|
+
if (through && !registeredTables.has(through)) warnings.push(`// ⚠ Detected ManyToMany "${modelDef.name}" references table "${through}" but no model is registered for it.\n// Add a model to include the pivot table.`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const upBody = [...parts, ...indexParts].join("\n\n");
|
|
60
|
+
const downTables = [...models.values()].filter((m) => m.table).map((m) => ` await db.schema.dropTable("${m.table}").ifExists().execute()`).join("\n");
|
|
61
|
+
return `import type { Kysely } from "kysely"\nimport { sql } from "kysely"\n\nexport async function up(db: Kysely<any>): Promise<void> {\n${warnings.length > 0 ? ` // Warnings:\n${warnings.join("\n")}\n\n` : ""}${upBody}\n}\n\nexport async function down(db: Kysely<any>): Promise<void> {\n${downTables}\n}\n`;
|
|
62
|
+
}
|
|
63
|
+
return { generateInitialMigration };
|
|
64
|
+
}
|
|
65
|
+
function generateCreateTable(table, columns) {
|
|
66
|
+
const lines = [` await db.schema.createTable("${table}").ifNotExists()`];
|
|
67
|
+
for (const [name, col] of Object.entries(columns)) lines.push(` .addColumn("${name}", "${mapType(col)}"${columnCallback(col)})`);
|
|
68
|
+
lines.push(" .execute()");
|
|
69
|
+
return lines.join("\n");
|
|
70
|
+
}
|
|
71
|
+
function generateCreateIndex(table, column) {
|
|
72
|
+
return [
|
|
73
|
+
` await db.schema.createIndex("${table}_${column}_index")`,
|
|
74
|
+
` .on("${table}")`,
|
|
75
|
+
` .column("${column}")`,
|
|
76
|
+
" .execute()"
|
|
77
|
+
].join("\n");
|
|
78
|
+
}
|
|
79
|
+
function columnCallback(col) {
|
|
80
|
+
const calls = [];
|
|
81
|
+
if (col.isPrimaryKey) {
|
|
82
|
+
if (col.dataType === "integer") calls.push("autoIncrement()");
|
|
83
|
+
calls.push("primaryKey()");
|
|
84
|
+
}
|
|
85
|
+
if (!col.isNullable && !col.isPrimaryKey) calls.push("notNull()");
|
|
86
|
+
const dv = col.defaultValue;
|
|
87
|
+
if (dv !== void 0 && typeof dv !== "function") calls.push(`defaultTo(${JSON.stringify(dv)})`);
|
|
88
|
+
if (col.isUnique && !col.isPrimaryKey) calls.push("unique()");
|
|
89
|
+
const refConstraint = col.constraints.find((c) => c.type === "references");
|
|
90
|
+
if (refConstraint?.args[0]) {
|
|
91
|
+
const targetTable = (typeof refConstraint.args[0] === "function" ? refConstraint.args[0]() : refConstraint.args[0])?.table;
|
|
92
|
+
const targetColumns = refConstraint.args[1];
|
|
93
|
+
if (typeof targetTable === "string" && targetTable && targetColumns?.length) calls.push(`references("${targetTable}.${targetColumns[0]}")`);
|
|
94
|
+
}
|
|
95
|
+
return calls.length === 0 ? "" : `, (c) => c.${calls.join(".")}`;
|
|
96
|
+
}
|
|
97
|
+
function mapType(col) {
|
|
98
|
+
switch (col.dataType) {
|
|
99
|
+
case "integer":
|
|
100
|
+
case "smallint":
|
|
101
|
+
case "bigint":
|
|
102
|
+
case "text":
|
|
103
|
+
case "boolean":
|
|
104
|
+
case "timestamp":
|
|
105
|
+
case "date":
|
|
106
|
+
case "float":
|
|
107
|
+
case "double":
|
|
108
|
+
case "uuid": return col.dataType;
|
|
109
|
+
case "string": {
|
|
110
|
+
const max = col.args[0];
|
|
111
|
+
return max != null ? `varchar(${max})` : "varchar";
|
|
112
|
+
}
|
|
113
|
+
case "json":
|
|
114
|
+
case "jsonb": return "json";
|
|
115
|
+
case "decimal": {
|
|
116
|
+
const p = col.args[0];
|
|
117
|
+
const s = col.args[1];
|
|
118
|
+
return p != null ? `decimal(${p}, ${s ?? 0})` : "decimal";
|
|
119
|
+
}
|
|
120
|
+
case "enum": return "text";
|
|
121
|
+
default: return col.dataType;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
//#endregion
|
|
125
|
+
//#region src/runner.ts
|
|
126
|
+
function createMigrationRunner(db, table = "_peta_migrations") {
|
|
127
|
+
async function ensureTable() {
|
|
128
|
+
await db.schema.createTable(table).ifNotExists().addColumn("name", "varchar", (c) => c.notNull().primaryKey()).addColumn("applied_at", "timestamp", (c) => c.notNull().defaultTo(sql`CURRENT_TIMESTAMP`)).execute();
|
|
129
|
+
}
|
|
130
|
+
async function getCompleted() {
|
|
131
|
+
try {
|
|
132
|
+
return (await db.selectFrom(table).select(["name", "applied_at"]).orderBy("name", "asc").execute()).map((r) => ({
|
|
133
|
+
name: String(r.name),
|
|
134
|
+
appliedAt: String(r.applied_at)
|
|
135
|
+
}));
|
|
136
|
+
} catch {
|
|
137
|
+
return [];
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
async function up(migrations) {
|
|
141
|
+
await ensureTable();
|
|
142
|
+
const completed = await getCompleted();
|
|
143
|
+
const completedNames = new Set(completed.map((r) => r.name));
|
|
144
|
+
for (const m of migrations.filter((m) => !completedNames.has(m.name)).sort(byName)) {
|
|
145
|
+
await m.up(db);
|
|
146
|
+
await db.insertInto(table).values({
|
|
147
|
+
name: m.name,
|
|
148
|
+
applied_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
149
|
+
}).execute();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
async function down(migrations) {
|
|
153
|
+
const completed = await getCompleted();
|
|
154
|
+
if (completed.length === 0 || migrations.length === 0) return;
|
|
155
|
+
for (const m of migrations.filter((m) => completed.some((r) => r.name === m.name)).sort(byName).reverse()) {
|
|
156
|
+
await m.down(db);
|
|
157
|
+
await db.deleteFrom(table).where("name", "=", m.name).execute();
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
async function status(migrations) {
|
|
161
|
+
const completed = await getCompleted();
|
|
162
|
+
const completedNames = new Set(completed.map((r) => r.name));
|
|
163
|
+
return {
|
|
164
|
+
completed,
|
|
165
|
+
pending: migrations.filter((m) => !completedNames.has(m.name)).sort(byName)
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
return {
|
|
169
|
+
ensureTable,
|
|
170
|
+
getCompleted,
|
|
171
|
+
up,
|
|
172
|
+
down,
|
|
173
|
+
status
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function byName(a, b) {
|
|
177
|
+
return a.name.localeCompare(b.name);
|
|
178
|
+
}
|
|
179
|
+
//#endregion
|
|
180
|
+
export { loadMigrationFiles as a, loadConfig as i, createMigrationGenerator as n, defineConfig as r, createMigrationRunner as t };
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "peta-migrate",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"description": "Migration tools for peta-orm",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/zfadhli/peta-stack.git"
|
|
10
|
+
},
|
|
11
|
+
"module": "src/index.ts",
|
|
12
|
+
"main": "./dist/index.mjs",
|
|
13
|
+
"types": "./dist/index.d.mts",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"import": "./dist/index.mjs",
|
|
17
|
+
"types": "./dist/index.d.mts"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"bin": {
|
|
21
|
+
"peta": "./bin/peta"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"bin/",
|
|
25
|
+
"dist/",
|
|
26
|
+
"README.md",
|
|
27
|
+
"LICENSE"
|
|
28
|
+
],
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"cac": "^7.0.0",
|
|
31
|
+
"ora": "^9.4.0"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"kysely": "^0.28.17",
|
|
35
|
+
"typescript": "^6.0.0"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@types/bun": "^1.3.14",
|
|
39
|
+
"tsdown": "^0.22.2"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"build": "tsdown",
|
|
43
|
+
"prepublish": "bun run build",
|
|
44
|
+
"typecheck": "bun x tsc --noEmit"
|
|
45
|
+
}
|
|
46
|
+
}
|