UNPKG

30.8 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, 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: OmitFirst<Model[Scope]>) => 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 * Preload function on a model instance
198 */
199 interface LucidRowPreload<Model extends LucidRow> extends Preload<Model, Promise<void>> {
200 (callback: (preloader: PreloaderContract<Model>) => void): Promise<void>;
201 }
202 /**
203 * An extension of the simple paginator with support for serializing models
204 */
205 interface ModelPaginatorContract<Result extends LucidRow> extends Omit<SimplePaginatorContract<Result>, 'toJSON'> {
206 serialize(cherryPick?: CherryPick): {
207 meta: any;
208 data: ModelObject[];
209 };
210 toJSON(): {
211 meta: any;
212 data: ModelObject[];
213 };
214 }
215 /**
216 * ------------------------------------------------------
217 * Model Query Builder
218 * ------------------------------------------------------
219 */
220 /**
221 * Model query builder will have extras methods on top of the Database query builder
222 */
223 interface ModelQueryBuilderContract<Model extends LucidModel, Result = InstanceType<Model>> extends ChainableContract, ExcutableQueryBuilderContract<Result[]> {
224 model: Model;
225 /**
226 * Define a callback to transform a row
227 */
228 rowTransformer(callback: (row: LucidRow) => void): this;
229 /**
230 * Define a custom preloader for the current query
231 */
232 usePreloader(preloader: PreloaderContract<LucidRow>): this;
233 /**
234 * Whether or not the query is a child query generated for `.where`
235 * callbacks
236 */
237 isChildQuery: boolean;
238 /**
239 * Alias for the @withScopes method
240 */
241 apply<Scopes extends ExtractScopes<Model>>(callback: (scopes: Scopes) => void): this;
242 /**
243 * Apply model query scopes on the query bulder
244 */
245 withScopes<Scopes extends ExtractScopes<Model>>(callback: (scopes: Scopes) => void): this;
246 /**
247 * A copy of client options.
248 */
249 readonly clientOptions: ModelAdapterOptions;
250 /**
251 * Reference to query client used for making queries
252 */
253 client: QueryClientContract;
254 /**
255 * Clone query builder instance
256 */
257 clone<ClonedResult = Result>(): ModelQueryBuilderContract<Model, ClonedResult>;
258 /**
259 * A custom set of sideloaded properties defined on the query
260 * builder, this will be passed to the model instance created
261 * by the query builder
262 */
263 sideload(value: ModelObject): this;
264 /**
265 * Execute and get first result
266 */
267 first(): Promise<Result | null>;
268 /**
269 * Return the first matching row or fail
270 */
271 firstOrFail(): Promise<Result>;
272 /**
273 * Perform delete operation
274 */
275 del(): ModelQueryBuilderContract<Model, any>;
276 delete(): ModelQueryBuilderContract<Model, any>;
277 /**
278 * A shorthand to define limit and offset based upon the
279 * current page
280 */
281 forPage(page: number, perPage?: number): this;
282 /**
283 * Execute query with pagination
284 */
285 paginate(page: number, perPage?: number): Promise<Result extends LucidRow ? ModelPaginatorContract<Result> : SimplePaginatorContract<Result>>;
286 /**
287 * Mutations (update and increment can be one query aswell)
288 */
289 update: Update<ModelQueryBuilderContract<Model, any>>;
290 increment: Counter<ModelQueryBuilderContract<Model, any>>;
291 decrement: Counter<ModelQueryBuilderContract<Model, any>>;
292 /**
293 * Fetch relationship count
294 */
295 withCount: WithCount<InstanceType<Model>, this>;
296 /**
297 * Fetch aggregate value for a given relationship
298 */
299 withAggregate: WithAggregate<InstanceType<Model>, this>;
300 /**
301 * Add where constraint using the relationship
302 */
303 has: Has<InstanceType<Model>, this>;
304 orHas: Has<InstanceType<Model>, this>;
305 andHas: Has<InstanceType<Model>, this>;
306 doesntHave: Has<InstanceType<Model>, this>;
307 orDoesntHave: Has<InstanceType<Model>, this>;
308 andDoesntHave: Has<InstanceType<Model>, this>;
309 /**
310 * Add where constraint using the relationship with a custom callback
311 */
312 whereHas: WhereHas<InstanceType<Model>, this>;
313 orWhereHas: WhereHas<InstanceType<Model>, this>;
314 andWhereHas: WhereHas<InstanceType<Model>, this>;
315 whereDoesntHave: WhereHas<InstanceType<Model>, this>;
316 orWhereDoesntHave: WhereHas<InstanceType<Model>, this>;
317 andWhereDoesntHave: WhereHas<InstanceType<Model>, this>;
318 /**
319 * Define relationships to be preloaded
320 */
321 preload: Preload<InstanceType<Model>, this>;
322 /**
323 * Aggregates
324 */
325 count: Aggregate<this>;
326 countDistinct: Aggregate<this>;
327 min: Aggregate<this>;
328 max: Aggregate<this>;
329 sum: Aggregate<this>;
330 avg: Aggregate<this>;
331 avgDistinct: Aggregate<this>;
332 /**
333 * Executes the callback when dialect matches one of the mentioned
334 * dialects
335 */
336 ifDialect(dialect: DialectContract['name'] | DialectContract['name'][], matchCallback: (query: this) => any, noMatchCallback?: (query: this) => any): this;
337 /**
338 * Executes the callback when dialect matches doesn't all the mentioned
339 * dialects
340 */
341 unlessDialect(dialect: DialectContract['name'] | DialectContract['name'][], matchCallback: (query: this) => any, noMatchCallback?: (query: this) => any): this;
342 /**
343 * Get rows back as a plain javascript object and not an array
344 * of model instances
345 */
346 pojo<T>(): ModelQueryBuilderContract<Model, T>;
347 }
348 /**
349 * Shape of model keys
350 */
351 interface ModelKeysContract {
352 add(key: string, value: string): void;
353 get(key: string, defaultValue: string): string;
354 get(key: string, defaultValue?: string): string | undefined;
355 resolve(key: string): string;
356 all(): ModelObject;
357 }
358 /**
359 * ------------------------------------------------------
360 * Shape of Model instance
361 * ------------------------------------------------------
362 */
363 /**
364 * Shape of the model instance. We prefix the properties with a `$` to
365 * differentiate between special properties provided by the base
366 * model but with exception to `save`, `delete`, `fill`, `merge`
367 * and `toJSON`.
368 *
369 * @note: Since the interface name appears next to the inherited model
370 * methods, we have to choose a succinct name
371 */
372 interface LucidRow {
373 $attributes: ModelObject;
374 $extras: ModelObject;
375 $original: ModelObject;
376 $preloaded: {
377 [relation: string]: LucidRow | LucidRow[];
378 };
379 /**
380 * Columns is a property to get type information for model
381 * attributes. This must be declared by the end user
382 */
383 $columns: undefined;
384 $sideloaded: ModelObject;
385 $primaryKeyValue?: number | string;
386 $isPersisted: boolean;
387 $isNew: boolean;
388 $isLocal: boolean;
389 $dirty: ModelObject;
390 $isDirty: boolean;
391 $isDeleted: boolean;
392 $options?: ModelOptions;
393 $trx?: TransactionClientContract;
394 $setOptionsAndTrx(options?: ModelAdapterOptions): void;
395 useTransaction(trx: TransactionClientContract): this;
396 useConnection(connection: string): this;
397 /**
398 * Gives an option to the end user to define constraints for update, insert
399 * and delete queries. Since the query builder for these queries aren't
400 * exposed to the end user, this method opens up the API to build
401 * custom queries.
402 */
403 $getQueryFor(action: 'insert', client: QueryClientContract): ReturnType<QueryClientContract['insertQuery']>;
404 $getQueryFor(action: 'update' | 'delete' | 'refresh', client: QueryClientContract): ModelQueryBuilderContract<LucidModel>;
405 /**
406 * Read/write attributes. Following methods are intentionally loosely typed,
407 * so that one can bypass the public facing API and type checking for
408 * advanced use cases
409 */
410 $setAttribute(key: string, value: any): void;
411 $getAttribute(key: string): any;
412 $getAttributeFromCache(key: string, callback: CacheNode['getter']): any;
413 /**
414 * Read/write realtionships. Following methods are intentionally loosely typed,
415 * so that one can bypass the public facing API and type checking for
416 * advanced use cases
417 */
418 $hasRelated(key: string): boolean;
419 $setRelated(key: string, result: OneOrMany<LucidRow> | null): void;
420 $pushRelated(key: string, result: OneOrMany<LucidRow> | null): void;
421 $getRelated(key: string, defaultValue?: any): OneOrMany<LucidRow> | undefined | null;
422 /**
423 * Consume the adapter result and hydrate the model
424 */
425 $consumeAdapterResult(adapterResult: ModelObject, sideloadAttributes?: ModelObject): void;
426 $hydrateOriginals(): void;
427 fill(value: Partial<ModelAttributes<this>>, allowExtraProperties?: boolean): this;
428 merge(value: Partial<ModelAttributes<this>>, allowExtraProperties?: boolean): this;
429 /**
430 * Actions to perform on the instance
431 */
432 save(): Promise<this>;
433 delete(): Promise<void>;
434 refresh(): Promise<this>;
435 /**
436 * Load relationships onto the instance
437 */
438 load: LucidRowPreload<this>;
439 /**
440 * Alias for "load"
441 * @deprecated
442 */
443 preload: LucidRowPreload<this>;
444 /**
445 * Serialize attributes to a plain object
446 */
447 serializeAttributes(fields?: CherryPickFields, raw?: boolean): ModelObject;
448 /**
449 * Serialize computed properties to a plain object
450 */
451 serializeComputed(fields?: CherryPickFields): ModelObject;
452 /**
453 * Serialize relationships to key-value pair of model instances and
454 * their serializeAs keys
455 */
456 serializeRelations(fields: undefined, raw: true): {
457 [key: string]: LucidRow | LucidRow[];
458 };
459 /**
460 * Serialize relationships to key-value pair of plain nested objects
461 */
462 serializeRelations(cherryPick: CherryPick['relations'] | undefined, raw: false | undefined): ModelObject;
463 serializeRelations(cherryPick?: CherryPick['relations'], raw?: boolean): ModelObject;
464 /**
465 * Serialize model to a plain object
466 */
467 serialize(cherryPick?: CherryPick): ModelObject;
468 /**
469 * Converts model to an object. It just returns the properties
470 * of the model, along with preloaded relationships
471 */
472 toObject(): ModelObject;
473 /**
474 * Serialize everything
475 */
476 toJSON(): ModelObject;
477 /**
478 * Returns related model for a given relationship
479 */
480 related<Name extends ExtractModelRelations<this>>(relation: Name): this[Name] extends ModelRelations ? this[Name]['client'] : never;
481 }
482 /**
483 * ------------------------------------------------------
484 * Shape of Model constructor
485 * ------------------------------------------------------
486 */
487 /**
488 * Shape of the model static properties. The `$` prefix is to denote
489 * special properties from the base model.
490 *
491 * @note: Since the interface name appears next to the inherited model
492 * methods, we have to choose a succinct name
493 */
494 interface LucidModel {
495 /**
496 * Whether or not model has been booted. After this model configurations
497 * are ignored
498 */
499 readonly booted: boolean;
500 /**
501 * A map of defined columns
502 */
503 $columnsDefinitions: Map<string, ModelColumnOptions>;
504 /**
505 * A map of defined relationships
506 */
507 $relationsDefinitions: Map<string, RelationshipsContract>;
508 /**
509 * A map of computed properties
510 */
511 $computedDefinitions: Map<string, ComputedOptions>;
512 /**
513 * The primary key for finding unique referencing to a
514 * model
515 */
516 primaryKey: string;
517 /**
518 * Custom database connection to use
519 */
520 connection?: string;
521 /**
522 * Naming strategy to use
523 */
524 namingStrategy: NamingStrategyContract;
525 /**
526 * Database table to use
527 */
528 table: string;
529 /**
530 * Self assign the primary instead of relying on the database to
531 * return it back
532 */
533 selfAssignPrimaryKey: boolean;
534 /**
535 * Adapter to work as a bridge between query builder and the model
536 */
537 $adapter: AdapterContract;
538 /**
539 * Reference to hooks
540 */
541 $hooks: Hooks;
542 /**
543 * A copy of internal keys mapping. One should be able to resolve between
544 * all key versions
545 */
546 $keys: {
547 attributesToColumns: ModelKeysContract;
548 attributesToSerialized: ModelKeysContract;
549 columnsToAttributes: ModelKeysContract;
550 columnsToSerialized: ModelKeysContract;
551 serializedToColumns: ModelKeysContract;
552 serializedToAttributes: ModelKeysContract;
553 };
554 /**
555 * Creating model from adapter results
556 */
557 $createFromAdapterResult<T extends LucidModel>(this: T, result?: ModelObject, sideloadAttributes?: ModelObject, options?: ModelAdapterOptions): null | InstanceType<T>;
558 /**
559 * Creating multiple model instances from an array of adapter
560 * result
561 */
562 $createMultipleFromAdapterResult<T extends LucidModel>(this: T, results: ModelObject[], sideloadAttributes?: ModelObject, options?: ModelAdapterOptions): InstanceType<T>[];
563 /**
564 * Managing columns
565 */
566 $addColumn(name: string, options: Partial<ColumnOptions>): ColumnOptions;
567 $hasColumn(name: string): boolean;
568 $getColumn(name: string): ModelColumnOptions | undefined;
569 /**
570 * Managing computed columns
571 */
572 $addComputed(name: string, options: Partial<ComputedOptions>): ComputedOptions;
573 $hasComputed(name: string): boolean;
574 $getComputed(name: string): ComputedOptions | undefined;
575 /**
576 * Managing relationships
577 */
578 $addRelation(name: string, type: ModelRelationTypes['__opaque_type'], relatedModel: () => LucidModel, options: ModelRelationOptions): void;
579 /**
580 * Find if a relationship exists
581 */
582 $hasRelation(name: string): boolean;
583 /**
584 * Get relationship declaration
585 */
586 $getRelation<Model extends LucidModel, Name extends ExtractModelRelations<InstanceType<Model>>>(this: Model, name: Name): InstanceType<Model>[Name] extends ModelRelations ? InstanceType<Model>[Name]['client']['relation'] : RelationshipsContract;
587 $getRelation<Model extends LucidModel>(this: Model, name: string): RelationshipsContract;
588 /**
589 * Boot model
590 */
591 boot(): void;
592 /**
593 * Register a before hook
594 */
595 before<Model extends LucidModel, Event extends 'find' | 'fetch'>(this: Model, event: Event, handler: HooksHandler<ModelQueryBuilderContract<Model>, Event>): void;
596 before<Model extends LucidModel>(this: Model, event: 'paginate', handler: HooksHandler<[
597 ModelQueryBuilderContract<Model>,
598 ModelQueryBuilderContract<Model>
599 ], 'paginate'>): void;
600 before<Model extends LucidModel, Event extends EventsList>(this: Model, event: Event, handler: HooksHandler<InstanceType<Model>, Event>): void;
601 /**
602 * Register an after hook
603 */
604 after<Model extends LucidModel>(this: Model, event: 'fetch', handler: HooksHandler<InstanceType<Model>[], 'fetch'>): void;
605 after<Model extends LucidModel>(this: Model, event: 'paginate', handler: HooksHandler<ModelPaginatorContract<InstanceType<Model>>, 'paginate'>): void;
606 after<Model extends LucidModel, Event extends EventsList>(this: Model, event: Event, handler: HooksHandler<InstanceType<Model>, Event>): void;
607 /**
608 * Create model and return its instance back
609 */
610 create<T extends LucidModel>(this: T, values: Partial<ModelAttributes<InstanceType<T>>>, options?: ModelAdapterOptions): Promise<InstanceType<T>>;
611 /**
612 * Create many of model instances
613 */
614 createMany<T extends LucidModel>(this: T, values: Partial<ModelAttributes<InstanceType<T>>>[], options?: ModelAdapterOptions): Promise<InstanceType<T>[]>;
615 /**
616 * Find one using the primary key
617 */
618 find<T extends LucidModel>(this: T, value: any, options?: ModelAdapterOptions): Promise<null | InstanceType<T>>;
619 /**
620 * Find one using the primary key or fail
621 */
622 findOrFail<T extends LucidModel>(this: T, value: any, options?: ModelAdapterOptions): Promise<InstanceType<T>>;
623 /**
624 * Find one using a key-value pair
625 */
626 findBy<T extends LucidModel>(this: T, key: string, value: any, options?: ModelAdapterOptions): Promise<null | InstanceType<T>>;
627 /**
628 * Find one using a key-value pair or fail
629 */
630 findByOrFail<T extends LucidModel>(this: T, key: string, value: any, options?: ModelAdapterOptions): Promise<InstanceType<T>>;
631 /**
632 * Same as `query().first()`
633 */
634 first<T extends LucidModel>(this: T, options?: ModelAdapterOptions): Promise<null | InstanceType<T>>;
635 /**
636 * Same as `query().firstOrFail()`
637 */
638 firstOrFail<T extends LucidModel>(this: T, options?: ModelAdapterOptions): Promise<InstanceType<T>>;
639 /**
640 * Find many using an array of primary keys
641 */
642 findMany<T extends LucidModel>(this: T, value: any[], options?: ModelAdapterOptions): Promise<InstanceType<T>[]>;
643 /**
644 * Returns the first row or create a new instance of model without
645 * persisting it
646 */
647 firstOrNew<T extends LucidModel>(this: T, searchPayload: Partial<ModelAttributes<InstanceType<T>>>, savePayload?: Partial<ModelAttributes<InstanceType<T>>>, options?: ModelAdapterOptions): Promise<InstanceType<T>>;
648 /**
649 * Returns the first row or save it to the database
650 */
651 firstOrCreate<T extends LucidModel>(this: T, searchPayload: Partial<ModelAttributes<InstanceType<T>>>, savePayload?: Partial<ModelAttributes<InstanceType<T>>>, options?: ModelAdapterOptions): Promise<InstanceType<T>>;
652 /**
653 * Returns the first row or save it to the database
654 */
655 updateOrCreate<T extends LucidModel>(this: T, searchPayload: Partial<ModelAttributes<InstanceType<T>>>, updatePayload: Partial<ModelAttributes<InstanceType<T>>>, options?: ModelAdapterOptions): Promise<InstanceType<T>>;
656 /**
657 * Find rows or create in-memory instances of the missing
658 * one's.
659 */
660 fetchOrNewUpMany<T extends LucidModel>(this: T, predicate: keyof ModelAttributes<InstanceType<T>> | (keyof ModelAttributes<InstanceType<T>>)[], payload: Partial<ModelAttributes<InstanceType<T>>>[], options?: ModelAdapterOptions): Promise<InstanceType<T>[]>;
661 /**
662 * Find rows or create many when missing. One db call is invoked
663 * for each create
664 */
665 fetchOrCreateMany<T extends LucidModel>(this: T, predicate: keyof ModelAttributes<InstanceType<T>> | (keyof ModelAttributes<InstanceType<T>>)[], payload: Partial<ModelAttributes<InstanceType<T>>>[], options?: ModelAdapterOptions): Promise<InstanceType<T>[]>;
666 /**
667 * Update existing rows or create new one's.
668 */
669 updateOrCreateMany<T extends LucidModel>(this: T, predicate: keyof ModelAttributes<InstanceType<T>> | (keyof ModelAttributes<InstanceType<T>>)[], payload: Partial<ModelAttributes<InstanceType<T>>>[], options?: ModelAdapterOptions): Promise<InstanceType<T>[]>;
670 /**
671 * Fetch all rows
672 */
673 all<T extends LucidModel>(this: T, options?: ModelAdapterOptions): Promise<InstanceType<T>[]>;
674 /**
675 * Returns the query for fetching a model instance
676 */
677 query<Model extends LucidModel, Result = InstanceType<Model>>(this: Model, options?: ModelAdapterOptions): ModelQueryBuilderContract<Model, Result>;
678 /**
679 * Truncate model table
680 */
681 truncate(cascade?: boolean): Promise<void>;
682 new (): LucidRow;
683 }
684 /**
685 * ------------------------------------------------------
686 * Database Adapter
687 * ------------------------------------------------------
688 */
689 /**
690 * Every adapter must adhere to the Adapter contract
691 */
692 interface AdapterContract {
693 /**
694 * Returns query client for a model instance by inspecting it's options
695 */
696 modelClient(instance: LucidRow): QueryClientContract;
697 /**
698 * Returns query client for a model constructor
699 */
700 modelConstructorClient(modelConstructor: LucidModel, options?: ModelAdapterOptions): QueryClientContract;
701 /**
702 * Delete model instance
703 */
704 delete(instance: LucidRow): Promise<void>;
705 /**
706 * Refresh model instance to reflect new values
707 * from the database
708 */
709 refresh(instance: LucidRow): Promise<void>;
710 /**
711 * Perform insert
712 */
713 insert(instance: LucidRow, attributes: ModelObject): Promise<void>;
714 /**
715 * Perform update
716 */
717 update(instance: LucidRow, attributes: ModelObject): Promise<void>;
718 /**
719 * Must return the query builder for the model
720 */
721 query(modelConstructor: LucidModel, options?: ModelAdapterOptions): ModelQueryBuilderContract<LucidModel, LucidRow>;
722 }
723 /**
724 * Naming strategy for model
725 */
726 interface NamingStrategyContract {
727 /**
728 * The default table name for the given model
729 */
730 tableName(model: LucidModel): string;
731 /**
732 * The database column name for a given model attribute
733 */
734 columnName(model: LucidModel, attributeName: string): string;
735 /**
736 * The post serialization name for a given model attribute
737 */
738 serializedName(model: LucidModel, attributeName: string): string;
739 /**
740 * The local key for a given model relationship
741 */
742 relationLocalKey(relation: ModelRelations['__opaque_type'], model: LucidModel, relatedModel: LucidModel, relationName: string): string;
743 /**
744 * The foreign key for a given model relationship
745 */
746 relationForeignKey(relation: ModelRelations['__opaque_type'], model: LucidModel, relatedModel: LucidModel, relationName: string): string;
747 /**
748 * Pivot table name for many to many relationship
749 */
750 relationPivotTable(relation: 'manyToMany', model: LucidModel, relatedModel: LucidModel, relationName: string): string;
751 /**
752 * Pivot foreign key for many to many relationship
753 */
754 relationPivotForeignKey(relation: 'manyToMany', model: LucidModel, relatedModel: LucidModel, relationName: string): string;
755 /**
756 * Keys for the pagination meta
757 */
758 paginationMetaKeys(): SimplePaginatorMetaKeys;
759 }
760}
761
\No newline at end of file