postgrest-parser 0.2.0

PostgREST URL-to-SQL parser for Rust and WASM
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
# TypeScript Type-Safe API Guide

This guide covers the improved type-safe TypeScript API for the PostgREST parser.

## Overview

The PostgREST parser now provides two APIs:

1. **Type-Safe Client API** (Recommended) - `client.ts`
   - Fully typed with zero `any` types
   - Object-based APIs (no JSON string manipulation)
   - Better IntelliSense and autocomplete
   - Idiomatic TypeScript patterns

2. **Low-Level WASM API** - `postgrest_parser.js`
   - Auto-generated by wasm-bindgen
   - Direct WASM bindings
   - Use only when you need low-level control

## Installation

```bash
npm install postgrest-parser
# or
yarn add postgrest-parser
# or
pnpm add postgrest-parser
```

## Quick Start

### Using the Type-Safe Client (Recommended)

```typescript
import { createClient } from 'postgrest-parser';
import type { QueryResult } from 'postgrest-parser/types';

const client = createClient();

// SELECT query
const result: QueryResult = client.select("users", {
  filters: { "age": "gte.18", "status": "eq.active" },
  order: ["created_at.desc"],
  limit: 10
});

console.log(result.query);   // SQL query string
console.log(result.params);  // ["18", "active"]
console.log(result.tables);  // ["users"]
```

### Using the Low-Level WASM API

```typescript
import { parseQueryString } from 'postgrest-parser/wasm';

const result = parseQueryString("users", "age=gte.18&status=eq.active");
console.log(result.query);
console.log(result.params);
```

## Type Safety Improvements

### Before: Auto-Generated WASM Bindings

```typescript
// ❌ Too many 'any' types - no type safety
export class WasmQueryResult {
  toJSON(): any;              // Unknown return type
  readonly params: any;       // No idea what params can be
  readonly tables: any;       // Could be anything
}

// ❌ Redundant optionals
parseDelete(table: string, query_string: string, headers?: string | null)
//                                                           ^^^^^^^^^^^^
// Both optional (?) and nullable (| null) is redundant

// ❌ Loose string type for HTTP methods
parseRequest(method: string, path: string, ...)
//                   ^^^^^^ - Any string accepted, no validation
```

### After: Type-Safe Client API

```typescript
// ✅ Fully typed with proper interfaces
export interface QueryResult {
  query: string;
  params: SqlParam[];         // (string | number | boolean | null | string[])[]
  tables: string[];
}

// ✅ Clean optional parameters
parseDelete(table: string, queryString: string, headers?: RequestHeaders)
//                                              ^^^^^^^^^ - Properly optional

// ✅ Strict HTTP method type
parseRequest(method: HttpMethod, path: string, ...)
//                   ^^^^^^^^^^^ - "GET" | "POST" | "PUT" | "PATCH" | "DELETE"
```

## API Comparison

### SELECT Queries

#### WASM API (Old)
```typescript
import { parseQueryString } from 'postgrest-parser/wasm';

const result = parseQueryString(
  "users",
  "age=gte.18&status=eq.active&order=created_at.desc&limit=10"
);
// ❌ Manual query string construction
// ❌ No type checking on filters
// ❌ Easy to make syntax errors
```

#### Client API (New)
```typescript
import { createClient } from 'postgrest-parser';

const client = createClient();
const result = client.select("users", {
  filters: {
    age: "gte.18",
    status: "eq.active"
  },
  order: ["created_at.desc"],
  limit: 10
});
// ✅ Object-based configuration
// ✅ IntelliSense for all options
// ✅ No manual string manipulation
```

### INSERT Queries

#### WASM API (Old)
```typescript
import { parseInsert } from 'postgrest-parser/wasm';

const result = parseInsert(
  "users",
  JSON.stringify({ name: "Alice", email: "alice@example.com" }),
  "returning=id,name",
  JSON.stringify({ Prefer: "return=representation" })
);
// ❌ Manual JSON stringification
// ❌ Headers passed as JSON string
// ❌ Query string concatenation
```

#### Client API (New)
```typescript
import { createClient } from 'postgrest-parser';

const client = createClient();
const result = client.insert("users", {
  name: "Alice",
  email: "alice@example.com"
}, {
  returning: ["id", "name"],  // or "id,name"
  prefer: { return: "representation" }
});
// ✅ Native objects, no stringification
// ✅ Typed prefer options
// ✅ Array or string for returning
```

