@encore.dev/sdk 2.0.0-beta.6 → 2.0.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (356) hide show
  1. package/README.md +55 -0
  2. package/app_meta.ts +8 -0
  3. package/config/config.test.ts +10 -3
  4. package/config/config.ts +75 -21
  5. package/config/mod.ts +4 -3
  6. package/config/secrets.ts +72 -55
  7. package/cron/mod.ts +32 -0
  8. package/dist/app_meta.d.ts +7 -0
  9. package/dist/app_meta.d.ts.map +1 -0
  10. package/dist/app_meta.js +1 -0
  11. package/dist/app_meta.js.map +1 -1
  12. package/dist/config/config.d.ts +44 -18
  13. package/dist/config/config.d.ts.map +1 -0
  14. package/dist/config/config.js +43 -18
  15. package/dist/config/config.js.map +1 -1
  16. package/dist/config/mod.d.ts +5 -4
  17. package/dist/config/mod.d.ts.map +1 -0
  18. package/dist/config/mod.js +2 -2
  19. package/dist/config/mod.js.map +1 -1
  20. package/dist/config/secrets.d.ts +62 -39
  21. package/dist/config/secrets.d.ts.map +1 -0
  22. package/dist/config/secrets.js +21 -37
  23. package/dist/config/secrets.js.map +1 -1
  24. package/dist/config/value.d.ts +1 -0
  25. package/dist/config/value.d.ts.map +1 -0
  26. package/dist/cron/mod.d.ts +31 -0
  27. package/dist/cron/mod.d.ts.map +1 -0
  28. package/dist/cron/mod.js +23 -0
  29. package/dist/cron/mod.js.map +1 -1
  30. package/dist/gateway/errors.d.ts +101 -0
  31. package/dist/gateway/errors.d.ts.map +1 -0
  32. package/dist/gateway/errors.js +146 -0
  33. package/dist/gateway/errors.js.map +1 -0
  34. package/dist/gateway/match.d.ts +127 -0
  35. package/dist/gateway/match.d.ts.map +1 -0
  36. package/dist/gateway/match.js +206 -0
  37. package/dist/gateway/match.js.map +1 -0
  38. package/dist/gateway/middleware.d.ts +108 -0
  39. package/dist/gateway/middleware.d.ts.map +1 -0
  40. package/dist/gateway/middleware.js +9 -0
  41. package/dist/gateway/middleware.js.map +1 -0
  42. package/dist/gateway/mod.d.ts +129 -0
  43. package/dist/gateway/mod.d.ts.map +1 -0
  44. package/dist/gateway/mod.js +187 -0
  45. package/dist/gateway/mod.js.map +1 -0
  46. package/dist/gateway/request.d.ts +304 -0
  47. package/dist/gateway/request.d.ts.map +1 -0
  48. package/dist/gateway/request.js +403 -0
  49. package/dist/gateway/request.js.map +1 -0
  50. package/dist/gateway/serve.d.ts +114 -0
  51. package/dist/gateway/serve.d.ts.map +1 -0
  52. package/dist/gateway/serve.js +510 -0
  53. package/dist/gateway/serve.js.map +1 -0
  54. package/dist/internal/clients/call.d.ts +147 -0
  55. package/dist/internal/clients/call.d.ts.map +1 -0
  56. package/dist/internal/clients/call.js +274 -0
  57. package/dist/internal/clients/call.js.map +1 -0
  58. package/dist/internal/clients/grpc.d.ts +90 -0
  59. package/dist/internal/clients/grpc.d.ts.map +1 -0
  60. package/dist/internal/clients/grpc.js +355 -0
  61. package/dist/internal/clients/grpc.js.map +1 -0
  62. package/dist/internal/clients/mod.d.ts +81 -0
  63. package/dist/internal/clients/mod.d.ts.map +1 -0
  64. package/dist/internal/clients/mod.js +237 -0
  65. package/dist/internal/clients/mod.js.map +1 -0
  66. package/dist/internal/fetch.d.ts +54 -0
  67. package/dist/internal/fetch.d.ts.map +1 -0
  68. package/dist/internal/fetch.js +240 -0
  69. package/dist/internal/fetch.js.map +1 -0
  70. package/dist/internal/otel/backend.d.ts +2 -0
  71. package/dist/internal/otel/backend.d.ts.map +1 -0
  72. package/dist/internal/otel/context.d.ts +1 -0
  73. package/dist/internal/otel/context.d.ts.map +1 -0
  74. package/dist/internal/otel/context_manager.d.ts +1 -0
  75. package/dist/internal/otel/context_manager.d.ts.map +1 -0
  76. package/dist/internal/otel/encode.d.ts +2 -0
  77. package/dist/internal/otel/encode.d.ts.map +1 -0
  78. package/dist/internal/otel/index.d.ts +2 -2
  79. package/dist/internal/otel/index.d.ts.map +1 -0
  80. package/dist/internal/otel/index.js +1 -2
  81. package/dist/internal/otel/index.js.map +1 -1
  82. package/dist/internal/otel/meter.d.ts +1 -0
  83. package/dist/internal/otel/meter.d.ts.map +1 -0
  84. package/dist/internal/otel/propagator.d.ts +1 -0
  85. package/dist/internal/otel/propagator.d.ts.map +1 -0
  86. package/dist/internal/otel/provider.d.ts +1 -0
  87. package/dist/internal/otel/provider.d.ts.map +1 -0
  88. package/dist/internal/otel/span.d.ts +4 -0
  89. package/dist/internal/otel/span.d.ts.map +1 -0
  90. package/dist/internal/otel/span.js +5 -0
  91. package/dist/internal/otel/span.js.map +1 -1
  92. package/dist/internal/otel/tracer.d.ts +1 -0
  93. package/dist/internal/otel/tracer.d.ts.map +1 -0
  94. package/dist/internal/otel/tracer.js +11 -5
  95. package/dist/internal/otel/tracer.js.map +1 -1
  96. package/dist/internal/reqfields.d.ts +150 -0
  97. package/dist/internal/reqfields.d.ts.map +1 -0
  98. package/dist/internal/reqfields.js +312 -0
  99. package/dist/internal/reqfields.js.map +1 -0
  100. package/dist/internal/runtime/meter.d.ts +1 -0
  101. package/dist/internal/runtime/meter.d.ts.map +1 -0
  102. package/dist/internal/runtime/mod.d.ts +6 -0
  103. package/dist/internal/runtime/mod.d.ts.map +1 -0
  104. package/dist/internal/runtime/mod.js +32 -2
  105. package/dist/internal/runtime/mod.js.map +1 -1
  106. package/dist/internal/runtime/napi/napi.cjs +160 -16
  107. package/dist/internal/runtime/napi/napi.d.cts +474 -29
  108. package/dist/internal/runtime/shutdown.d.ts +5 -0
  109. package/dist/internal/runtime/shutdown.d.ts.map +1 -0
  110. package/dist/internal/runtime/shutdown.js +9 -1
  111. package/dist/internal/runtime/shutdown.js.map +1 -1
  112. package/dist/internal/testing/runner.d.ts +2 -0
  113. package/dist/internal/testing/runner.d.ts.map +1 -0
  114. package/dist/internal/testing/runner.js +10 -0
  115. package/dist/internal/testing/runner.js.map +1 -0
  116. package/dist/internal/testing/scope.d.ts +81 -0
  117. package/dist/internal/testing/scope.d.ts.map +1 -0
  118. package/dist/internal/testing/scope.js +237 -0
  119. package/dist/internal/testing/scope.js.map +1 -0
  120. package/dist/internal/utils/constraints.d.ts +1 -0
  121. package/dist/internal/utils/constraints.d.ts.map +1 -0
  122. package/dist/log/index.d.ts +1 -0
  123. package/dist/log/index.d.ts.map +1 -0
  124. package/dist/log/logger.d.ts +2 -0
  125. package/dist/log/logger.d.ts.map +1 -0
  126. package/dist/log/runtime.d.ts +2 -0
  127. package/dist/log/runtime.d.ts.map +1 -0
  128. package/dist/log/stderr.d.ts +1 -0
  129. package/dist/log/stderr.d.ts.map +1 -0
  130. package/dist/metrics/mod.d.ts +45 -118
  131. package/dist/metrics/mod.d.ts.map +1 -0
  132. package/dist/metrics/mod.js +44 -179
  133. package/dist/metrics/mod.js.map +1 -1
  134. package/dist/mod.d.ts +1 -2
  135. package/dist/mod.d.ts.map +1 -0
  136. package/dist/mod.js +0 -1
  137. package/dist/mod.js.map +1 -1
  138. package/dist/otel.d.ts +1 -0
  139. package/dist/otel.d.ts.map +1 -0
  140. package/dist/pubsub/encoding.d.ts +5 -0
  141. package/dist/pubsub/encoding.d.ts.map +1 -0
  142. package/dist/pubsub/encoding.js +10 -2
  143. package/dist/pubsub/encoding.js.map +1 -1
  144. package/dist/pubsub/mod.d.ts +4 -3
  145. package/dist/pubsub/mod.d.ts.map +1 -0
  146. package/dist/pubsub/mod.js +2 -2
  147. package/dist/pubsub/mod.js.map +1 -1
  148. package/dist/pubsub/refs.d.ts +8 -0
  149. package/dist/pubsub/refs.d.ts.map +1 -0
  150. package/dist/pubsub/refs.js.map +1 -1
  151. package/dist/pubsub/subscription.d.ts +104 -10
  152. package/dist/pubsub/subscription.d.ts.map +1 -0
  153. package/dist/pubsub/subscription.js +98 -16
  154. package/dist/pubsub/subscription.js.map +1 -1
  155. package/dist/pubsub/topic.d.ts +87 -23
  156. package/dist/pubsub/topic.d.ts.map +1 -0
  157. package/dist/pubsub/topic.js +143 -40
  158. package/dist/pubsub/topic.js.map +1 -1
  159. package/dist/reqctx/mod.d.ts +191 -0
  160. package/dist/reqctx/mod.d.ts.map +1 -0
  161. package/dist/reqctx/mod.js +160 -0
  162. package/dist/reqctx/mod.js.map +1 -0
  163. package/dist/services/index.d.ts +145 -4
  164. package/dist/services/index.d.ts.map +1 -0
  165. package/dist/services/index.js +155 -8
  166. package/dist/services/index.js.map +1 -1
  167. package/dist/shutdown/mod.d.ts +1 -0
  168. package/dist/shutdown/mod.d.ts.map +1 -0
  169. package/dist/storage/objects/bucket.d.ts +312 -7
  170. package/dist/storage/objects/bucket.d.ts.map +1 -0
  171. package/dist/storage/objects/bucket.js +305 -15
  172. package/dist/storage/objects/bucket.js.map +1 -1
  173. package/dist/storage/objects/error.d.ts +10 -0
  174. package/dist/storage/objects/error.d.ts.map +1 -0
  175. package/dist/storage/objects/error.js +25 -1
  176. package/dist/storage/objects/error.js.map +1 -1
  177. package/dist/storage/objects/mod.d.ts +4 -3
  178. package/dist/storage/objects/mod.d.ts.map +1 -0
  179. package/dist/storage/objects/mod.js +1 -1
  180. package/dist/storage/objects/mod.js.map +1 -1
  181. package/dist/storage/objects/refs.d.ts +20 -4
  182. package/dist/storage/objects/refs.d.ts.map +1 -0
  183. package/dist/storage/objects/refs.js +6 -0
  184. package/dist/storage/objects/refs.js.map +1 -1
  185. package/dist/storage/postgres/database.d.ts +81 -25
  186. package/dist/storage/postgres/database.d.ts.map +1 -0
  187. package/dist/storage/postgres/database.js +125 -37
  188. package/dist/storage/postgres/database.js.map +1 -1
  189. package/dist/storage/postgres/errors.d.ts +120 -0
  190. package/dist/storage/postgres/errors.d.ts.map +1 -0
  191. package/dist/storage/postgres/errors.js +162 -0
  192. package/dist/storage/postgres/errors.js.map +1 -0
  193. package/dist/storage/postgres/interval.d.ts +44 -0
  194. package/dist/storage/postgres/interval.d.ts.map +1 -0
  195. package/dist/storage/postgres/interval.js +153 -0
  196. package/dist/storage/postgres/interval.js.map +1 -0
  197. package/dist/storage/postgres/mod.d.ts +4 -1
  198. package/dist/storage/postgres/mod.d.ts.map +1 -0
  199. package/dist/storage/postgres/mod.js +2 -0
  200. package/dist/storage/postgres/mod.js.map +1 -1
  201. package/dist/storage/redis/bitfield.d.ts +67 -0
  202. package/dist/storage/redis/bitfield.d.ts.map +1 -0
  203. package/dist/storage/redis/bitfield.js +114 -0
  204. package/dist/storage/redis/bitfield.js.map +1 -0
  205. package/dist/storage/redis/command.d.ts +45 -0
  206. package/dist/storage/redis/command.d.ts.map +1 -0
  207. package/dist/storage/redis/command.js +78 -0
  208. package/dist/storage/redis/command.js.map +1 -0
  209. package/dist/storage/redis/commands.d.ts +223 -139
  210. package/dist/storage/redis/commands.d.ts.map +1 -0
  211. package/dist/storage/redis/commands.js +128 -6
  212. package/dist/storage/redis/commands.js.map +1 -1
  213. package/dist/storage/redis/database.d.ts +56 -22
  214. package/dist/storage/redis/database.d.ts.map +1 -0
  215. package/dist/storage/redis/database.js +62 -0
  216. package/dist/storage/redis/database.js.map +1 -1
  217. package/dist/storage/redis/mod.d.ts +31 -4
  218. package/dist/storage/redis/mod.d.ts.map +1 -0
  219. package/dist/storage/redis/mod.js +26 -1
  220. package/dist/storage/redis/mod.js.map +1 -1
  221. package/dist/storage/redis/native.d.ts +8 -0
  222. package/dist/storage/redis/native.d.ts.map +1 -0
  223. package/dist/storage/redis/native.js +10 -0
  224. package/dist/storage/redis/native.js.map +1 -1
  225. package/dist/storage/redis/options.d.ts +1 -0
  226. package/dist/storage/redis/options.d.ts.map +1 -0
  227. package/dist/storage/redis/pubsub.d.ts +2 -0
  228. package/dist/storage/redis/pubsub.d.ts.map +1 -0
  229. package/dist/storage/redis/reply.d.ts +34 -0
  230. package/dist/storage/redis/reply.d.ts.map +1 -0
  231. package/dist/storage/redis/reply.js +40 -1
  232. package/dist/storage/redis/reply.js.map +1 -1
  233. package/dist/storage/redis/scan.d.ts +1 -0
  234. package/dist/storage/redis/scan.d.ts.map +1 -0
  235. package/dist/storage/redis/script.d.ts +1 -0
  236. package/dist/storage/redis/script.d.ts.map +1 -0
  237. package/dist/storage/redis/target.d.ts +5 -3
  238. package/dist/storage/redis/target.d.ts.map +1 -0
  239. package/dist/storage/redis/target.js +39 -28
  240. package/dist/storage/redis/target.js.map +1 -1
  241. package/dist/storage/redis/wire.d.ts +7 -10
  242. package/dist/storage/redis/wire.d.ts.map +1 -0
  243. package/dist/storage/redis/wire.js +8 -32
  244. package/dist/storage/redis/wire.js.map +1 -1
  245. package/dist/testing/bun.d.ts +8 -0
  246. package/dist/testing/bun.d.ts.map +1 -0
  247. package/dist/testing/bun.js +13 -0
  248. package/dist/testing/bun.js.map +1 -0
  249. package/dist/testing/jest.d.ts +8 -0
  250. package/dist/testing/jest.d.ts.map +1 -0
  251. package/dist/testing/jest.js +11 -0
  252. package/dist/testing/jest.js.map +1 -0
  253. package/dist/testing/mod.d.ts +160 -0
  254. package/dist/testing/mod.d.ts.map +1 -0
  255. package/dist/testing/mod.js +227 -0
  256. package/dist/testing/mod.js.map +1 -0
  257. package/dist/testing/node.d.ts +9 -0
  258. package/dist/testing/node.d.ts.map +1 -0
  259. package/dist/testing/node.js +12 -0
  260. package/dist/testing/node.js.map +1 -0
  261. package/dist/testing/vitest.d.ts +8 -0
  262. package/dist/testing/vitest.d.ts.map +1 -0
  263. package/dist/testing/vitest.js +13 -0
  264. package/dist/testing/vitest.js.map +1 -0
  265. package/dist/tracing/mod.d.ts +19 -0
  266. package/dist/tracing/mod.d.ts.map +1 -0
  267. package/dist/tracing/mod.js +46 -0
  268. package/dist/tracing/mod.js.map +1 -0
  269. package/dist/tsconfig.build.tsbuildinfo +1 -1
  270. package/dist/types/mod.d.ts +1 -0
  271. package/dist/types/mod.d.ts.map +1 -0
  272. package/gateway/errors.ts +172 -0
  273. package/gateway/gateway.e2e.test.ts +297 -0
  274. package/gateway/gateway.test.ts +891 -0
  275. package/gateway/match.ts +239 -0
  276. package/gateway/middleware.ts +134 -0
  277. package/gateway/mod.ts +210 -0
  278. package/gateway/request.ts +578 -0
  279. package/gateway/serve.ts +738 -0
  280. package/internal/clients/call.ts +389 -0
  281. package/internal/clients/grpc.test.ts +368 -0
  282. package/internal/clients/grpc.ts +485 -0
  283. package/internal/clients/mod.test.ts +464 -0
  284. package/internal/clients/mod.ts +337 -0
  285. package/internal/fetch.ts +276 -0
  286. package/internal/otel/index.ts +1 -7
  287. package/internal/otel/span.ts +6 -0
  288. package/internal/otel/tracer.test.ts +43 -15
  289. package/internal/otel/tracer.ts +12 -5
  290. package/internal/reqfields.ts +390 -0
  291. package/internal/runtime/mod.ts +41 -2
  292. package/internal/runtime/napi/napi.cjs +160 -16
  293. package/internal/runtime/napi/napi.d.cts +474 -29
  294. package/internal/runtime/shutdown.ts +11 -1
  295. package/internal/testing/runner.ts +10 -0
  296. package/internal/testing/scope.ts +273 -0
  297. package/metrics/mod.test.ts +13 -16
  298. package/metrics/mod.ts +57 -226
  299. package/mod.ts +0 -8
  300. package/otel.test.ts +13 -6
  301. package/package.json +67 -15
  302. package/pubsub/encoding.ts +11 -1
  303. package/pubsub/mod.ts +10 -3
  304. package/pubsub/pubsub.test.ts +232 -14
  305. package/pubsub/refs.ts +16 -0
  306. package/pubsub/subscription.ts +194 -16
  307. package/pubsub/topic.test.ts +26 -0
  308. package/pubsub/topic.ts +220 -25
  309. package/reqctx/mod.ts +284 -0
  310. package/reqctx/reqctx.test.ts +193 -0
  311. package/scripts/postprocess-docs.test.ts +48 -0
  312. package/services/index.test.ts +341 -1
  313. package/services/index.ts +183 -8
  314. package/storage/objects/bucket.test.ts +573 -0
  315. package/storage/objects/bucket.ts +649 -20
  316. package/storage/objects/error.ts +28 -1
  317. package/storage/objects/mod.ts +15 -0
  318. package/storage/objects/refs.ts +51 -3
  319. package/storage/postgres/database.integration.test.ts +275 -0
  320. package/storage/postgres/database.test.ts +193 -6
  321. package/storage/postgres/database.ts +202 -55
  322. package/storage/postgres/errors.ts +186 -0
  323. package/storage/postgres/interval.test.ts +72 -0
  324. package/storage/postgres/interval.ts +170 -0
  325. package/storage/postgres/mod.ts +4 -0
  326. package/storage/redis/bitfield.ts +162 -0
  327. package/storage/redis/command.ts +84 -0
  328. package/storage/redis/commands.ts +271 -21
  329. package/storage/redis/database.ts +77 -23
  330. package/storage/redis/mod.ts +38 -2
  331. package/storage/redis/native.ts +11 -0
  332. package/storage/redis/redis.test.ts +170 -10
  333. package/storage/redis/reply.ts +76 -1
  334. package/storage/redis/runtime.test.ts +15 -0
  335. package/storage/redis/target.ts +47 -44
  336. package/storage/redis/wire.ts +8 -32
  337. package/testing/bun.ts +13 -0
  338. package/testing/jest.ts +11 -0
  339. package/testing/mod.ts +337 -0
  340. package/testing/node.ts +12 -0
  341. package/testing/vitest.ts +13 -0
  342. package/tracing/mod.ts +82 -0
  343. package/tracing/native.test.ts +170 -0
  344. package/tracing/tracing.test.ts +317 -0
  345. package/dist/internal/otel/request_context.d.ts +0 -11
  346. package/dist/internal/otel/request_context.js +0 -20
  347. package/dist/internal/otel/request_context.js.map +0 -1
  348. package/dist/internal/reqtrack/mod.d.ts +0 -6
  349. package/dist/internal/reqtrack/mod.js +0 -28
  350. package/dist/internal/reqtrack/mod.js.map +0 -1
  351. package/dist/req_meta.d.ts +0 -47
  352. package/dist/req_meta.js +0 -26
  353. package/dist/req_meta.js.map +0 -1
  354. package/internal/otel/request_context.ts +0 -32
  355. package/internal/reqtrack/mod.ts +0 -39
  356. package/req_meta.ts +0 -75
