db.d.cts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import type { Cache } from "../cache/core/cache.cjs";
  2. import { entityKind } from "../entity.cjs";
  3. import type { GelDialect } from "./dialect.cjs";
  4. import { GelDeleteBase, GelInsertBuilder, GelSelectBuilder, GelUpdateBuilder, QueryBuilder } from "./query-builders/index.cjs";
  5. import type { GelQueryResultHKT, GelSession, GelTransaction } from "./session.cjs";
  6. import type { GelTable } from "./table.cjs";
  7. import type { TypedQueryBuilder } from "../query-builders/query-builder.cjs";
  8. import type { ExtractTablesWithRelations, RelationalSchemaConfig, TablesRelationalConfig } from "../relations.cjs";
  9. import { type ColumnsSelection, type SQL, type SQLWrapper } from "../sql/sql.cjs";
  10. import { WithSubquery } from "../subquery.cjs";
  11. import type { DrizzleTypeError } from "../utils.cjs";
  12. import type { GelColumn } from "./columns/index.cjs";
  13. import { GelCountBuilder } from "./query-builders/count.cjs";
  14. import { RelationalQueryBuilder } from "./query-builders/query.cjs";
  15. import { GelRaw } from "./query-builders/raw.cjs";
  16. import type { SelectedFields } from "./query-builders/select.types.cjs";
  17. import type { WithSubqueryWithSelection } from "./subquery.cjs";
  18. import type { GelViewBase } from "./view-base.cjs";
  19. export declare class GelDatabase<TQueryResult extends GelQueryResultHKT, TFullSchema extends Record<string, unknown> = Record<string, never>, TSchema extends TablesRelationalConfig = ExtractTablesWithRelations<TFullSchema>> {
  20. static readonly [entityKind]: string;
  21. readonly _: {
  22. readonly schema: TSchema | undefined;
  23. readonly fullSchema: TFullSchema;
  24. readonly tableNamesMap: Record<string, string>;
  25. readonly session: GelSession<TQueryResult, TFullSchema, TSchema>;
  26. };
  27. query: TFullSchema extends Record<string, never> ? DrizzleTypeError<'Seems like the schema generic is missing - did you forget to add it to your DB type?'> : {
  28. [K in keyof TSchema]: RelationalQueryBuilder<TSchema, TSchema[K]>;
  29. };
  30. constructor(
  31. /** @internal */
  32. dialect: GelDialect,
  33. /** @internal */
  34. session: GelSession<any, any, any>, schema: RelationalSchemaConfig<TSchema> | undefined);
  35. /**
  36. * Creates a subquery that defines a temporary named result set as a CTE.
  37. *
  38. * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
  39. *
  40. * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
  41. *
  42. * @param alias The alias for the subquery.
  43. *
  44. * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
  45. *
  46. * @example
  47. *
  48. * ```ts
  49. * // Create a subquery with alias 'sq' and use it in the select query
  50. * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
  51. *
  52. * const result = await db.with(sq).select().from(sq);
  53. * ```
  54. *
  55. * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
  56. *
  57. * ```ts
  58. * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
  59. * const sq = db.$with('sq').as(db.select({
  60. * name: sql<string>`upper(${users.name})`.as('name'),
  61. * })
  62. * .from(users));
  63. *
  64. * const result = await db.with(sq).select({ name: sq.name }).from(sq);
  65. * ```
  66. */
  67. $with<TAlias extends string>(alias: TAlias): {
  68. as<TSelection extends ColumnsSelection>(qb: TypedQueryBuilder<TSelection> | ((qb: QueryBuilder) => TypedQueryBuilder<TSelection>)): WithSubqueryWithSelection<TSelection, TAlias>;
  69. };
  70. $count(source: GelTable | GelViewBase | SQL | SQLWrapper, filters?: SQL<unknown>): GelCountBuilder<GelSession<any, any, any>>;
  71. /**
  72. * Incorporates a previously defined CTE (using `$with`) into the main query.
  73. *
  74. * This method allows the main query to reference a temporary named result set.
  75. *
  76. * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
  77. *
  78. * @param queries The CTEs to incorporate into the main query.
  79. *
  80. * @example
  81. *
  82. * ```ts
  83. * // Define a subquery 'sq' as a CTE using $with
  84. * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
  85. *
  86. * // Incorporate the CTE 'sq' into the main query and select from it
  87. * const result = await db.with(sq).select().from(sq);
  88. * ```
  89. */
  90. with(...queries: WithSubquery[]): {
  91. select: {
  92. (): GelSelectBuilder<undefined>;
  93. <TSelection extends SelectedFields>(fields: TSelection): GelSelectBuilder<TSelection>;
  94. };
  95. selectDistinct: {
  96. (): GelSelectBuilder<undefined>;
  97. <TSelection extends SelectedFields>(fields: TSelection): GelSelectBuilder<TSelection>;
  98. };
  99. selectDistinctOn: {
  100. (on: (GelColumn | SQLWrapper)[]): GelSelectBuilder<undefined>;
  101. <TSelection extends SelectedFields>(on: (GelColumn | SQLWrapper)[], fields: TSelection): GelSelectBuilder<TSelection>;
  102. };
  103. update: <TTable extends GelTable>(table: TTable) => GelUpdateBuilder<TTable, TQueryResult>;
  104. insert: <TTable extends GelTable>(table: TTable) => GelInsertBuilder<TTable, TQueryResult>;
  105. delete: <TTable extends GelTable>(table: TTable) => GelDeleteBase<TTable, TQueryResult>;
  106. };
  107. /**
  108. * Creates a select query.
  109. *
  110. * Calling this method with no arguments will select all columns from the table. Pass a selection object to specify the columns you want to select.
  111. *
  112. * Use `.from()` method to specify which table to select from.
  113. *
  114. * See docs: {@link https://orm.drizzle.team/docs/select}
  115. *
  116. * @param fields The selection object.
  117. *
  118. * @example
  119. *
  120. * ```ts
  121. * // Select all columns and all rows from the 'cars' table
  122. * const allCars: Car[] = await db.select().from(cars);
  123. *
  124. * // Select specific columns and all rows from the 'cars' table
  125. * const carsIdsAndBrands: { id: number; brand: string }[] = await db.select({
  126. * id: cars.id,
  127. * brand: cars.brand
  128. * })
  129. * .from(cars);
  130. * ```
  131. *
  132. * Like in SQL, you can use arbitrary expressions as selection fields, not just table columns:
  133. *
  134. * ```ts
  135. * // Select specific columns along with expression and all rows from the 'cars' table
  136. * const carsIdsAndLowerNames: { id: number; lowerBrand: string }[] = await db.select({
  137. * id: cars.id,
  138. * lowerBrand: sql<string>`lower(${cars.brand})`,
  139. * })
  140. * .from(cars);
  141. * ```
  142. */
  143. select(): GelSelectBuilder<undefined>;
  144. select<TSelection extends SelectedFields>(fields: TSelection): GelSelectBuilder<TSelection>;
  145. /**
  146. * Adds `distinct` expression to the select query.
  147. *
  148. * Calling this method will return only unique values. When multiple columns are selected, it returns rows with unique combinations of values in these columns.
  149. *
  150. * Use `.from()` method to specify which table to select from.
  151. *
  152. * See docs: {@link https://orm.drizzle.team/docs/select#distinct}
  153. *
  154. * @param fields The selection object.
  155. *
  156. * @example
  157. * ```ts
  158. * // Select all unique rows from the 'cars' table
  159. * await db.selectDistinct()
  160. * .from(cars)
  161. * .orderBy(cars.id, cars.brand, cars.color);
  162. *
  163. * // Select all unique brands from the 'cars' table
  164. * await db.selectDistinct({ brand: cars.brand })
  165. * .from(cars)
  166. * .orderBy(cars.brand);
  167. * ```
  168. */
  169. selectDistinct(): GelSelectBuilder<undefined>;
  170. selectDistinct<TSelection extends SelectedFields>(fields: TSelection): GelSelectBuilder<TSelection>;
  171. /**
  172. * Adds `distinct on` expression to the select query.
  173. *
  174. * Calling this method will specify how the unique rows are determined.
  175. *
  176. * Use `.from()` method to specify which table to select from.
  177. *
  178. * See docs: {@link https://orm.drizzle.team/docs/select#distinct}
  179. *
  180. * @param on The expression defining uniqueness.
  181. * @param fields The selection object.
  182. *
  183. * @example
  184. * ```ts
  185. * // Select the first row for each unique brand from the 'cars' table
  186. * await db.selectDistinctOn([cars.brand])
  187. * .from(cars)
  188. * .orderBy(cars.brand);
  189. *
  190. * // Selects the first occurrence of each unique car brand along with its color from the 'cars' table
  191. * await db.selectDistinctOn([cars.brand], { brand: cars.brand, color: cars.color })
  192. * .from(cars)
  193. * .orderBy(cars.brand, cars.color);
  194. * ```
  195. */
  196. selectDistinctOn(on: (GelColumn | SQLWrapper)[]): GelSelectBuilder<undefined>;
  197. selectDistinctOn<TSelection extends SelectedFields>(on: (GelColumn | SQLWrapper)[], fields: TSelection): GelSelectBuilder<TSelection>;
  198. $cache: {
  199. invalidate: Cache['onMutate'];
  200. };
  201. /**
  202. * Creates an update query.
  203. *
  204. * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
  205. *
  206. * Use `.set()` method to specify which values to update.
  207. *
  208. * See docs: {@link https://orm.drizzle.team/docs/update}
  209. *
  210. * @param table The table to update.
  211. *
  212. * @example
  213. *
  214. * ```ts
  215. * // Update all rows in the 'cars' table
  216. * await db.update(cars).set({ color: 'red' });
  217. *
  218. * // Update rows with filters and conditions
  219. * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
  220. *
  221. * // Update with returning clause
  222. * const updatedCar: Car[] = await db.update(cars)
  223. * .set({ color: 'red' })
  224. * .where(eq(cars.id, 1))
  225. * .returning();
  226. * ```
  227. */
  228. update<TTable extends GelTable>(table: TTable): GelUpdateBuilder<TTable, TQueryResult>;
  229. /**
  230. * Creates an insert query.
  231. *
  232. * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
  233. *
  234. * See docs: {@link https://orm.drizzle.team/docs/insert}
  235. *
  236. * @param table The table to insert into.
  237. *
  238. * @example
  239. *
  240. * ```ts
  241. * // Insert one row
  242. * await db.insert(cars).values({ brand: 'BMW' });
  243. *
  244. * // Insert multiple rows
  245. * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
  246. *
  247. * // Insert with returning clause
  248. * const insertedCar: Car[] = await db.insert(cars)
  249. * .values({ brand: 'BMW' })
  250. * .returning();
  251. * ```
  252. */
  253. insert<TTable extends GelTable>(table: TTable): GelInsertBuilder<TTable, TQueryResult>;
  254. /**
  255. * Creates a delete query.
  256. *
  257. * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
  258. *
  259. * See docs: {@link https://orm.drizzle.team/docs/delete}
  260. *
  261. * @param table The table to delete from.
  262. *
  263. * @example
  264. *
  265. * ```ts
  266. * // Delete all rows in the 'cars' table
  267. * await db.delete(cars);
  268. *
  269. * // Delete rows with filters and conditions
  270. * await db.delete(cars).where(eq(cars.color, 'green'));
  271. *
  272. * // Delete with returning clause
  273. * const deletedCar: Car[] = await db.delete(cars)
  274. * .where(eq(cars.id, 1))
  275. * .returning();
  276. * ```
  277. */
  278. delete<TTable extends GelTable>(table: TTable): GelDeleteBase<TTable, TQueryResult>;
  279. execute<TRow extends Record<string, unknown> = Record<string, unknown>>(query: SQLWrapper | string): GelRaw<TRow[]>;
  280. transaction<T>(transaction: (tx: GelTransaction<TQueryResult, TFullSchema, TSchema>) => Promise<T>): Promise<T>;
  281. }
  282. export type GelWithReplicas<Q> = Q & {
  283. $primary: Q;
  284. $replicas: Q[];
  285. };
  286. export declare const withReplicas: <HKT extends GelQueryResultHKT, TFullSchema extends Record<string, unknown>, TSchema extends TablesRelationalConfig, Q extends GelDatabase<HKT, TFullSchema, TSchema extends Record<string, unknown> ? ExtractTablesWithRelations<TFullSchema> : TSchema>>(primary: Q, replicas: [Q, ...Q[]], getReplica?: (replicas: Q[]) => Q) => GelWithReplicas<Q>;