@ghom/orm 1.7.1 → 1.8.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.
@@ -1,104 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.Table = void 0;
7
- const chalk_1 = __importDefault(require("chalk"));
8
- class Table {
9
- constructor(options) {
10
- this.options = options;
11
- }
12
- get db() {
13
- if (!this.orm)
14
- throw new Error("missing ORM");
15
- return this.orm.database;
16
- }
17
- get query() {
18
- return this.db(this.options.name);
19
- }
20
- async count(where) {
21
- return this.query
22
- .select(this.db.raw("count(*) as total"))
23
- .whereRaw(where ?? "1=1")
24
- .then((rows) => rows[0].total);
25
- }
26
- async hasColumn(name) {
27
- return this.db.schema.hasColumn(this.options.name, name);
28
- }
29
- async getColumn(name) {
30
- return this.db(this.options.name).columnInfo(name);
31
- }
32
- async getColumns() {
33
- return this.db(this.options.name).columnInfo();
34
- }
35
- async getColumnNames() {
36
- return this.getColumns().then(Object.keys);
37
- }
38
- async isEmpty() {
39
- return this.count().then((count) => count === 0);
40
- }
41
- async make() {
42
- if (!this.orm)
43
- throw new Error("missing ORM");
44
- try {
45
- await this.db.schema.createTable(this.options.name, this.options.setup);
46
- this.orm.config.logger?.log(`created table ${chalk_1.default[this.orm.config.loggerColors?.highlight ?? "blueBright"](this.options.name)}${this.options.description
47
- ? ` ${chalk_1.default[this.orm.config.loggerColors?.description ?? "grey"](this.options.description)}`
48
- : ""}`);
49
- }
50
- catch (error) {
51
- if (error.toString().includes("syntax error")) {
52
- this.orm.config.logger?.error(`you need to implement the "setup" method in options of your ${chalk_1.default[this.orm.config.loggerColors?.highlight ?? "blueBright"](this.options.name)} table!`);
53
- throw error;
54
- }
55
- else {
56
- this.orm.config.logger?.log(`loaded table ${chalk_1.default[this.orm.config.loggerColors?.highlight ?? "blueBright"](this.options.name)}${this.options.description
57
- ? ` ${chalk_1.default[this.orm.config.loggerColors?.description ?? "grey"](this.options.description)}`
58
- : ""}`);
59
- }
60
- }
61
- try {
62
- const migrated = await this.migrate();
63
- if (migrated !== false) {
64
- this.orm.config.logger?.log(`migrated table ${chalk_1.default[this.orm.config.loggerColors?.highlight ?? "blueBright"](this.options.name)} to version ${chalk_1.default[this.orm.config.loggerColors?.rawValue ?? "magentaBright"](migrated)}`);
65
- }
66
- }
67
- catch (error) {
68
- this.orm.config.logger?.error(error);
69
- throw error;
70
- }
71
- if ((await this.count()) === 0)
72
- await this.options.then?.bind(this)(this);
73
- return this;
74
- }
75
- async migrate() {
76
- if (!this.options.migrations)
77
- return false;
78
- const migrations = new Map(Object.entries(this.options.migrations)
79
- .sort((a, b) => Number(a[0]) - Number(b[0]))
80
- .map((entry) => [Number(entry[0]), entry[1]]));
81
- const fromDatabase = await this.db("migration")
82
- .where("table", this.options.name)
83
- .first();
84
- const data = fromDatabase || {
85
- table: this.options.name,
86
- version: -Infinity,
87
- };
88
- const baseVersion = data.version;
89
- await this.db.schema.alterTable(this.options.name, (builder) => {
90
- migrations.forEach((migration, version) => {
91
- if (version <= data.version)
92
- return;
93
- migration(builder);
94
- data.version = version;
95
- });
96
- });
97
- await this.db("migration")
98
- .insert(data)
99
- .onConflict("table")
100
- .merge();
101
- return baseVersion === data.version ? false : data.version;
102
- }
103
- }
104
- exports.Table = Table;
package/dist/cjs/index.js DELETED
@@ -1,18 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./app/orm.js"), exports);
18
- __exportStar(require("./app/table.js"), exports);
@@ -1,67 +0,0 @@
1
- import fs from "fs";
2
- import url from "url";
3
- import path from "path";
4
- import { Handler } from "@ghom/handler";
5
- import { default as knex } from "knex";
6
- import { Table } from "./table.js";
7
- const defaultBackupDir = path.join(process.cwd(), "backup");
8
- const pack = JSON.parse(fs.readFileSync(path.join(process.cwd(), "package.json"), "utf8"));
9
- const isCJS = pack.type === "commonjs" || pack.type == void 0;
10
- export class ORM {
11
- config;
12
- database;
13
- handler;
14
- constructor(config) {
15
- this.config = config;
16
- this.database = knex(config.database ?? {
17
- client: "sqlite3",
18
- useNullAsDefault: true,
19
- connection: {
20
- filename: ":memory:",
21
- },
22
- });
23
- this.handler = new Handler(config.location, {
24
- loader: (filepath) => import(isCJS ? filepath : url.pathToFileURL(filepath).href).then((file) => file.default),
25
- pattern: /\.js$/,
26
- });
27
- }
28
- get cachedTables() {
29
- return [...this.handler.elements.values()];
30
- }
31
- get cachedTableNames() {
32
- return this.cachedTables.map((table) => table.options.name);
33
- }
34
- hasCachedTable(name) {
35
- return this.cachedTables.some((table) => table.options.name);
36
- }
37
- async hasTable(name) {
38
- return this.database.schema.hasTable(name);
39
- }
40
- /**
41
- * Handle the table files and create the tables in the database.
42
- */
43
- async init() {
44
- await this.handler.init();
45
- try {
46
- await this.database.raw("PRAGMA foreign_keys = ON;");
47
- }
48
- catch (error) { }
49
- const migration = new Table({
50
- name: "migration",
51
- priority: Infinity,
52
- setup: (table) => {
53
- table.string("table").unique().notNullable();
54
- table.integer("version").notNullable();
55
- },
56
- });
57
- migration.orm = this;
58
- await migration.make();
59
- for (const table of this.cachedTables.sort((a, b) => (b.options.priority ?? 0) - (a.options.priority ?? 0))) {
60
- table.orm = this;
61
- await table.make();
62
- }
63
- }
64
- raw(sql) {
65
- return this.database.raw(sql);
66
- }
67
- }
package/dist/esm/index.js DELETED
@@ -1,2 +0,0 @@
1
- export * from "./app/orm.js";
2
- export * from "./app/table.js";
@@ -1,47 +0,0 @@
1
- import { Handler } from "@ghom/handler";
2
- import { Knex } from "knex";
3
- import { Table } from "./table.js";
4
- import { Color } from "chalk";
5
- export interface ILogger {
6
- log: (message: string) => void;
7
- error: (error: string | Error) => void;
8
- warn: (warning: string) => void;
9
- }
10
- export interface ORMConfig {
11
- /**
12
- * path to the directory that contains js files of tables
13
- */
14
- location: string;
15
- /**
16
- * database configuration
17
- */
18
- database?: Knex.Config;
19
- /**
20
- * Logger used to log the table files loaded or created.
21
- */
22
- logger?: ILogger;
23
- /**
24
- * Pattern used on logs when the table files are loaded or created. <br>
25
- * Based on Chalk color-method names.
26
- */
27
- loggerColors?: {
28
- highlight: typeof Color;
29
- rawValue: typeof Color;
30
- description: typeof Color;
31
- };
32
- }
33
- export declare class ORM {
34
- config: ORMConfig;
35
- database: Knex;
36
- handler: Handler<Table<any>>;
37
- constructor(config: ORMConfig);
38
- get cachedTables(): Table<any>[];
39
- get cachedTableNames(): string[];
40
- hasCachedTable(name: string): boolean;
41
- hasTable(name: string): Promise<boolean>;
42
- /**
43
- * Handle the table files and create the tables in the database.
44
- */
45
- init(): Promise<void>;
46
- raw(sql: Knex.Value): Knex.Raw;
47
- }
@@ -1,39 +0,0 @@
1
- import { Knex } from "knex";
2
- import { ORM } from "./orm.js";
3
- export interface MigrationData {
4
- table: string;
5
- version: number;
6
- }
7
- export interface TableOptions<Type extends object = object> {
8
- name: string;
9
- description?: string;
10
- priority?: number;
11
- migrations?: {
12
- [version: number]: (table: Knex.CreateTableBuilder) => void;
13
- };
14
- then?: (this: Table<Type>, table: Table<Type>) => unknown;
15
- setup: (table: Knex.CreateTableBuilder) => void;
16
- }
17
- export declare class Table<Type extends object = object> {
18
- readonly options: TableOptions<Type>;
19
- orm?: ORM;
20
- constructor(options: TableOptions<Type>);
21
- get db(): Knex<any, any[]>;
22
- get query(): Knex.QueryBuilder<Type, {
23
- _base: Type;
24
- _hasSelection: false;
25
- _keys: never;
26
- _aliases: {};
27
- _single: false;
28
- _intersectProps: {};
29
- _unionProps: never;
30
- }[]>;
31
- count(where?: string): Promise<number>;
32
- hasColumn(name: keyof Type & string): Promise<boolean>;
33
- getColumn(name: keyof Type & string): Promise<Knex.ColumnInfo>;
34
- getColumns(): Promise<Record<keyof Type & string, Knex.ColumnInfo>>;
35
- getColumnNames(): Promise<Array<keyof Type & string>>;
36
- isEmpty(): Promise<boolean>;
37
- make(): Promise<this>;
38
- private migrate;
39
- }
@@ -1,2 +0,0 @@
1
- export * from "./app/orm.js";
2
- export * from "./app/table.js";
package/fixup.sh DELETED
@@ -1,11 +0,0 @@
1
- cat >dist/cjs/package.json <<!EOF
2
- {
3
- "type": "commonjs"
4
- }
5
- !EOF
6
-
7
- cat >dist/esm/package.json <<!EOF
8
- {
9
- "type": "module"
10
- }
11
- !EOF
package/tsconfig-cjs.json DELETED
@@ -1,10 +0,0 @@
1
- {
2
- "extends": "./tsconfig.json",
3
- "compilerOptions": {
4
- "outDir": "dist/cjs",
5
- "module": "CommonJS",
6
- "target": "es2020",
7
- "declaration": true,
8
- "declarationDir": "dist/typings"
9
- }
10
- }
package/tsconfig-esm.json DELETED
@@ -1,8 +0,0 @@
1
- {
2
- "extends": "./tsconfig.json",
3
- "compilerOptions": {
4
- "outDir": "dist/esm",
5
- "module": "esnext",
6
- "target": "esnext",
7
- }
8
- }