db.d.cts 12 KB

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