Giter Club home page Giter Club logo

node-mysql-utilities's Introduction

Node MySql Utilities

Utilities for node-mysql driver with specialized result types, introspection and other helpful functionality for node.js. Initially this utilities were part of Impress Application Server and extracted separately for use with other frameworks.

CI Status NPM Version NPM Downloads/Month NPM Downloads

impress logo

Installation

$ npm install mysql-utilities

Features

  • MySQL Data Access Methods
    • Query selecting single row: connection.queryRow(sql, values, callback)
    • Query selecting scalar (single value): connection.queryValue(sql, values, callback)
    • Query selecting column into array: connection.queryCol(sql, values, callback)
    • Query selecting hash of records: connection.queryHash(sql, values, callback)
    • Query selecting key/value hash: connection.queryKeyValue(sql, values, callback)
  • MySQL Introspection Methods
    • Get primary key metadata: connection.primary(table, callback)
    • Get foreign key metadata: connection.foreign(table, callback)
    • Get table constraints metadata: connection.constraints(table, callback)
    • Get table fields metadata: connection.fields(table, callback)
    • Get connection databases array: connection.databases(callback)
    • Get database tables list for current db: connection.tables(callback)
    • Get database tables list for given db: connection.databaseTables(database, callback)
    • Get table metadata: connection.tableInfo(table, callback)
    • Get table indexes metadata: connection.indexes(table, callback)
    • Get server process list: connection.processes(callback)
    • Get server global variables: connection.globalVariables(callback)
    • Get server global status: connection.globalStatus(callback)
    • Get database users: connection.users(callback)
  • MySQL SQL Statements Autogenerating Methods
    • Selecting record(s): connection.select(table, whereFilter, callback)
    • Inserting record: connection.insert(table, row, callback)
    • Updating record: connection.update(table, row, where, callback)
    • Inserting or selecting record: connection.upsert(table, row, callback)
    • Count records with filter: connection.count(table, whereFilter, callback)
    • Delete record(s): connection.delete(table, whereFilter, callback)
  • Events
    • Catch any query execution: connection.on('query', function(err, res, fields, query) {});
    • Catch errors: connection.on('error', function(err, query) {});
    • Catch slow query execution: connection.on('slow', function(err, res, fields, query, executionTime) {});

Initialization

Utilities can be attached to connection using mix-ins:

// Library dependencies
const mysql = require('mysql');
const mysqlUtilities = require('mysql-utilities');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'userName',
  password: 'secret',
  database: 'databaseName',
});

connection.connect();

// Mix-in for Data Access Methods and SQL Autogenerating Methods
mysqlUtilities.upgrade(connection);

// Mix-in for Introspection Methods
mysqlUtilities.introspection(connection);

// Do something using utilities
connection.queryRow(
  'SELECT * FROM _Language where LanguageId=?',
  [3],
  (err, row) => {
    console.dir({ queryRow: row });
  }
);

// Release connection
connection.end();

Examples

Single row selection: connection.queryRow(sql, values, callback) returns hash as callback second parameter, field names becomes hash keys.

connection.queryRow(
  'SELECT * FROM Language where LanguageId=?',
  [3],
  (err, row) => {
    console.dir({ queryRow: row });
  }
);

Output:

queryRow: {
  LanguageId: 3,
  LanguageName: 'Russian',
  LanguageSign: 'ru',
  LanguageISO: 'ru',
  Caption: 'Русский'
}

Single value selection: connection.queryValue(sql, values, callback) returns single value as callback second parameter (instead of array in array). For example, for Id selection by name with LIMIT 1 or count(*), max(field) etc.

connection.queryValue(
  'SELECT LanguageName FROM Language where LanguageId=?',
  [8],
  (err, name) => {
    console.dir({ queryValue: name });
  }
);

Output:

{
  queryValue: 'Italiano';
}

Single column selection: connection.queryCol(sql, values, callback) returns array as callback second parameter.