@@ -1,6 +1,9 @@
1
1
  import {activeCtxBytes} from '../../internal/otel/index';
2
2
  import * as runtime from '../../internal/runtime/mod';
3
+ import {currentScope, testMode} from '../../internal/testing/scope';
3
4
  import {StringLiteral} from '../../internal/utils/constraints';
5
+ import {native, TooManyRowsError} from './errors';
6
+ import type {Interval} from './interval';
4
7
 
5
8
  /**
6
9
  * Configures how database migrations are managed for a `Database`.
@@ -14,10 +17,27 @@ export interface MigrationsConfig {
14
17
  */
15
18
  export interface DatabaseConfig {
16
19
  migrations?: string | MigrationsConfig;
20
+
21
+ /**
22
+ * Tags that classify the database, for policies to read: written out as
23
+ * string literals, as in `{data: "pci"}`. Keys and values are lowercase
24
+ * letters, digits, `_` and `-`, at most 63 characters; a key starts with a
25
+ * letter, and not with `encore`, which is reserved. At most 32 tags.
26
+ */
27
+ tags?: Record<string, string>;
17
28
  }
18
29
 
19
30
  /**
20
- * Represents a single row from a query result
31
+ * Represents a single row from a query result, keyed by column name.
32
+ *
33
+ * Integers and floats are numbers, except an `int8` beyond what a number
34
+ * holds exactly (±(2^53−1)), which is a `bigint` so it is never rounded.
35
+ * `numeric` is a `Decimal`, `interval` a string in ISO 8601's form
36
+ * (`'P1Y2M3DT4H5M6.5S'`; see {@link Interval}), `timestamp`/`timestamptz` a
37
+ * `Date`, and `bytea` an `ArrayBuffer`. A type the SDK doesn't decode (`money`, `timetz`, ranges,
38
+ * `bit`, `xml`, `tsvector`, an extension's) is a string in the server's text
39
+ * form, and an array of one an array of such strings; a parameter of such a
40
+ * type takes a string, which the server parses.
21
41
  */
