UNPKG

32.9 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: Model[Scope] extends QueryScopeCallback ? OmitFirst<Model[Scope]> : never) => 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 * Enable force update even when no attributes
451 * are dirty
452 */
453 enableForceUpdate(): this;
454 /**
455 * Actions to perform on the instance
456 */
457 save(): Promise<this>;
458 delete(): Promise<void>;
459 refresh(): Promise<this>;
460 /**
461 * Load relationships onto the instance
462 */
463 load: LucidRowPreload<this>;
464 /**
465 * Alias for "load"
466 * @deprecated
467 */
468 preload: LucidRowPreload<this>;
469 /**
470 * Load aggregates
471 */
472 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>;
473 /**
474 * Load count
475 */
476 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>;
477 /**
478 * Serialize attributes to a plain object
479 */
480 serializeAttributes(fields?: CherryPickFields, raw?: boolean): ModelObject;
481 /**
482 * Serialize computed properties to a plain object
483 */
484 serializeComputed(fields?: CherryPickFields): ModelObject;
485 /**
486 * Serialize relationships to key-value pair of model instances and
487 * their serializeAs keys
488 */
489 serializeRelations(fields: undefined, raw: true): {
490 [key: string]: LucidRow | LucidRow[];
491 };
492 /**
493 * Serialize relationships to key-value pair of plain nested objects
494 */
495 serializeRelations(cherryPick: CherryPick['relations'] | undefined, raw: false | undefined): ModelObject;
496 serializeRelations(cherryPick?: CherryPick['relations'], raw?: boolean): ModelObject;
497 /**
498 * Serialize model to a plain object
499 */
500 serialize(cherryPick?: CherryPick): ModelObject;
501 /**
502 * Converts model to an object. It just returns the properties
503 * of the model, along with preloaded relationships
504 */
505 toObject(): ModelObject;
506 /**
507 * Serialize everything
508 */
509 toJSON(): ModelObject;
510 /**
511 * Returns related model for a given relationship
512 */
513 related<Name extends ExtractModelRelations<this>>(relation: Name): this[Name] extends ModelRelations ? this[Name]['client'] : never;
514 }
515 /**
516 * ------------------------------------------------------
517 * Shape of Model constructor
518 * ------------------------------------------------------
519 */
520 /**
521 * Shape of the model static properties. The `$` prefix is to denote
522 * special properties from the base model.
523 *
524 * @note: Since the interface name appears next to the inherited model
525 * methods, we have to choose a succinct name
526 */
527 interface LucidModel {
528 /**
529 * Whether or not model has been booted. After this model configurations
530 * are ignored
531 */
532 readonly booted: boolean;
533 /**
534 * A map of defined columns
535 */
536 $columnsDefinitions: Map<string, ModelColumnOptions>;
537 /**
538 * A map of defined relationships
539 */
540 $relationsDefinitions: Map<string, RelationshipsContract>;
541 /**
542 * A map of computed properties
543 */
544 $computedDefinitions: Map<string, ComputedOptions>;
545 /**
546 * The primary key for finding unique referencing to a
547 * model
548 */
549 primaryKey: string;
550 /**
551 * Custom database connection to use
552 */
553 connection?: string;
554 /**
555 * Naming strategy to use
556 */
557 namingStrategy: NamingStrategyContract;
558 /**
559 * Database table to use
560 */
561 table: string;
562 /**
563 * Self assign the primary instead of relying on the database to
564 * return it back
565 */
566 selfAssignPrimaryKey: boolean;
567 /**
568 * Adapter to work as a bridge between query builder and the model
569 */
570 $adapter: AdapterContract;
571 /**
572 * Reference to hooks
573 */
574 $hooks: Hooks;
575 /**
576 * A copy of internal keys mapping. One should be able to resolve between
577 * all key versions
578 */
579 $keys: {
580 attributesToColumns: ModelKeysContract;
581 attributesToSerialized: ModelKeysContract;
582 columnsToAttributes: ModelKeysContract;
583 columnsToSerialized: ModelKeysContract;
584 serializedToColumns: ModelKeysContract;
585 serializedToAttributes: ModelKeysContract;
586 };
587 /**
588 * Creating model from adapter results
589 */
590 $createFromAdapterResult<T extends LucidModel>(this: T, result?: ModelObject, sideloadAttributes?: ModelObject, options?: ModelAdapterOptions): null | InstanceType<T>;
591 /**
592 * Creating multiple model instances from an array of adapter
593 * result
594 */
595 $createMultipleFromAdapterResult<T extends LucidModel>(this: T, results: ModelObject[], sideloadAttributes?: ModelObject, options?: ModelAdapterOptions): InstanceType<T>[];
596 /**
597 * Managing columns
598 */
599 $addColumn(name: string, options: Partial<ColumnOptions>): ColumnOptions;
600 $hasColumn(name: string): boolean;
601 $getColumn(name: string): ModelColumnOptions | undefined;
602 /**
603 * Managing computed columns
604 */
605 $addComputed(name: string, options: Partial<ComputedOptions>): ComputedOptions;
606 $hasComputed(name: string): boolean;
607 $getComputed(name: string): ComputedOptions | undefined;
608 /**
609 * Managing relationships
610 */
611 $addRelation(name: string, type: ModelRelationTypes['__opaque_type'], relatedModel: () => LucidModel, options: ModelRelationOptions): void;
612 /**
613 * Find if a relationship exists
614 */
615 $hasRelation(name: string): boolean;
616 /**
617 * Get relationship declaration
618 */
619 $getRelation<Model extends LucidModel, Name extends ExtractModelRelations<InstanceType<Model>>>(this: Model, name: Name): InstanceType<Model>[Name] extends ModelRelations ? InstanceType<Model>[Name]['client']['relation'] : RelationshipsContract;
620 $getRelation<Model extends LucidModel>(this: Model, name: string): RelationshipsContract;
621 /**
622 * Define a static property on the model using the inherit or
623 * define strategy.
624 *
625 * Inherit strategy will clone the property from the parent model
626 * and will set it on the current model
627 */
628 $defineProperty<Model extends LucidModel, Prop extends keyof Model>(this: Model, propertyName: Prop, defaultValue: Model[Prop], strategy: 'inherit' | 'define' | ((value: Model[Prop]) => Model[Prop])): void;
629 /**
630 * Boot model
631 */
632 boot(): void;
633 /**
634 * Register a before hook
635 */
636 before<Model extends LucidModel, Event extends 'find' | 'fetch'>(this: Model, event: Event, handler: HooksHandler<ModelQueryBuilderContract<Model>, Event>): void;
637 before<Model extends LucidModel>(this: Model, event: 'paginate', handler: HooksHandler<[
638 ModelQueryBuilderContract<Model>,
639 ModelQueryBuilderContract<Model>
640 ], 'paginate'>): void;
641 before<Model extends LucidModel, Event extends EventsList>(this: Model, event: Event, handler: HooksHandler<InstanceType<Model>, Event>): void;
642 /**
643 * Register an after hook
644 */
645 after<Model extends LucidModel>(this: Model, event: 'fetch', handler: HooksHandler<InstanceType<Model>[], 'fetch'>): void;
646 after<Model extends LucidModel>(this: Model, event: 'paginate', handler: HooksHandler<ModelPaginatorContract<InstanceType<Model>>, 'paginate'>): void;
647 after<Model extends LucidModel, Event extends EventsList>(this: Model, event: Event, handler: HooksHandler<InstanceType<Model>, Event>): void;
648 /**
649 * Create model and return its instance back
650 */
651 create<T extends LucidModel>(this: T, values: Partial<ModelAttributes<InstanceType<T>>>, options?: ModelAssignOptions): Promise<InstanceType<T>>;
652 /**
653 * Create many of model instances
654 */
655 createMany<T extends LucidModel>(this: T, values: Partial<ModelAttributes<InstanceType<T>>>[], options?: ModelAssignOptions): Promise<InstanceType<T>[]>;
656 /**
657 * Find one using the primary key
658 */
659 find<T extends LucidModel>(this: T, value: any, options?: ModelAdapterOptions): Promise<null | InstanceType<T>>;
660 /**
661 * Find one using the primary key or fail
662 */
663 findOrFail<T extends LucidModel>(this: T, value: any, options?: ModelAdapterOptions): Promise<InstanceType<T>>;
664 /**
665 * Find one using a key-value pair
666 */
667 findBy<T extends LucidModel>(this: T, key: string, value: any, options?: ModelAdapterOptions): Promise<null | InstanceType<T>>;
668 /**
669 * Find one using a key-value pair or fail
670 */
671 findByOrFail<T extends LucidModel>(this: T, key: string, value: any, options?: ModelAdapterOptions): Promise<InstanceType<T>>;
672 /**
673 * Same as `query().first()`
674 */
675 first<T extends LucidModel>(this: T, options?: ModelAdapterOptions): Promise<null | InstanceType<T>>;
676 /**
677 * Same as `query().firstOrFail()`
678 */
679 firstOrFail<T extends LucidModel>(this: T, options?: ModelAdapterOptions): Promise<InstanceType<T>>;
680 /**
681 * Find many using an array of primary keys
682 */
683 findMany<T extends LucidModel>(this: T, value: any[], options?: ModelAdapterOptions): Promise<InstanceType<T>[]>;
684 /**
685 * Returns the first row or create a new instance of model without
686 * persisting it
687 */
688 firstOrNew<T extends LucidModel>(this: T, searchPayload: Partial<ModelAttributes<InstanceType<T>>>, savePayload?: Partial<ModelAttributes<InstanceType<T>>>, options?: ModelAssignOptions): Promise<InstanceType<T>>;
689 /**
690 * Returns the first row or save it to the database
691 */
692 firstOrCreate<T extends LucidModel>(this: T, searchPayload: Partial<ModelAttributes<InstanceType<T>>>, savePayload?: Partial<ModelAttributes<InstanceType<T>>>, options?: ModelAssignOptions): Promise<InstanceType<T>>;
693 /**
694 * Returns the first row or save it to the database
695 */
696 updateOrCreate<T extends LucidModel>(this: T, searchPayload: Partial<ModelAttributes<InstanceType<T>>>, updatePayload: Partial<ModelAttributes<InstanceType<T>>>, options?: ModelAssignOptions): Promise<InstanceType<T>>;
697 /**
698 * Find rows or create in-memory instances of the missing
699 * one's.
700 */
701 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>[]>;
702 /**
703 * Find rows or create many when missing. One db call is invoked
704 * for each create
705 */
706 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>[]>;
707 /**
708 * Update existing rows or create new one's.
709 */
710 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>[]>;
711 /**
712 * Fetch all rows
713 */
714 all<T extends LucidModel>(this: T, options?: ModelAdapterOptions): Promise<InstanceType<T>[]>;
715 /**
716 * Returns the query for fetching a model instance
717 */
718 query<Model extends LucidModel, Result = InstanceType<Model>>(this: Model, options?: ModelAdapterOptions): ModelQueryBuilderContract<Model, Result>;
719 /**
720 * Truncate model table
721 */
722 truncate(cascade?: boolean): Promise<void>;
723 new (): LucidRow;
724 }
725 /**
726 * ------------------------------------------------------
727 * Database Adapter
728 * ------------------------------------------------------
729 */
730 /**
731 * Every adapter must adhere to the Adapter contract
732 */
733 interface AdapterContract {
734 /**
735 * Returns query client for a model instance by inspecting it's options
736 */
737 modelClient(instance: LucidRow): QueryClientContract;
738 /**
739 * Returns query client for a model constructor
740 */
741 modelConstructorClient(modelConstructor: LucidModel, options?: ModelAdapterOptions): QueryClientContract;
742 /**
743 * Delete model instance
744 */
745 delete(instance: LucidRow): Promise<void>;
746 /**
747 * Refresh model instance to reflect new values
748 * from the database
749 */
750 refresh(instance: LucidRow): Promise<void>;
751 /**
752 * Perform insert
753 */
754 insert(instance: LucidRow, attributes: ModelObject): Promise<void>;
755 /**
756 * Perform update
757 */
758 update(instance: LucidRow, attributes: ModelObject): Promise<void>;
759 /**
760 * Must return the query builder for the model
761 */
762 query(modelConstructor: LucidModel, options?: ModelAdapterOptions): ModelQueryBuilderContract<LucidModel, LucidRow>;
763 }
764 /**
765 * Naming strategy for model
766 */
767 interface NamingStrategyContract {
768 /**
769 * The default table name for the given model
770 */
771 tableName(model: LucidModel): string;
772 /**
773 * The database column name for a given model attribute
774 */
775 columnName(model: LucidModel, attributeName: string): string;
776 /**
777 * The post serialization name for a given model attribute
778 */
779 serializedName(model: LucidModel, attributeName: string): string;
780 /**
781 * The local key for a given model relationship
782 */
783 relationLocalKey(relation: ModelRelations['__opaque_type'], model: LucidModel, relatedModel: LucidModel, relationName: string): string;
784 /**
785 * The foreign key for a given model relationship
786 */
787 relationForeignKey(relation: ModelRelations['__opaque_type'], model: LucidModel, relatedModel: LucidModel, relationName: string): string;
788 /**
789 * Pivot table name for many to many relationship
790 */
791 relationPivotTable(relation: 'manyToMany', model: LucidModel, relatedModel: LucidModel, relationName: string): string;
792 /**
793 * Pivot foreign key for many to many relationship
794 */
795 relationPivotForeignKey(relation: 'manyToMany', model: LucidModel, relatedModel: LucidModel, relationName: string): string;
796 /**
797 * Keys for the pagination meta
798 */
799 paginationMetaKeys(): SimplePaginatorMetaKeys;
800 }
801}
802
\No newline at end of file