Skip to content
Open
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
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,8 @@ dist

# TernJS port file
.tern-port

.yarn/
.pnp.*
yarn.lock
node_modules/
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,28 @@ const arrays = conn.execute(query, [1], { as: 'array' })
// arrays.rows => [['1', '2']]
```

### Bulk Insert Helper

You can use the `createBulkInsert` helper to easily construct SQL and parameters for bulk inserts:

```ts
import { connect } from '@planetscale/database'
import { createBulkInsert } from './src/bulkInsert'

const conn = connect({
host: '<host>',
username: '<user>',
password: '<password>'
})

const { sql, params } = createBulkInsert(
'INSERT INTO x VALUES',
[[1, 2, 3], [4, 5, 6]]
)
const result = await conn.execute(sql, params)
console.log(result)
```

## Development

```sh
Expand Down
18 changes: 18 additions & 0 deletions __tests__/bulkInsert.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { createBulkInsert } from '../src/bulkInsert'

describe('createBulkInsert', () => {
it('creates SQL and params for bulk insert', () => {
const baseSql = 'INSERT INTO x VALUES'
const rows = [ [1, 2, 3], [4, 5, 6] ]
const { sql, params } = createBulkInsert(baseSql, rows)
expect(sql).toBe('INSERT INTO x VALUES (?, ?, ?), (?, ?, ?)')
expect(params).toEqual([1, 2, 3, 4, 5, 6])
})

it('throws if no rows', () => {
expect(() => createBulkInsert('INSERT INTO x VALUES', [])).toThrow('No rows provided')
})
})



1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^5.0.0",
"jest": "^29.6.1",
"jest-util": "^30.0.5",
"prettier": "^3.0.0",
"sqlstring": "^2.3.3",
"ts-jest": "^29.1.1",
Expand Down
15 changes: 15 additions & 0 deletions src/bulkInsert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* Helper to create bulk insert SQL and parameters.
* @param baseSql The base SQL, e.g. "INSERT INTO x VALUES"
* @param rows Array of rows, e.g. [[1,2,3],[4,5,6]]
* @returns { sql: string, params: any[] }
*/
export function createBulkInsert(baseSql: string, rows: any[][]) {
if (!rows.length) throw new Error('No rows provided')
const placeholders = rows.map(row => `(${row.map(() => '?').join(', ')})`).join(', ')
const sql = `${baseSql} ${placeholders}`
const params = rows.flat()
return { sql, params }
}