connection.queryCol('SELECT LanguageSign FROM Language', [], (err, result) => {
  console.dir({ queryCal: result });
});

Output:

queryArray: ['de', 'en', 'es', 'fr', 'it', 'pl', 'ru', 'ua'];

Hash selection: connection.queryHash(sql, values, callback) returns hash as callback second parameter, hash keyed by first field values from SQL statement.

connection.queryHash(
  'SELECT LanguageSign, LanguageId, LanguageName, Caption, LanguageISO FROM Language',
  [],
  (err, result) => {
    console.dir({ queryHash: result });
  }
);

Output:

queryHash: {
  en: {
    LanguageSign: 'en',
    LanguageId: 2,
    LanguageName: 'English',
    Caption: 'Английский',
    LanguageISO: 'en' },
  ru: {
    LanguageSign: 'ru',
    LanguageId: 3,
    LanguageName: 'Russian',
    Caption: 'Русский',
    LanguageISO: 'ru' },
  de: {
    LanguageSign: 'de',
    LanguageId: 7,
    LanguageName: 'Deutsch',
    Caption: 'Немецкий',
    LanguageISO: 'de' },
  it: {
    LanguageSign: 'it',
    LanguageId: 8,
    LanguageName: 'Italiano',
    Caption: 'Итальянский',
    LanguageISO: 'it'
  }
}

Key/value pair selection: connection.queryKeyValue(sql, values, callback) returns hash as callback second parameter, hash keyed by first field, values filled by second field.

connection.queryKeyValue(
  'SELECT LanguageISO, LanguageName FROM Language',
  [],
  (err, keyValue) => {
    console.dir({ queryKeyValue: keyValue });
  }
);

Output:

keyValue: {
  en: 'English',
  ru: 'Russian',
  uk: 'Ukrainian',
  es: 'Espanol',
  fr: 'Francais',
  de: 'Deutsch',
  it: 'Italiano',
  pl: 'Poliski'
}

Get primary key list with metadata: connection.primary(table, callback) returns metadata as callback second parameter.

connection.primary('Language', (err, primary) => {
  console.dir({ primary });
});

Output:

primary: {
  Table: 'language',
  Non_unique: 0,
  Key_name: 'PRIMARY',
  Seq_in_index: 1,
  Column_name: 'LanguageId',
  Collation: 'A',
  Cardinality: 9,
  Sub_part: null,
  Packed: null,
  Null: '',
  Index_type: 'BTREE',
  Comment: '',
  Index_comment: ''
}

Get foreign key list with metadata: connection.foreign(table, callback) returns metadata as callback second parameter.

connection.foreign('TemplateCaption', (err, foreign) => {
  console.dir({ foreign });
});

Output:

foreign: {
  fkTemplateCaptionLanguage: {
    CONSTRAINT_NAME: 'fkTemplateCaptionLanguage',
    COLUMN_NAME: 'LanguageId',
    ORDINAL_POSITION: 1,
    POSITION_IN_UNIQUE_CONSTRAINT: 1,
    REFERENCED_TABLE_NAME: 'language',
    REFERENCED_COLUMN_NAME: 'LanguageId' },
  fkTemplateCaptionTemplate: {
    CONSTRAINT_NAME: 'fkTemplateCaptionTemplate',
    COLUMN_NAME: 'TemplateId',
    ORDINAL_POSITION: 1,
    POSITION_IN_UNIQUE_CONSTRAINT: 1,
    REFERENCED_TABLE_NAME: 'template',
    REFERENCED_COLUMN_NAME: 'TemplateId'
  }
}

Referential constraints list with metadata: connection.constraints(table, callback).

connection.constraints('TemplateCaption', (err, constraints) => {
  console.dir({ constraints });
});

Output:

