new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Drizzle · MySQL · all subjects

drivers

77 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

AWS Data API for MySQL support status

AWS Data API for MySQL is not currently implemented in Drizzle ORM.

Initialize Drizzle with Bun SQL MySQL - automatic connection

To initialize Drizzle with Bun SQL for MySQL with automatic connection handling, import from 'drizzle-orm/bun-sql/mysql' and call drizzle(process.env.DATABASE_URL).

Initialize Drizzle with Bun SQL MySQL - existing driver

To provide an existing Bun SQL driver instance to Drizzle, import SQL from 'bun', create a new SQL instance with the connection string, then pass it to drizzle({ client }) where the import is from 'drizzle-orm/bun-sql/mysql'.

Bun SQL native bindings for MySQL

Drizzle ORM natively supports the bun sql module, which provides native bindings for working with MySQL databases. The bun sql module is part of Bun, a fast all-in-one JavaScript runtime.

Bun SQL MySQL driver installation

To use Drizzle ORM with Bun SQL and MySQL, install drizzle-orm@rc and drizzle-kit@rc.

Supported MySQL drivers and providers

Drizzle ORM supports the following MySQL drivers and providers: MySQL, PlanetScale MySQL, TiDB, AWS Data API MySQL, Bun SQL, and Drizzle HTTP proxy.

Install packages for PlanetScale MySQL

To use PlanetScale MySQL with Drizzle, install drizzle-orm@rc and @planetscale/database as dependencies, and drizzle-kit@rc as a dev dependency.

PlanetScale MySQL also supports TCP with mysql2

In addition to the HTTP-based planetscale-serverless driver, PlanetScale MySQL can be accessed through TCP using the mysql2 driver, which is the standard MySQL driver for Drizzle.

Initialize PlanetScale driver with connection credentials

Initialize the Drizzle driver for PlanetScale by importing drizzle from 'drizzle-orm/planetscale-serverless' and passing an object with connection properties: host, username, and password from environment variables.

PlanetScale drizzle initialization example with direct credentials

Example code: import { drizzle } from "drizzle-orm/planetscale-serverless"; const db = drizzle({ connection: { host: process.env["DATABASE_HOST"], username: process.env["DATABASE_USERNAME"], password: process.env["DATABASE_PASSWORD"], }}); const response = await db.select().from(...)

PlanetScale drizzle initialization with Client object

Example code: import { drizzle } from "drizzle-orm/planetscale-serverless"; import { Client } from "@planetscale/database"; const client = new Client({ host: process.env["DATABASE_HOST"], username: process.env["DATABASE_USERNAME"], password: process.env["DATABASE_PASSWORD"], }); const db = drizzle({ client });

PlanetScale offers MySQL and PostgreSQL

PlanetScale offers both MySQL (Vitess) and PostgreSQL databases. PlanetScale MySQL is accessed through the planetscale-serverless driver, while PlanetScale PostgreSQL requires a separate connection guide.

PlanetScale MySQL connection package

Drizzle ORM provides the drizzle-orm/planetscale-serverless package for connecting to PlanetScale MySQL over HTTP through the PlanetScale database-js driver. This package supports both serverless and serverfull environments.

TiDB Serverless driver package

Drizzle ORM supports TiDB Serverless via the `drizzle-orm/tidb-serverless` package. TiDB Serverless provides an HTTP driver designed for edge environments and is natively supported by Drizzle ORM.

TiDB Serverless packages to install

To use TiDB Serverless with Drizzle, install `drizzle-orm@rc`, `@tidbcloud/serverless`, and `drizzle-kit@rc` (as dev dependency).

Initialize TiDB Serverless driver without client

TiDB Serverless can be initialized by passing a connection configuration with a URL directly to drizzle. The code is: `import { drizzle } from 'drizzle-orm/tidb-serverless'; const db = drizzle({ connection: { url: process.env.TIDB_URL }});`

Initialize TiDB Serverless driver with existing client

If you have an existing TiDB Serverless client, you can pass it to Drizzle. The code is: `import { connect } from '@tidbcloud/serverless'; import { drizzle } from 'drizzle-orm/tidb-serverless'; const client = connect({ url: process.env.TIDB_URL }); const db = drizzle({ client });`

TiDB Serverless description

According to the official TiDB website, TiDB Serverless is a fully-managed, autonomous DBaaS (Database-as-a-Service) with split-second cluster provisioning and consumption-based pricing.

TiDB Serverless MySQL compatibility

TiDB Serverless is compatible with MySQL, so the MySQL connection guide can be used to connect to TiDB Serverless.

drizzle-kit check requires dialect parameter

The drizzle-kit check command requires you to specify the dialect parameter. You can provide it either via the drizzle.config.ts config file or via CLI options using --dialect=mysql.

drizzle-kit check with CLI options example

To use drizzle-kit check with CLI options, run 'npx drizzle-kit check --dialect=mysql' without needing a config file.

drizzle-kit check CLI examples

Examples of drizzle-kit check CLI usage: 'npx drizzle-kit check --dialect=mysql' and 'npx drizzle-kit check --dialect=mysql --out=./migrations-folder'.

