Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(connectors): mysql2 support #86

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
27 changes: 22 additions & 5 deletions docs/2.connectors/mysql.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,27 @@ icon: simple-icons:mysql

# MySQL

> Connect DB0 to Mysql Database
> Connect DB0 to Mysql Database using mysql2

:read-more{to="https://github.com/sidorares/node-mysql2"}
## Usage

::read-more{to="https://github.com/unjs/db0/issues/32"}
This connector is planned to be supported. Follow up via [unjs/db0#32](https://github.com/unjs/db0/issues/32).
::
For this connector, you need to install [`mysql2`](https://www.npmjs.com/package/mysql2) dependency:

:pm-install{name="mysql2"}

Use `mysql2` connector:

```js
import { createDatabase, sql } from "db0";
import mysql from "db0/connectors/mysql2";

const db = createDatabase(
mysql({
/* options */
}),
);
```

## Options

:read-more{to="https://github.com/sidorares/node-mysql2/blob/master/typings/mysql/lib/Connection.d.ts#L82-L329"}
34 changes: 34 additions & 0 deletions examples/mysql/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { createDatabase } from "../../src";
import mysqlConnector from "../../src/connectors/mysql2"


async function main() {
const db = createDatabase(mysqlConnector({
host: "localhost",
user: "root",
password: "root",
database: "db0",
}));

await db.sql`CREATE TABLE IF NOT EXISTS users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL
)`;

await db.sql`INSERT INTO users (name) VALUES (${randomValue()})`;

const users = await db.sql`SELECT * FROM users`;

console.log({ rows: users.rows });
}

// eslint-disable-next-line unicorn/prefer-top-level-await
main().catch((error) => {
console.error(error);
// eslint-disable-next-line unicorn/no-process-exit
process.exit(1);
});

function randomValue() {
return Math.random().toString(36).slice(7);
}
10 changes: 10 additions & 0 deletions examples/mysql/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "db0-with-mysql",
"private": true,
"scripts": {
"start": "jiti ./index.ts"
},
"devDependencies": {
"db0": "latest"
}
}
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"build": "unbuild",
"db0": "pnpm jiti src/cli",
"dev": "vitest",
"start": "f () { pnpm --filter db0-with-${1:-'*'} start ;}; f",
"lint": "eslint --ext .ts . && prettier -c src test",
"lint:fix": "eslint --ext .ts . --fix && prettier -w src test",
"prepack": "pnpm build",
Expand All @@ -64,6 +65,7 @@
"eslint": "^8.57.0",
"eslint-config-unjs": "^0.2.1",
"jiti": "^1.21.0",
"mysql2": "^3.9.6",
"pg": "^8.11.5",
"prettier": "^3.2.5",
"typescript": "^5.4.5",
Expand All @@ -87,4 +89,4 @@
}
},
"packageManager": "[email protected]"
}
}
95 changes: 91 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

47 changes: 47 additions & 0 deletions src/connectors/mysql2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import mysql from "mysql2/promise";

import type { Connector, Statement } from "../types";

export default function mysqlConnector(opts: mysql.ConnectionOptions) {
let _connection: mysql.Connection | undefined;
const getConnection = async () => {
if (_connection) {
return _connection;
}

_connection = await mysql.createConnection({
Copy link
Author

Choose a reason for hiding this comment

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

I wan't sure if we want to have some options as default, for example we can set the host to localhost or password to ""...

Choose a reason for hiding this comment

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

Would be nice to default to root@localhost:3306 but unsure how useful in practice :)

Copy link
Author

Choose a reason for hiding this comment

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

yes, or we can set root@localhost:3306 to default only in dev

...opts,
})

return _connection;
};

return <Connector>{
name: "mysql",
exec(sql: string) {
return getConnection().then((c) => c.query(sql).then((res) => res[0]));
},
prepare(sql: string) {
const stmt = <Statement>{
_sql: sql,
_params: [],
bind(...params) {
if (params.length > 0) {
this._params = params;
}
return stmt;
},
all(...params) {
return getConnection().then((c) => c.query(this._sql, params || this._params).then((res) => res[0]));
},
run(...params) {
return getConnection().then((c) => c.query(this._sql, params || this._params).then((res) => res[0]));
},
get(...params) {
return getConnection().then((c) => c.query(this._sql, params || this._params).then((res) => res[0][0]));
},
};
return stmt;
},
};
}
17 changes: 17 additions & 0 deletions test/connectors/mysql2.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { describe } from "vitest";
import connector from "../../src/connectors/mysql2";
import { testConnector } from "./_tests";

describe.runIf(process.env.POSTGRESQL_URL)(
"connectors: mysql2.test",
() => {
testConnector({
connector: connector({
host: "localhost",
user: "root",
password: "root",
database: "db0",
}),
});
},
);