outlet-orm 6.0.0 → 6.5.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/README.md +4 -2
- package/package.json +1 -1
- package/src/Model.js +154 -2
- package/src/QueryBuilder.js +82 -0
- package/types/index.d.ts +41 -0
package/README.md
CHANGED
|
@@ -86,8 +86,9 @@ my-project/
|
|
|
86
86
|
├── database/
|
|
87
87
|
│ ├── config.js # Config migrations (outlet-init)
|
|
88
88
|
│ ├── migrations/ # Migration files
|
|
89
|
-
│
|
|
90
|
-
│
|
|
89
|
+
│ ├── seeds/ # Test/demo data
|
|
90
|
+
│ │ └── UserSeeder.js
|
|
91
|
+
│ └── backups/ # 🗄️ Backup files (full / partial / journal)
|
|
91
92
|
│
|
|
92
93
|
├── public/ # ✅ Public static files
|
|
93
94
|
│ ├── images/
|
|
@@ -195,6 +196,7 @@ async store(req, res) {
|
|
|
195
196
|
- **Ergonomic aliases**: `columns([...])`, `ordrer()` (typo alias for `orderBy`)
|
|
196
197
|
- **Raw queries**: `executeRawQuery()` and `execute()` (native driver results)
|
|
197
198
|
- **Complete Migrations** (create/alter/drop, index, foreign keys, batch tracking)
|
|
199
|
+
- **Database Backup** (v6.0.0): full/partial/journal backups, recurring scheduler, AES-256-GCM encryption, TCP daemon + remote client, automatic restore
|
|
198
200
|
- **Handy CLI tools**: `outlet-init`, `outlet-migrate`, `outlet-convert`
|
|
199
201
|
- **`.env` configuration** (loaded automatically)
|
|
200
202
|
- **Multi-database**: MySQL, PostgreSQL, and SQLite
|
package/package.json
CHANGED
package/src/Model.js
CHANGED
|
@@ -665,6 +665,147 @@ class Model {
|
|
|
665
665
|
return this.query().with(...relations);
|
|
666
666
|
}
|
|
667
667
|
|
|
668
|
+
// ==================== Convenience Query Methods ====================
|
|
669
|
+
|
|
670
|
+
/**
|
|
671
|
+
* Find the first record matching conditions or create a new one
|
|
672
|
+
* @param {Object} conditions - Where conditions to search
|
|
673
|
+
* @param {Object} [values={}] - Additional attributes for creation
|
|
674
|
+
* @returns {Promise<Model>}
|
|
675
|
+
*/
|
|
676
|
+
static async firstOrCreate(conditions, values = {}) {
|
|
677
|
+
const query = this.query();
|
|
678
|
+
for (const [key, val] of Object.entries(conditions)) {
|
|
679
|
+
query.where(key, val);
|
|
680
|
+
}
|
|
681
|
+
const existing = await query.first();
|
|
682
|
+
if (existing) return existing;
|
|
683
|
+
return this.create({ ...conditions, ...values });
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* Find the first record matching conditions or return a new (unsaved) instance
|
|
688
|
+
* @param {Object} conditions - Where conditions to search
|
|
689
|
+
* @param {Object} [values={}] - Additional attributes for the new instance
|
|
690
|
+
* @returns {Promise<Model>}
|
|
691
|
+
*/
|
|
692
|
+
static async firstOrNew(conditions, values = {}) {
|
|
693
|
+
const query = this.query();
|
|
694
|
+
for (const [key, val] of Object.entries(conditions)) {
|
|
695
|
+
query.where(key, val);
|
|
696
|
+
}
|
|
697
|
+
const existing = await query.first();
|
|
698
|
+
if (existing) return existing;
|
|
699
|
+
const instance = new this({ ...conditions, ...values });
|
|
700
|
+
return instance;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/**
|
|
704
|
+
* Find a record matching conditions and update it, or create a new one
|
|
705
|
+
* @param {Object} conditions - Where conditions to search
|
|
706
|
+
* @param {Object} values - Attributes to update or set on creation
|
|
707
|
+
* @returns {Promise<Model>}
|
|
708
|
+
*/
|
|
709
|
+
static async updateOrCreate(conditions, values = {}) {
|
|
710
|
+
const query = this.query();
|
|
711
|
+
for (const [key, val] of Object.entries(conditions)) {
|
|
712
|
+
query.where(key, val);
|
|
713
|
+
}
|
|
714
|
+
const existing = await query.first();
|
|
715
|
+
if (existing) {
|
|
716
|
+
for (const [key, val] of Object.entries(values)) {
|
|
717
|
+
existing.setAttribute(key, val);
|
|
718
|
+
}
|
|
719
|
+
await existing.save();
|
|
720
|
+
return existing;
|
|
721
|
+
}
|
|
722
|
+
return this.create({ ...conditions, ...values });
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
/**
|
|
726
|
+
* Insert or update multiple records in bulk.
|
|
727
|
+
* @param {Array<Object>} rows - Array of records to upsert
|
|
728
|
+
* @param {string|string[]} uniqueBy - Column(s) that determine uniqueness
|
|
729
|
+
* @param {string[]} [update] - Columns to update on conflict (default: all non-unique columns)
|
|
730
|
+
* @returns {Promise<any>}
|
|
731
|
+
*/
|
|
732
|
+
static async upsert(rows, uniqueBy, update) {
|
|
733
|
+
if (!rows || rows.length === 0) return;
|
|
734
|
+
this.ensureConnection();
|
|
735
|
+
const uniqueCols = Array.isArray(uniqueBy) ? uniqueBy : [uniqueBy];
|
|
736
|
+
|
|
737
|
+
// Determine columns to update on conflict
|
|
738
|
+
const allCols = Object.keys(rows[0]);
|
|
739
|
+
const updateCols = update || allCols.filter(c => !uniqueCols.includes(c));
|
|
740
|
+
|
|
741
|
+
// Build driver-specific upsert SQL
|
|
742
|
+
const table = this.table;
|
|
743
|
+
const columns = allCols;
|
|
744
|
+
const placeholders = rows.map(() => `(${columns.map(() => '?').join(', ')})`).join(', ');
|
|
745
|
+
const values = rows.flatMap(r => columns.map(c => r[c] !== undefined ? r[c] : null));
|
|
746
|
+
|
|
747
|
+
const conn = this.connection;
|
|
748
|
+
const driver = conn.config ? conn.config.driver : 'mysql';
|
|
749
|
+
|
|
750
|
+
let sql;
|
|
751
|
+
if (driver === 'sqlite') {
|
|
752
|
+
const updateSet = updateCols.map(c => `\`${c}\` = excluded.\`${c}\``).join(', ');
|
|
753
|
+
sql = `INSERT INTO \`${table}\` (${columns.map(c => `\`${c}\``).join(', ')}) VALUES ${placeholders} ON CONFLICT (${uniqueCols.map(c => `\`${c}\``).join(', ')}) DO UPDATE SET ${updateSet}`;
|
|
754
|
+
} else if (driver === 'postgres' || driver === 'postgresql') {
|
|
755
|
+
const updateSet = updateCols.map(c => `"${c}" = EXCLUDED."${c}"`).join(', ');
|
|
756
|
+
sql = `INSERT INTO "${table}" (${columns.map(c => `"${c}"`).join(', ')}) VALUES ${placeholders} ON CONFLICT (${uniqueCols.map(c => `"${c}"`).join(', ')}) DO UPDATE SET ${updateSet}`;
|
|
757
|
+
} else {
|
|
758
|
+
// MySQL: INSERT ... ON DUPLICATE KEY UPDATE
|
|
759
|
+
const updateSet = updateCols.map(c => `\`${c}\` = VALUES(\`${c}\`)`).join(', ');
|
|
760
|
+
sql = `INSERT INTO \`${table}\` (${columns.map(c => `\`${c}\``).join(', ')}) VALUES ${placeholders} ON DUPLICATE KEY UPDATE ${updateSet}`;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
return conn.execute(sql, values);
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
// ==================== Observer ====================
|
|
767
|
+
|
|
768
|
+
/**
|
|
769
|
+
* Register an observer class that listens to model events.
|
|
770
|
+
* The observer may define methods: creating, created, updating, updated,
|
|
771
|
+
* saving, saved, deleting, deleted, restoring, restored.
|
|
772
|
+
* @param {Object|Function} observer - Observer instance or class
|
|
773
|
+
*/
|
|
774
|
+
static observe(observer) {
|
|
775
|
+
const instance = typeof observer === 'function' ? new observer() : observer;
|
|
776
|
+
const events = [
|
|
777
|
+
'creating', 'created', 'updating', 'updated',
|
|
778
|
+
'saving', 'saved', 'deleting', 'deleted',
|
|
779
|
+
'restoring', 'restored'
|
|
780
|
+
];
|
|
781
|
+
for (const event of events) {
|
|
782
|
+
if (typeof instance[event] === 'function') {
|
|
783
|
+
this.on(event, (model) => instance[event](model));
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// ==================== Cursor / Stream ====================
|
|
789
|
+
|
|
790
|
+
/**
|
|
791
|
+
* Lazily iterate over all matching records using an async generator.
|
|
792
|
+
* Yields one model instance at a time, consuming minimal memory.
|
|
793
|
+
* @param {number} [chunkSize=100] - Number of records per internal query
|
|
794
|
+
* @returns {AsyncGenerator<Model>}
|
|
795
|
+
*/
|
|
796
|
+
static async *cursor(chunkSize = 100) {
|
|
797
|
+
let offset = 0;
|
|
798
|
+
while (true) {
|
|
799
|
+
const results = await this.query().limit(chunkSize).offset(offset).get();
|
|
800
|
+
if (results.length === 0) break;
|
|
801
|
+
for (const model of results) {
|
|
802
|
+
yield model;
|
|
803
|
+
}
|
|
804
|
+
if (results.length < chunkSize) break;
|
|
805
|
+
offset += chunkSize;
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
668
809
|
/**
|
|
669
810
|
* Include hidden attributes in query results
|
|
670
811
|
* @returns {QueryBuilder}
|
|
@@ -704,18 +845,24 @@ class Model {
|
|
|
704
845
|
}
|
|
705
846
|
|
|
706
847
|
/**
|
|
707
|
-
* Set an attribute
|
|
848
|
+
* Set an attribute (runs mutator if defined)
|
|
708
849
|
* @param {string} key
|
|
709
850
|
* @param {any} value
|
|
710
851
|
* @returns {this}
|
|
711
852
|
*/
|
|
712
853
|
setAttribute(key, value) {
|
|
854
|
+
// Check for mutator: set{Key}Attribute
|
|
855
|
+
const mutator = `set${key.charAt(0).toUpperCase()}${key.slice(1).replace(/_([a-z])/g, (_, c) => c.toUpperCase())}Attribute`;
|
|
856
|
+
if (typeof this[mutator] === 'function') {
|
|
857
|
+
this[mutator](value);
|
|
858
|
+
return this;
|
|
859
|
+
}
|
|
713
860
|
this.attributes[key] = this.castAttribute(key, value);
|
|
714
861
|
return this;
|
|
715
862
|
}
|
|
716
863
|
|
|
717
864
|
/**
|
|
718
|
-
* Get an attribute
|
|
865
|
+
* Get an attribute (runs accessor if defined)
|
|
719
866
|
* @param {string} key
|
|
720
867
|
* @returns {any}
|
|
721
868
|
*/
|
|
@@ -723,6 +870,11 @@ class Model {
|
|
|
723
870
|
if (this.relations[key]) {
|
|
724
871
|
return this.relations[key];
|
|
725
872
|
}
|
|
873
|
+
// Check for accessor: get{Key}Attribute
|
|
874
|
+
const accessor = `get${key.charAt(0).toUpperCase()}${key.slice(1).replace(/_([a-z])/g, (_, c) => c.toUpperCase())}Attribute`;
|
|
875
|
+
if (typeof this[accessor] === 'function') {
|
|
876
|
+
return this[accessor](this.attributes[key]);
|
|
877
|
+
}
|
|
726
878
|
return this.castAttribute(key, this.attributes[key]);
|
|
727
879
|
}
|
|
728
880
|
|
package/src/QueryBuilder.js
CHANGED
|
@@ -623,6 +623,88 @@ class QueryBuilder {
|
|
|
623
623
|
return result;
|
|
624
624
|
}
|
|
625
625
|
|
|
626
|
+
/**
|
|
627
|
+
* Get the first record matching current wheres or create a new one
|
|
628
|
+
* @param {Object} [values={}] - Additional attributes to merge on creation
|
|
629
|
+
* @returns {Promise<Model>}
|
|
630
|
+
*/
|
|
631
|
+
async firstOrCreate(values = {}) {
|
|
632
|
+
const existing = await this.first();
|
|
633
|
+
if (existing) return existing;
|
|
634
|
+
// Build conditions from current wheres
|
|
635
|
+
const conditions = {};
|
|
636
|
+
for (const w of this.wheres) {
|
|
637
|
+
if (w.type === 'basic' && w.operator === '=') {
|
|
638
|
+
conditions[w.column] = w.value;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
const instance = new this.model({ ...conditions, ...values });
|
|
642
|
+
return instance.save();
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/**
|
|
646
|
+
* Get the first record matching current wheres or return a new (unsaved) instance
|
|
647
|
+
* @param {Object} [values={}] - Additional attributes for the instance
|
|
648
|
+
* @returns {Promise<Model>}
|
|
649
|
+
*/
|
|
650
|
+
async firstOrNew(values = {}) {
|
|
651
|
+
const existing = await this.first();
|
|
652
|
+
if (existing) return existing;
|
|
653
|
+
const conditions = {};
|
|
654
|
+
for (const w of this.wheres) {
|
|
655
|
+
if (w.type === 'basic' && w.operator === '=') {
|
|
656
|
+
conditions[w.column] = w.value;
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
return new this.model({ ...conditions, ...values });
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* Find a record matching current wheres and update it, or create a new one
|
|
664
|
+
* @param {Object} values - Attributes to update or set on creation
|
|
665
|
+
* @returns {Promise<Model>}
|
|
666
|
+
*/
|
|
667
|
+
async updateOrCreate(values = {}) {
|
|
668
|
+
const existing = await this.first();
|
|
669
|
+
if (existing) {
|
|
670
|
+
for (const [key, val] of Object.entries(values)) {
|
|
671
|
+
existing.setAttribute(key, val);
|
|
672
|
+
}
|
|
673
|
+
await existing.save();
|
|
674
|
+
return existing;
|
|
675
|
+
}
|
|
676
|
+
const conditions = {};
|
|
677
|
+
for (const w of this.wheres) {
|
|
678
|
+
if (w.type === 'basic' && w.operator === '=') {
|
|
679
|
+
conditions[w.column] = w.value;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
const instance = new this.model({ ...conditions, ...values });
|
|
683
|
+
return instance.save();
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* Lazily iterate over matching records using an async generator.
|
|
688
|
+
* Yields one model instance at a time, consuming minimal memory.
|
|
689
|
+
* @param {number} [chunkSize=100] - Number of records per internal query
|
|
690
|
+
* @returns {AsyncGenerator<Model>}
|
|
691
|
+
*/
|
|
692
|
+
async *cursor(chunkSize = 100) {
|
|
693
|
+
let offset = 0;
|
|
694
|
+
while (true) {
|
|
695
|
+
const cloned = this.clone();
|
|
696
|
+
cloned.limitValue = chunkSize;
|
|
697
|
+
cloned.offsetValue = offset;
|
|
698
|
+
const results = await cloned.get();
|
|
699
|
+
if (results.length === 0) break;
|
|
700
|
+
for (const model of results) {
|
|
701
|
+
yield model;
|
|
702
|
+
}
|
|
703
|
+
if (results.length < chunkSize) break;
|
|
704
|
+
offset += chunkSize;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
626
708
|
/**
|
|
627
709
|
* Paginate the results
|
|
628
710
|
* @param {number} page
|
package/types/index.d.ts
CHANGED
|
@@ -153,6 +153,20 @@ declare module 'outlet-orm' {
|
|
|
153
153
|
to: number;
|
|
154
154
|
}
|
|
155
155
|
|
|
156
|
+
/** Observer interface for model lifecycle events */
|
|
157
|
+
export interface ModelObserver<T extends Model = Model> {
|
|
158
|
+
creating?(model: T): boolean | void | Promise<boolean | void>;
|
|
159
|
+
created?(model: T): void | Promise<void>;
|
|
160
|
+
updating?(model: T): boolean | void | Promise<boolean | void>;
|
|
161
|
+
updated?(model: T): void | Promise<void>;
|
|
162
|
+
saving?(model: T): boolean | void | Promise<boolean | void>;
|
|
163
|
+
saved?(model: T): void | Promise<void>;
|
|
164
|
+
deleting?(model: T): boolean | void | Promise<boolean | void>;
|
|
165
|
+
deleted?(model: T): void | Promise<void>;
|
|
166
|
+
restoring?(model: T): boolean | void | Promise<boolean | void>;
|
|
167
|
+
restored?(model: T): void | Promise<void>;
|
|
168
|
+
}
|
|
169
|
+
|
|
156
170
|
export class QueryBuilder<T extends Model> {
|
|
157
171
|
constructor(model: typeof Model);
|
|
158
172
|
|
|
@@ -204,6 +218,12 @@ declare module 'outlet-orm' {
|
|
|
204
218
|
get(): Promise<T[]>;
|
|
205
219
|
first(): Promise<T | null>;
|
|
206
220
|
firstOrFail(): Promise<T>;
|
|
221
|
+
/** Get the first record matching current wheres or create a new one */
|
|
222
|
+
firstOrCreate(values?: Record<string, any>): Promise<T>;
|
|
223
|
+
/** Get the first record matching current wheres or return a new unsaved instance */
|
|
224
|
+
firstOrNew(values?: Record<string, any>): Promise<T>;
|
|
225
|
+
/** Find a record matching current wheres and update it, or create a new one */
|
|
226
|
+
updateOrCreate(values?: Record<string, any>): Promise<T>;
|
|
207
227
|
paginate(page?: number, perPage?: number): Promise<PaginationResult<T>>;
|
|
208
228
|
count(): Promise<number>;
|
|
209
229
|
exists(): Promise<boolean>;
|
|
@@ -214,6 +234,8 @@ declare module 'outlet-orm' {
|
|
|
214
234
|
delete(): Promise<any>;
|
|
215
235
|
increment(column: string, amount?: number): Promise<any>;
|
|
216
236
|
decrement(column: string, amount?: number): Promise<any>;
|
|
237
|
+
/** Lazily iterate over matching records using an async generator */
|
|
238
|
+
cursor(chunkSize?: number): AsyncGenerator<T, void, unknown>;
|
|
217
239
|
|
|
218
240
|
clone(): QueryBuilder<T>;
|
|
219
241
|
}
|
|
@@ -344,6 +366,25 @@ declare module 'outlet-orm' {
|
|
|
344
366
|
static whereNull<T extends Model>(this: new () => T, column: string): QueryBuilder<T>;
|
|
345
367
|
static whereNotNull<T extends Model>(this: new () => T, column: string): QueryBuilder<T>;
|
|
346
368
|
static count(): Promise<number>;
|
|
369
|
+
|
|
370
|
+
// Convenience query methods
|
|
371
|
+
/** Find the first record matching conditions or create a new one */
|
|
372
|
+
static firstOrCreate<T extends Model>(this: new () => T, conditions: Record<string, any>, values?: Record<string, any>): Promise<T>;
|
|
373
|
+
/** Find the first record matching conditions or return a new unsaved instance */
|
|
374
|
+
static firstOrNew<T extends Model>(this: new () => T, conditions: Record<string, any>, values?: Record<string, any>): Promise<T>;
|
|
375
|
+
/** Find a record matching conditions and update it, or create a new one */
|
|
376
|
+
static updateOrCreate<T extends Model>(this: new () => T, conditions: Record<string, any>, values?: Record<string, any>): Promise<T>;
|
|
377
|
+
/** Insert or update multiple records in bulk (ON CONFLICT / ON DUPLICATE KEY) */
|
|
378
|
+
static upsert(rows: Record<string, any>[], uniqueBy: string | string[], update?: string[]): Promise<any>;
|
|
379
|
+
|
|
380
|
+
// Observer
|
|
381
|
+
/** Register an observer class that listens to model lifecycle events */
|
|
382
|
+
static observe(observer: ModelObserver | (new () => ModelObserver)): void;
|
|
383
|
+
|
|
384
|
+
// Cursor / Stream
|
|
385
|
+
/** Lazily iterate over all matching records using an async generator */
|
|
386
|
+
static cursor<T extends Model>(this: new () => T, chunkSize?: number): AsyncGenerator<T, void, unknown>;
|
|
387
|
+
|
|
347
388
|
static with<T extends Model>(this: new () => T, ...relations: string[] | [Record<string, (qb: QueryBuilder<any>) => void> | string[]]): QueryBuilder<T>;
|
|
348
389
|
/** Include hidden attributes in query results */
|
|
349
390
|
static withHidden<T extends Model>(this: new () => T): QueryBuilder<T>;
|