UNPKG

@mikro-orm/core

Version:

TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.

137 lines (136 loc) 7.33 kB
import type { AnyString, Dictionary, EntityKey } from '../typings.js'; declare const rawFragmentSymbolBrand: unique symbol; /** Branded symbol type used as a unique key for tracking raw SQL fragments in object properties. */ export type RawQueryFragmentSymbol = symbol & { readonly [rawFragmentSymbolBrand]: true; }; /** Checks whether the given value is a `RawQueryFragment` instance. */ export declare function isRaw(value: unknown): value is RawQueryFragment; /** Represents a raw SQL fragment with optional parameters, usable as both a value and an object key via Symbol coercion. */ export declare class RawQueryFragment<Alias extends string = string> { #private; readonly sql: string; readonly params: unknown[]; /** @internal Type-level only - used to track the alias for type inference */ private readonly __alias?; constructor(sql: string, params?: unknown[]); /** Returns a unique symbol key for this fragment, creating and caching it on first access. */ get key(): RawQueryFragmentSymbol; /** Creates a new fragment with an alias appended via `as ??`. */ as<A extends string>(alias: A): RawQueryFragment<A>; [Symbol.toPrimitive](hint: 'string'): RawQueryFragmentSymbol; get [Symbol.toStringTag](): string; toJSON(): string; clone(): this; /** Checks whether the given value is a symbol that maps to a known raw query fragment. */ static isKnownFragmentSymbol(key: unknown): key is RawQueryFragmentSymbol; /** Checks whether an object has any symbol keys that are known raw query fragments. */ static hasObjectFragments(object: unknown): boolean; /** Checks whether the given value is a RawQueryFragment instance or a known fragment symbol. */ static isKnownFragment(key: unknown): key is RawQueryFragment | symbol; /** Retrieves the RawQueryFragment associated with the given key (instance or symbol). */ static getKnownFragment(key: unknown): RawQueryFragment | undefined; } export { RawQueryFragment as Raw }; /** @internal */ export declare const ALIAS_REPLACEMENT = "[::alias::]"; /** @internal */ export declare const ALIAS_REPLACEMENT_RE = "\\[::alias::\\]"; /** * Creates raw SQL query fragment that can be assigned to a property or part of a filter. This fragment is represented * by `RawQueryFragment` class instance that can be serialized to a string, so it can be used both as an object value * and key. When serialized, the fragment key gets cached and only such cached key will be recognized by the ORM. * This adds a runtime safety to the raw query fragments. * * > **`raw()` helper is required since v6 to use a raw fragment in your query, both through EntityManager and QueryBuilder.** * * ```ts * // as a value * await em.find(User, { time: raw('now()') }); * * // as a key * await em.find(User, { [raw('lower(name)')]: name.toLowerCase() }); * * // value can be empty array * await em.find(User, { [raw('(select 1 = 1)')]: [] }); * ``` * * The `raw` helper supports several signatures, you can pass in a callback that receives the current property alias: * * ```ts * await em.find(User, { [raw(alias => `lower(${alias}.name)`)]: name.toLowerCase() }); * ``` * * You can also use the `sql` tagged template function, which works the same, but supports only the simple string signature: * * ```ts * await em.find(User, { [sql`lower(name)`]: name.toLowerCase() }); * ``` * * When using inside filters, you might have to use a callback signature to create new raw instance for every filter usage. * * ```ts * @Filter({ name: 'long', cond: () => ({ [raw('length(perex)')]: { $gt: 10000 } }) }) * ``` * * The `raw` helper can be used within indexes and uniques to write database-agnostic SQL expressions. In that case, you can use `'??'` to tag your database identifiers (table name, column names, index name, ...) inside your expression, and pass those identifiers as a second parameter to the `raw` helper. Internally, those will automatically be quoted according to the database in use: * * ```ts * // On postgres, will produce: create index "index custom_idx_on_name" on "library.author" ("country") * // On mysql, will produce: create index `index custom_idx_on_name` on `library.author` (`country`) * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => raw(`create index ?? on ?? (??)`, ['custom_idx_on_name', table, columns.name]) }) * @Entity({ schema: 'library' }) * export class Author { ... } * ``` * * You can also use the `quote` tag function to write database-agnostic SQL expressions. The end-result is the same as using the `raw` function regarding database identifiers quoting, only to have a more elegant expression syntax: * * ```ts * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => quote`create index ${'custom_idx_on_name'} on ${table} (${columns.name})` }) * @Entity({ schema: 'library' }) * export class Author { ... } * ``` */ export declare function raw<R = RawQueryFragment & symbol, T extends object = any>(sql: EntityKey<T> | EntityKey<T>[] | AnyString | ((alias: string) => string) | RawQueryFragment, params?: readonly unknown[] | Dictionary<unknown>): R; /** * Alternative to the `raw()` helper allowing to use it as a tagged template function for the simple cases. * * ```ts * // as a value * await em.find(User, { time: sql`now()` }); * * // as a key * await em.find(User, { [sql`lower(name)`]: name.toLowerCase() }); * * // value can be empty array * await em.find(User, { [sql`(select 1 = 1)`]: [] }); * * // with type parameter for assignment without casting * entity.date = sql<Date>`now()`; * ``` */ export declare function sql<R = RawQueryFragment & symbol>(sql: readonly string[], ...values: unknown[]): R; export declare namespace sql { var ref: <T extends object = any>(...keys: string[]) => RawQueryFragment & symbol; var now: (length?: number) => RawQueryFragment & symbol; var lower: <R = RawQueryFragment<string> & symbol, T extends object = any>(key: string | ((alias: string) => string)) => R; var upper: <R = RawQueryFragment<string> & symbol, T extends object = any>(key: string | ((alias: string) => string)) => R; } /** Creates a raw SQL function expression wrapping the given key (e.g., `lower(name)`). */ export declare function createSqlFunction<R = RawQueryFragment & symbol, T extends object = any>(func: string, key: string | ((alias: string) => string)): R; /** * Tag function providing quoting of db identifiers (table name, columns names, index names, ...). * * Within the template literal on which the tag function is applied, all placeholders are considered to be database identifiers, and will thus be quoted as so according to the database in use. * * ```ts * // On postgres, will produce: create index "index custom_idx_on_name" on "library.author" ("name") * // On mysql, will produce: create index `index custom_idx_on_name` on `library.author` (`name`) * @Index({ name: 'custom_idx_on_name', expression: (table, columns, indexName) => quote`create index ${indexName} on ${table} (${columns.name})` }) * @Entity({ schema: 'library' }) * export class Author { ... } * ``` */ export declare function quote(expParts: readonly string[], ...values: (string | { toString(): string; })[]): RawQueryFragment & symbol;