constraints: {
  fkTemplateCaptionLanguage: {
    CONSTRAINT_NAME: 'fkTemplateCaptionLanguage',
    UNIQUE_CONSTRAINT_NAME: 'PRIMARY',
    REFERENCED_TABLE_NAME: 'Language',
    MATCH_OPTION: 'NONE',
    UPDATE_RULE: 'RESTRICT',
    DELETE_RULE: 'CASCADE' },
  fkTemplateCaptionTemplate: {
    CONSTRAINT_NAME: 'fkTemplateCaptionTemplate',
    UNIQUE_CONSTRAINT_NAME: 'PRIMARY',
    REFERENCED_TABLE_NAME: 'Template',
    MATCH_OPTION: 'NONE',
    UPDATE_RULE: 'RESTRICT',
    DELETE_RULE: 'CASCADE'
  }
}

Get table fields with metadata: connection.fields(table, callback).

connection.fields('Language', (err, fields) => {
  console.dir({ fields });
});

Output:

fields: {
  LanguageId: {
    Field: 'LanguageId',
    Type: 'int(10) unsigned',
    Collation: null,
    Null: 'NO',
    Key: 'PRI',
    Default: null,
    Extra: 'auto_increment',
    Privileges: 'select,insert,update,references',
    Comment: 'Id(EN),Код(RU)' },
  LanguageName: {
    Field: 'LanguageName',
    Type: 'varchar(32)',
    Collation: 'utf8_general_ci',
    Null: 'NO',
    Key: 'UNI',
    Default: null,
    Extra: '',
    Privileges: 'select,insert,update,references',
    Comment: 'Name(EN),Имя(RU)'
  }, ...
}

Get database list for current connection: connection.databases(callback).

connection.databases((err, databases) => {
  console.dir({ databases });
});

Output:

databases: [
  'information_schema',
  'mezha',
  'mysql',
  'performance_schema',
  'test',
];

Get table list for current database: connection.tables(callback).

connection.tables((err, tables) => {
  console.dir({ tables });
});

Output:

tables: {
  Language: {
    TABLE_NAME: 'Language',
    TABLE_TYPE: 'BASE TABLE',
    ENGINE: 'InnoDB',
    VERSION: 10,
    ROW_FORMAT: 'Compact',
    TABLE_ROWS: 9,
    AVG_ROW_LENGTH: 1820,
    DATA_LENGTH: 16384,
    MAX_DATA_LENGTH: 0,
    INDEX_LENGTH: 49152,
    DATA_FREE: 8388608,
    AUTO_INCREMENT: 10,
    CREATE_TIME: Mon Jul 15 2013 03:06:08 GMT+0300 (Финляндия (лето)),
    UPDATE_TIME: null,
    CHECK_TIME: null,
    TABLE_COLLATION: 'utf8_general_ci',
    CHECKSUM: null,
    CREATE_OPTIONS: '',
    TABLE_COMMENT: '_Language:Languages(EN),Языки(RU)'
  }, ...
}

Get table list for specified database: connection.databaseTables(database, callback).

connection.databaseTables('databaseName', (err, tables) => {
  console.dir({ databaseTables: tables });
});

Output:

tables: {
  Language: {
    TABLE_NAME: 'Language',
    TABLE_TYPE: 'BASE TABLE',
    ENGINE: 'InnoDB',
    VERSION: 10,
    ROW_FORMAT: 'Compact',
    TABLE_ROWS: 9,
    AVG_ROW_LENGTH: 1820,
    DATA_LENGTH: 16384,
    MAX_DATA_LENGTH: 0,
    INDEX_LENGTH: 49152,
    DATA_FREE: 8388608,
    AUTO_INCREMENT: 10,
    CREATE_TIME: Mon Jul 15 2013 03:06:08 GMT+0300 (Финляндия (лето)),
    UPDATE_TIME: null,
    CHECK_TIME: null,
    TABLE_COLLATION: 'utf8_general_ci',
    CHECKSUM: null,
    CREATE_OPTIONS: '',
    TABLE_COMMENT: '_Language:Languages(EN),Языки(RU)'
  }, ...
}

Get table metadata: connection.tableInfo(table, callback).

connection.tableInfo('Language', (err, info) => {
  console.dir({ tableInfo: info });
});

