vite-plugin-postgres-import 0.4.1 → 0.6.0

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 (4) hide show
  1. package/README.md +26 -7
  2. package/index.d.ts +27 -0
  3. package/package.json +12 -2
  4. package/parse.js +64 -30
package/README.md CHANGED
@@ -43,7 +43,7 @@ where foo = :foo;
43
43
  import { Pool } from "pg";
44
44
  import { Query, UpdateQuery, QueryMany, MultiStatement } from "./module.sql";
45
45
 
46
- const pool = new Pool('...');
46
+ const pool = new Pool("...");
47
47
 
48
48
  const { id } = await Query(pool, { id: 1 });
49
49
 
@@ -55,7 +55,7 @@ const array = await QueryMany(pool);
55
55
  const [all, something, deleted] = await MultiStatement(pool, { foo: "bar" });
56
56
  ```
57
57
 
58
- > ### **Note**
58
+ > [!Warning]
59
59
  >
60
60
  > Postgres does _NOT_ allow using parameters in multi-statement queries.
61
61
  >
@@ -81,15 +81,15 @@ The only 4 sqlc annotations that are available are the following:
81
81
 
82
82
  ex.: `Query(c): Promise<number>`
83
83
 
84
- 2 additional annotations not found in sqlc are available:
84
+ 4 additional annotations not found in sqlc are available:
85
85
 
86
86
  - `:prepare` - prepares the statement by passing query's name to query config.
87
87
 
88
- > ### **Warning**
88
+ > [!Warning]
89
89
  >
90
90
  > Similarly to parameters, Postgres does _NOT_ allow preparing multi-statement queries. Using `:prepare` on a multi-statement query will result in an error. I warned you!
91
91
 
92
- > ### **Warning**
92
+ > [!Warning]
93
93
  >
94
94
  > Don't use identical names for prepared queries, regardless whether they're in different `.sql` modules or not:
95
95
  >
@@ -127,9 +127,28 @@ The only 4 sqlc annotations that are available are the following:
127
127
 
128
128
  ex. `:execresult`: `Query<R extends any[] = [ ... ]>(c): Promise<QueryArrayResult<R>>`
129
129
 
130
- ex. `:one`: `Query<R = [ ... ]>(c): Promise<R>`
130
+ ex. `:one`: `Query<R extends any[] = [ ... ]>(c): Promise<R>`
131
131
 
132
- ex. `:many`: `Query<R = [ ... ]>(c): Promise<R[]>`
132
+ ex. `:many`: `Query<R extends any[] = [ ... ]>(c): Promise<R[]>`
133
+
134
+ - `:iterable` - returns an `AsyncGenerator`. Once [Async Iterator Helpers](https://github.com/tc39/proposal-async-iterator-helpers)
135
+ are in the standard, you can use crazy piping as following:
136
+
137
+ ```js
138
+ const result = await IterableQuery<{ ... }>(c, { foo: 'bar' })
139
+ .flatMap(superComplicatedCodeThatIsMoreUsefulToRunFromJS)
140
+ .filter(Boolean)
141
+ .toArray();
142
+ ```
143
+
144
+ Well maybe that didn't look too crazy, but if some filtering forces your squeel to become convoluted, and you're fine with moving
145
+ some of that computation to JS, you can finally do that! Or at least when that proposal is in the language, that is.
146
+
147
+ - `:cursor` - returns an `Cursor`
148
+
149
+ ex.: `Query<R extends QueryResultRow = { ... }>(c): Promise<Cursor<R>>`
150
+
151
+ ex. `:array`: `Query<R extends any[] = [ ... ]>(c): Promise<Cursor<R>>`
133
152
 
134
153
  ## Configuring
135
154
 
package/index.d.ts CHANGED
@@ -1,3 +1,12 @@
1
+ import type {
2
+ QueryArrayConfig,
3
+ QueryArrayResult,
4
+ QueryConfig,
5
+ QueryConfigValues,
6
+ QueryResult,
7
+ QueryResultRow,
8
+ Submittable,
9
+ } from "pg";
1
10
  import type { Plugin } from "vite";
2
11
 
3
12
  export default function postgres(opts?: {
@@ -18,3 +27,21 @@ export default function postgres(opts?: {
18
27
  */
19
28
  rootFolder?: string;
20
29
  }): Plugin;
30
+
31
+ export interface QueryableObject {
32
+ query<T extends Submittable>(queryStream: T): T;
33
+
34
+ query<R extends any[] = any[], I = any[]>(
35
+ queryConfig: QueryArrayConfig<I>,
36
+ values?: QueryConfigValues<I>
37
+ ): Promise<QueryArrayResult<R>>;
38
+
39
+ query<R extends QueryResultRow = any, I = any>(queryConfig: QueryConfig<I>): Promise<QueryResult<R>>;
40
+
41
+ query<R extends QueryResultRow = any, I = any[]>(
42
+ queryTextOrConfig: string | QueryConfig<I>,
43
+ values?: QueryConfigValues<I>
44
+ ): Promise<QueryResult<R>>;
45
+ }
46
+
47
+ export type Queryable = QueryableObject | Promise<QueryableObject>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "vite-plugin-postgres-import",
3
3
  "description": "Vite plugin for importing SQL files as JS modules with sqlc-style annotations",
4
- "version": "0.4.1",
4
+ "version": "0.6.0",
5
5
  "main": "plugin.js",
6
6
  "type": "module",
7
7
  "author": "SirKostya009",
@@ -22,7 +22,17 @@
22
22
  "vite": "^6"
23
23
  },
24
24
  "peerDependencies": {
25
- "pg": "*"
25
+ "pg": "*",
26
+ "pg-cursor": "*",
27
+ "@types/pg": "*"
28
+ },
29
+ "peerDependenciesMeta": {
30
+ "pg-cursor": {
31
+ "optional": true
32
+ },
33
+ "@types/pg": {
34
+ "optional": true
35
+ }
26
36
  },
27
37
  "engines": {
28
38
  "node": ">=22.0.0"
package/parse.js CHANGED
@@ -92,7 +92,7 @@ export function codegen(
92
92
  ) {
93
93
  let dts = [
94
94
  // `declare module '${modulePrefix}${filename}.sql' {`
95
- `import type { Pool, ClientBase, QueryResultRow, QueryResult, QueryArrayResult } from 'pg';`,
95
+ `import type { QueryResultRow, QueryResult, QueryArrayResult } from 'pg';\nimport { Queryable } from 'vite-plugin-postgres-import';`,
96
96
  ];
97
97
  let js = [`import { escapeLiteral } from 'pg';`];
98
98
 
@@ -117,6 +117,11 @@ export function codegen(
117
117
  module.returnSymbols = module.returnSymbols.map((rs) => [...new Set(rs)]);
118
118
  }
119
119
 
120
+ if (module.mode) {
121
+ dts[0] += `\nimport Cursor from 'pg-cursor';`;
122
+ js.push(`import Cursor from 'pg-cursor';`);
123
+ }
124
+
120
125
  const keys = module.params
121
126
  .values()
122
127
  .map((k) => `'${k}'`)
@@ -141,20 +146,28 @@ export function ${module.name}<${module.returnSymbols
141
146
  }${r.length > 3 ? "\n" : " "}}`
142
147
  )
