db.d.ts 10 KB

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