Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion docs/runtime/sql.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1180,12 +1180,49 @@ console.log(typeof x, x); // "bigint" 9223372036854777n

---

## Column Name Transforms

You can automatically transform column names (for example, `snake_case` from your database to `camelCase` in JavaScript) by passing the `transform` option to the SQL client:

```ts
import { SQL, postgres } from "bun";

const sql = new SQL({
transform: postgres.camel, // convert snake_case column names to camelCase
});

const [user] = await sql`SELECT first_name, last_name FROM users WHERE id = 1`;
console.log(user.firstName, user.lastName); // "Alice" "Smith"

// When using query helpers, Object property keys are automatically converted back to snake_case column names in SQL:
await sql`INSERT INTO users ${sql({ firstName: "Bob", lastName: "Jones" })}`;
// SQL generated: INSERT INTO users ("first_name", "last_name") VALUES ($1, $2)
```

Bun supports built-in Unicode-aware transformers:

- `postgres.camel` / `SQL.camel` (`snake_case` <-> `camelCase`)
- `postgres.pascal` / `SQL.pascal` (`snake_case` <-> `PascalCase`)
- `postgres.kebab` / `SQL.kebab` (`snake_case` <-> `kebab-case`)
- `postgres.snake` / `SQL.snake` (`camelCase` <-> `snake_case`)

Or pass a custom transform function:

```ts
const sql = new SQL({
transform: {
column: (name) => name.toUpperCase(),
},
});
```
Comment on lines +1209 to +1217

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document transform.value and transform.row.

The section only covers transform.column, but value ({ to, from }, applied on read and to bound helper values on write) and row are both supported and typed in sql.d.ts. Worth a short example so the bidirectional value semantics aren't discovered by reading the source.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/runtime/sql.mdx` around lines 1209 - 1217, Extend the custom transform
documentation near the existing transform.column example to also cover
transform.value and transform.row. Add a concise example describing value’s
bidirectional { to, from } behavior for reads and bound helper values on writes,
and document row as another supported transform option consistent with the types
in sql.d.ts.


---

## Roadmap

Things we haven't finished yet:

- Connection preloading with the `--db-preconnect` Bun CLI flag
- Column name transforms (for example, `snake_case` to `camelCase`). This is mostly blocked on a unicode-aware implementation of changing the case in C++ using WebKit's `WTF::String`.
- Column type transforms

---
Expand Down
41 changes: 41 additions & 0 deletions packages/bun-types/sql.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,13 +159,44 @@ declare module "bun" {
constructor(message: string, options: { code: string; errno: number; byteOffset?: number | undefined });
}

const camel: ColumnTransform;
const pascal: ColumnTransform;
const kebab: ColumnTransform;
const snake: ColumnTransform;
function toCamel(str: string): string;
function toPascal(str: string): string;
function toKebab(str: string): string;
function toSnake(str: string): string;
function fromCamel(str: string): string;
function fromPascal(str: string): string;
function fromKebab(str: string): string;
function fromSnake(str: string): string;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

type AwaitPromisesArray<T extends Array<PromiseLike<any>>> = {
[K in keyof T]: Awaited<T[K]>;
};

type ContextCallbackResult<T> = T extends Array<PromiseLike<any>> ? AwaitPromisesArray<T> : Awaited<T>;
type ContextCallback<T, SQL> = (sql: SQL) => Bun.MaybePromise<T>;

interface ColumnTransform {
(column: string): string;
to?: (column: string) => string;
from?: (column: string) => string;
}

interface TransformOptions {
column?: ColumnTransform | {
to?: (column: string) => string;
from?: (column: string) => string;
} | undefined;
value?: ((value: any) => any) | {
to?: (value: any) => any;
from?: (value: any) => any;
} | undefined;
row?: ((row: any) => any) | undefined;
}
Comment on lines +188 to +198

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

TransformOptions doesn't express the top-level { to, from } shape the runtime accepts.

parseTransform in src/js/internal/sql/shared.ts (Lines 2304-2307) treats an object with bare to/from and no column key as a column transform, but that form is a type error against this declaration. Either add it to the union or drop the runtime branch so the public contract and the parser agree.