### UPDATE Queries

#### WASM API (Old)
```typescript
import { parseUpdate } from 'postgrest-parser/wasm';

const result = parseUpdate(
  "users",
  JSON.stringify({ status: "active" }),
  "id=eq.123",
  null
);
// ❌ Filters as query string
// ❌ Body as JSON string
```

#### Client API (New)
```typescript
import { createClient } from 'postgrest-parser';

const client = createClient();
const result = client.update("users", {
  status: "active"
}, {
  id: "eq.123"
}, {
  returning: "id,status"
});
// ✅ Filters as object
// ✅ Body as object
// ✅ Type-safe options
```

### UPSERT Queries (PUT)

#### WASM API (Old)
```typescript
import { parseRequest } from 'postgrest-parser/wasm';

const result = parseRequest(
  "PUT",
  "users",
  "email=eq.alice@example.com&returning=id,name",
  JSON.stringify({ email: "alice@example.com", name: "Alice" }),
  null
);
// ❌ Must manually construct filter for conflict detection
// ❌ Risk of mismatch between filter and body
```

#### Client API (New)
```typescript
import { createClient } from 'postgrest-parser';

const client = createClient();
const result = client.upsert("users", {
  email: "alice@example.com",
  name: "Alice"
}, ["email"], {  // Conflict columns
  returning: ["id", "name"]
});
// ✅ Auto-generates ON CONFLICT from conflict columns
// ✅ Type-safe, declarative API
// ✅ No risk of filter/body mismatch
```

### DELETE Queries

#### WASM API (Old)
```typescript
import { parseDelete } from 'postgrest-parser/wasm';

const result = parseDelete(
  "users",
  "status=eq.inactive&last_login=lt.2023-01-01",
  null
);
// ❌ Filters as query string
```

#### Client API (New)
```typescript
import { createClient } from 'postgrest-parser';

const client = createClient();
const result = client.delete("users", {
  status: "eq.inactive",
  last_login: "lt.2023-01-01"
}, {
  returning: "id"
});
// ✅ Filters as object
// ✅ Optional returning
```

### RPC Calls

#### WASM API (Old)
```typescript
import { parseRpc } from 'postgrest-parser/wasm';

const result = parseRpc(
  "calculate_total",
  JSON.stringify({ order_id: 123, tax_rate: 0.08 }),
  "select=total,tax&limit=1",
  null
);
// ❌ Args as JSON string
// ❌ Options as query string
```

#### Client API (New)
```typescript
import { createClient } from 'postgrest-parser';

const client = createClient();
const result = client.rpc("calculate_total", {
  order_id: 123,
  tax_rate: 0.08
}, {
  select: ["total", "tax"],
  limit: 1
});
// ✅ Native objects throughout
// ✅ Type-safe options
```

## Available Types

### Core Types

```typescript
import type {
  HttpMethod,           // "GET" | "POST" | "PUT" | "PATCH" | "DELETE"
  QueryResult,          // { query: string; params: SqlParam[]; tables: string[] }
  SqlParam,            // string | number | boolean | null | string[]
  FilterOperator,      // "eq" | "neq" | "gt" | "gte" | "lt" | ...
  OrderDirection,      // "asc" | "desc"
  RequestHeaders,      // { Prefer?: string; [key: string]: string }
} from 'postgrest-parser/types';
```

### Option Types

```typescript
import type {
  SelectOptions,       // { filters?, order?, limit?, offset?, count? }
  InsertOptions,       // { returning?, onConflict?, prefer? }
  UpdateOptions,       // { returning?, prefer? }
  DeleteOptions,       // { returning?, prefer? }
  RpcOptions,         // { select?, filters?, order?, limit?, offset? }
  PreferOptions,      // { return?, resolution?, missing?, count? }
} from 'postgrest-parser/types';
```

### Advanced Types

```typescript
import type {
  Filter,             // Single filter condition
  LogicCondition,     // AND/OR/NOT logic tree
  OrderBy,           // Order clause with direction and nulls position
  ParsedQuery,       // Complete parsed query structure
} from 'postgrest-parser/types';
```

