Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A Fetch API-compatible PlanetScale database driver

License

NotificationsYou must be signed in to change notification settings

planetscale/database-js

Repository files navigation

PlanetScale serverless driver for JavaScript

PlanetScale serverless JavaScript driver for Vitess/MySQL

A Fetch API-compatible PlanetScale Vitess/MySQL database driver for serverless and edge compute platforms that require HTTP external connections, such as Cloudflare Workers or Vercel Edge Functions

Installation

npm install @planetscale/database

Usage

import{connect}from'@planetscale/database'constconfig={host:'<host>',username:'<user>',password:'<password>'}constconn=connect(config)constresults=awaitconn.execute('select 1 from dual where 1=?',[1])console.log(results)

Database URL

A single database URL value can be used to configure thehost,username, andpassword values.

import{connect}from'@planetscale/database'constconfig={url:process.env['DATABASE_URL']||'mysql://user:pass@host'}constconn=connect(config)

Connection factory

Use theClient connection factory class to create fresh connections for each transaction or web request handler.

import{Client}from'@planetscale/database'constclient=newClient({host:'<host>',username:'<user>',password:'<password>'})constconn=client.connection()constresults=awaitconn.execute('select 1 from dual')console.log(results)

Transactions

Use thetransaction function to safely perform database transactions. If any unhandled errors are thrown during execution of the transaction, the transaction will be rolled back.

The following example is based onthe Slotted Counter Pattern.

import{connect}from'@planetscale/database'constconfig={host:'<host>',username:'<user>',password:'<password>'}constconn=connect(config)constresults=awaitconn.transaction(async(tx)=>{constwhenBranch=awaittx.execute('INSERT INTO branches (database_id, name) VALUES (?, ?)',[42,"planetscale"])constwhenCounter=awaittx.execute('INSERT INTO slotted_counters(record_type, record_id, slot, count) VALUES (?, ?, RAND() * 100, 1) ON DUPLICATE KEY UPDATE count = count + 1',['branch_count',42])return[whenBranch,whenCounter]})console.log(results)

Custom fetch function

Node.js version 18 includes a built-in globalfetch function. When using an older version of Node.js, you can provide a custom fetch function implementation. We recommend theundici package on which Node's built-in fetch is based.

import{connect}from'@planetscale/database'import{fetch}from'undici'constconfig={  fetch,host:'<host>',username:'<user>',password:'<password>'}constconn=connect(config)constresults=awaitconn.execute('select 1 from dual')console.log(results)

To leverage HTTP/2, you can use thefetch-h2 shim.fetch-h2 also supports Node.js 12+.

import{connect}from'@planetscale/database'import{context}from'fetch-h2'const{ fetch, disconnectAll}=context()constconfig={  fetch,host:'<host>',username:'<user>',password:'<password>'}constconn=connect(config)constresults=awaitconn.execute('select 1 from dual')console.log(results)awaitdisconnectAll()

Custom query parameter format function

Query replacement parameters identified with? are replaced with escaped values. Named replacement parameters are supported with a colon prefix.

constresults1=awaitconn.execute('select 1 from dual where 1=?',[42])constresults2=awaitconn.execute('select 1 from dual where 1=:id',{id:42})

Providing a custom format function overrides the built-in escaping with an external library, likesqlstring.

import{connect}from'@planetscale/database'importSqlStringfrom'sqlstring'constconfig={format:SqlString.format,host:'<host>',username:'<user>',password:'<password>'}constconn=connect(config)constresults=awaitconn.execute('select 1 from dual where 1=?',[42])console.log(results)

Custom type casting function

Column values are converted to their corresponding JavaScript data types. This can be customized by providing acast function.

import{connect,cast}from'@planetscale/database'functioninflate(field,value){if(field.type==='INT64'||field.type==='UINT64'){returnBigInt(value)}returncast(field,value)}constconfig={cast:inflate,host:'<host>',username:'<user>',password:'<password>'}constconn=connect(config)

You can also pass a customcast function toexecute. If present, this will override thecast function set by the connection:

constresult=awaitconn.execute('SELECT userId, SUM(balance) AS balance FROM UserBalanceItem GROUP BY userId',{},{cast:(field,value)=>{if(field.name==='balance'){returnBigInt(value)}returncast(field,value)}})

Row return values

Rows can be returned as an object or an array of column values by passing anas option toexecute.

constquery='select 1 as one, 2 as two where 1=?'constobjects=conn.execute(query,[1],{as:'object'})// objects.rows => [{one: '1', two: '2'}]constarrays=conn.execute(query,[1],{as:'array'})// arrays.rows => [['1', '2']]

Development

npm installnpmtest

Need help?

Get help fromthe PlanetScale support team, orjoin our community on Discord orGitHub discussion board to see how others are using PlanetScale.

License

Distributed under the Apache 2.0 license. See LICENSE for details.


[8]ページ先頭

©2009-2025 Movatter.jp