UNPKG

32.7 kBTypeScriptView Raw
1/// <reference types="@adonisjs/profiler/build/adonis-typings/profiler" />
2declare module '@ioc:Adonis/Lucid/Orm' {
3 import { DateTime } from 'luxon';
4 import { Hooks } from '@poppinss/hooks';
5 import { ProfilerContract, ProfilerRowContract } from '@ioc:Adonis/Core/Profiler';
6 import { Update, Counter, OneOrMany, Aggregate, Returning, DialectContract, ChainableContract, QueryClientContract, SimplePaginatorMetaKeys, SimplePaginatorContract, TransactionClientContract, ExcutableQueryBuilderContract } from '@ioc:Adonis/Lucid/Database';
7 /**
8 * ------------------------------------------------------
9 * Helpers
10 * ------------------------------------------------------
11 */
12 /**
13 * Same as [[Parameters]] but omits the first parameter
14 */
15 type OmitFirst<T extends (...args: any) => any> = T extends (x: any, ...args: infer P) => any ? P : never;
16 /**
17 * Same as [[Pick]] but picks by value and not the key
18 */
19 type PickProperties<T, P> = Pick<T, {
20 [K in keyof T]: T[K] extends P ? K : never;
21 }[keyof T]>;
22 /**
23 * Decorator function
24 */
25 type DecoratorFn = (target: any, property: any) => void;
26 /**
27 * Typed decorator
28 */
29 type TypedDecorator<PropType> = <TKey extends string, TTarget extends {
30 [K in TKey]: PropType;
31 }>(target: TTarget, property: TKey) => void;
32 /**
33 * Typed decorator that also represents an optional property
34 */
35 type OptionalTypedDecorator<PropType> = <TKey extends string, TTarget extends {
36 [K in TKey]?: PropType;
37 }>(target: TTarget, property: TKey) => void;
38 /**
39 * A complex type that filters out functions and relationships from the
40 * model attributes and consider all other properties as database
41 * columns. Alternatively, the user can self define a `$columns`
42 * property.
43 */
44 type ModelAttributes<Model extends LucidRow> = Model['$columns'] extends undefined ? {
45 [Filtered in {
46 [P in keyof Model]: P extends keyof LucidRow | 'serializeExtras' ? never : Model[P] extends Function | ModelRelationTypes ? never : P;
47 }[keyof Model]]: Model[Filtered];
48 } : Model['$columns'];
49 /**
50 * Extract the query scopes of a model
51 */
52 type ExtractScopes<Model> = {
53 [Scope in keyof PickProperties<Model, QueryScope<QueryScopeCallback>>]: (...args: any[]) => ExtractScopes<Model>;
54 };
55 /**
56 * Reusable interface to define an object.
57 */
58 interface ModelObject {
59 [key: string]: any;
60 }
61 /**
62 * Shape of cache node to keep getters optimized
63 */
64 type CacheNode = {
65 original: any;
66 resolved: any;
67 getter: (value: any) => any;
68 };
69 /**
70 * Shape for cherry picking fields
71 */
72 type CherryPickFields = string[] | {
73 pick?: string[];
74 omit?: string[];
75 };
76 /**
77 * Shape for cherry picking fields on nested relationships
78 */
79 type CherryPick = {
80 fields?: CherryPickFields;
81 relations?: {
82 [relation: string]: CherryPick;
83 };
84 };
85 /**
86 * List of events for which a model will trigger hooks
87 */
88 type EventsList = 'save' | 'create' | 'update' | 'delete' | 'fetch' | 'find' | 'paginate';
89 type HooksHandler<Data, Event extends EventsList> = ((data: Data, event: Event) => Promise<void> | void) | string;
90 /**
91 * ------------------------------------------------------
92 * Query Scope
93 * ------------------------------------------------------
94 */
95 /**
96 * Generic query scope callback
97 */
98 type QueryScopeCallback<Model extends LucidModel = LucidModel> = (query: ModelQueryBuilderContract<Model>, ...args: any[]) => void;
99 /**
100 * Query scope
101 */
102 type QueryScope<Scope extends QueryScopeCallback> = Scope & {
103 readonly isQueryScope: true;
104 };
105 /**
106 * A function to mark a method as query scope
107 */
108 type ScopeFn = <Model extends LucidModel, Scope extends QueryScopeCallback = QueryScopeCallback<Model>>(callback: Scope) => QueryScope<Scope>;
109 /**
110 * ------------------------------------------------------
111 * Decorators and Options
112 * ------------------------------------------------------
113 */
114 /**
115 * Options for defining a column
116 */
117 type ColumnOptions = {
118 columnName: string;
119 serializeAs: string | null;
120 isPrimary: boolean;
121 meta?: any;
122 /**
123 * Invoked before serializing process happens
124 */
125 serialize?: (value: any, attribute: string, model: LucidRow) => any;
126 /**
127 * Invoked before create or update happens
128 */
129 prepare?: (value: any, attribute: string, model: LucidRow) => any;
130 /**
131 * Invoked when row is fetched from the database
132 */
133 consume?: (value: any, attribute: string, model: LucidRow) => any;
134 };
135 /**
136 * Shape of column options after they have set on the model
137 */
138 type ModelColumnOptions = ColumnOptions & {
139 hasGetter: boolean;
140 hasSetter: boolean;
141 };
142 /**
143 * Represents a computed property on the model
144 */
145 type ComputedOptions = {
146 serializeAs: string | null;
147 meta?: any;
148 };
149 /**
150 * Options accepted by the Model.$addRelation method
151 */
152 type ModelRelationOptions = RelationOptions<ModelRelations> | ManyToManyRelationOptions<ModelRelations> | ThroughRelationOptions<ModelRelations>;
153 /**
154 * Signature for column decorator function
155 */
156 type ColumnDecorator = (options?: Partial<ColumnOptions>) => DecoratorFn;
157 /**
158 * Signature for computed decorator function
159 */
160 type ComputedDecorator = (options?: Partial<ComputedOptions>) => DecoratorFn;
161 /**
162 * Decorator for defining date columns
163 */
164 type DateColumnDecorator = (options?: Partial<ColumnOptions & {
165 autoCreate: boolean;
166 autoUpdate: boolean;
167 }>) => OptionalTypedDecorator<DateTime | null>;
168 /**
169 * Decorator for defining date time columns. It is same as
170 * date column as of now
171 */
172 type DateTimeColumnDecorator = DateColumnDecorator;
173 /**
174 * Decorator for defining hooks. The generics enforces that
175 * decorator is used on static properties only
176 */
177 type HooksDecorator = () => <Model extends LucidModel>(target: Model, property: string) => void;
178 /**
179 * ------------------------------------------------------
180 * Model Options
181 * ------------------------------------------------------
182 */
183 /**
184 * Model options to be used when making queries
185 */
186 type ModelOptions = {
187 connection?: string;
188 profiler?: ProfilerContract | ProfilerRowContract;
189 };
190 /**
191 * Adapter also accepts a client directly
192 */
193 type ModelAdapterOptions = ModelOptions & {
194 client?: QueryClientContract;
195 };
196 /**
197 * Options used by the method that internally invokes
198 * the merge method.
199 ] */
200 type ModelAssignOptions = ModelAdapterOptions & {
201 allowExtraProperties?: boolean;
202 };
203 /**
204 * Preload function on a model instance
205 */
206 interface LucidRowPreload<Model extends LucidRow> extends Preload<Model, Promise<void>> {
207 (callback: (preloader: PreloaderContract<Model>) => void): Promise<void>;
208 }
209 interface LucidRowAggregate<Model extends LucidRow> extends Preload<Model, Promise<void>> {
210 (callback: (preloader: PreloaderContract<Model>) => void): Promise<void>;
211 }
212 /**
213 * An extension of the simple paginator with support for serializing models
214 */
215 interface ModelPaginatorContract<Result extends LucidRow> extends Omit<SimplePaginatorContract<Result>, 'toJSON'> {
216 serialize(cherryPick?: CherryPick): {
217 meta: any;
218 data: ModelObject[];
219 };
220 toJSON(): {
221 meta: any;
222 data: ModelObject[];
223 };
224 }
225 /**
226 * Lazy load aggregates for a given model instance
227 */
228 interface LazyLoadAggregatesContract<Model extends LucidRow> extends Promise<void> {
229 loadAggregate: WithAggregate<Model, this>;
230 loadCount: WithCount<Model, this>;
231 exec(): Promise<void>;
232 }
233 /**
234 * ------------------------------------------------------
235 * Model Query Builder
236 * ------------------------------------------------------
237 */
238 /**
239 * Model query builder will have extras methods on top of the Database query builder
240 */
241 interface ModelQueryBuilderContract<Model extends LucidModel, Result = InstanceType<Model>> extends ChainableContract, ExcutableQueryBuilderContract<Result[]> {
242 model: Model;
243 returning: Returning<this>;
244 /**
245 * Define a callback to transform a row
246 */
247 rowTransformer(callback: (row: LucidRow) => void): this;
248 /**
249 * Define a custom preloader for the current query
250 */
251 usePreloader(preloader: PreloaderContract<LucidRow>): this;
252 /**
253 * Whether or not the query is a child query generated for `.where`
254 * callbacks
255 */
256 isChildQuery: boolean;
257 /**
258 * Alias for the @withScopes method
259 */
260 apply<Scopes extends ExtractScopes<Model>>(callback: (scopes: Scopes) => void): this;
261 /**
262 * Apply model query scopes on the query bulder
263 */
264 withScopes<Scopes extends ExtractScopes<Model>>(callback: (scopes: Scopes) => void): this;
265 /**
266 * A copy of client options.
267 */
268 readonly clientOptions: ModelAdapterOptions;
269 /**
270 * Reference to query client used for making queries
271 */
272 client: QueryClientContract;
273 /**
274 * Clone query builder instance
275 */
276 clone<ClonedResult = Result>(): ModelQueryBuilderContract<Model, ClonedResult>;
277 /**
278 * A custom set of sideloaded properties defined on the query
279 * builder, this will be passed to the model instance created
280 * by the query builder
281 */
282 sideload(value: ModelObject): this;
283 /**
284 * Execute and get first result
285 */
286 first(): Promise<Result | null>;
287 /**
288 * Return the first matching row or fail
289 */
290 firstOrFail(): Promise<Result>;
291 /**
292 * Perform delete operation
293 */
294 del(returning?: OneOrMany<string>): ModelQueryBuilderContract<Model, any>;
295 delete(returning?: OneOrMany<string>): ModelQueryBuilderContract<Model, any>;
296 /**
297 * A shorthand to define limit and offset based upon the
298 * current page
299 */
300 forPage(page: number, perPage?: number): this;
301 /**
302 * Execute query with pagination
303 */
304 paginate(page: number, perPage?: number): Promise<Result extends LucidRow ? ModelPaginatorContract<Result> : SimplePaginatorContract<Result>>;
305 /**
306 * Mutations (update and increment can be one query aswell)
307 */
308 update: Update<ModelQueryBuilderContract<Model, any>>;
309 increment: Counter<ModelQueryBuilderContract<Model, any>>;
310 decrement: Counter<ModelQueryBuilderContract<Model, any>>;
311 /**
312 * Fetch relationship count
313 */
314 withCount: WithCount<InstanceType<Model>, this>;
315 /**
316 * Fetch aggregate value for a given relationship
317 */
318 withAggregate: WithAggregate<InstanceType<Model>, this>;
319 /**
320 * Add where constraint using the relationship
321 */
322 has: Has<InstanceType<Model>, this>;
323 orHas: Has<InstanceType<Model>, this>;
324 andHas: Has<InstanceType<Model>, this>;
325 doesntHave: Has<InstanceType<Model>, this>;
326 orDoesntHave: Has<InstanceType<Model>, this>;
327 andDoesntHave: Has<InstanceType<Model>, this>;
328 /**
329 * Add where constraint using the relationship with a custom callback
330 */
331 whereHas: WhereHas<InstanceType<Model>, this>;
332 orWhereHas: WhereHas<InstanceType<Model>, this>;
333 andWhereHas: WhereHas<InstanceType<Model>, this>;
334 whereDoesntHave: WhereHas<InstanceType<Model>, this>;
335 orWhereDoesntHave: WhereHas<InstanceType<Model>, this>;
336 andWhereDoesntHave: WhereHas<InstanceType<Model>, this>;
337 /**
338 * Define relationships to be preloaded
339 */
340 preload: Preload<InstanceType<Model>, this>;
341 /**
342 * Aggregates
343 */
344 count: Aggregate<this>;
345 countDistinct: Aggregate<this>;
346 min: Aggregate<this>;
347 max: Aggregate<this>;
348 sum: Aggregate<this>;
349 sumDistinct: Aggregate<this>;
350 avg: Aggregate<this>;
351 avgDistinct: Aggregate<this>;
352 /**
353 * Executes the callback when dialect matches one of the mentioned
354 * dialects
355 */
356 ifDialect(dialect: DialectContract['name'] | DialectContract['name'][], matchCallback: (query: this) => any, noMatchCallback?: (query: this) => any): this;
357 /**
358 * Executes the callback when dialect matches doesn't all the mentioned
359 * dialects
360 */
361 unlessDialect(dialect: DialectContract['name'] | DialectContract['name'][], matchCallback: (query: this) => any, noMatchCallback?: (query: this) => any): this;
362 /**
363 * Get rows back as a plain javascript object and not an array
364 * of model instances
365 */
366 pojo<T>(): ModelQueryBuilderContract<Model, T>;
367 }
368 /**
369 * Shape of model keys
370 */
371 interface ModelKeysContract {
372 add(key: string, value: string): void;
373 get(key: string, defaultValue: string): string;
374 get(key: string, defaultValue?: string): string | undefined;
375 resolve(key: string): string;
376 all(): ModelObject;
377 }
378 /**
379 * ------------------------------------------------------
380 * Shape of Model instance
381 * ------------------------------------------------------
382 */
383 /**
384 * Shape of the model instance. We prefix the properties with a `$` to
385 * differentiate between special properties provided by the base
386 * model but with exception to `save`, `delete`, `fill`, `merge`
387 * and `toJSON`.
388 *
389 * @note: Since the interface name appears next to the inherited model
390 * methods, we have to choose a succinct name
391 */
392 interface LucidRow {
393 $attributes: ModelObject;
394 $extras: ModelObject;
395 $original: ModelObject;
396 $preloaded: {
397 [relation: string]: LucidRow | LucidRow[];
398 };
399 /**
400 * Columns is a property to get type information for model
401 * attributes. This must be declared by the end user
402 */
403 $columns: undefined;
404 $sideloaded: ModelObject;
405 $primaryKeyValue?: number | string;
406 $isPersisted: boolean;
407 $isNew: boolean;
408 $isLocal: boolean;
409 $dirty: ModelObject;
410 $isDirty: boolean;
411 $isDeleted: boolean;
412 $options?: ModelOptions;
413 $trx?: TransactionClientContract;
414 $setOptionsAndTrx(options?: ModelAdapterOptions): void;
415 useTransaction(trx: TransactionClientContract): this;
416 useConnection(connection: string): this;
417 /**
418 * Gives an option to the end user to define constraints for update, insert
419 * and delete queries. Since the query builder for these queries aren't
420 * exposed to the end user, this method opens up the API to build
421 * custom queries.
422 */
423 $getQueryFor(action: 'insert', client: QueryClientContract): ReturnType<QueryClientContract['insertQuery']>;
424 $getQueryFor(action: 'update' | 'delete' | 'refresh', client: QueryClientContract): ModelQueryBuilderContract<LucidModel>;
425 /**
426 * Read/write attributes. Following methods are intentionally loosely typed,
427 * so that one can bypass the public facing API and type checking for
428 * advanced use cases
429 */
430 $setAttribute(key: string, value: any): void;
431 $getAttribute(key: string): any;
432 $getAttributeFromCache(key: string, callback: CacheNode['getter']): any;
433 /**
434 * Read/write realtionships. Following methods are intentionally loosely typed,
435 * so that one can bypass the public facing API and type checking for
436 * advanced use cases
437 */
438 $hasRelated(key: string): boolean;
439 $setRelated(key: string, result: OneOrMany<LucidRow> | null): void;
440 $pushRelated(key: string, result: OneOrMany<LucidRow> | null): void;
441 $getRelated(key: string, defaultValue?: any): OneOrMany<LucidRow> | undefined | null;
442 /**
443 * Consume the adapter result and hydrate the model
444 */
445 $consumeAdapterResult(adapterResult: ModelObject, sideloadAttributes?: ModelObject): void;
446 $hydrateOriginals(): void;
447 fill(value: Partial<ModelAttributes<this>>, allowExtraProperties?: boolean): this;
448 merge(value: Partial<ModelAttributes<this>>, allowExtraProperties?: boolean): this;
449 /**
450 * Actions to perform on the instance
451 */
452 save(): Promise<this>;
453 delete(): Promise<void>;
454 refresh(): Promise<this>;
455 /**
456 * Load relationships onto the instance
457 */
458 load: LucidRowPreload<this>;
459 /**
460 * Alias for "load"
461 * @deprecated
462 */
463 preload: LucidRowPreload<this>;
464 /**
465 * Load aggregates
466 */
467 loadAggregate: <Self extends this, Name extends ExtractModelRelations<Self>, RelatedBuilder = Self[Name] extends ModelRelations ? Self[Name]['subQuery'] : never>(name: Name, callback: (builder: RelatedBuilder) => void) => LazyLoadAggregatesContract<Self>;
468 /**
469 * Load count
470 */
471 loadCount: <Self extends this, Name extends ExtractModelRelations<Self>, RelatedBuilder = Self[Name] extends ModelRelations ? Self[Name]['subQuery'] : never>(name: Name, callback?: (builder: RelatedBuilder) => void) => LazyLoadAggregatesContract<Self>;
472 /**
473 * Serialize attributes to a plain object
474 */
475 serializeAttributes(fields?: CherryPickFields, raw?: boolean): ModelObject;
476 /**
477 * Serialize computed properties to a plain object
478 */
479 serializeComputed(fields?: CherryPickFields): ModelObject;
480 /**
481 * Serialize relationships to key-value pair of model instances and
482 * their serializeAs keys
483 */
484 serializeRelations(fields: undefined, raw: true): {
485 [key: string]: LucidRow | LucidRow[];
486 };
487 /**
488 * Serialize relationships to key-value pair of plain nested objects
489 */
490 serializeRelations(cherryPick: CherryPick['relations'] | undefined, raw: false | undefined): ModelObject;
491 serializeRelations(cherryPick?: CherryPick['relations'], raw?: boolean): ModelObject;
492 /**
493 * Serialize model to a plain object
494 */
495 serialize(cherryPick?: CherryPick): ModelObject;
496 /**
497 * Converts model to an object. It just returns the properties
498 * of the model, along with preloaded relationships
499 */
500 toObject(): ModelObject;
501 /**
502 * Serialize everything
503 */
504 toJSON(): ModelObject;
505 /**
506 * Returns related model for a given relationship
507 */
508 related<Name extends ExtractModelRelations<this>>(relation: Name): this[Name] extends ModelRelations ? this[Name]['client'] : never;
509 }
510 /**
511 * ------------------------------------------------------
512 * Shape of Model constructor
513 * ------------------------------------------------------
514 */
515 /**
516 * Shape of the model static properties. The `$` prefix is to denote
517 * special properties from the base model.
518 *
519 * @note: Since the interface name appears next to the inherited model
520 * methods, we have to choose a succinct name
521 */
522 interface LucidModel {
523 /**
524 * Whether or not model has been booted. After this model configurations
525 * are ignored
526 */
527 readonly booted: boolean;
528 /**
529 * A map of defined columns
530 */
531 $columnsDefinitions: Map<string, ModelColumnOptions>;
532 /**
533 * A map of defined relationships
534 */
535 $relationsDefinitions: Map<string, RelationshipsContract>;
536 /**
537 * A map of computed properties
538 */
539 $computedDefinitions: Map<string, ComputedOptions>;
540 /**
541 * The primary key for finding unique referencing to a
542 * model
543 */
544 primaryKey: string;
545 /**
546 * Custom database connection to use
547 */
548 connection?: string;
549 /**
550 * Naming strategy to use
551 */
552 namingStrategy: NamingStrategyContract;
553 /**
554 * Database table to use
555 */
556 table: string;
557 /**
558 * Self assign the primary instead of relying on the database to
559 * return it back
560 */
561 selfAssignPrimaryKey: boolean;
562 /**
563 * Adapter to work as a bridge between query builder and the model
564 */
565 $adapter: AdapterContract;
566 /**
567 * Reference to hooks
568 */
569 $hooks: Hooks;
570 /**
571 * A copy of internal keys mapping. One should be able to resolve between
572 * all key versions
573 */
574 $keys: {
575 attributesToColumns: ModelKeysContract;
576 attributesToSerialized: ModelKeysContract;
577 columnsToAttributes: ModelKeysContract;
578 columnsToSerialized: ModelKeysContract;
579 serializedToColumns: ModelKeysContract;
580 serializedToAttributes: ModelKeysContract;
581 };
582 /**
583 * Creating model from adapter results
584 */
585 $createFromAdapterResult<T extends LucidModel>(this: T, result?: ModelObject, sideloadAttributes?: ModelObject, options?: ModelAdapterOptions): null | InstanceType<T>;
586 /**
587 * Creating multiple model instances from an array of adapter
588 * result
589 */
590 $createMultipleFromAdapterResult<T extends LucidModel>(this: T, results: ModelObject[], sideloadAttributes?: ModelObject, options?: ModelAdapterOptions): InstanceType<T>[];
591 /**
592 * Managing columns
593 */
594 $addColumn(name: string, options: Partial<ColumnOptions>): ColumnOptions;
595 $hasColumn(name: string): boolean;
596 $getColumn(name: string): ModelColumnOptions | undefined;
597 /**
598 * Managing computed columns
599 */
600 $addComputed(name: string, options: Partial<ComputedOptions>): ComputedOptions;
601 $hasComputed(name: string): boolean;
602 $getComputed(name: string): ComputedOptions | undefined;
603 /**
604 * Managing relationships
605 */
606 $addRelation(name: string, type: ModelRelationTypes['__opaque_type'], relatedModel: () => LucidModel, options: ModelRelationOptions): void;
607 /**
608 * Find if a relationship exists
609 */
610 $hasRelation(name: string): boolean;
611 /**
612 * Get relationship declaration
613 */
614 $getRelation<Model extends LucidModel, Name extends ExtractModelRelations<InstanceType<Model>>>(this: Model, name: Name): InstanceType<Model>[Name] extends ModelRelations ? InstanceType<Model>[Name]['client']['relation'] : RelationshipsContract;
615 $getRelation<Model extends LucidModel>(this: Model, name: string): RelationshipsContract;
616 /**
617 * Define a static property on the model using the inherit or
618 * define strategy.
619 *
620 * Inherit strategy will clone the property from the parent model
621 * and will set it on the current model
622 */
623 $defineProperty<Model extends LucidModel, Prop extends keyof Model>(this: Model, propertyName: Prop, defaultValue: Model[Prop], strategy: 'inherit' | 'define' | ((value: Model[Prop]) => Model[Prop])): void;
624 /**
625 * Boot model
626 */
627 boot(): void;
628 /**
629 * Register a before hook
630 */
631 before<Model extends LucidModel, Event extends 'find' | 'fetch'>(this: Model, event: Event, handler: HooksHandler<ModelQueryBuilderContract<Model>, Event>): void;
632 before<Model extends LucidModel>(this: Model, event: 'paginate', handler: HooksHandler<[
633 ModelQueryBuilderContract<Model>,
634 ModelQueryBuilderContract<Model>
635 ], 'paginate'>): void;
636 before<Model extends LucidModel, Event extends EventsList>(this: Model, event: Event, handler: HooksHandler<InstanceType<Model>, Event>): void;
637 /**
638 * Register an after hook
639 */
640 after<Model extends LucidModel>(this: Model, event: 'fetch', handler: HooksHandler<InstanceType<Model>[], 'fetch'>): void;
641 after<Model extends LucidModel>(this: Model, event: 'paginate', handler: HooksHandler<ModelPaginatorContract<InstanceType<Model>>, 'paginate'>): void;
642 after<Model extends LucidModel, Event extends EventsList>(this: Model, event: Event, handler: HooksHandler<InstanceType<Model>, Event>): void;
643 /**
644 * Create model and return its instance back
645 */
646 create<T extends LucidModel>(this: T, values: Partial<ModelAttributes<InstanceType<T>>>, options?: ModelAssignOptions): Promise<InstanceType<T>>;
647 /**
648 * Create many of model instances
649 */
650 createMany<T extends LucidModel>(this: T, values: Partial<ModelAttributes<InstanceType<T>>>[], options?: ModelAssignOptions): Promise<InstanceType<T>[]>;
651 /**
652 * Find one using the primary key
653 */
654 find<T extends LucidModel>(this: T, value: any, options?: ModelAdapterOptions): Promise<null | InstanceType<T>>;
655 /**
656 * Find one using the primary key or fail
657 */
658 findOrFail<T extends LucidModel>(this: T, value: any, options?: ModelAdapterOptions): Promise<InstanceType<T>>;
659 /**
660 * Find one using a key-value pair
661 */
662 findBy<T extends LucidModel>(this: T, key: string, value: any, options?: ModelAdapterOptions): Promise<null | InstanceType<T>>;
663 /**
664 * Find one using a key-value pair or fail
665 */
666 findByOrFail<T extends LucidModel>(this: T, key: string, value: any, options?: ModelAdapterOptions): Promise<InstanceType<T>>;
667 /**
668 * Same as `query().first()`
669 */
670 first<T extends LucidModel>(this: T, options?: ModelAdapterOptions): Promise<null | InstanceType<T>>;
671 /**
672 * Same as `query().firstOrFail()`
673 */
674 firstOrFail<T extends LucidModel>(this: T, options?: ModelAdapterOptions): Promise<InstanceType<T>>;
675 /**
676 * Find many using an array of primary keys
677 */
678 findMany<T extends LucidModel>(this: T, value: any[], options?: ModelAdapterOptions): Promise<InstanceType<T>[]>;
679 /**
680 * Returns the first row or create a new instance of model without
681 * persisting it
682 */
683 firstOrNew<T extends LucidModel>(this: T, searchPayload: Partial<ModelAttributes<InstanceType<T>>>, savePayload?: Partial<ModelAttributes<InstanceType<T>>>, options?: ModelAssignOptions): Promise<InstanceType<T>>;
684 /**
685 * Returns the first row or save it to the database
686 */
687 firstOrCreate<T extends LucidModel>(this: T, searchPayload: Partial<ModelAttributes<InstanceType<T>>>, savePayload?: Partial<ModelAttributes<InstanceType<T>>>, options?: ModelAssignOptions): Promise<InstanceType<T>>;
688 /**
689 * Returns the first row or save it to the database
690 */
691 updateOrCreate<T extends LucidModel>(this: T, searchPayload: Partial<ModelAttributes<InstanceType<T>>>, updatePayload: Partial<ModelAttributes<InstanceType<T>>>, options?: ModelAssignOptions): Promise<InstanceType<T>>;
692 /**
693 * Find rows or create in-memory instances of the missing
694 * one's.
695 */
696 fetchOrNewUpMany<T extends LucidModel>(this: T, predicate: keyof ModelAttributes<InstanceType<T>> | (keyof ModelAttributes<InstanceType<T>>)[], payload: Partial<ModelAttributes<InstanceType<T>>>[], options?: ModelAssignOptions): Promise<InstanceType<T>[]>;
697 /**
698 * Find rows or create many when missing. One db call is invoked
699 * for each create
700 */
701 fetchOrCreateMany<T extends LucidModel>(this: T, predicate: keyof ModelAttributes<InstanceType<T>> | (keyof ModelAttributes<InstanceType<T>>)[], payload: Partial<ModelAttributes<InstanceType<T>>>[], options?: ModelAssignOptions): Promise<InstanceType<T>[]>;
702 /**
703 * Update existing rows or create new one's.
704 */
705 updateOrCreateMany<T extends LucidModel>(this: T, predicate: keyof ModelAttributes<InstanceType<T>> | (keyof ModelAttributes<InstanceType<T>>)[], payload: Partial<ModelAttributes<InstanceType<T>>>[], options?: ModelAssignOptions): Promise<InstanceType<T>[]>;
706 /**
707 * Fetch all rows
708 */
709 all<T extends LucidModel>(this: T, options?: ModelAdapterOptions): Promise<InstanceType<T>[]>;
710 /**
711 * Returns the query for fetching a model instance
712 */
713 query<Model extends LucidModel, Result = InstanceType<Model>>(this: Model, options?: ModelAdapterOptions): ModelQueryBuilderContract<Model, Result>;
714 /**
715 * Truncate model table
716 */
717 truncate(cascade?: boolean): Promise<void>;
718 new (): LucidRow;
719 }
720 /**
721 * ------------------------------------------------------
722 * Database Adapter
723 * ------------------------------------------------------
724 */
725 /**
726 * Every adapter must adhere to the Adapter contract
727 */
728 interface AdapterContract {
729 /**
730 * Returns query client for a model instance by inspecting it's options
731 */
732 modelClient(instance: LucidRow): QueryClientContract;
733 /**
734 * Returns query client for a model constructor
735 */
736 modelConstructorClient(modelConstructor: LucidModel, options?: ModelAdapterOptions): QueryClientContract;
737 /**
738 * Delete model instance
739 */
740 delete(instance: LucidRow): Promise<void>;
741 /**
742 * Refresh model instance to reflect new values
743 * from the database
744 */
745 refresh(instance: LucidRow): Promise<void>;
746 /**
747 * Perform insert
748 */
749 insert(instance: LucidRow, attributes: ModelObject): Promise<void>;
750 /**
751 * Perform update
752 */
753 update(instance: LucidRow, attributes: ModelObject): Promise<void>;
754 /**
755 * Must return the query builder for the model
756 */
757 query(modelConstructor: LucidModel, options?: ModelAdapterOptions): ModelQueryBuilderContract<LucidModel, LucidRow>;
758 }
759 /**
760 * Naming strategy for model
761 */
762 interface NamingStrategyContract {
763 /**
764 * The default table name for the given model
765 */
766 tableName(model: LucidModel): string;
767 /**
768 * The database column name for a given model attribute
769 */
770 columnName(model: LucidModel, attributeName: string): string;
771 /**
772 * The post serialization name for a given model attribute
773 */
774 serializedName(model: LucidModel, attributeName: string): string;
775 /**
776 * The local key for a given model relationship
777 */
778 relationLocalKey(relation: ModelRelations['__opaque_type'], model: LucidModel, relatedModel: LucidModel, relationName: string): string;
779 /**
780 * The foreign key for a given model relationship
781 */
782 relationForeignKey(relation: ModelRelations['__opaque_type'], model: LucidModel, relatedModel: LucidModel, relationName: string): string;
783 /**
784 * Pivot table name for many to many relationship
785 */
786 relationPivotTable(relation: 'manyToMany', model: LucidModel, relatedModel: LucidModel, relationName: string): string;
787 /**
788 * Pivot foreign key for many to many relationship
789 */
790 relationPivotForeignKey(relation: 'manyToMany', model: LucidModel, relatedModel: LucidModel, relationName: string): string;
791 /**
792 * Keys for the pagination meta
793 */
794 paginationMetaKeys(): SimplePaginatorMetaKeys;
795 }
796}
797
\No newline at end of file