## Integration Examples

### Express.js

```typescript
import express from 'express';
import { createClient } from 'postgrest-parser';
import { Pool } from 'pg';
import type { QueryResult } from 'postgrest-parser/types';

const app = express();
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const parser = createClient();

app.use(express.json());

app.get('/api/:table', async (req, res) => {
  try {
    const result: QueryResult = parser.select(req.params.table, {
      filters: req.query as Record<string, string>,
      limit: req.query.limit ? parseInt(req.query.limit as string) : undefined
    });

    const { rows } = await pool.query(result.query, result.params);
    res.json(rows);
  } catch (error) {
    res.status(500).json({ error: (error as Error).message });
  }
});

app.post('/api/:table', async (req, res) => {
  try {
    const result: QueryResult = parser.insert(req.params.table, req.body, {
      returning: "*",
      prefer: { return: "representation" }
    });

    const { rows } = await pool.query(result.query, result.params);
    res.json(rows[0]);
  } catch (error) {
    res.status(500).json({ error: (error as Error).message });
  }
});
```

### Next.js API Route

```typescript
// pages/api/users.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { createClient } from 'postgrest-parser';
import { query } from '@/lib/db';
import type { QueryResult } from 'postgrest-parser/types';

const parser = createClient();

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method === 'GET') {
    const result: QueryResult = parser.select("users", {
      filters: req.query as Record<string, string>,
      limit: 10
    });

    const rows = await query(result.query, result.params);
    res.json(rows);
  } else if (req.method === 'POST') {
    const result: QueryResult = parser.insert("users", req.body, {
      returning: "*"
    });

    const rows = await query(result.query, result.params);
    res.json(rows[0]);
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
}
```

### Supabase Edge Function

```typescript
// supabase/functions/users/index.ts
import { createClient } from '../_shared/postgrest-parser/client.ts';
import { createClient as createSupabaseClient } from '@supabase/supabase-js';
import type { QueryResult } from '../_shared/postgrest-parser/types.ts';

const supabase = createSupabaseClient(
  Deno.env.get('SUPABASE_URL')!,
  Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
);

const parser = createClient();

Deno.serve(async (req) => {
  const url = new URL(req.url);
  const filters = Object.fromEntries(url.searchParams);

  const result: QueryResult = parser.select("users", {
    filters,
    limit: 10
  });

  // Execute via Supabase
  const { data, error } = await supabase.rpc('execute_sql', {
    query: result.query,
    params: result.params
  });

  if (error) {
    return new Response(JSON.stringify({ error: error.message }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }

  return new Response(JSON.stringify(data), {
    headers: { 'Content-Type': 'application/json' }
  });
});
```

### Custom Type-Safe Wrapper

```typescript
import { createClient } from 'postgrest-parser';
import { Pool } from 'pg';
import type { QueryResult } from 'postgrest-parser/types';

export class Database {
  private parser = createClient();
  private pool: Pool;

  constructor(connectionString: string) {
    this.pool = new Pool({ connectionString });
  }

  async select<T = any>(
    table: string,
    options: Parameters<typeof this.parser.select>[1] = {}
  ): Promise<T[]> {
    const result: QueryResult = this.parser.select(table, options);
    const { rows } = await this.pool.query<T>(result.query, result.params);
    return rows;
  }

  async insert<T = any>(
    table: string,
    data: Record<string, unknown> | Record<string, unknown>[],
    options: Parameters<typeof this.parser.insert>[2] = {}
  ): Promise<T[]> {
    const result: QueryResult = this.parser.insert(table, data, options);
    const { rows } = await this.pool.query<T>(result.query, result.params);
    return rows;
  }

  async update<T = any>(
    table: string,
    data: Record<string, unknown>,
    filters: Record<string, string>,
    options: Parameters<typeof this.parser.update>[3] = {}
  ): Promise<T[]> {
    const result: QueryResult = this.parser.update(table, data, filters, options);
    const { rows } = await this.pool.query<T>(result.query, result.params);
    return rows;
  }

  async delete<T = any>(
    table: string,
    filters: Record<string, string>,
    options: Parameters<typeof this.parser.delete>[2] = {}
  ): Promise<T[]> {
    const result: QueryResult = this.parser.delete(table, filters, options);
    const { rows } = await this.pool.query<T>(result.query, result.params);
    return rows;
  }

  async rpc<T = any>(
    functionName: string,
    args: Record<string, unknown> = {},
    options: Parameters<typeof this.parser.rpc>[2] = {}
  ): Promise<T[]> {
    const result: QueryResult = this.parser.rpc(functionName, args, options);
    const { rows } = await this.pool.query<T>(result.query, result.params);
    return rows;
  }
}

// Usage
const db = new Database(process.env.DATABASE_URL!);

interface User {
  id: number;
  name: string;
  email: string;
  status: string;
}

const users = await db.select<User>("users", {
  filters: { status: "eq.active" },
  limit: 10
});
// users is typed as User[]
```

