-
Notifications
You must be signed in to change notification settings - Fork 50
feat: MSSQL connector #197
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
Open
vkuttyp
wants to merge
24
commits into
unjs:main
Choose a base branch
from
vkuttyp:add-mssql-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
ccb2dc7
Add MSSQL Server support to db0
vkuttyp 351643d
testing fixed MSSQL support
vkuttyp ccb0822
added stored procedure tests
vkuttyp f0555c9
added test for json auto
vkuttyp bb523ac
.env.example updated
vkuttyp 081db35
added sql server in docker-compose.yml
vkuttyp 30de038
Added create database test
vkuttyp 4efde4e
test updates
vkuttyp e7ac3e9
chore: apply automated updates
autofix-ci[bot] 4fe1fb6
Bug fix
vkuttyp e83f6d7
chore: apply automated updates
autofix-ci[bot] 18425a6
fixed docker-compose.yml
vkuttyp 9f38ae2
Fix TypeScript errors in MSSQL connector
vkuttyp ba0d00b
chore: apply automated updates
autofix-ci[bot] 513c8e4
Trigger CI workflow
vkuttyp 7998351
Add Codecov coverage upload to CI workflow
vkuttyp 5295f64
Added more tests
vkuttyp 561fd7b
chore: apply automated updates
autofix-ci[bot] a527256
Trigger CI workflow to test coverage and autofix
vkuttyp 9007758
Upgraded tedious to the latest version and added more tests
vkuttyp a5fa0e0
chore: apply automated updates
autofix-ci[bot] f34f985
Merge branch 'main' into add-mssql-support
vkuttyp aed2083
Merge branch 'main' into add-mssql-support
vkuttyp e02e32a
chore: apply automated updates
autofix-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| --- | ||
| icon: devicon-plain:microsoftsqlserver | ||
| --- | ||
|
|
||
| # MSSQL | ||
|
|
||
| > Connect DB0 to MSSQL Database using `tedious` | ||
|
|
||
| ## Usage | ||
|
|
||
| For this connector, you need to install [`tedious`](https://www.npmjs.com/package/tedious) dependency: | ||
|
|
||
| :pm-install{name="tedious"} | ||
|
|
||
| Use `mssql` connector: | ||
|
|
||
| ```js | ||
| import { createDatabase } from "db0"; | ||
| import mssql from "db0/connectors/mssql"; | ||
|
|
||
| const db = createDatabase( | ||
| mssql({ | ||
| /* options */ | ||
| }), | ||
| ); | ||
| ``` | ||
|
|
||
| ## Options | ||
|
|
||
| :read-more{to="https://tediousjs.github.io/tedious/api-connection.html#function_newConnection"} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,229 @@ | ||
| import { | ||
| Connection, | ||
| Request, | ||
| Connection as TediousConnection, | ||
| type ConnectionConfiguration, | ||
| TYPES, | ||
| } from "tedious"; | ||
|
|
||
| import type { Connector, Statement, Primitive } from "db0"; | ||
|
|
||
| // Type for tedious DataType | ||
| type DataType = (typeof TYPES)[keyof typeof TYPES]; | ||
|
|
||
| export type ConnectorOptions = ConnectionConfiguration; | ||
|
|
||
| export default function mssqlConnector(opts: ConnectorOptions) { | ||
| let _client: undefined | TediousConnection; | ||
| async function getClient(): Promise<TediousConnection> { | ||
| if (_client && _client.state === _client.STATE.LOGGED_IN) { | ||
| return _client; | ||
| } | ||
|
|
||
| return new Promise((resolve, reject) => { | ||
| const client = new Connection(opts); | ||
| client.connect((error) => { | ||
| if (error) { | ||
| reject(error); | ||
| } | ||
|
|
||
| _client = client; | ||
| }); | ||
|
vkuttyp marked this conversation as resolved.
|
||
|
|
||
| client.on("connect", () => { | ||
| if (_client) { | ||
| resolve(_client); | ||
| } | ||
| }); | ||
| client.on("error", reject); | ||
| }); | ||
| } | ||
|
|
||
| async function _run(sql: string, parameters?: unknown[]) { | ||
| if (!sql) { | ||
| throw new Error("SQL query must be provided"); | ||
| } | ||
|
|
||
| const connection = await getClient(); | ||
| const { sql: _sql, parameters: _parameters } = prepareSqlParameters( | ||
| sql, | ||
| parameters, | ||
| ); | ||
|
|
||
| const query = new Promise<{ rows: unknown[]; success: boolean }>( | ||
| (resolve, reject) => { | ||
| let success = false; | ||
| const request = new Request(_sql, (error) => { | ||
| if (error) { | ||
| reject(error); | ||
| } else { | ||
| success = true; | ||
| } | ||
| }); | ||
|
|
||
| const parameterKeys = Object.keys(_parameters); | ||
| for (const key of parameterKeys) { | ||
| const parameter = _parameters[key]; | ||
|
|
||
| request.addParameter(parameter.name, parameter.type, parameter.value); | ||
| } | ||
|
|
||
| const rows: unknown[] = []; | ||
| request.on("row", (columns = []) => { | ||
| const currentRow: Record<string, unknown> = {}; | ||
| for (const column of columns) { | ||
| const { value, metadata } = column; | ||
| const { colName } = metadata; | ||
|
|
||
| currentRow[colName] = value; | ||
| } | ||
|
|
||
| rows.push(currentRow); | ||
| }); | ||
|
|
||
| request.on("requestCompleted", () => { | ||
| connection.close(); | ||
| resolve({ rows, success }); | ||
| }); | ||
|
|
||
| request.on("error", (error) => { | ||
| connection.close(); | ||
| reject(error); | ||
| }); | ||
|
vkuttyp marked this conversation as resolved.
|
||
|
|
||
| connection.execSql(request); | ||
| }, | ||
| ); | ||
|
|
||
| try { | ||
| const { rows, success } = await query; | ||
|
|
||
| return { | ||
| rows, | ||
| success, | ||
| }; | ||
| } catch (error: any) { | ||
| error.sql = _sql; | ||
| error.parameters = parameters; | ||
| throw error; | ||
| } | ||
| } | ||
|
|
||
| return <Connector<TediousConnection>>{ | ||
| name: "mssql", | ||
| dialect: "mssql", | ||
| getInstance: () => getClient(), | ||
| exec(sql: string) { | ||
| return _run(sql, []); | ||
| }, | ||
| prepare(sql: string) { | ||
| const _sql = sql; | ||
| let _params: Primitive[] = []; | ||
|
|
||
| const statement: Statement = { | ||
| bind(...params: Primitive[]) { | ||
| if (params.length > 0) { | ||
| _params = params; | ||
| } | ||
| return statement; | ||
| }, | ||
| async all(...params: Primitive[]) { | ||
| const { rows } = await _run( | ||
| _sql, | ||
| params.length > 0 ? params : _params, | ||
| ); | ||
| return rows; | ||
| }, | ||
| async run(...params: Primitive[]) { | ||
| const { success = false } = | ||
| (await _run(_sql, params.length > 0 ? params : _params)) || {}; | ||
| return { | ||
| success, | ||
| }; | ||
| }, | ||
| async get(...params: Primitive[]) { | ||
| const { | ||
| rows: [row], | ||
| } = await _run(_sql, params.length > 0 ? params : _params); | ||
| return row; | ||
| }, | ||
| }; | ||
|
|
||
| return statement; | ||
| }, | ||
| }; | ||
| } | ||
|
vkuttyp marked this conversation as resolved.
|
||
|
|
||
| // taken from the `kysely` library: https://github.com/kysely-org/kysely/blob/413a88516c20be42dc8cbebade68c27669a3ac1a/src/dialect/mssql/mssql-driver.ts#L440 | ||
| export function getTediousDataType(value: unknown): DataType { | ||
| if (value === null || value === undefined || typeof value === "string") { | ||
| return TYPES.NVarChar; | ||
| } | ||
|
|
||
| if ( | ||
| typeof value === "bigint" || | ||
| (typeof value === "number" && value % 1 === 0) | ||
| ) { | ||
| return value < -2_147_483_648 || value > 2_147_483_647 | ||
| ? TYPES.BigInt | ||
| : TYPES.Int; | ||
| } | ||
|
|
||
| if (typeof value === "number") { | ||
| return TYPES.Float; | ||
| } | ||
|
|
||
| if (typeof value === "boolean") { | ||
| return TYPES.Bit; | ||
| } | ||
|
|
||
| if (value instanceof Date) { | ||
| return TYPES.DateTime2; | ||
| } | ||
|
|
||
| if (typeof Buffer !== "undefined" && Buffer.isBuffer(value)) { | ||
| return TYPES.VarBinary; | ||
| } | ||
|
|
||
| return TYPES.NVarChar; | ||
| } | ||
|
|
||
| // replace `?` placeholders with `@1`, `@2`, etc. | ||
| export function prepareSqlParameters( | ||
| sql: string, | ||
| parameters: unknown[] = [], | ||
| ): { | ||
| sql: string; | ||
| parameters: Record<string, { name: string; type: DataType; value: unknown }>; | ||
| } { | ||
| const parameterIndexes: number[] = []; | ||
| const tokens = [...sql]; | ||
|
|
||
| // find all `?` placeholders in the SQL string | ||
| for (const [i, token] of tokens.entries()) { | ||
| if (token === "?") { | ||
| parameterIndexes.push(i); | ||
| } | ||
| } | ||
|
vkuttyp marked this conversation as resolved.
|
||
|
|
||
| const namedParameters: Record< | ||
| string, | ||
| { name: string; type: DataType; value: unknown } | ||
| > = {}; | ||
| for (const [index, parameterIndex] of parameterIndexes.entries()) { | ||
| const incrementedIndex = index + 1; | ||
| // replace `?` placeholder with index-based parameter name | ||
| tokens[parameterIndex] = `@${incrementedIndex}`; | ||
| // store the parameter value and type with the index-based parameter name | ||
| namedParameters[`@${incrementedIndex}`] = { | ||
| name: String(incrementedIndex), | ||
| type: getTediousDataType(parameters[index]), | ||
| value: parameters[index], | ||
| }; | ||
| } | ||
|
|
||
| return { | ||
| sql: tokens.join(""), // join the tokens back into a SQL string | ||
| parameters: namedParameters, | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.