Drizzle migrations log table

When running drizzle-kit migrate, Drizzle records information about successfully applied migrations in a log table named __drizzle_migrations by default. This table name can be customized via the migrations config option.

defineConfig function from drizzle-kit

To create a Drizzle configuration file, import defineConfig from 'drizzle-kit' and use it to export a default configuration object with properties like dialect, schema, out, and other options.

MySQL dialect configuration

Set the dialect property to 'mysql' when configuring Drizzle Kit for MySQL databases.

Drizzle Kit configuration: dialect property

The dialect property specifies which database dialect to use. Type: string. Default: required. Supported in commands: generate, push, pull, studio, migrate, up, export. For MySQL, set dialect to 'mysql'.

Drizzle Kit configuration: schema property

The schema property accepts a glob-based path to drizzle schema file(s) or folder(s) containing schema files. Type: string or string[]. Default: required. Supported in commands: generate, push, export, studio. Example values: './src/schema.ts' or './src/schema/*'.

Drizzle Kit configuration: dbCredentials property

The dbCredentials property contains database connection credentials. Type: depends on dialect. Default: required. Supported in commands: push, pull, migrate, studio. For MySQL, can use either connection string format (url: 'mysql://user:password@host:port/db') or connection params (host, port, user, password, database, ssl).

MySQL dbCredentials with connection string

To connect using a connection string, set dbCredentials.url to 'mysql://user:password@host:port/db' format.

MySQL dbCredentials with connection params

To connect using individual parameters, use: host (string), port (number), user (string), password (string), database (string), and ssl (can be string or SslOptions from mysql2).

Introspect casing: camel vs preserve

When casing is set to 'camel', column names are converted to camelCase in the generated schema (e.g., 'first-name' becomes firstName, 'phone_number' becomes phoneNumber). When set to 'preserve', column names are kept exactly as they appear in the database.

Drizzle Kit configuration: tablesFilter property

The tablesFilter property specifies which tables to manage during drizzle-kit push and drizzle-kit pull commands. Type: string or string[]. Default: manages all tables. Supported in commands: push, pull. Accepts glob-based table name filters, e.g., ['users', 'user_info'] or 'user*'.

Use client or pool for querying based on requirements

For querying purposes, feel free to use either a client or pool based on business demands. Only migrations require a single client connection.

Initialize Drizzle with mysql2 using connection string

To initialize Drizzle with mysql2, import from drizzle-orm/mysql2 and call drizzle() with process.env.DATABASE_URL. This creates a db instance that can be used for queries like db.select().from(...).

Initialize Drizzle with mysql2 using config object

Drizzle can be initialized with a config object specifying connection options from mysql2. Use drizzle({ connection: { uri: process.env.DATABASE_URL } }) to pass mysql2 connection properties.

Create Drizzle instance with existing mysql2 pool connection

To use an existing mysql2 pool connection, import mysql from mysql2/promise, create a pool with mysql.createPool(), then pass it to drizzle({ client: poolConnection }). This allows connection pooling with full configuration control.

Use single client connection for migrations

For the built-in migrate function with DDL migrations, use a single client connection rather than a pool connection. Drizzle and drivers strongly encourage this approach for migrations.

MySQL driver installation for Drizzle

To use Drizzle with MySQL, install the mysql2 driver. The required packages are drizzle-orm@rc, mysql2, and drizzle-kit@rc as a dev dependency.

Mock driver for testing

Every drizzle driver provides a drizzle.mock() API to create a mock database instance without connecting to a real database. Can optionally pass schema/relations. Example: const db = drizzle.mock(); or const db = drizzle.mock({ relations });

Drizzle has exactly 0 dependencies

Drizzle ORM has no external dependencies, making it lightweight and suitable for serverless environments.

Supported database drivers and dialects

Drizzle operates natively through industry-standard database drivers and supports PostgreSQL, MySQL, SQLite, SingleStore, MSSQL, and CockroachDB drivers.

Drizzle is designed for serverless environments

Drizzle ORM is dialect-specific, slim, performant and serverless-ready by design with zero dependencies.

mode parameter removed from drizzle() constructor in v2

Relational Queries v2 uses the same strategy for all MySQL dialects, so the mode parameter is no longer needed in drizzle(). Pass relations instead of schema or mode.

Database instance migration from schema to relations parameter

When migrating to v2, change drizzle() instantiation from {schema} to {relations}. Example before: drizzle(url, {schema}). Example after: drizzle(url, {relations})

Generic type changes in MySql2Database for v2

MySql2Database generic changed from TSchema extends Record<string, unknown> to TRelations extends AnyRelations = EmptyRelations. Similar changes apply to MySql2Session and MySql2Transaction classes.

DrizzleConfig updated for v2 with relations

DrizzleConfig generic now uses TRelationConfigs extends AnyRelations = EmptyRelations. The config object now has relations?: TRelationConfigs field instead of schema field, plus added cache and jit optional fields.

New MSSQL and CockroachDB dialects

New MSSQL dialect support and new CockroachDB dialect support have been added in v1.