## Best Practices

### 1. Use the Type-Safe Client

```typescript
// ✅ Recommended
import { createClient } from 'postgrest-parser';
const client = createClient();

// ❌ Avoid (unless you need low-level control)
import { parseQueryString } from 'postgrest-parser/wasm';
```

### 2. Leverage Type Inference

```typescript
const result = client.select("users", {
  filters: { age: "gte.18" }
});
// result is automatically typed as QueryResult
```

### 3. Use Type Imports

```typescript
import type { QueryResult, SelectOptions } from 'postgrest-parser/types';

function buildQuery(options: SelectOptions): QueryResult {
  return client.select("users", options);
}
```

### 4. Handle Errors Properly

```typescript
try {
  const result = client.select("users", {
    filters: { age: "invalid" }
  });
  const rows = await db.query(result.query, result.params);
} catch (error) {
  if (error instanceof Error) {
    console.error('Parse error:', error.message);
  }
}
```

### 5. Reuse Client Instance

```typescript
// ✅ Create once, reuse
const client = createClient();

export function getUsers() {
  return client.select("users", { ... });
}

export function createUser(data) {
  return client.insert("users", data, { ... });
}
```

## Migration Guide

### From WASM API to Client API

```typescript
// Before (WASM API)
import { parseQueryString, parseInsert } from 'postgrest-parser/wasm';

const selectResult = parseQueryString(
  "users",
  "age=gte.18&order=created_at.desc&limit=10"
);

const insertResult = parseInsert(
  "users",
  JSON.stringify({ name: "Alice" }),
  "returning=id",
  JSON.stringify({ Prefer: "return=representation" })
);

// After (Client API)
import { createClient } from 'postgrest-parser';

const client = createClient();

const selectResult = client.select("users", {
  filters: { age: "gte.18" },
  order: ["created_at.desc"],
  limit: 10
});

const insertResult = client.insert("users", {
  name: "Alice"
}, {
  returning: "id",
  prefer: { return: "representation" }
});
```

## Type Safety Benefits

1. **No `any` Types**: All return values are properly typed
2. **IntelliSense Support**: Full autocomplete for all options
3. **Compile-Time Validation**: Catch errors before runtime
4. **Refactoring Safety**: TypeScript will catch breaking changes
5. **Self-Documenting**: Types serve as inline documentation
6. **Better DX**: Less time debugging, more time building

## Performance

The type-safe client is a thin wrapper around the WASM bindings with **zero runtime overhead**:

- No additional parsing or validation
- Direct pass-through to WASM functions
- Type checking happens at compile time only
- Same performance as using WASM API directly

## Summary

| Feature | WASM API | Client API |
|---------|----------|------------|
| Type Safety | ❌ Many `any` types | ✅ Fully typed |
| API Style | JSON strings | ✅ Native objects |
| HTTP Methods | Any string | ✅ Strict union type |
| Headers | JSON string | ✅ Typed object |
| IntelliSense | ❌ Limited | ✅ Full support |
| Error Messages | ❌ Generic | ✅ Detailed |
| Bundle Size | Smaller | +~2KB (minified) |
| Performance | Fast | ✅ Same (zero overhead) |

## Conclusion

The type-safe client provides a significantly better developer experience while maintaining the same performance as the low-level WASM API. Use it for all new code.

For more examples, see:
- [examples/typescript_client_example.ts]examples/typescript_client_example.ts
- [examples/wasm_mutations_example.ts]examples/wasm_mutations_example.ts