143
148
  .join(", ")}>(
144
- tx: Pool | ClientBase | Promise<ClientBase>,${keys.length ? `\n\tparams: Record<${keys}, unknown>` : ``}
145
- ): Promise<${module.multiStatement && "["}${module.returnSymbols
146
- .map((_, i) =>
147
- module.execution[i] === ":execresult"
148
- ? `Query${module.rowArray ? "Array" : ""}Result<R${i + 1}>`
149
- : module.execution[i] === ":one"
150
- ? `R${i + 1}`
151
- : module.execution[i] === ":many"
152
- ? `R${i + 1}[]`
153
- : module.execution[i] === ":execrows"
154
- ? `number`
155
- : "unknown"
156
- )
157
- .join(", ")}${module.multiStatement && "]"}>;`);
149
+ tx: Queryable,${keys && `\n\tparams: Record<${keys}, unknown>,`}${
150
+ module.mode === ":iterable" ? `\n\tread?: number,` : ""
151
+ }
152
+ ): ${
153
+ module.mode === ":cursor"
154
+ ? `Cursor<R1>`
155
+ : module.mode === ":iterable"
156
+ ? `AsyncGenerator<R1, void, unknown>`
157
+ : `Promise<${module.multiStatement && "["}${module.returnSymbols
158
+ .map((_, i) =>
159
+ module.execution[i] === ":execresult"
160
+ ? `Query${module.rowArray ? "Array" : ""}Result<R${i + 1}>`
161
+ : module.execution[i] === ":one"
162
+ ? `R${i + 1}`
163
+ : module.execution[i] === ":many"
164
+ ? `R${i + 1}[]`
165
+ : module.execution[i] === ":execrows"
166
+ ? `number`
167
+ : "unknown"
168
+ )
169
+ .join(", ")}${module.multiStatement && "]"}>`
170
+ };`);
158
171
 
