Skip to content

Commit f82fb78

Browse files
authored
website: pg-sql2 examples in docs (#2746)
2 parents 6dd07a5 + 5d50088 commit f82fb78

21 files changed

+502
-135
lines changed

.changeset/legal-apes-beam.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"@dataplan/pg": patch
3+
"pg-sql2": patch
4+
---
5+
6+
New: `sql.comment("...", true)` forces comments to be included, even in
7+
production.

grafast/dataplan-pg/src/steps/pgSelect.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3843,7 +3843,10 @@ function buildQueryParts<TResource extends PgResource<any, any, any, any, any>>(
38433843
const extraSelectIndexes = extraSelects.map((_, i) => i + l);
38443844

38453845
return {
3846-
comment: sql.comment(`From ${info.sourceStepDescription}`),
3846+
comment: sql.comment(
3847+
`From ${info.sourceStepDescription}`,
3848+
process.env.DATAPLAN_PG_DEBUG === "1",
3849+
),
38473850
selects,
38483851
from,
38493852
joins: info.joins,

utils/pg-sql2/src/index.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ const isDev =
3333
(process.env.GRAPHILE_ENV === "development" ||
3434
process.env.GRAPHILE_ENV === "test");
3535

36-
const includeComments =
37-
typeof process !== "undefined" && process.env.PGSQL2_DEBUG === "1";
36+
const defaultIncludeComments =
37+
isDev || (typeof process !== "undefined" && process.env.PGSQL2_DEBUG === "1");
3838

3939
const nodeInspect: CustomInspectFunction = function (
4040
this: SQLNode | SQLQuery,
@@ -1099,9 +1099,12 @@ export function placeholder(symbol: symbol, fallback?: SQL): SQL {
10991099
return makePlaceholderNode(symbol, fallback);
11001100
}
11011101

1102-
export function comment(commentText: string): SQLCommentNode | SQLRawNode {
1103-
if (includeComments) {
1104-
return makeCommentNode(commentText);
1102+
export function comment(
1103+
text: string,
1104+
include = defaultIncludeComments,
1105+
): SQLCommentNode | SQLRawNode {
1106+
if (include) {
1107+
return makeCommentNode(text);
11051108
} else {
11061109
return sql.blank;
11071110
}

utils/website/pg-sql2/api/sql-comment.md

Lines changed: 51 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,17 @@ sidebar_position: 10
33
title: "sql.comment()"
44
---
55

6-
# `sql.comment(text)`
6+
# `sql.comment(text, include)`
77

88
Creates an SQL comment fragment that can be embedded in queries. Comments are
99
useful for documenting query logic, adding debugging information, or providing
10-
context for complex operations. Comments are ignored during SQL execution but
11-
can be valuable for debugging and maintenance.
10+
context for complex operations.
11+
12+
Comments are ignored during SQL execution by default but
13+
can be valuable for debugging and maintenance. By default, comments only appear when
14+
[`GRAPHILE_ENV=development`](../development-mode.md) is set, but you can force
15+
them to appear by setting `include` to `true` (or force them to be hidden via
16+
`include` set to `false`).
1217

1318
:::warning[Do not include user-generated content!]
1419

@@ -21,20 +26,21 @@ vulnerable SQL.
2126
## Syntax
2227

2328
```typescript
24-
sql.comment(text: string): SQL
29+
sql.comment(text: string, include?: boolean): SQL
2530
```
2631

2732
## Parameters
2833

2934
- `text` - The comment text to include
35+
- `include` - Optional boolean to force inclusion (`true`) or exclusion (`false`) of the comment regardless of environment. Defaults to `undefined`, which means comments are included only in development mode.
3036

3137
## Return value
3238

3339
Returns a `SQL` fragment containing the properly formatted SQL comment.
3440

3541
## Examples
3642

37-
### Document query
43+
### Leading comment
3844

3945
```js
4046
import { sql } from "pg-sql2";
@@ -44,36 +50,15 @@ ${sql.comment("Fetch active users with their order counts")}
4450
SELECT u.id, COUNT(o.id) as order_count ...
4551
`;
4652

47-
// `sql.compile(query).text` will be something like:
53+
console.log(sql.compile(query).text);
4854
// /* Fetch active users with their order counts */
4955
// SELECT u.id, COUNT(o.id) as order_count ...
5056
```
5157

52-
### Inline comment
58+
### Dynamic comment content
5359

5460
```js
55-
const complexCalculation = sql`
56-
${sql.comment(`Calculate total with shipping and tax at ${parseFloat(taxPercentage)}%`)}
57-
(price + ${sql.value(deliveryCharge)}) * ${sql.value(1 + taxPercentage / 100)}
58-
`;
59-
60-
sql`
61-
UPDATE orders
62-
SET total = ${complexCalculation}
63-
WHERE id = ${sql.value(orderId)}
64-
`;
65-
```
66-
67-
### Conditional comments
68-
69-
```js
70-
const isDevelopment = process.env.NODE_ENV === "development";
71-
7261
function addDebugComments(query, debugInfo) {
73-
if (!isDevelopment) {
74-
return query;
75-
}
76-
7762
return sql`
7863
${sql.comment(`DEBUG: Query generated at ${new Date().toISOString()}`)}
7964
${sql.comment(`DEBUG: Filters applied - ${JSON.stringify(debugInfo)}`)}
@@ -87,22 +72,54 @@ const query = addDebugComments(
8772
);
8873
```
8974

75+
### Inline comment
76+
77+
```js
78+
import { sql } from "pg-sql2";
79+
80+
const taxPercentage = 20.0;
81+
const deliveryCharge = 1.99;
82+
const orderId = 123;
83+
84+
const complexCalculation = sql`
85+
${sql.comment(`Calculate total with shipping and tax at ${parseFloat(taxPercentage)}%`)}
86+
(price + ${sql.value(deliveryCharge)}) * ${sql.value(1 + taxPercentage / 100)}
87+
`;
88+
89+
const query = sql`
90+
UPDATE orders
91+
SET total = ${complexCalculation}
92+
WHERE id = ${sql.value(orderId)}
93+
`;
94+
95+
console.log(sql.compile(query).text);
96+
// UPDATE orders
97+
// SET total =
98+
// /* Calculate total with shipping and tax at 20% */
99+
// (price + $1) * $2
100+
// WHERE id = $3
101+
102+
console.log(sql.compile(query).values);
103+
// The values of $1, $2 and $3:
104+
// [1.99, 1.2, 123]
105+
```
106+
90107
### Comment formatting
91108

92109
```js
93110
// Single line comments become /* comment */
94111
sql.comment("Single line comment");
95-
// -> /* Single line comment */
112+
// /* Single line comment */
96113

97114
// Multi-line comments preserve formatting
98115
sql.comment(`
99116
Line 1
100117
Line 2
101118
Line 3
102119
`);
103-
// -> /*
104-
// Line 1
105-
// Line 2
106-
// Line 3
107-
// */
120+
// /*
121+
// Line 1
122+
// Line 2
123+
// Line 3
124+
// */
108125
```

utils/website/pg-sql2/api/sql-compile.md

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ await client.query(text, values);
4444
### Basic usage
4545

4646
```js
47-
import sql from "pg-sql2";
47+
import { sql } from "pg-sql2";
4848

4949
const userId = 123;
5050
const status = "active";
@@ -59,14 +59,16 @@ const query = sql`
5959
const { text, values } = sql.compile(query);
6060

6161
console.log(text);
62-
// -> SELECT id, name, email FROM users WHERE id = $1 AND status = $2
62+
// SELECT id, name, email FROM users WHERE id = $1 AND status = $2
6363
console.log(values);
64-
// -> [123, 'active']
64+
// [123, 'active']
6565
```
6666

6767
### Complex example
6868

6969
```js
70+
import { sql } from "pg-sql2";
71+
7072
const filters = {
7173
status: "active",
7274
minAge: 18,
@@ -91,21 +93,24 @@ const query = sql`
9193
const compiled = sql.compile(query);
9294

9395
console.log(compiled.text);
94-
// -> SELECT "id", "name", "email", "role", "created_at"
95-
// FROM "users"
96-
// WHERE status = $1
97-
// AND age >= $2
98-
// AND role = ANY($3)
99-
// ORDER BY "created_at" DESC
100-
// LIMIT 50
96+
/* SELECT "id", "name", "email", "role", "created_at"
97+
FROM "users"
98+
WHERE status = $1
99+
AND age >= $2
100+
AND role = ANY($3)
101+
ORDER BY "created_at" DESC
102+
LIMIT 50
103+
*/
101104

102105
console.log(compiled.values);
103-
// -> ['active', 18, ['admin', 'user', 'moderator']]
106+
// ['active', 18, ['admin', 'user', 'moderator']]
104107
```
105108

106109
### With placeholders
107110

108111
```js
112+
import { sql } from "pg-sql2";
113+
109114
const $$table = Symbol("table");
110115
const $$orderBy = Symbol("orderBy");
111116

@@ -118,8 +123,9 @@ const query = sql`
118123

119124
// Compile with defaults
120125
const q1 = sql.compile(query);
126+
121127
console.log(q1.text);
122-
// -> SELECT * FROM "default_table" ORDER BY id ASC
128+
// SELECT * FROM "default_table" ORDER BY id ASC
123129

124130
// Compile with placeholder values
125131
const q2 = sql.compile(query, {
@@ -128,6 +134,7 @@ const q2 = sql.compile(query, {
128134
[$$orderBy, sql`created_at DESC`],
129135
]),
130136
});
137+
131138
console.log(q2.text);
132-
// -> SELECT * FROM "users" ORDER BY created_at DESC
139+
// SELECT * FROM "users" ORDER BY created_at DESC
133140
```

0 commit comments

Comments
 (0)