prorm API Reference
    Preparing search index...

    Interface ModelStatic<T>

    The static side of a model class — the finders, writers and association declarations, as opposed to an instance of it.

    interface ModelStatic<T extends Model> {
        addColumn(
            columnName: string,
            definition: TableColumnDefinition,
            options?: QueryInterfaceOptions,
        ): Promise<void>;
        removeColumn(
            columnName: string,
            options?: QueryInterfaceOptions,
        ): Promise<void>;
        changeColumn(
            columnName: string,
            definition: TableColumnDefinition,
            options?: QueryInterfaceOptions,
        ): Promise<void>;
        renameColumn(
            oldColumnName: string,
            newColumnName: string,
            options?: QueryInterfaceOptions,
        ): Promise<void>;
        addIndex(
            fieldsOrName: string | string[] | IndexFieldDefinition[],
            fieldsOrOptions?:
                | string[]
                | IndexFieldDefinition[]
                | IndexOptions & QueryInterfaceOptions,
            options?: IndexOptions & QueryInterfaceOptions,
        ): Promise<void>;
        removeIndex(
            indexName: string,
            options?: QueryInterfaceOptions,
        ): Promise<void>;
        showIndexes(): Promise<
            { name: string; fields: string[]; unique: boolean }[],
        >;
        indexExists(indexName: string): Promise<boolean>;
        createFullTextIndex(
            options: Omit<FullTextIndexOptions, "table"> & { table?: string },
        ): Promise<void>;
        addConstraint(
            constraintNameOrOptions:
                | string
                | ConstraintDefinition & { name?: string },
            constraintOrOptions?: ConstraintDefinition,
            options?: QueryInterfaceOptions,
        ): Promise<void>;
        removeConstraint(
            constraintName: string,
            typeOrOptions?: string | QueryInterfaceOptions,
        ): Promise<void>;
        getConstraints(): Promise<any[]>;
        getForeignKeys(): Promise<any[]>;
        tableExists(): Promise<boolean>;
        renameTable(
            newName: string,
            options?: QueryInterfaceOptions,
        ): Promise<void>;
        enableRowLevelSecurity(): Promise<void>;
        disableRowLevelSecurity(): Promise<void>;
        createPolicy(
            options: Omit<CreatePolicyOptions, "table"> & { table?: string },
        ): Promise<void>;
        dropPolicy(name: string, options?: { ifExists?: boolean }): Promise<void>;
        createTrigger(
            trigger: Omit<TriggerDefinition, "table"> & { table?: string },
        ): Promise<void>;
        dropTrigger(name: string, options?: { ifExists?: boolean }): Promise<void>;
        createPartition(
            options: Omit<CreatePartitionOptions, "parentTable"> & {
                parentTable?: string;
            },
        ): Promise<void>;
        attachPartition(
            options: Omit<AttachPartitionOptions, "parentTable"> & {
                parentTable?: string;
            },
        ): Promise<void>;
        detachPartition(options: DetachPartitionOptions): Promise<void>;
        dropPartition(
            partitionName: string,
            options?: { ifExists?: boolean; cascade?: boolean } & QueryInterfaceOptions,
        ): Promise<void>;
        describeTable(): Promise<TableDescription>;
        name: string;
        tableName: string;
        schema?: string;
        rawAttributes: Record<string, AttributeOptions>;
        associations: Record<string, Association>;
        isNewRecord: false;
        where(field: string, operator: unknown, value?: unknown): WhereOptions;
        findOne(options?: FindOptions): Promise<T | null>;
        findAll(options?: FindOptions): Promise<T[]>;
        findAndCountAll(
            options?: FindOptions,
        ): Promise<{ rows: T[]; count: number }>;
        create(values?: Partial<T>, options?: CreateOptions): Promise<T>;
        update(values: Partial<T>, options: UpdateOptions): Promise<[number, T[]]>;
        destroy(options: DestroyOptions): Promise<number>;
        bulkDestroy(options: DestroyOptions): Promise<number>;
        restore(
            options?: RestoreOptions & { where?: WhereOptions<any> },
        ): Promise<number>;
        bulkRestore(
            options?: RestoreOptions & { where?: WhereOptions<any> },
        ): Promise<number>;
        bulkCreate(
            records: Partial<T>[],
            options?: BulkCreateOptions,
        ): Promise<T[]>;
        count(options?: CountOptions): Promise<number>;
        count(options?: WindowFunctionOptions & { countField?: string }): any;
        avg(attribute: string, options?: AggregateOptions): Promise<number>;
        avg(field: string, options?: WindowFunctionOptions): any;
        max(attribute: string, options?: AggregateOptions): Promise<any>;
        max(field: string, options?: WindowFunctionOptions): any;
        min(attribute: string, options?: AggregateOptions): Promise<any>;
        min(field: string, options?: WindowFunctionOptions): any;
        sum(
            attribute: string,
            options?: AggregateOptions & { distinct?: boolean },
        ): Promise<number>;
        sum(field: string, options?: WindowFunctionOptions): any;
        rowNumber(options: WindowFunctionOptions): number;
        rank(options: WindowFunctionOptions): number;
        denseRank(options: WindowFunctionOptions): number;
        lag(field: string, options?: WindowFunctionOptions): any;
        lead(field: string, options?: WindowFunctionOptions): any;
        firstValue(field: string, options?: WindowFunctionOptions): any;
        lastValue(field: string, options?: WindowFunctionOptions): any;
        nthValue(field: string, n: number, options?: WindowFunctionOptions): any;
        ntile(n: number, options?: WindowFunctionOptions): any;
        percentRank(options?: WindowFunctionOptions): any;
        cumeDist(options?: WindowFunctionOptions): any;
        windowFunction(
            functionName: string,
            args: any[],
            options: WindowFunctionOptions,
        ): { sql: string; values: any[] };
        upsert(values: Partial<T>, options?: UpsertOptions): Promise<[T, boolean]>;
        findOrCreate(
            options: FindOptions & { defaults?: Partial<T> },
        ): Promise<[T, boolean]>;
        findOrBuild(
            options: FindOptions & { defaults?: Partial<T> },
        ): Promise<[T, boolean]>;
        findOrInitialize(
            options: FindOptions & { defaults?: Partial<T> },
        ): Promise<[T, boolean]>;
        truncate(options?: TruncateOptions): Promise<void>;
        describe(): Promise<Record<string, AttributeOptions>>;
        drop(options?: DropOptions): Promise<void>;
        getTableName(): string;
        refresh(options?: RefreshOptions): Promise<void>;
        isMaterializedView?: boolean;
        hook(hookName: string, handler: HookHandler): ModelStatic<T>;
        addHook(
            hookName: string,
            name: string,
            handler: HookHandler,
        ): ModelStatic<T>;
        hasHook(hookName: string): boolean;
        removeHook(
            hookName: string,
            hookOrHookId?: string | HookHandler,
        ): ModelStatic<T>;
        createView(
            viewName: string,
            definition?: ModelViewDefinition,
            options?: Record<string, unknown>,
        ): Promise<void>;
        createMaterializedView(
            viewName: string,
            definition?: ModelViewDefinition,
            options?: Record<string, unknown>,
        ): Promise<void>;
        dropView(
            viewName: string,
            options?: Record<string, unknown>,
        ): Promise<void>;
    }

    Type Parameters

    Hierarchy (View Summary)

    Index
    name: string
    tableName: string
    schema?: string

    Schema the model belongs to

    rawAttributes: Record<string, AttributeOptions>
    associations: Record<string, Association>
    isNewRecord: false

    Static property indicating this is a model class (always false for static check)

    isMaterializedView?: boolean

    Check if this model is a materialized view

    True if the model is a materialized view

    • Drop a policy from this model's table.

      Parameters

      • name: string
      • Optionaloptions: { ifExists?: boolean }

      Returns Promise<void>

    • Drop a trigger from this model's table.

      Parameters

      • name: string
      • Optionaloptions: { ifExists?: boolean }

      Returns Promise<void>

    • Build a WHERE condition using operator symbols

      Parameters

      • field: string
      • operator: unknown
      • Optionalvalue: unknown

      Returns WhereOptions

      // Simple equality
      User.where('status', 'active')
      // => { status: 'active' }

      // With operator
      User.where('age', Op.gte, 18)
      // => { age: { $gte: 18 } }

      // Using with findAll
      User.findAll({ where: User.where('status', 'active') })
    • Find all records matching the given options and return both rows and total count

      Parameters

      Returns Promise<{ rows: T[]; count: number }>

      Object with rows array and count total

      // Basic find and count all
      const result = await User.findAndCountAll();
      console.log(result.count); // total number of matching records
      console.log(result.rows); // array of model instances
      // With pagination - get 10 records starting from record 20
      const result = await User.findAndCountAll({
      limit: 10,
      offset: 20,
      where: { status: 'active' }
      });
      // With subquery optimization
      const result = await User.findAndCountAll({
      include: [{ model: Post, where: { status: 'published' } }],
      subquery: false
      });
    • Parameters

      Returns Promise<number>

    • COUNT() as window function - counts rows or non-null values

      Parameters

      • Optionaloptions: WindowFunctionOptions & { countField?: string }

        Window function options (partitionBy, orderBy, windowFrame, countField)

      Returns any

      The count value

      const users = await User.findAll({
      attributes: [[User.count({ partitionBy: 'department' }), 'deptCount']]
      });
    • Parameters

      Returns Promise<number>

    • AVG() as window function - calculates average in a partition

      Parameters

      • field: string

        The field to average

      • Optionaloptions: WindowFunctionOptions

        Window function options (partitionBy, orderBy, windowFrame)

      Returns any

      The average value

      const orders = await Order.findAll({
      attributes: [[Order.avg('amount', { partitionBy: 'customerId' }), 'avgOrder']]
      });
    • Parameters

      Returns Promise<any>

    • MAX() as window function - returns maximum value in a partition

      Parameters

      • field: string

        The field to find maximum

      • Optionaloptions: WindowFunctionOptions

        Window function options (partitionBy, orderBy, windowFrame)

      Returns any

      The maximum value

      const orders = await Order.findAll({
      attributes: [[Order.max('amount', { partitionBy: 'customerId' }), 'maxOrder']]
      });
    • Parameters

      Returns Promise<any>

    • MIN() as window function - returns minimum value in a partition

      Parameters

      • field: string

        The field to find minimum

      • Optionaloptions: WindowFunctionOptions

        Window function options (partitionBy, orderBy, windowFrame)

      Returns any

      The minimum value

      const orders = await Order.findAll({
      attributes: [[Order.min('amount', { partitionBy: 'customerId' }), 'minOrder']]
      });
    • Parameters

      Returns Promise<number>

    • SUM() as window function - sums values in a partition

      Parameters

      • field: string

        The field to sum

      • Optionaloptions: WindowFunctionOptions

        Window function options (partitionBy, orderBy, windowFrame)

      Returns any

      The sum value

      const orders = await Order.findAll({
      attributes: [[Order.sum('amount', { partitionBy: 'customerId', orderBy: 'orderDate' }), 'runningTotal']]
      });
    • ROW_NUMBER() - Returns the row number within the partition

      Parameters

      Returns number

      The row number

      // Get row numbers partitioned by category
      const users = await User.findAll({
      attributes: [[User.rowNumber({ partitionBy: 'department', orderBy: ['createdAt', 'DESC'] }), 'rowNum']]
      });
    • RANK() - Returns the rank of the current row within the partition (with gaps)

      Parameters

      Returns number

      The rank value

      const users = await User.findAll({
      attributes: [[User.rank({ orderBy: ['score', 'DESC'] }), 'rank']]
      });
    • DENSE_RANK() - Returns the rank of the current row within the partition (without gaps)

      Parameters

      Returns number

      The dense rank value

      const users = await User.findAll({
      attributes: [[User.denseRank({ orderBy: ['score', 'DESC'] }), 'denseRank']]
      });
    • LAG() - Returns the value from the preceding row in the partition

      Parameters

      • field: string

        The field to get value from

      • Optionaloptions: WindowFunctionOptions

        Window function options (partitionBy, orderBy, windowFrame)

      Returns any

      The value from the preceding row

      const users = await User.findAll({
      attributes: [[User.lag('salary', { partitionBy: 'department', orderBy: 'hireDate' }), 'prevSalary']]
      });
    • LEAD() - Returns the value from the following row in the partition

      Parameters

      • field: string

        The field to get value from

      • Optionaloptions: WindowFunctionOptions

        Window function options (partitionBy, orderBy, windowFrame)

      Returns any

      The value from the following row

      const users = await User.findAll({
      attributes: [[User.lead('salary', { partitionBy: 'department', orderBy: 'hireDate' }), 'nextSalary']]
      });
    • FIRST_VALUE() - Returns the first value in the partition

      Parameters

      • field: string

        The field to get first value from

      • Optionaloptions: WindowFunctionOptions

        Window function options (partitionBy, orderBy, windowFrame)

      Returns any

      The first value in the partition

      const users = await User.findAll({
      attributes: [[User.firstValue('salary', { partitionBy: 'department', orderBy: 'hireDate' }), 'firstSalary']]
      });
    • LAST_VALUE() - Returns the last value in the partition

      Parameters

      • field: string

        The field to get last value from

      • Optionaloptions: WindowFunctionOptions

        Window function options (partitionBy, orderBy, windowFrame)

      Returns any

      The last value in the partition

      const users = await User.findAll({
      attributes: [[User.lastValue('salary', { partitionBy: 'department', orderBy: 'hireDate' }), 'lastSalary']]
      });
    • NTH_VALUE() - Returns the nth value in the partition

      Parameters

      • field: string

        The field to get nth value from

      • n: number

        The position (1-based)

      • Optionaloptions: WindowFunctionOptions

        Window function options (partitionBy, orderBy, windowFrame)

      Returns any

      The nth value in the partition

      const users = await User.findAll({
      attributes: [[User.nthValue('salary', 2, { partitionBy: 'department', orderBy: 'hireDate' }), 'secondSalary']]
      });
    • NTILE() - Distributes rows into n buckets

      Parameters

      • n: number

        Number of buckets

      • Optionaloptions: WindowFunctionOptions

        Window function options (partitionBy, orderBy)

      Returns any

      The bucket number (1 to n)

      const users = await User.findAll({
      attributes: [[User.ntile(4, { partitionBy: 'department', orderBy: 'salary' }), 'quartile']]
      });
    • PERCENT_RANK() - Returns the relative rank of a row (0 to 1)

      Parameters

      Returns any

      The percent rank value

      const users = await User.findAll({
      attributes: [[User.percentRank({ orderBy: ['score', 'DESC'] }), 'pctRank']]
      });
    • CUME_DIST() - Returns the cumulative distribution (0 to 1)

      Parameters

      Returns any

      The cumulative distribution value

      const users = await User.findAll({
      attributes: [[User.cumeDist({ orderBy: ['score', 'DESC'] }), 'cumeDist']]
      });
    • Generate a window function SQL expression for use in queries

      Parameters

      • functionName: string

        The window function name (ROW_NUMBER, RANK, etc.)

      • args: any[]

        Arguments to the window function

      • options: WindowFunctionOptions

        Window function options

      Returns { sql: string; values: any[] }

      Object with sql and values for the window function

      const expr = User.windowFunction('ROW_NUMBER', [], { partitionBy: 'department', orderBy: ['createdAt', 'DESC'] });
      
    • Find a record by the given where clause, or create it if not found

      Parameters

      • options: FindOptions & { defaults?: Partial<T> }

        Find options with where clause and defaults for creation

      Returns Promise<[T, boolean]>

      A tuple of [instance, created] where created is true if a new record was created

      const [user, created] = await User.findOrCreate({
      where: { email: 'test@test.com' },
      defaults: { name: 'Test User' }
      });
    • Find a record by the given where clause, or build (but not save) it if not found

      Parameters

      • options: FindOptions & { defaults?: Partial<T> }

        Find options with where clause and defaults for building

      Returns Promise<[T, boolean]>

      A tuple of [instance, created] where created is true if a new instance was built

      const [user, created] = await User.findOrBuild({
      where: { email: 'test@test.com' },
      defaults: { name: 'Test User' }
      });
    • Find a record by the given where clause, or build (but not save) it if not found Alias for findOrBuild

      Parameters

      Returns Promise<[T, boolean]>

    • Refresh a materialized view (PostgreSQL only)

      Parameters

      Returns Promise<void>

      Promise

      // Simple refresh
      await User.refresh();

      // Concurrent refresh (requires unique index)
      await User.refresh({ concurrently: true });

      // Refresh without data
      await User.refresh({ withNoData: true });
    • Check if a hook is registered

      Parameters

      • hookName: string

        Name of the hook

      Returns boolean

      True if hook is registered

    • Drop a view created from this model.

      Parameters

      • viewName: string
      • Optionaloptions: Record<string, unknown>

      Returns Promise<void>