159
172
  const paramsString = module.params
160
173
  .values()
@@ -178,26 +191,47 @@ export function ${module.name}<${module.returnSymbols
178
191
  }
179
192
 
180
193
  js.push(
181
- `export const ${module.name} = async (tx, { ${paramsString} } = {}) => (await tx).query({
194
+ module.mode === ":cursor"
195
+ ? `export const ${module.name} = async (tx${
196
+ paramsString && `, { ${paramsString} } = {}`
197
+ }) => (await tx).query(new Cursor(\`${module.query}\`${paramsString && `, [ ${paramsString} ]`}${
198
+ module.rowArray ? `, { rowMode: "array" }` : ""
199
+ }));`
200
+ : module.mode === ":iterable"
201
+ ? `export async function* ${module.name}(tx, ${paramsString && `{ ${paramsString} } = {}, `}read = 10) {
202
+ const cursor = (await tx).query(new Cursor(\`${module.query}\`${paramsString && `, [ ${paramsString} ]`}${
203
+ module.rowArray ? `, { rowMode: "array" }` : ""
204
+ }));
205
+ try {
206
+ let _read;
207
+ do {
208
+ _read = await cursor.read(read);
209
+ yield* _read;
210
+ } while (_read.length === read);
211
+ } finally {
212
+ await cursor.close();
213
+ }
214
+ }`
215
+ : `export const ${module.name} = async (tx, { ${paramsString} } = {}) => (await tx).query({
182
216
  ${module.prepared ? `name: "${module.name}",` : ""}
183
217
  text: \`${module.multiStatement ? module.query : module.query}\`,
184
218
  values: [ ${module.multiStatement || paramsString} ],
185
219
  ${module.rowArray ? `rowMode: "array",` : ""}
186
220
  }).then((${module.multiStatement && "["}${module.returnSymbols.map((_, i) => `r${i + 1}`).join()}${
187
- module.multiStatement && "]"
188
- }) => ${module.multiStatement && "["}${module.returnSymbols
189
- .map(
190
- (_, i) =>
191
- `r${i + 1}` +
192
- (module.execution[i] === ":one"
193
- ? `.rows[0]`
194
- : module.execution[i] === ":many"
195
- ? `.rows`
196
- : module.execution[i] === ":execrows"
197
- ? `.rowCount`
198
- : "")
199
- )
200
- .join()}${module.multiStatement && "]"});`
221
+ module.multiStatement && "]"
222
+ }) => ${module.multiStatement && "["}${module.returnSymbols
223
+ .map(
224
+ (_, i) =>
225
+ `r${i + 1}` +
226
+ (module.execution[i] === ":one"
227
+ ? `.rows[0]`
228
+ : module.execution[i] === ":many"
229
+ ? `.rows`
230
+ : module.execution[i] === ":execrows"
231
+ ? `.rowCount`
232
+ : "")
233
+ )
234
+ .join()}${module.multiStatement && "]"});`
201
235
  );
202
236
  }
203
237