types / mysql2 Goto Github PK
View Code? Open in Web Editor NEWTypings for https://github.com/sidorares/node-mysql2
License: ISC License
Typings for https://github.com/sidorares/node-mysql2
License: ISC License
When i run npm install --save-dev types/mysql2#semver:1.0.0
it gives me the types that are pre PR-18. For instance, the createConnection method in promise.d.ts still returns a Connection, not Promise.
export function createConnection(connectionUri: string): Connection;
export function createConnection(config: ConnectionOptions): Connection;
Am I doing something wrong? Thanks
npm package name shoud be @types/mysql2
, instead of types/mysql2
.
e.g. @types/node, @types/mysql
Hello,
It seems the library can't be used with ts 3.7 due to newly fixed recursive import/export. Actually the recursive import/export is in @types/mysql files but that is affecting this package too.
Hello.
Sorry, if I don't understand how it works.
In d.ts file we have such declaration
declare interface RowDataPacket {
constructor: {
name: 'RowDataPacket'
};
[column: string]: any;
[column: number]: any;
}
But actually RowDataPacket is a binaryRow and thus it has same name in constructor.
thanks
Hi
I don't know what I'm doing wrong. I cannot properly type results when the option rowsAsArray
is enabled.
My SQL returns an array of arrays that contains only one string eg:
// connection.promise().query("SHOW TABLES LIKE 'table_%';");
[
[ 'table_1'], [ 'table_2'],
[ 'table_3'], [ 'table_4'],
]
I want to flat this result in my helper function but TS complaints about types mismatch.
See example below
const listTablesSql = "SHOW TABLES LIKE 'table_%';"
async strictTypeInQuery(): Promise<string[]> {
// error: `Type 'string' is not assignable to type 'RowDataPacket'`
const [rows] = await connection.promise().query<string[]>({sql: listTablesSql, rowsAsArray: true});
return rows.flat(1);
}
async inferType(): Promise<string[]> {
// error: `Type 'string' is not assignable to type 'RowDataPacket'`
const [rows] = await connection.promise().query({sql: listTablesSql, rowsAsArray: true});
return rows.flat(1); // TS:error `Type 'RowDataPacket' is not assignable to type 'string'.`
}
Can you help me and point what I'm doing wrong?
The most recent commit fails to compile (using TS 3.8.3):
node_modules/@types/mysql2/index.d.ts:19:18 - error TS2430: Interface 'Pool' incorrectly extends interface 'Connection'.
Types of property 'end' are incompatible.
Type '(callback?: ((err: Error) => any) | undefined) => void' is not assignable to type '{ (callback?: ((err: QueryError | null) => void) | undefined): void; (options: any, callback?: ((err: QueryError | null) => void) | undefined): void; }'.
Types of parameters 'callback' and 'callback' are incompatible.
Types of parameters 'err' and 'err' are incompatible.
Type 'Error' is missing the following properties from type 'QueryError': code, fatal
19 export interface Pool extends mysql.Connection {
~~~~
Are there any plans of putting these typings on DefinitelyTyped? AFAIK the typings tool is outdated, and the proper way to publish types now is with DefinitelyTyped. That would allow npm install --save-dev @types/mysql2
.
It is possible to release it to npm? #19 is on hold for a long time for some reason, also I didn't notice any progress on sidorares/node-mysql2#1028 😢
I haven't looked much into this, but promise.d.ts
defines a Connection
interface with a changeUser
method, but https://github.com/sidorares/node-mysql2/blob/master/promise.js defines PromiseConnection
with a different structure. I noticed this when I got a run-time error stating my Connection
object had no changeUser
method.
This PromiseConnection
is what is returned from createConnection
.
https://github.com/sidorares/node-mysql2/blob/master/promise.js does not define a createUser
method, but you do have access to the underlying Connection
.
There seem to be some missing options on the ConnectionOptions/PoolOptions interfaces. From a quick look over the code, specifically decimalNumbers, namedPlaceholders, and nestTables. I ran into this issue in trying to use the namedPlaceholders option over the bulky queryFormat example in the documentation.
https://github.com/sidorares/node-mysql2/blob/master/lib/connection_config.js#L29,L43
This code (from promises sample)
import * as mysql from 'mysql2/promise';
let connection = mysql.createConnection(process.env['DB']);
connection.connect()
.then(() => connection.query<mysql.RowDataPacket[]>('SELECT 1 + 1 AS solution'))
.then(([rows, fields]) => {
console.log('The solution is: ', rows[0]['solution']);
});
Is causing he following error in runtime:
TypeError: connection.connect is not a function
Please, do notice the error occurs just in runtime. The TypeScript compiler doesn't shows any errors.
Using TypeScript
version 2.3.2
, Node.js
version v6.10.3
and mysql2
version 1.2.0
(tried to downgrade to 1.1.1
but the problem remains).
Upon console logging an INSERT
, I can see the following:
ResultSetHeader {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
info: '',
serverStatus: 2,
warningStatus: 1 }
This would imply that there's a warning. What return packet type would contain this information?
The signature for .query
is RowDataPacket[][] | RowDataPacket[] | OkPacket | OkPacket[]
, and since this is an INSERT
I'd expect the result to be an OkPacket
if anything, however the OkPacket
type definition is:
OkPacket {
constructor: {
name: 'OkPacket'
};
fieldCount: number;
affectedRows: number;
changedRows: number;
insertId: number;
serverStatus: number;
warningCount: number;
message: string;
procotol41: boolean;
}
Observations:
warningStatus
vs warningCount
procotol41
(odd spelling, can't find any reference to this elsewhere)So unless I typecast as any
I don't believe I can determine if a query has had a warning, but I'd just like to confirm if this is the case and raise this just in case there is indeed an issue in the definition.
I think it would be a good idea to move this repo to DefinitelyTyped.
As described over here: https://github.com/sidorares/node-mysql2
// For pool initialization, see above
pool.getConnection(function(conn) {
// Do something with the connection
conn.query(/* ... */);
// Don't forget to release the connection when finished!
pool.releaseConnection(conn);
})
It should be possible to also call pool.releaseConnection
. Currently it says: 'Property 'releaseConnection' does not exist on type 'Pool'.
I don't know if conn.release()
is also fine, or should this example be updated on their page (sidorares)?
Correct me if I'm wrong.
Regards,
Melroy
Hi! I'm fairly new with Node and Typescript in general and, while following a tutorial, I've encountered an issue trying to install types/mysql2 via the command npm i types/mysql2 -D
When running the command, I get the following error:
npm ERR! path git
npm ERR! code ENOENT
npm ERR! errno ENOENT
npm ERR! syscall spawn git
npm ERR! enoent Error while executing:
npm ERR! enoent undefined ls-remote -h -t ssh://[email protected]/types/mysql2.git
npm ERR! enoent
npm ERR! enoent
npm ERR! enoent spawn git ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
npm ERR! A complete log of this run can be found in:
npm ERR! C:\[redacted path]\AppData\Roaming\npm-cache\_logs\2019-07-24T21_06_57_398Z-debug.log
The log file reads as follows:
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli 'install',
1 verbose cli 'types/mysql2',
1 verbose cli '-D' ]
2 info using [email protected]
3 info using [email protected]
4 verbose npm-session ffaebe21627f68a6
5 silly install loadCurrentTree
6 silly install readLocalPackageData
7 silly fetchPackageMetaData error for github:types/mysql2 Error while executing:
7 silly fetchPackageMetaData undefined ls-remote -h -t ssh://[email protected]/types/mysql2.git
7 silly fetchPackageMetaData
7 silly fetchPackageMetaData
7 silly fetchPackageMetaData spawn git ENOENT
8 timing stage:rollbackFailedOptional Completed in 0ms
9 timing stage:runTopLevelLifecycles Completed in 1172ms
10 verbose stack Error: spawn git ENOENT
10 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
10 verbose stack at onErrorNT (internal/child_process.js:415:16)
10 verbose stack at process._tickCallback (internal/process/next_tick.js:63:19)
11 verbose cwd C:\[redacted path, recipient folder for my DB]
12 verbose Windows_NT 10.0.17763
13 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "types/mysql2" "-D"
14 verbose node v10.16.0
15 verbose npm v6.9.0
16 error path git
17 error code ENOENT
18 error errno ENOENT
19 error syscall spawn git
20 error enoent Error while executing:
20 error enoent undefined ls-remote -h -t ssh://[email protected]/types/mysql2.git
20 error enoent
20 error enoent
20 error enoent spawn git ENOENT
21 error enoent This is related to npm not being able to find a file.
22 verbose exit [ 1, true ]
Apparently it's an issue with the retrival of files from GitHub, but would like to be sure about it, since I've found nothing looking up for this issue. I appreciate the attention and help beforehand and hope you all are having a nice day! :)
Hi there,
The function promise() is not available on the Pool class :( !?
Thanks for your help !
Branch | Build failing 🚨 |
---|---|
Dependency | typescript |
Current Version | 2.2.0 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As typescript is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.
I recommend you give this issue a high priority. I’m sure you can resolve this 💪
For release notes, check out the release announcement
For new features, check out the What's new in TypeScript 2.2.
For breaking changes, check out the Breaking changes in TypeScript 2.2 page.
For the complete list of fixed issues, check out the issues fixed in Typescript 2.2 RC and after Typescript 2.2 RC.
Download:
Special thanks to all contributors to this release:
The new version differs by 218 commits .
a29e8cf
Update LKG
1120971
Fix #14136: Make Object.create
return any
all the time
6b5c448
Merge pull request #14131 from Microsoft/release-2.2_default_import_name
125a8fa
Merge pull request #14133 from aozgaa/MissingPropertyFix-2.2
b62b467
add periods
f2770a1
widen type, index signature, and add tests
a4cf12e
cleanup
d9e0fff
use getBaseTypeOfLiteralType
150e2fb
add tests
f133a67
wip testing
2187e67
Get Widened Type
533262c
wip
ee13f31
Handle undefined import name
510b384
Update LKG
08fe20e
[release-2.2] use separate process to probe if drive is safe to watch (#14098) (#14124)
There are 218 commits in total. See the full diff.
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot 🌴
Branch | Build failing 🚨 |
---|---|
Dependency | tslint |
Current Version | 5.4.3 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As tslint is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.
I recommend you give this issue a high priority. I’m sure you can resolve this 💪
Editor's note: This release features an important bugfix for overlapping fixes when using --project
and --fix
(#2864).
completed-docs
: Add enum-members
option (#2911)no-this-reassignment
(#2931)encoding
closes files correctly (#2958)whitespace
fix whitespace "check-module"
to properly lint and fix errors (#2401) (#2825)whitespace
: now correctly handles dynamic imports introduced in [email protected] (#2924)switch-final-break
: don't fail if break jumps to a label outside of the switch (#2914)no-shadowed-variable
: exempt this
parameter (#2598)prefer-for-of
correctly handles variable scopes and other unrelated identifiers (#2984)no-unused-variable
autofix removes whole import (#2901)-v
option (#2926)no-empty
(#2886)prefer-const
: handle destructuring in for-of loop initializer as if {"destructuring": "all"}
was specified (#2904)no-shadowed-variable
: added checks for other shadowing declarations, e.g. interfaces, classes, type parameters, imports, etc. (#2598)no-shadowed-variable
no longer fails for declarations in the same scope, e.g. var foo; var foo;
. Use the rule no-duplicate-variable
to find such errors. (#2598)Thanks to our contributors!
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot 🌴
Branch | Build failing 🚨 |
---|---|
Dependency | typescript |
Current Version | 2.4.0 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As typescript is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.
I recommend you give this issue a high priority. I’m sure you can resolve this 💪
For release notes, check out the release announcement
For new features, check out the What's new in TypeScript 2.4.
For breaking changes, check out the Breaking changes in TypeScript 2.4 page.
For the complete list of fixed issues, check out the fixed issues query for Typescript 2.4.
Download:
The new version differs by 141 commits.
8b2fe13
Update LKG.
14d95ed
Test:Block-scoped definition of Promise works
a8846bf
Skip block scope check with no error location
44f2336
Merge pull request #16633 from Microsoft/release-2.4_fixIncrementalParsing
4875a27
Add tests
15ef20d
Set the structureReused to be safemoudles when dynamic import change
6d33083
Add tests
11b9f6e
Wip-fix incremental parsing
2721fd4
In TypeScript code, never bind JSDoc normally, just set parent pointers (#16555) (#16561)
0968ed9
Revert string enum changes (#16569)
096f8cc
Update LKG
9241175
Allow running in strict mode (#16557)
f49b007
Update LKG
f1b0f59
Update version to 2.4.1
ed9cde9
Update LKG
There are 141 commits in total.
See the full diff
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot 🌴
mysql2 supports getting query results back as an array of arrays but currently the typedefs don't include this query option (as it's not in the relied-upon @types/mysql lib) and its return value (an array of arrays) is also missing as an option for functions like query
and execute
.
export const validateCredentials = async (user: User): Promise<boolean> => {
let result;
connection.query('SELECT password from users WHERE email = ? AND password = ?', [user.email, user.password], (err: QueryError, rows: RowDataPacket[]) => {
console.log(rows[0][user.password]); //this is the users password
result = rows[0][user.password];
});
console.log(result) // result is always undefined
return result != undefined;
};
the provided email and password are correct and rows[0][user.password] is holding a value. now i want to return this value outside the callback function, how do i do that?
When fetching FieldPacket
s from a query, I'm observing that packet.type
is undefined, in violation of its type: https://github.com/sidorares/node-mysql2/blob/master/typings/mysql/lib/protocol/packets/FieldPacket.d.ts#L18
Example code:
$ const [res, fields] = await conn.execute<RowDataPacket[]>(sql);
$ fields[0].type
undefined
These typings are unfortunately out of date, missing at least the promise()
shortcut function on Pool
and Connection
.
I would love to contribute a PR to fix this but I don't know this library well enough to know what the return type would be.
Is there any possibility this project could be mirrored on npm?
I am using exec
to execute stored procedures, but the return type is not accurate.
Stored procedure:
DELIMITER //
CREATE PROCEDURE `user_get_by_username`(
IN in_username VARCHAR(25)
)
BEGIN
SELECT `id`, `username` FROM `user` WHERE `username` = in_username;
END //
DELIMITER ;
Code
import { RowDataPacket } from 'mysql2';
import configuration from '../configuration';
export interface User extends RowDataPacket {
id: number;
username: string;
}
databaseConnection = mysql.createConnection({
database: configuration.mySQL.database(),
host: configuration.mySQL.host(),
password: configuration.mySQL.password(),
user: configuration.mySQL.username(),
});
const userGetByUsername = ({ username }: { username: string }) =>
new Promise<User | null>((resolve, reject) => {
databaseConnection.execute<User[][]>(
{ sql: 'CALL user_get_by_username(?)', values: [username] },
(error, response) => {
console.log('response', response);
if (error) {
reject(
new Error(`Failed to get user '${username}': ${error.message}`)
);
} else {
resolve(response[0].length > 0 ? response[0][0] : null);
}
}
);
});
The issue is that execute
does not return User[][]
, but instead it returns [User[], ResultSetHeader]
,
and I cannot use the following as it does not work:
databaseConnection.execute<[User[], ResultSetHeader]>(
This code (from README, using non-promises version) hangs after displaying The solution is: 2
import {createConnection, QueryError, RowDataPacket} from 'mysql2';
const connection = createConnection(process.env['DB']);
connection.query('SELECT 1 + 1 AS solution', (err: QueryError, rows: RowDataPacket[]) => {
console.log('The solution is: ', rows[0]['solution']);
});
I had to add a
connection.end();
to the end of file to fix this. Then the program finishes normally.
Is this the expected behavior?
Using mysql2
version 1.2.0
. Node.js
version v6.10.3
.
Branch | Build failing 🚨 |
---|---|
Dependency | tslint |
Current Version | 4.5.0 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As tslint is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.
I recommend you give this issue a high priority. I’m sure you can resolve this 💪
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot 🌴
api_1 | [0] node_modules/@types/mysql/index.d.ts(2,1): error TS2440: Import declaration conflicts with local declaration of 'Connection'.
api_1 | [0] node_modules/@types/mysql/index.d.ts(4,1): error TS2440: Import declaration conflicts with local declaration of 'PoolConnection'.
api_1 | [0] node_modules/@types/mysql/index.d.ts(5,1): error TS2440: Import declaration conflicts with local declaration of 'Pool'.
api_1 | [0] node_modules/@types/mysql/index.d.ts(7,1): error TS2440: Import declaration conflicts with local declaration of 'PoolCluster'.
api_1 | [0] node_modules/@types/mysql/index.d.ts(9,1): error TS2440: Import declaration conflicts with local declaration of 'Query'.
when I try to install the typing using the instructions in the readme it says:
typings install --save mysql2
bash: typings: command not found
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.