22
42
  export type Row = Record<string, any>;
23
43
 
@@ -32,6 +52,8 @@ export type Primitive =
32
52
  | Buffer
33
53
  | Date
34
54
  | Date[]
55
+ | Interval
56
+ | Interval[]
35
57
  | Record<string, any>
36
58
  | Record<string, any>[]
37
59
  // Preserve the existing public input type during the style migration.
@@ -51,8 +73,15 @@ export interface ExecResult {
51
73
  }
52
74
 
53
75
  /** Base class containing shared query functionality */
54
- class BaseQueryExecutor {
55
- constructor(protected readonly impl: SQLQueryExecutor) {}
76
+ class BaseQueryExecutor<I extends SQLQueryExecutor = SQLQueryExecutor> {
77
+ /** The native handle, or how to find it for each call: a database's is
78
+ * the current test's instance of it, in test mode. */
79
+ constructor(private readonly handle: I | (() => I)) {}
80
+
81
+ /** The native handle statements run on. */
82
+ protected get impl(): I {
83
+ return typeof this.handle === 'function' ? this.handle() : this.handle;
84
+ }
56
85
 
57
86
  /**
58
87
  * query queries the database using a template string, replacing your placeholders in the template
@@ -96,19 +125,17 @@ class BaseQueryExecutor {
96
125
  query: string,
97
126
  ...params: Primitive[]
98
127
  ): AsyncGenerator<T> {
99
- const cursor = await this.impl.query(
100
- query,
101
- buildQueryArgs(params),
102
- activeCtxBytes(),
128
+ const cursor = await native(
129
+ this.impl.query(query, buildQueryArgs(params), activeCtxBytes()),
103
130
  );
104
131
  try {
105
132
  while (true) {
106
- const row = await cursor.next();
133
+ const row = await native(cursor.next());
107
134
  if (row === null) break;
108
135
  yield row.values() as T;
109
136
  }
110
137
  } finally {
111
- await cursor.close();
138
+ await native(cursor.close());
112
139
  }
113
140
  }
114
141
 
@@ -155,7 +182,7 @@ class BaseQueryExecutor {
155
182
  /**
156
183
  * queryRow is like query but returns only a single row.
157
184
  * If the query selects no rows it returns null.
158
- * It throws if more than one row matches.
185
+ * It throws a {@link TooManyRowsError} if more than one row matches.
159
186
  *
160
187
  * @example
161
188
  * const email = "foo@example.com";
@@ -171,7 +198,7 @@ class BaseQueryExecutor {
171
198
  /**
172
199
  * rawQueryRow is like rawQuery but returns only a single row.
173
200
  * If the query selects no rows, it returns null.
174
- * It throws if more than one row matches.
201
+ * It throws a {@link TooManyRowsError} if more than one row matches.
175
202
  *
176
203
  * @example
177
204
  * const query = "SELECT id FROM users WHERE email=$1";
@@ -189,7 +216,7 @@ class BaseQueryExecutor {
189
216
  ): Promise<T | null> {
190
217
  let first: T | null = null;
191
218
  for await (const row of this.rawQuery<T>(query, ...params)) {
192
- if (first !== null) throw new Error('query returned more than one row');
219
+ if (first !== null) throw new TooManyRowsError();
193
220
  first = row;
194
221
  }
195
222
  return first;
@@ -222,20 +249,84 @@ class BaseQueryExecutor {
222
249
  * @returns The affected-row count after the statement completes.
223
250
  */
224
251
  async rawExec(query: string, ...params: Primitive[]): Promise<ExecResult> {
225
- const cursor = await this.impl.query(
226
- query,
227
- buildQueryArgs(params),
228
- activeCtxBytes(),
252
+ const cursor = await native(
253
+ this.impl.query(query, buildQueryArgs(params), activeCtxBytes()),
229
254
  );
230
255
  try {
231
- while ((await cursor.next()) !== null) {
256
+ while ((await native(cursor.next())) !== null) {
232
257
  /* Discard RETURNING rows. */
233
258
  }
234
- return {rowsAffected: await cursor.rowsAffected()};
259
+ return {rowsAffected: await native(cursor.rowsAffected())};
235
260
  } finally {
236
- await cursor.close();
261
+ await native(cursor.close());
262
+ }
263
+ }
264
+ }
265
+
266
+ /** The isolation level of a transaction. */
267
+ export type IsolationLevel =
268
+ 'read_committed' | 'repeatable_read' | 'serializable';
269
+
270
+ /**
271
+ * How a transaction runs. What isn't set is the database's default:
272
+ * `read_committed`, read-write (read-only on a read handle), not deferrable.
273
+ */
274
+ export interface TransactionOptions {
275
+ isolation?: IsolationLevel;
276
+ /**
277
+ * Begin the transaction `READ ONLY`, or with `false` `READ WRITE`. A read
278
+ * handle's transactions are read-only whatever this says, so `false`
279
+ * throws a `TypeError` on one.
280
+ */
281
+ readOnly?: boolean;
282
+ /**
283
+ * Begin the transaction `DEFERRABLE`, or with `false` `NOT DEFERRABLE`. It
284
+ * matters only to a serializable, read-only transaction, which then waits
285
+ * until it can run without serialization failures.
286
+ */
287
+ deferrable?: boolean;
288
+ }
289
+
290
+ const isolationLevels: Record<IsolationLevel, runtime.SQLIsolationLevel> = {
291
+ read_committed: runtime.SQLIsolationLevel.ReadCommitted,
292
+ repeatable_read: runtime.SQLIsolationLevel.RepeatableRead,
293
+ serializable: runtime.SQLIsolationLevel.Serializable,
294
+ };
295
+
296
+ /**
297
+ * Begins a transaction on `impl`, a pool or connection, with `options`.
298
+ * Throws a `TypeError` for an unknown isolation level, or for
299
+ * `readOnly: false` on a read handle's pool or connection.
300
+ */
301
+ async function beginOn(
302
+ impl: runtime.SQLDatabase | runtime.SQLConn,
303
+ options: TransactionOptions | undefined,
304
+ ): Promise<Transaction> {
305
+ let opts: runtime.SQLTransactionOptions | undefined;
306
+ if (options !== undefined) {
307
+ const {isolation, readOnly, deferrable} = options;
308
+ if (
309
+ isolation !== undefined &&
310
+ !Object.prototype.hasOwnProperty.call(isolationLevels, isolation)
311
+ ) {
312
+ throw new TypeError(
313
+ `unknown isolation level ${JSON.stringify(isolation)}: ` +
314
+ `expected one of ${Object.keys(isolationLevels).join(', ')}`,
315
+ );
237
316
  }
317
+ if (readOnly === false && impl.isReadOnly()) {
318
+ throw new TypeError(
319
+ "a read handle's transactions are read-only: readOnly cannot be false",
320
+ );
321
+ }
322
+ opts = {
323
+ isolation:
324
+ isolation === undefined ? undefined : isolationLevels[isolation],
325
+ readOnly,
326
+ deferrable,
327
+ };
238
328
  }
329
+ return new Transaction(await native(impl.begin(opts, activeCtxBytes())));
239
330
  }
240
331
 
241
332
  /**
@@ -243,7 +334,9 @@ class BaseQueryExecutor {
243
334
  * Obtain one with read(), write(), or admin(), or use a connection/transaction.
244
335
  * A Database declaration deliberately does not implement this interface.
245
336
  */
246
- export abstract class Queryable extends BaseQueryExecutor {
337
+ export abstract class Queryable<
338
+ I extends SQLQueryExecutor = SQLQueryExecutor,
339
+ > extends BaseQueryExecutor<I> {
247
340
  private readonly queryableBrand = true;
248
341
  }
249
342
 
@@ -260,10 +353,10 @@ export interface ReadOptions {
260
353
  * A database handle with access recorded by Encore's parser at its creation site.
261
354
  *
262
355
  * Handles share the declaration's pool. A read handle runs on read-only
263
- * connections: a statement that writes fails with `read_only_sql_transaction`
264
- * (SQLSTATE 25006), and the transactions it begins, and those of the
265
- * connections it acquires, are read-only. A write or admin handle runs
266
- * read-write.
356
+ * connections: a statement that writes fails with a `DatabaseError` whose
357
+ * code is `read_only_transaction` (SQLSTATE 25006), and the transactions it
358
+ * begins, and those of the connections it acquires, are read-only. A write
359
+ * or admin handle runs read-write.
267
360
  *
268
361
  * On the database's own pool, which a read handle shares when there is no
269
362
  * read-only pool for it, that refuses mistaken writes, not deliberate ones:
@@ -271,10 +364,8 @@ export interface ReadOptions {
271
364
  * connection (`SET default_transaction_read_only = off`) lifts it. Against
272
365
  * untrusted code, the read-only pool's database role is what refuses writes.
273
366
  */
274
- export class DatabaseRef extends Queryable {
275
- declare protected readonly impl: runtime.SQLDatabase;
276
-
277
- constructor(impl: runtime.SQLDatabase) {
367
+ export class DatabaseRef extends Queryable<runtime.SQLDatabase> {
368
+ constructor(impl: runtime.SQLDatabase | (() => runtime.SQLDatabase)) {
278
369
  super(impl);
279
370
  }
280
371
 
@@ -297,11 +388,15 @@ export class DatabaseRef extends Queryable {
297
388
  * See {@link Database.acquire}.
298
389
  */
299
390
  async acquire(): Promise<Connection> {
300
- return new Connection(await this.impl.acquire());
391
+ return new Connection(await native(this.impl.acquire()));
301
392
  }
302
393
 
303
- async begin(): Promise<Transaction> {
304
- return new Transaction(await this.impl.begin(activeCtxBytes()));
394
+ /**
395
+ * Begins a transaction with this handle's access. See {@link Database.begin}.
396
+ * A read handle's transactions are read-only.
397
+ */
398
+ async begin(options?: TransactionOptions): Promise<Transaction> {
399
+ return beginOn(this.impl, options);
305
400
  }
306
401
  }
307
402
 
@@ -312,14 +407,15 @@ export class DatabaseRef extends Queryable {
312
407
  * If you want to reference an existing database, use `Database.named(name)` as it is a
313
408
  * compile error to create duplicate databases.
314
409
  */
315
- export class Database extends BaseQueryExecutor {
316
- declare protected readonly impl: runtime.SQLDatabase;
410
+ export class Database extends BaseQueryExecutor<runtime.SQLDatabase> {
317
411
  /** The read handles, made on first use. */
318
412
  private reader?: DatabaseRef;
319
413
  private primaryReader?: DatabaseRef;
414
+ private readonly dbName: string;
320
415
 
321
416
  constructor(name: string, _cfg?: DatabaseConfig) {
322
- super(runtime.RT.sqlDatabase(name));
417
+ super(testMode ? testHandle(name) : runtime.RT.sqlDatabase(name));
418
+ this.dbName = name;
323
419
  }
324
420
 
325
421
  /**
@@ -344,16 +440,23 @@ export class Database extends BaseQueryExecutor {
344
440
 
345
441
  /** Select reader and writer access. */
346
442
  write(): DatabaseRef {
347
- return new DatabaseRef(this.impl);
443
+ return new DatabaseRef(testMode ? () => this.impl : this.impl);
348
444
  }
349
445
 
350
446
  /** Select reader, writer, and admin access. */
351
447
  admin(): DatabaseRef {
352
- return new DatabaseRef(this.impl);
448
+ return this.write();
353
449
  }
354
450
 
355
451
  private ref(access: runtime.SQLAccess): DatabaseRef {
356
- return new DatabaseRef(this.impl.withAccess(access));
452
+ if (!testMode) return new DatabaseRef(this.impl.withAccess(access));
453
+ // The current test's instance, for each call.
454
+ let own: runtime.SQLDatabase | undefined;
455
+ return new DatabaseRef(() => {
456
+ const scope = currentScope();
457
+ if (scope !== null) return scope.sqlDatabase(this.dbName, access);
458
+ return (own ??= this.impl.withAccess(access));
459
+ });
357
460
  }
358
461
 
359
462
  /**
@@ -378,7 +481,7 @@ export class Database extends BaseQueryExecutor {
378
481
  * @returns a new connection to the database
379
482
  */
380
483
  async acquire(): Promise<Connection> {
381
- const impl = await this.impl.acquire();
484
+ const impl = await native(this.impl.acquire());
382
485
  return new Connection(impl);
383
486
  }
384
487
 
@@ -398,12 +501,17 @@ export class Database extends BaseQueryExecutor {
398
501
  * If you can't use `await using`, make sure to always call `commit`
399
502
  * or `rollback` yourself to prevent hanging transactions.
400
503
  *
504
+ * `options` sets the transaction's isolation level and whether it is
505
+ * read-only or deferrable:
506
+ *
507
+ * ```ts
508
+ * await using tx = await db.begin({isolation: 'serializable'});
509
+ * ```
510
+ *
401
511
  * @returns a transaction object that implements `AsyncDisposable`
402
512
  */
403
- async begin(): Promise<Transaction> {
404
- const source = activeCtxBytes();
405
- const impl = await this.impl.begin(source);
406
- return new Transaction(impl);
513
+ async begin(options?: TransactionOptions): Promise<Transaction> {
514
+ return beginOn(this.impl, options);
407
515
  }
408
516
  }
409
517
 
@@ -424,8 +532,10 @@ export class Database extends BaseQueryExecutor {
424
532
  * If you can't use `await using`, make sure to always call `commit` or
425
533
  * `rollback` yourself to prevent hanging transactions.
426
534
  */
427
- export class Transaction extends Queryable implements AsyncDisposable {
428
- declare protected readonly impl: runtime.Transaction;
535
+ export class Transaction
536
+ extends Queryable<runtime.Transaction>
537
+ implements AsyncDisposable
538
+ {
429
539
  private done: boolean = false;
430
540
 
431
541
  constructor(impl: runtime.Transaction) {
@@ -437,7 +547,7 @@ export class Transaction extends Queryable implements AsyncDisposable {
437
547
  */
438
548
  async commit() {
439
549
  try {
440
- await this.impl.commit();
550
+ await native(this.impl.commit());
441
551
  } finally {
442
552
  this.done = this.impl.isClosed();
443
553
  }
@@ -448,7 +558,7 @@ export class Transaction extends Queryable implements AsyncDisposable {
448
558
  */
449
559
  async rollback() {
450
560
  try {
451
- await this.impl.rollback();
561
+ await native(this.impl.rollback());
452
562
  } finally {
453
563
  this.done = this.impl.isClosed();
454
564
  }
@@ -464,16 +574,21 @@ export class Transaction extends Queryable implements AsyncDisposable {
464
574
  /**
465
575
  * Represents a dedicated connection to a database.
466
576
  */
467
- export class Connection extends Queryable implements AsyncDisposable {
468
- declare protected readonly impl: runtime.SQLConn;
469
-
577
+ export class Connection
578
+ extends Queryable<runtime.SQLConn>
579
+ implements AsyncDisposable
580
+ {
470
581
  constructor(impl: runtime.SQLConn) {
471
582
  super(impl);
472
583
  }
473
584
 
474
- /** Begin a transaction that exclusively borrows this connection until completion. */
475
- async begin(): Promise<Transaction> {
476
- return new Transaction(await this.impl.begin(activeCtxBytes()));
585
+ /**
586
+ * Begin a transaction that exclusively borrows this connection until
587
+ * completion. See {@link Database.begin}. A connection acquired from a
588
+ * read handle begins read-only transactions.
589
+ */
590
+ async begin(options?: TransactionOptions): Promise<Transaction> {
591
+ return beginOn(this.impl, options);
477
592
  }
478
593
 
479
594
  async [Symbol.asyncDispose]() {
@@ -484,10 +599,21 @@ export class Connection extends Queryable implements AsyncDisposable {
484
599
  * Returns the connection to the database pool.
485
600
  */
486
601
  async close() {
487
- await this.impl.close();
602
+ await native(this.impl.close());
488
603
  }
489
604
  }
490
605
 
606
+ /**
607
+ * The handle of the database `name` in test mode, for each call: the current
608
+ * test's instance of it, or the process's own outside any test, made on
609
+ * first use.
610
+ */
611
+ function testHandle(name: string): () => runtime.SQLDatabase {
612
+ let own: runtime.SQLDatabase | undefined;
613
+ return () =>
614
+ currentScope()?.sqlDatabase(name) ?? (own ??= runtime.RT.sqlDatabase(name));
615
+ }
616
+
491
617
  function buildQuery(strings: TemplateStringsArray, expr: Primitive[]): string {
492
618
  let query = '';
493
619
  for (let i = 0; i < strings.length; i++) {
@@ -502,6 +628,27 @@ function buildQuery(strings: TemplateStringsArray, expr: Primitive[]): string {
502
628
  }
503
629
 
504
630
  function buildQueryArgs(params: Primitive[]): runtime.QueryArgs {
505
- // Convert undefined to null.
506
- return new runtime.QueryArgs(params.map(p => p ?? null));
631
+ return new runtime.QueryArgs(
632
+ params.map(p => (Array.isArray(p) ? p.map(param) : param(p as Primitive))),
633
+ );
634
+ }
635
+
636
+ /**
637
+ * `p` as the native module takes it: null for undefined, and a
638
+ * `Temporal.Duration`'s ISO 8601 string, which Postgres parses as an
639
+ * `interval`.
640
+ */
641
+ function param(p: Primitive): Primitive {
642
+ if (p === undefined) return null;
643
+ if (isTemporalDuration(p)) return p.toString();
644
+ return p;
645
+ }
646
+
647
+ /** Whether `p` is a `Temporal.Duration`, where the runtime has Temporal. */
648
+ function isTemporalDuration(p: unknown): p is {toString(): string} {
649
+ return (
650
+ typeof p === 'object' &&
651
+ p !== null &&
652
+ Object.prototype.toString.call(p) === '[object Temporal.Duration]'
653
+ );
507
654
  }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * What kind of error a database reported, by its SQLSTATE: the cases an app
3
+ * most often handles. `other` is any other; the SQLSTATE says what.
4
+ *
5
+ * @example
6
+ * try {
7
+ * await db.exec`INSERT INTO users (email) VALUES (${email})`;
8
+ * } catch (err) {
9
+ * if (err instanceof DatabaseError && err.code === ErrorCode.UniqueViolation) {
10
+ * return {taken: true};
11
+ * }
12
+ * throw err;
13
+ * }
14
+ */
15
+ export const ErrorCode = {
16
+ /** None of the others; the SQLSTATE says what. */
17
+ Other: 'other',
18
+ /** A `NOT NULL` constraint would be violated (23502). */
19
+ NotNullViolation: 'not_null_violation',
20
+ /** A foreign key constraint would be violated (23503). */
21
+ ForeignKeyViolation: 'foreign_key_violation',
22
+ /** A unique constraint would be violated (23505). */
23
+ UniqueViolation: 'unique_violation',
24
+ /** A check constraint would be violated (23514). */
25
+ CheckViolation: 'check_violation',
26
+ /** An exclusion constraint would be violated (23P01). */
27
+ ExcludeViolation: 'exclude_violation',
28
+ /** A statement ran in a transaction an earlier statement failed (25P02). */
29
+ TransactionFailed: 'transaction_failed',
30
+ /** A deadlock was detected (40P01). */
31
+ DeadlockDetected: 'deadlock_detected',
32
+ /** The server refused a connection: it has as many as it allows (53300). */
33
+ TooManyConnections: 'too_many_connections',
34
+ /**
35
+ * A serializable or repeatable read transaction could not be serialized
36
+ * with a concurrent one (40001); retrying it may succeed.
37
+ */
38
+ SerializationFailure: 'serialization_failure',
39
+ /** A write in a read-only transaction (25006), such as one through a read handle. */
40
+ ReadOnlyTransaction: 'read_only_transaction',
41
+ /**
42
+ * A lock could not be taken without waiting (55P03), as with
43
+ * `FOR UPDATE NOWAIT` or `lock_timeout`.
44
+ */
45
+ LockNotAvailable: 'lock_not_available',
46
+ /** The statement was canceled (57014): by a timeout, or on request. */
47
+ QueryCanceled: 'query_canceled',
48
+ /** The database could not be reached, or the connection to it was lost (class 08). */
49
+ ConnectionFailure: 'connection_failure',
50
+ } as const;
51
+
52
+ /** One of the {@link ErrorCode} values: `'unique_violation'`. */
53
+ export type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
54
+
55
+ /**
56
+ * An error a database reported, or a failure to reach it.
57
+ *
58
+ * A failure to reach the database, which the server can't report, has
59
+ * `sqlState` `"08001"`, `code` `connection_failure`, the client's message
60
+ * and none of the optional fields. The caller's own mistakes, such as a
61
+ * parameter of the wrong type, and using a busy or closed handle, are plain
62
+ * errors instead.
63
+ *
64
+ * The optional fields are sent only for some errors (see
65
+ * https://www.postgresql.org/docs/current/protocol-error-fields.html); one
66
+ * being there says nothing about the others.
67
+ *
68
+ * Its `message` reads `ERROR: duplicate key value violates unique constraint
69
+ * "users_pkey" (Code unique_violation: SQLSTATE 23505)`. A subscription
70
+ * handler that throws one fails with the API error code of its SQLSTATE:
71
+ * `already_exists` for a unique violation.
72
+ */
73
+ export class DatabaseError extends Error {
74
+ declare readonly name: 'DatabaseError';
75
+ /** What kind of error it is, by its SQLSTATE. */
76
+ readonly code: ErrorCode;
77
+ /** The SQLSTATE: `"23505"`. */
78
+ readonly sqlState: string;
79
+ /** `ERROR`, `FATAL` or `PANIC`. */
80
+ readonly severity: string;
81
+ /**
82
+ * A secondary message with more detail, such as the key a unique
83
+ * violation conflicted on.
84
+ */
85
+ readonly detail?: string;
86
+ /** A suggestion what to do about it. */
87
+ readonly hint?: string;
88
+ /** The schema of the object the error is about. */
89
+ readonly schemaName?: string;
90
+ /** The table the error is about. */
91
+ readonly tableName?: string;
92
+ /** The column the error is about. */
93
+ readonly columnName?: string;
94
+ /** The data type the error is about. */
95
+ readonly dataTypeName?: string;
96
+ /** The constraint the error is about; an index counts as one. */
97
+ readonly constraintName?: string;
98
+
99
+ constructor(fields: {
100
+ message: string;
101
+ code: ErrorCode;
102
+ sqlState: string;
103
+ severity: string;
104
+ detail?: string;
105
+ hint?: string;
106
+ schemaName?: string;
107
+ tableName?: string;
108
+ columnName?: string;
109
+ dataTypeName?: string;
110
+ constraintName?: string;
111
+ }) {
112
+ super(fields.message);
113
+ Object.defineProperty(this, 'name', {
114
+ value: 'DatabaseError',
115
+ enumerable: false,
116
+ configurable: true,
117
+ });
118
+ this.code = fields.code;
119
+ this.sqlState = fields.sqlState;
120
+ this.severity = fields.severity;
121
+ this.detail = fields.detail;
122
+ this.hint = fields.hint;
123
+ this.schemaName = fields.schemaName;
124
+ this.tableName = fields.tableName;
125
+ this.columnName = fields.columnName;
126
+ this.dataTypeName = fields.dataTypeName;
127
+ this.constraintName = fields.constraintName;
128
+ }
129
+ }
130
+
131
+ /** Thrown by `queryRow` and `rawQueryRow` for a query that returns more than one row. */
132
+ export class TooManyRowsError extends Error {
133
+ declare readonly name: 'TooManyRowsError';
134
+
135
+ constructor() {
136
+ super('query returned more than one row');
137
+ Object.defineProperty(this, 'name', {
138
+ value: 'TooManyRowsError',
139
+ enumerable: false,
140
+ configurable: true,
141
+ });
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Begins the message of an error the native module rejects with for a
147
+ * `DatabaseError`, which the rest of the message holds as JSON. The same as
148
+ * `DATABASE_ERROR_PREFIX` in `sdk/ts/src/postgres.rs`.
149
+ */
150
+ const DATABASE_ERROR_PREFIX = 'encore:postgres.DatabaseError:';
151
+
152
+ /**
153
+ * Awaits a native database call, throwing the error it rejects with as a
154
+ * `DatabaseError` if it is one.
155
+ */
156
+ export async function native<T>(call: Promise<T>): Promise<T> {
157
+ try {
158
+ return await call;
159
+ } catch (err) {
160
+ throw fromNative(err);
161
+ }
162
+ }
163
+
164
+ /** `err`, a native database call's, as a `DatabaseError` if it is one. */
165
+ function fromNative(err: unknown): unknown {
166
+ if (
167
+ !(err instanceof Error) ||
168
+ !err.message.startsWith(DATABASE_ERROR_PREFIX)
169
+ ) {
170
+ return err;
171
+ }
172
+ const f = JSON.parse(err.message.slice(DATABASE_ERROR_PREFIX.length));
173
+ return new DatabaseError({
174
+ message: f.message,
175
+ code: f.code,
176
+ sqlState: f.sqlState,
177
+ severity: f.severity,
178
+ detail: f.detail ?? undefined,
179
+ hint: f.hint ?? undefined,
180
+ schemaName: f.schemaName ?? undefined,
181
+ tableName: f.tableName ?? undefined,
182
+ columnName: f.columnName ?? undefined,
183
+ dataTypeName: f.dataTypeName ?? undefined,
184
+ constraintName: f.constraintName ?? undefined,
185
+ });
186
+ }