New NetlifyDB driver support

New NetlifyDB driver support has been added in v1. The Netlify Database driver is developed and maintained by the Netlify team.

Drizzle HTTP Proxy purpose and use cases

Drizzle Proxy is used when you need to implement your own driver communication with the database. It can be used to add custom logic at the query stage with existing drivers. The most common use is with an HTTP driver, which sends queries to your server with the database, executes the query on your database, and responds with raw data that Drizzle ORM can then map to results.

HTTP Proxy callback function signature

Drizzle ORM supports using an asynchronous callback function for executing SQL. The callback receives three parameters: sql (a query string with placeholders), params (an array of parameters), and method (either 'all' or 'execute' depending on the SQL statement). The callback must return either {rows: string[][]} or {rows: string[]}. When method is 'execute', return {rows: string[]}. Otherwise, return {rows: string[][]}.

HTTP Proxy driver implementation example

Example of Drizzle HTTP proxy driver implementation: ```typescript import { drizzle } from 'drizzle-orm/mysql-proxy'; import axios from "axios"; const db = drizzle(async (sql, params, method) => { try { const rows = await axios.post('http://localhost:3000/query', { sql, params, method }); return { rows: rows.data }; } catch (e: any) { console.error('Error from mysql proxy server: ', e.response.data) return { rows: [] }; } }); ``` This example shows how to create a Drizzle database instance using the mysql-proxy driver with an HTTP endpoint that receives sql, params, and method, then returns the data.

HTTP Proxy server implementation example with mysql2

Example of HTTP proxy server implementation using mysql2/promise and Express: ```typescript import * as mysql from 'mysql2/promise'; import express from 'express'; const app = express(); app.use(express.json()); const port = 3000; const main = async () => { const connection = await mysql.createConnection('•••••://root:mysql@127.0.0.1:5432/drizzle'); app.post('/query', async (req, res) => { const { sql, params, method } = req.body; const sqlBody = sql.replace(/;/g, ''); try { const result = await connection.query({ sql: sqlBody, values: params, rowsAsArray: method === 'all', typeCast: function(field: any, next: any) { if (field.type === 'TIMESTAMP' || field.type === 'DATETIME' || field.type === 'DATE') { return field.string(); } return next(); }, }); } catch (e: any) { res.status(500).json({ error: e }); } if (method === 'all') { res.send(result[0]); } else if (method === 'execute') { res.send(result); } res.status(500).json({ error: 'Unknown method value' }); }); app.listen(port, () => { console.log(`Example app listening on port ${port}`); }); }; main(); ``` This server receives POST requests with sql, params, and method in the body, executes queries against a MySQL database using mysql2/promise, handles type casting for TIMESTAMP, DATETIME, and DATE fields, and returns results formatted based on the method type.

HTTP Proxy query execution workflow

The HTTP Proxy workflow consists of four steps: (1) Drizzle ORM builds a query, (2) the built query is sent via HTTP to an HTTP Server with the database, (3) the HTTP server executes the query and sends raw results back, and (4) Drizzle ORM maps the data and returns the result.

HTTP Proxy prevent multiple queries security measure

In HTTP Proxy server implementation, semicolons should be removed from SQL statements using sql.replace(/;/g, '') to prevent multiple queries from being executed in a single request.

HTTP Proxy rowsAsArray parameter usage

When using mysql2/promise with Drizzle HTTP Proxy, set rowsAsArray to true when method is 'all' to return data as arrays instead of objects, which is required for the {rows: string[][]} return format.

driver config option

The driver option explicitly specifies a database driver. Drizzle Kit automatically picks available drivers based on the provided dialect, but some vendor-specific databases require different connection parameters. Type is from available drivers list. No default value. Used in commands: push, migrate, pull, studio.

sqlite-proxy and SQL.js .get() empty result fix

In DrizzleORM v0.28.3, the response from .get() method for sqlite-proxy and SQL.js was fixed to properly handle when the result is empty.

PostgreSQL Proxy Driver in v0.29.0

A new PostgreSQL proxy driver is available in v0.29.0, allowing custom HTTP driver implementation. Import with: import { drizzle } from 'drizzle-orm/pg-proxy' and import { migrate } from 'drizzle-orm/pg-proxy/migrator'. The driver accepts a callback: drizzle(async (sql, params, method) => { ... }). Implementation examples are in ./examples/pg-proxy folder. Requires server endpoints for queries and optional migrate endpoint.

PostgreSQL proxy driver callback signature

The PostgreSQL proxy driver callback function has the signature: async (sql, params, method) => { ... }. The callback receives the SQL string, parameters array, and method name, and must return an object with a rows property: { rows: rows.data }.

Expo SQLite driver installation and setup

To use the Expo SQLite driver with Drizzle, install the drizzle-orm and expo-sqlite packages. Run: npm install drizzle-orm expo-sqlite@next. Import drizzle from 'drizzle-orm/expo-sqlite' and openDatabaseSync from 'expo-sqlite'. Create a database instance with openDatabaseSync('db.db') and pass it to drizzle().

Give your agent this brain