Output:

tableInfo: {
  Name: 'language',
  Engine: 'InnoDB',
  Version: 10,
  Row_format: 'Compact',
  Rows: 9,
  Avg_row_length: 1820,
  Data_length: 16384,
  Max_data_length: 0,
  Index_length: 49152,
  Data_free: 9437184,
  Auto_increment: 10,
  Create_time: Mon Jul 15 2013 03:06:08 GMT+0300 (Финляндия (лето)),
  Update_time: null,
  Check_time: null,
  Collation: 'utf8_general_ci',
  Checksum: null,
  Create_options: '',
  Comment: ''
}

Get table indexes metadata: connection.indexes(table, callback).

connection.indexes('Language', function (err, info) {
  console.dir({ tableInfo: info });
});

Output:

indexes: {
  PRIMARY: {
    Table: 'language',
    Non_unique: 0,
    Key_name: 'PRIMARY',
    Seq_in_index: 1,
    Column_name: 'LanguageId',
    Collation: 'A',
    Cardinality: 9,
    Sub_part: null,
    Packed: null,
    Null: '',
    Index_type: 'BTREE',
    Comment: '',
    Index_comment: '' },
  akLanguage: {
    Table: 'language',
    Non_unique: 0,
    Key_name: 'akLanguage',
    Seq_in_index: 1,
    Column_name: 'LanguageName',
    Collation: 'A',
    Cardinality: 9,
    Sub_part: null,
    Packed: null,
    Null: '',
    Index_type: 'BTREE',
    Comment: '',
    Index_comment: ''
  }
}

Get MySQL process list: connection.processes(callback).

connection.processes(function (err, processes) {
  console.dir({ processes });
});

Output:

processes: [
  {
    ID: 62,
    USER: 'mezha',
    HOST: 'localhost:14188',
    DB: 'mezha',
    COMMAND: 'Query',
    TIME: 0,
    STATE: 'executing',
    INFO: 'SELECT * FROM information_schema.PROCESSLIST',
  },
  {
    ID: 33,
    USER: 'root',
    HOST: 'localhost:39589',
    DB: null,
    COMMAND: 'Sleep',
    TIME: 1,
    STATE: '',
    INFO: null,
  },
];

Get MySQL global variables: connection.globalVariables(callback)

connection.globalVariables((err, globalVariables) => {
  console.dir({ globalVariables });
});

Output:

globalVariables: {
  MAX_PREPARED_STMT_COUNT: '16382',
  MAX_JOIN_SIZE: '18446744073709551615',
  HAVE_CRYPT: 'NO',
  PERFORMANCE_SCHEMA_EVENTS_WAITS_HISTORY_LONG_SIZE: '10000',
  INNODB_VERSION: '5.5.32',
  FLUSH_TIME: '1800',
  MAX_ERROR_COUNT: '64',
  ...
}

Get MySQL global status: connection.globalStatus(callback)

connection.globalStatus((err, globalStatus) => {
  console.dir({ globalStatus });
});

Output:

globalStatus: {
  ABORTED_CLIENTS: '54',
  ABORTED_CONNECTS: '2',
  BINLOG_CACHE_DISK_USE: '0',
  BINLOG_CACHE_USE: '0',
  BINLOG_STMT_CACHE_DISK_USE: '0',
  BINLOG_STMT_CACHE_USE: '0',
  BYTES_RECEIVED: '654871',
  BYTES_SENT: '212454927',
  COM_ADMIN_COMMANDS: '594',
  ...
}

Get MySQL user list: connection.users(callback)

connection.users((err, users) => {
  console.dir({ users });
});

Output:

