Git Product home page Git Product logo

mysql2's People

Contributors

blakeembrey avatar dctrotz avatar felixfbecker avatar greenkeeper[bot] avatar hsjoberg avatar izzymg avatar jkruse14 avatar moberemk avatar rcoundon avatar solsson avatar stevenmiller888 avatar subtlepath avatar tnir avatar trevorr avatar unrealquester avatar worbunkel avatar ymhr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

mysql2's Issues

Interface 'Pool' incorrectly extends interface 'Connection'.

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 {
                    ~~~~

Inconsistencies with promise.js

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.

exec type for queries incorrect

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]>(

Sample code from README never ends?

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.

An in-range update of typescript is breaking the build 🚨

Version 2.4.1 of typescript just got published.

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 💪

Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details

Release Notes TypeScript 2.4

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:

Commits

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

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of tslint is breaking the build 🚨

Version 4.5.1 of tslint just got published.

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 💪


Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details
Release Notes v4.5.1
  • [enhancement] Updated recommended rules to include ban-types and no-duplicate-super (#2271)
  • [bugfix] object-literal-key-quotes handle negative number property name (#2273)
Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Confusion over query/execute's return type union via Promise API

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.

Publish with DefinitelyTyped?

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 .

Typing errors using typescript 3.8

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'.

Promises not working?

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).

Missing Pool Promise

Hi there,

The function promise() is not available on the Pool class :( !?
Thanks for your help !

Npm install is giving me pre PR-18 content

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

An in-range update of typescript is breaking the build 🚨

Version 2.2.1 of typescript just got published.

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 💪


Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details
Release Notes TypeScript 2.2

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:

  • Alexander Rusakov
  • Anatoly Ressin
  • Andreas Martin
  • Andrew Ochsner
  • Basarat Ali Syed
  • Dahan Gong
  • Dan Corder
  • David Sheldrick
  • @falsandtru
  • @flowmemo
  • Herrington Darkholme
  • Homa Wong
  • Joel Day
  • Kagami Sascha Rosylight
  • Klaus Meinhardt
  • Kārlis Gaņģis
  • Manish Giri
  • Masahiro Wakame
  • Raj Dosanjh
  • Slawomir Sadziak
  • Tingan Ho
  • Yuichi Nukiyama
Commits

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.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Incompatible with ts3.7

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.

Missing releaseConnection?

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

Missing promise() function (typings out of date)

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.

Move to DT

I think it would be a good idea to move this repo to DefinitelyTyped.

Error 'spawn git ENOENT' while installing types/mysql2

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! :)

Cannot properly type results for query with `rowsAsArray` option set to true

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?

RowDataPacket constructor

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

bash typings command not found

when I try to install the typing using the instructions in the readme it says:
typings install --save mysql2

bash: typings: command not found

Returning a value from the callback function

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?

Typedefs don't support rowsAsArray option

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.

An in-range update of tslint is breaking the build 🚨

Version 5.5.0 of tslint just got published.

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 💪

Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details

Release Notes v5.5.0

Editor's note: This release features an important bugfix for overlapping fixes when using --project and --fix (#2864).

🎉 New rules and options

🛠 Bugfixes & enhancements

Thanks to our contributors!

  • Klaus Meinhardt
  • Josh Goldberg
  • Petr Kosikhin
  • Pablo Núñez
  • Benny Neugebauer
  • Radon Rosborough
  • reduckted
  • Chris Barr
  • Julian Verdurmen
Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.