• Stars
    star
    1,166
  • Rank 40,051 (Top 0.8 %)
  • Language
    TypeScript
  • License
    Apache License 2.0
  • Created over 2 years ago
  • Updated 16 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Fetch API-compatible PlanetScale database driver

PlanetScale Serverless Driver for JavaScript

A Fetch API-compatible PlanetScale 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'

const config = {
  host: '<host>',
  username: '<user>',
  password: '<password>'
}

const conn = connect(config)
const results = await conn.execute('select 1 from dual where 1=?', [1])
console.log(results)

Database URL

A single database URL value can be used to configure the host, username, and password values.

import { connect } from '@planetscale/database'

const config = {
  url: process.env['DATABASE_URL'] || 'mysql://user:pass@host'
}

const conn = connect(config)

Connection factory

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

import { Client } from '@planetscale/database'

const client = new Client({
  host: '<host>',
  username: '<user>',
  password: '<password>'
})

const conn = client.connection()
const results = await conn.execute('select 1 from dual')
console.log(results)

Transactions

Use the transaction 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 on the Slotted Counter Pattern.

import { connect } from '@planetscale/database'

const config = {
  host: '<host>',
  username: '<user>',
  password: '<password>'
}

const conn = connect(config)
const results = await conn.transaction(async (tx) => {
  const whenBranch = await tx.execute('INSERT INTO branches (database_id, name) VALUES (?, ?)', [42, "planetscale"])
  const whenCounter = await tx.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)

Usage with PlanetScale Boost

To enable PlanetScale Boost, run SET @@boost_cached_queries = true once. All subsequent queries run on the same connection will use boost if it's enabled for the query pattern. Non-matching queries will run as normal.

To learn more, visit: Query caching with PlanetScale Boost

const conn = client.connection()
// Enable boost for the connection
await conn.execute('SET @@boost_cached_queries = true')

const results = await conn.execute('...')

// Optionally, you may disable boost for the connection by setting to false
await conn.execute('SET @@boost_cached_queries = false')

Custom fetch function

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

import { connect } from '@planetscale/database'
import { fetch } from 'undici'

const config = {
  fetch,
  host: '<host>',
  username: '<user>',
  password: '<password>'
}

const conn = connect(config)
const results = await conn.execute('select 1 from dual')
console.log(results)

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

import { connect } from '@planetscale/database'
import { context } from 'fetch-h2'
const { fetch, disconnectAll } = context()

const config = {
  fetch,
  host: '<host>',
  username: '<user>',
  password: '<password>'
}

const conn = connect(config)
const results = await conn.execute('select 1 from dual')
console.log(results)
await disconnectAll()

Custom query parameter format function

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

const results1 = await conn.execute('select 1 from dual where 1=?', [42])
const results2 = await conn.execute('select 1 from dual where 1=:id', { id: 42 })

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

import { connect } from '@planetscale/database'
import SqlString from 'sqlstring'

const config = {
  format: SqlString.format,
  host: '<host>',
  username: '<user>',
  password: '<password>'
}

const conn = connect(config)
const results = await conn.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 a cast function.

import { connect, cast } from '@planetscale/database'

function inflate(field, value) {
  if (field.type === 'INT64' || field.type === 'UINT64') {
    return BigInt(value)
  }
  return cast(field, value)
}

const config = {
  cast: inflate,
  host: '<host>',
  username: '<user>',
  password: '<password>'
}

const conn = connect(config)

You can also pass a custom cast function to execute. If present, this will override the cast function set by the connection:

const result = await conn.execute(
  'SELECT userId, SUM(balance) AS balance FROM UserBalanceItem GROUP BY userId',
  {},
  {
    cast: (field, value) => {
      if (field.name === 'balance') {
        return BigInt(value)
      }
      return cast(field, value)
    }
  }
)

Row return values

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

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

const arrays = conn.execute(query, [1], { as: 'array' })
// arrays.rows => [['1', '2']]

Development

npm install
npm test

License

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

More Repositories

1

beam

A simple message board for your organization or project
TypeScript
2,052
star
2

vtprotobuf

A Protocol Buffers compiler that generates optimized marshaling & unmarshaling Go code for ProtoBuf APIv2
Go
867
star
3

cli

The CLI for PlanetScale Database
Go
603
star
4

fast_page

Blazing fast pagination for ActiveRecord with deferred joins ⚡️
Ruby
308
star
5

vitess-operator

Kubernetes Operator for Vitess
Go
303
star
6

nextjs-planetscale-starter

A Next.js starter app with NextAuth.js (Auth), Prisma (ORM), and PlanetScale (database), ready to be deployed on Netlify
TypeScript
257
star
7

nextjs-starter

Next.js starter application using Prisma to connect to PlanetScale
JavaScript
136
star
8

f1-championship-stats

🏎
TypeScript
130
star
9

planetscale-go

Go client library to access the PlanetScale API
Go
125
star
10

docs

PlanetScale documentation
Shell
93
star
11

schemadiff

Declarative schema diffing, normalization, validation and manipulation via command line
Go
91
star
12

discussion

78
star
13

issues-calendar-for-github-projects

A tool to view GitHub Project Issues in a calendar view.
TypeScript
77
star
14

planetscale_rails

Make Rails schema migrations easy with PlanetScale
Ruby
62
star
15

planetscale-node

PlanetScale SQL Proxy NPM Module
TypeScript
55
star
16

sql-proxy

SQL Proxy for PlanetScale DB
Go
53
star
17

connection-examples

A collection of PlanetScale connection examples
Elixir
51
star
18

activerecord-sql_commenter

Rails query logging compatible with sqlcommenter
Ruby
43
star
19

nextjs-conf-2021

The code from "Databases as Code with PlanetScale and Prisma" talk at Next.js Conf 2021
JavaScript
34
star
20

vitess-releases

Vitess releases
Shell
30
star
21

ghcommit-action

GitHub Action to commit files to a git branch using the ghcommit utility
Shell
30
star
22

planetscale-ruby

Ruby client for PlanetScale databases
Ruby
30
star
23

ghcommit

Use GitHub's GraphQL API to commit files to a GitHub repository.
Go
28
star
24

express-example

Example Express.js app connecting to PlanetScale
JavaScript
28
star
25

setup-pscale-action

Setup the PlanetScale CLI for GitHub Actions
TypeScript
20
star
26

boost-beta

Welcome to the PlanetScale Boost Private Beta
17
star
27

create-branch-action

A GitHub Action that creates a new branch of your PlanetScale database
Shell
12
star
28

planetpets

A demo application that uses PlanetScale OAuth v2 to access users' databases and organizations.
TypeScript
11
star
29

planetscale-nestjs

Starter application demonstrating how to connect a NestJS API to a PlanetScale MySQL database
TypeScript
11
star
30

database-js-starter

A sample Node.js application that uses the database-js package.
JavaScript
11
star
31

figma-diagram-generator

Code to go along with the figma DB diagram creator video
TypeScript
11
star
32

airbyte-source

Airbyte source for PlanetScale databases
Go
9
star
33

django_psdb_engine

Disable foreign key constraints in Django
Python
9
star
34

deploy-deploy-request-action

A GitHub Action that deploys an existing deploy request of your PlanetScale database
Shell
8
star
35

laravel-example

Sample application showing how to integrate Laravel with PlanetScale
PHP
7
star
36

cloudflare-workers-quickstart

A sample repository demonstrating how to use PlanetScale with CloudFlare Workers.
JavaScript
7
star
37

laravel-crud-mysql

JavaScript
6
star
38

vitess-framework-testing

Validating Vitess across clients and frameworks.
Ruby
6
star
39

singer-tap

Singer.io tap for extracting PlanetScale data
Go
6
star
40

mysql-dds

Loadable MySQL functions for working with DDSketches
C++
6
star
41

terraform-provider-planetscale

Terraform provider for PlanetScale
Go
6
star
42

django-example

Connect a sample Django application to PlanetScale
Python
6
star
43

sysbench

A fork of sysbench to add Vitess specific Modifications
C
6
star
44

10-minute-app

Set up a stateful app fast
JavaScript
5
star
45

vercel-integration-example

JavaScript
5
star
46

go-planetscale-products

Go
5
star
47

create-deploy-request-action

A GitHub Action that creates a new deploy request for your PlanetScale database
Dockerfile
5
star
48

psdbproxy

MySQL proxy for local connections to a PlanetScale database over HTTP/2
Go
5
star
49

golang-example

Go
4
star
50

integrations

planetscale integration examples
JavaScript
4
star
51

fivetran-source

PlanetScale Source connector for FiveTran
Go
4
star
52

scoop-bucket

Scoop bucket for PlanetScale CLI binaries.
4
star
53

create-branch-password-action

A GitHub Action that creates a new password for your PlanetScale database branch
Shell
4
star
54

pscale-workflow-helper-scripts

Shell
4
star
55

vault-gcp-creds-buildkite-plugin

Retrieve time-limited oauth2 access token for an impersonated account from a Hashicorp Vault GCP Secrets Backend
Shell
4
star
56

heroku-buildpack-planetscale

A Heroku Buildpack for adding Planetscale CLI to your project
Ruby
3
star
57

golang-example-gin

Go
3
star
58

symfony-example

Connect a sample Symfony app to PlanetScale
PHP
3
star
59

log

🪵 📓 PlanetScale's opinionated structured logging library
Go
3
star
60

homebrew-tap

Homebrew repository for the pscale CLI
Ruby
3
star
61

php-example

Connect a sample PHP project to a PlanetScale database.
PHP
3
star
62

mysql-for-python-developers

Python
3
star
63

ps-prechecks

Shell
3
star
64

kubeconform-buildkite-plugin

Run kubeconform against your Kubernetes configurations
Shell
2
star
65

laravel-caching

Sample repo for Laravel caching blog post
PHP
2
star
66

k8s-demo

A simple demo of Vitess on Kubernetes
Python
2
star
67

psdb

Go
2
star
68

transmission

Writes data to MySQL. Quickly.
Rust
2
star
69

cloudranger

Go library for mapping IP address ranges to cloud provider regions (currently: AWS and GCP)
Go
2
star
70

vitess-types

Protobuf types extracted from Vitess
Go
2
star
71

go-bookings-api

An API written in Go simulating a travel booking agency.
Go
1
star
72

django-react-demo

JavaScript
1
star
73

go-logkeycheck

Ensure zap log field names are consistent
Go
1
star
74

vault-oidc-auth-buildkite-plugin

Authenticate to Hashicorp Vault with Buildkite OIDC (JWT) tokens.
Shell
1
star
75

core-prettier

Core Design System shared prettier config
JavaScript
1
star
76

vault-aws-creds-buildkite-plugin

Retrieve time-limited AWS credentials from a Hashicorp Vault AWS Secrets Backend
Shell
1
star
77

aws-connection-strings-example

JavaScript
1
star
78

pargzip

Fork of https://github.com/golang/build/tree/master/pargzip
Go
1
star