users: [
  {
    Host: 'localhost',
    User: 'root',
    Password: '*90E462C37378CED12064BB3388827D2BA3A9B689',
    Select_priv: 'Y',
    Insert_priv: 'Y',
    Update_priv: 'Y',
    Delete_priv: 'Y',
    Create_priv: 'Y',
    Drop_priv: 'Y',
    Reload_priv: 'Y',
    Shutdown_priv: 'Y',
    Process_priv: 'Y',
    File_priv: 'Y',
    Grant_priv: 'Y',
    References_priv: 'Y',
    Index_priv: 'Y',
    Alter_priv: 'Y',
    Show_db_priv: 'Y',
    Super_priv: 'Y',
    Create_tmp_table_priv: 'Y',
    Lock_tables_priv: 'Y',
    Execute_priv: 'Y',
    Repl_slave_priv: 'Y',
    Repl_client_priv: 'Y',
    Create_view_priv: 'Y',
    Show_view_priv: 'Y',
    Create_routine_priv: 'Y',
    Alter_routine_priv: 'Y',
    Create_user_priv: 'Y',
    Event_priv: 'Y',
    Trigger_priv: 'Y',
    Create_tablespace_priv: 'Y',
    ssl_type: '',
    ssl_cipher: <Buffer >,
    x509_issuer: <Buffer >,
    x509_subject: <Buffer >,
    max_questions: 0,
    max_updates: 0,
    max_connections: 0,
    max_user_connections: 0,
    plugin: '',
    authentication_string: ''
  }, ...
]

Generate MySQL WHERE statement: connection.where(conditions), works synchronously, no callback. Returns WHERE statement for given JSON-style conditions.

const where = connection.where({
  id: 5,
  year: '>2010',
  price: '100..200',
  level: '<=3',
  sn: '*str?',
  label: 'str',
  code: '(1,2,4,10,11)',
});
console.dir(where);
// Output: "id = 5 AND year > '2010' AND (price BETWEEN '100' AND '200') AND
// level <= '3' AND sn LIKE '%str_' AND label = 'str' AND code IN (1,2,4,10,11)"

Generate SELECT statement: connection.select(table, whereFilter, orderBy, callback)

connection.select(
  'Language',
  '*',
  { LanguageId: '1..3' },
  { LanguageId: 'desc' },
  (err, results) => {
    console.dir({ select: results });
  }
);

Generate INSERT statement: connection.insert(table, row, callback)

connection.insert(
  'Language',
  {
    LanguageName: 'Tatar',
    LanguageSign: 'TT',
    LanguageISO: 'TT',
    Caption: 'Tatar',
  },
  (err, recordId) => {
    console.dir({ insert: recordId });
  }
);

Generate UPDATE statement: connection.update(table, row, callback)

connection.update(
  'Language',
  {
    LanguageId: 25,
    LanguageName: 'Tatarca',
    LanguageSign: 'TT',
    LanguageISO: 'TT',
    Caption: 'Tatarca',
  },
  (err, affectedRows) => {
    console.dir({ update: affectedRows });
  }
);

Generate UPDATE statement with "where": connection.update(table, row, where, callback)

connection.update(
  'Language',
  { LanguageSign: 'TT' },
  { LanguageId: 1 },
  (err, affectedRows) => {
    console.dir({ update: affectedRows });
  }
);

Generate INSERT statement if record not exists or UPDATE if it exists: connection.upsert(table, row, callback)

connection.upsert(
  'Language',
  {
    LanguageId: 25,
    LanguageName: 'Tatarca',
    LanguageSign: 'TT',
    LanguageISO: 'TT',
    Caption: 'Tatarca',
  },
  (err, affectedRows) => {
    console.dir({ upsert: affectedRows });
  }
);

Get record count: connection.count(table, whereFilter, callback)

connection.count('Language', { LanguageId: '>3' }, (err, count) => {
  console.dir({ count });
  // count: 9
});

Generate DELETE statement: connection.delete(table, whereFilter, callback)

connection.delete('Language', { LanguageSign: 'TT' }, (err, affectedRows) => {
  console.dir({ delete: affectedRows });
});

License & Contributors

Copyright (c) 2012-2023 Metarhia <[email protected]> See github for full contributors list. Node MySql Utilities is MIT licensed.

node-mysql-utilities's People