♻️ Proposed type addition
     interface TransformOptions {
       column?: ColumnTransform | {
         to?: (column: string) => string;
         from?: (column: string) => string;
       } | undefined;
+      /** Shorthand for `column`, applied when `column` is not set. */
+      to?: ((column: string) => string) | undefined;
+      from?: ((column: string) => string) | undefined;
       value?: ((value: any) => any) | {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
interface TransformOptions {
column?: ColumnTransform | {
to?: (column: string) => string;
from?: (column: string) => string;
} | undefined;
value?: ((value: any) => any) | {
to?: (value: any) => any;
from?: (value: any) => any;
} | undefined;
row?: ((row: any) => any) | undefined;
}
interface TransformOptions {
column?: ColumnTransform | {
to?: (column: string) => string;
from?: (column: string) => string;
} | undefined;
/** Shorthand for `column`, applied when `column` is not set. */
to?: ((column: string) => string) | undefined;
from?: ((column: string) => string) | undefined;
value?: ((value: any) => any) | {
to?: (value: any) => any;
from?: (value: any) => any;
} | undefined;
row?: ((row: any) => any) | undefined;
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/bun-types/sql.d.ts` around lines 188 - 198, Update the
TransformOptions interface to include the top-level { to, from }
column-transform shape accepted by parseTransform when no column key is present,
adding it to the existing column union while preserving current function and
nested-object forms.


interface SQLiteOptions extends BunSQLite.DatabaseOptions {
adapter?: "sqlite";

Expand Down Expand Up @@ -195,6 +226,11 @@ declare module "bun" {
* Receives the closing `Error`, or `null`.
*/
onclose?: ((err: Error | null) => void) | undefined;

/**
* Column name and value transforms (e.g. `postgres.camel` for snake_case -> camelCase).
*/
transform?: TransformOptions | ColumnTransform | ((column: string) => string) | undefined;
Comment on lines +229 to +233

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

(column: string) => string is already subsumed by ColumnTransform.

ColumnTransform has a bare call signature with optional to/from, so a plain function satisfies it; the third union member is redundant noise in both option interfaces.

Also applies to: 428-432

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/bun-types/sql.d.ts` around lines 229 - 233, Remove the redundant
`(column: string) => string` union member from the `transform` property in both
option interfaces, leaving `TransformOptions | ColumnTransform | undefined`; use
`ColumnTransform` as the sole function-compatible type.

}

interface PostgresOrMySQLOptions {
Expand Down Expand Up @@ -389,6 +425,11 @@ declare module "bun" {
* @default false
*/
allowPublicKeyRetrieval?: boolean | undefined;

/**
* Column name and value transforms (e.g. `postgres.camel` for snake_case -> camelCase).
*/
transform?: TransformOptions | ColumnTransform | ((column: string) => string) | undefined;
}

/**
Expand Down
58 changes: 57 additions & 1 deletion src/js/bun/sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,26 @@ const { Query, SQLQueryFlags } = require("internal/sql/query");
const { PostgresAdapter } = require("internal/sql/postgres");
const { MySQLAdapter } = require("internal/sql/mysql");
const { SQLiteAdapter } = require("internal/sql/sqlite");
const { SQLHelper, parseOptions } = require("internal/sql/shared");
const {
SQLHelper,
parseOptions,
camel,
pascal,
kebab,
snake,
toCamel,
toPascal,
toKebab,
toSnake,
toCamelTransform,
fromCamelTransform,
toPascalTransform,
fromPascalTransform,
toKebabTransform,
fromKebabTransform,
toSnakeTransform,
fromSnakeTransform,
} = require("internal/sql/shared");
Comment on lines +10 to +29

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

toCamelTransform/toPascalTransform/toKebabTransform/toSnakeTransform are destructured but never used.

Only the from*Transform bindings are referenced (Lines 1067-1070, 1131-1134); the to*Transform aliases duplicate toCamel/toPascal/toKebab/toSnake and can be dropped from both this destructuring and the shared.ts export surface.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/js/bun/sql.ts` around lines 10 - 29, Remove the unused toCamelTransform,
toPascalTransform, toKebabTransform, and toSnakeTransform bindings from the
destructuring in sql.ts, and remove their corresponding exports from the
shared.ts export surface. Preserve the existing toCamel, toPascal, toKebab,
toSnake, and from*Transform APIs.


const { SQLError, PostgresError, SQLiteError, MySQLError } = require("internal/sql/errors");

Expand Down Expand Up @@ -1037,6 +1056,31 @@ SQL.SQLError = SQLError;
SQL.PostgresError = PostgresError;
SQL.SQLiteError = SQLiteError;
SQL.MySQLError = MySQLError;
SQL.camel = camel;
SQL.pascal = pascal;
SQL.kebab = kebab;
SQL.snake = snake;
SQL.toCamel = toCamel;
SQL.toPascal = toPascal;
SQL.toKebab = toKebab;
SQL.toSnake = toSnake;
SQL.fromCamel = fromCamelTransform;
SQL.fromPascal = fromPascalTransform;
SQL.fromKebab = fromKebabTransform;
SQL.fromSnake = fromSnakeTransform;

defaultSQLObject.camel = camel;
defaultSQLObject.pascal = pascal;
defaultSQLObject.kebab = kebab;
defaultSQLObject.snake = snake;
defaultSQLObject.toCamel = toCamel;
defaultSQLObject.toPascal = toPascal;
defaultSQLObject.toKebab = toKebab;
defaultSQLObject.toSnake = toSnake;
defaultSQLObject.fromCamel = fromCamelTransform;
defaultSQLObject.fromPascal = fromPascalTransform;
defaultSQLObject.fromKebab = fromKebabTransform;
defaultSQLObject.fromSnake = fromSnakeTransform;

// // Helper functions for native code to create error instances
// // These are internal functions used by native code
Expand Down Expand Up @@ -1076,4 +1120,16 @@ export default {
PostgresError,
MySQLError,
SQLiteError,
camel,
pascal,
kebab,
snake,
toCamel,
toPascal,
toKebab,
toSnake,
fromCamel: fromCamelTransform,
fromPascal: fromPascalTransform,
fromKebab: fromKebabTransform,
fromSnake: fromSnakeTransform,
};
11 changes: 11 additions & 0 deletions src/js/internal/sql/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,17 @@ class Query<T, Handle extends BaseQueryHandle<any>> extends PublicPromise<T> {

handle.done?.();

const transform = (this[_adapter] as any)?.connectionInfo?.transform;
if (transform) {
try {
const { applyResultTransform } = require("./shared");
applyResultTransform(x, transform);
} catch (err) {
this[_queryStatus] |= SQLQueryStatus.error;
return this.reject(err as Error);
}
}

return this[_resolve](x);
}

Expand Down
Loading
Loading