Contributors

2naive avatar batya15 avatar dependabot[bot] avatar profbiss avatar tshemsedinov 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-mysql-utilities's Issues

Feature request: implement `queryRows` to return array of rows

Is your feature request related to a problem? Please describe.
It would be nice implementing queryRows, to do what queryRow does, but returning array of rows instead.
(I guess the implementation would be close to queryHash but instead of returning object to return array of objects)

Describe the solution you'd like

e.g.

connection.queryRows(
  'SELECT * FROM Language',
  (err, rows) => {
    console.dir({ queryRows: rows });
  }
);

Output:

queryRows: [
{
  LanguageId: 1,
  LanguageName: 'English',
  LanguageSign: 'en',
  LanguageISO: 'en',
  Caption: 'English'
},
...
{
  LanguageId: 3,
  LanguageName: 'Russian',
  LanguageSign: 'ru',
  LanguageISO: 'ru',
  Caption: 'Русский'
}
]

Describe alternatives you've considered

Additional context

queryValue fails on empty response

some changes in the fillowing code will fix the problem of error on empty sql response:

connection.queryValue = function(sql, values, callback) {
if (typeof(values) === 'function') {
callback = values;
values = [];
}
return this.queryRow(sql, values, function(err, res, fields) {
if (err) res = false; else res = res[Object.keys(res)[0]];
^^^^^^ - here if queryRow returns "false" we'll get an error "Object.keys called on non-object". The following changes fixes this problem:
if (err||!res) res = false; else res = res[Object.keys(res)[0]];
^^^^

RangeError: Maximum call stack size exceeded inside connection.query.override

Ниже пример кода, который через 3-4 тысячи вызовов приводит к RangeError: Maximum call stack size exceeded
Это делает либу абсолютно неюзабельной на продакшене.
Стоит только убрать

mysqlUtilities.upgrade(connection);
mysqlUtilities.introspection(connection);

как ошибка исчезает. Методом научного тыка было выяснено, что проблема где-то в районе 37 строки utilities.js

var query = this.inherited(sql, values, function(err, res, fields) {

Пример

var mysql = require('mysql');
var mysqlUtilities = require('mysql-utilities');
var poolSettings = {
    connectionLimit : 100,
    host: 'localhost',
    user: 'fansy',
    password: 'fansy',
    database: 'fansyDevelop',
    debug : false
};
var pool = mysql.createPool(poolSettings);
var i = 0;
var recursiveTask = function() {
    pool.getConnection(function(err, connection) {
        if (!err) {
            mysqlUtilities.upgrade(connection);
            mysqlUtilities.introspection(connection);
            connection.beginTransaction(function(err) {
                if (!err) {
                    connection.release();
                    i++;
                    console.log("recursive task completed "+i);
                    recursiveTask();
                } else {
                    console.log("Failed to start db transaction");
                }
            });
        } else {
            console.dir({mysqlPoolErr:err});
            if (connection) {
                connection.release();
            }
        }
    });
}
recursiveTask();

Мозг сломал в попытках пофиксить. Раз в 2-3 дня приложение падает(

Update all

Hello. Thank you for a great library! It's looks like there is no way to update all the records, without WHERE clause. Both null and {} in where part of update give me an error. I understard it's rare case, but sometimes it's really usefull.

Update mysql version from 2.5.x to 2.15.x

Hello,

Trying to use this module within AWS BeanStalk with AWS Linux 2017.9 and its included nodeJS 4.4.3 and during the npm install it fails to complete.

Tracked it down to the node-mysql-utilities module because it is listing mysql as a dependency, but restricted to mysql = 2.5.x. The latest 2.5.5 mysql module requires bignumber=2.0.0 which is deprecated due to a critical bug -
MikeMcl/bignumber.js#58

I've been able to update node-mysql-utilities dependency to mysql 2.15.x and things work ok on my local machine, but since npm install is running on the beanstalk, I can't inject my updated mysql dependency into mysql-utilities.

Can you update the mysql dependency of this module to something newer, like mysql 2.15.x?

Проблема с точками в имени таблиц

Привет.
Есть таблица с точкой в имени:

CREATE TABLE `my.users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `login` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

При попытке вставить в нее запись

connection.insert('my.users', user)

происходит запрос:

SHOW FULL COLUMNS FROM my.users

Что собственно является запросом в другую БД под именем my, это не то, что нам нужно.

Собственно в первой строке библиотеки есть регулярка, которая используется для эскейпинга имен таблиц. И при наличии точки во входной строке эскейпа не происходит.

Я вижу два решения в лоб, или убрать точку из регулярки (но тогда мы не сможем обращаться к другим базам через точку в имени) или добавить в неё символ апострофа, чтобы уже эскейпленое имя повторно не эскейпить:

connection.insert('`my.users`'); // Сейчас в запросе FROM ``my.users``

Calling `connection.query` with an options object fails after a connection has been upgraded

Describe the bug
If a query connection has been upgraded, the corresponding query override function does not support all signatures of the initial query function. More specifically the third query signature form, is not working. This is the form which uses .query(options, callback).

  • I believe this bug is available not only for query but also for queryRow, queryHash, queryCol and queryKeyValue

To Reproduce

  1. Upgrade a connection
  2. Use the upgraded connection to query with query({sql: 'INSERT INTO ?? ..., values: [...]}, callbackFn)
  3. The values are getting replaced by an empty array so the resulting query inside of mysql is malformed.

Expected behavior
Expected the upgraded connection.query to work with the function signature form, which looks like query(optionsObj, callbackFn)

  • mysql - 2.18.1
  • Other system versions are irrelevant

Additional context

  • The problem lies in the fact that the override function replaces the current values with empty array over here
  • Whenever the first argument of the query is an object, the mysql package expects that the second argument is a function or else it would override the existing values from the object as implemented here. Since the override of mysql-utilities passes an empty array to the original mysql query, the latter is going to override the existing values leading to a malformed SQL because it cannot be properly formatted.
  • I will try to submit a PR to fix this -> #60

Upgraded connection fails to work in streaming mode

The code which works in vanilla mysql fails at mysql-utilities/utilities.js:40:5 with Uncaught TypeError: undefined is not a function

var query = connection.query('SELECT * FROM posts');
query
  .on('error', function(err) {
    // Handle error, an 'end' event will be emitted after this as well
  })
  .on('fields', function(fields) {
    // the field packets for the rows to follow
  })
  .on('result', function(row) {
    // Pausing the connnection is useful if your processing involves I/O
    connection.pause();

    processRow(row, function() {
      connection.resume();
    });
  })
  .on('end', function() {
    // all rows have been received
  });

Add support for node-mysql streaming queries.

node-mysql supports streaming rows as indicated here. However, when I attempt to do so after upgrading the connection, I receive the follow error:

TypeError: undefined is not a function
    at Query._callback (./node_modules/mysql-utilities/utilities.js:40:5)
    at Query.Sequence.end (./node_modules/mysql/lib/protocol/sequences/Sequence.js:78:24)
    at Query._handleFinalResultPacket (./node_modules/mysql/lib/protocol/sequences/Query.js:143:8)
    at Query.EofPacket (./node_modules/mysql/lib/protocol/sequences/Query.js:127:8)
    at Protocol._parsePacket (./node_modules/mysql/lib/protocol/Protocol.js:197:24)
    at Parser.write (./node_modules/mysql/lib/protocol/Parser.js:62:12)
    at Protocol.write (./node_modules/mysql/lib/protocol/Protocol.js:37:16)
    at Socket.ondata (stream.js:51:26)
    at Socket.EventEmitter.emit (events.js:117:20)
    at Socket.<anonymous> (_stream_readable.js:746:14)

Code to produce error:

conn.connect();

mysqlu.upgrade(conn);

conn.query("select 'worked!'")
.on('result', function(row){
  console.log(row)
})

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.