Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • Jan 31 2019 14:34
    willmorgan commented on 889cbf1
  • Jan 31 2019 13:15
    gsamal commented on 889cbf1
  • Jan 31 2019 13:10
    dhensby closed #797
  • Jan 31 2019 13:10
    dhensby commented #797
  • Jan 31 2019 13:07
    dhensby closed #795
  • Jan 31 2019 13:07
    dhensby commented #795
  • Jan 31 2019 12:58
    gsamal commented #789
  • Jan 31 2019 11:50
    cesco69 opened #797
  • Jan 31 2019 10:22

    dhensby on master

    Update changelog for v5 Merge pull request #796 from dh… (compare)

  • Jan 31 2019 10:22
    dhensby closed #796
  • Jan 31 2019 09:53
    dhensby commented #789
  • Jan 31 2019 09:52
    dhensby commented #778
  • Jan 31 2019 09:51
    dhensby review_requested #796
  • Jan 31 2019 09:51
    dhensby opened #796
  • Jan 31 2019 06:45
    suckerp commented #795
  • Jan 31 2019 02:58
    liumorgan starred tediousjs/node-mssql
  • Jan 31 2019 02:15
    zhoukk starred tediousjs/node-mssql
  • Jan 30 2019 22:22
    vjpr edited #795
  • Jan 30 2019 22:22
    vjpr edited #795
  • Jan 30 2019 22:22
    vjpr opened #795
Wellington Rodriguez
@wrod7
image.png
David Gasperoni
@mcdado
@snenp I did it… i think i simply created more connection pools
connectionPool = new mssql.ConnectionPool({user, password, server, database});
and keep around the returned Promise from connectionPool.connect()
David Gasperoni
@mcdado
@wrod7 i think it depends on the version you're using… connect() returns a promise, so you need to chain a .then() to wait for the connection
@karooga here's how I've dealt with it:
const fs = require('fs');
const os = require('os');
const mssql = require('mssql');

class Database {

  /**
   * Ottieni il riferimento alla libreria di riferimento
   *
   * @static
   * @returns
   *
   * @memberof Database
   */
  static getLib() {
    return mssql;
  }

  /**
   * Apri connessione al database usando le configurazioni impostate.
   *
   * @private
   * @static
   * @param {string} [username]
   * @param {string} [password]
   * @param {string} [server]
   * @param {string} [database]
   * @returns
   *
   * @memberof Database
   */
  static openConnection(username, password, server, database) {
    if (Object.prototype.hasOwnProperty.call(this, 'connectionPromise') === true && this.connectionPromise !== null) {
      return this.connectionPromise;
    }

    const configuration = this.getConfiguration(username, password, server, database);

    if (!this.enable) {
      return Promise.reject('Database disabled.');
    }


    this.connectionPool = new mssql.ConnectionPool(configuration);
    this.connectionPromise = this.connectionPool.connect();

    return this.connectionPromise;
  }

  static closeConnection() {
    this.connectionPool.close();
  }

  /**
   * Promessa alla connessione del database, che verrà avviata non appena viene richiesta la prima volta.
   *
   * @public
   * @static
   * @returns {Promise} <ConnectionPool>
   *
   * @memberof Database
   */
  static willConnect() {
    if (Object.prototype.hasOwnProperty.call(this, 'connectionPromise') === false || this.connectionPromise === null) {
      try {
        return this.openConnection();
      } catch (err) {
        console.error('willConnect: Database not connected.');
        throw new Error(err);
      }
    }

    return this.connectionPromise;
  }

  static getConnectionPool() {
    return this.connectionPool;
  }

  /**
   * Ottieni l'oggetto di configurazione per la connessione al database.
   *
   * @private
   * @static
   * @param {string} [username]
   * @param {string} [password]
   * @param {string} [server]
   * @param {string} [database]
   * @memberof Database
   */
  static getConfiguration(username, password, server, database) {
    let storedUsername = null;
    let storedPassword = null;
    let storedServer = null;
    let storedDatabase = null;
    let storedTimeout = null;

    try {
      fs.accessSync(`${__dirname}/../../config.js`);

      const config = require(`${__dirname}/../../config`);

      this.enable = config[this.configKey] ? config[this.configKey].enable : this.enable;
      storedUsername = config[this.configKey] ? config[this.configKey].username : null;
      storedPassword = config[this.configKey] ? config[this.configKey].password : null;
      storedServer = config[this.configKey] ? config[this.configKey].server : null;
      storedDatabase = config[this.configKey] ? config[this.configKey].database : null;
      storedTimeout = config[this.configKey] ? config[this.configKey].timeout : null;
    } catch (err) {
      console.warn(err);
    }

    return {
      user: storedUsername || username || '',
      password: storedPassword || password || '',
      server: storedServer || server || 'localhost',
      database: storedDatabase || database || '',
      connectionTimeout: storedTimeout || '15000',
      requestTimeout: storedTimeout || '15000',
      options: {
        appName: os.hostname(),
      },
    };
  }
  /**
   * Metodo generalista per lanciare query
   *
   * @public
   * @static
   * @param {string} query
   * @param {array} [fields]
   * @returns {Promise}
   *
   * @memberof Database
   */
  static query(query, fields) {
    const validQuery = typeof query === 'string';
    const validFields = typeof fields === 'object' || typeof fields === 'undefined';

    if (!validQuery || !validFields) {
      throw new Error('Invalid parameters');
    }

    // il parametro fields è opzionale
    const fieldsArray = fields || [];

    const connection = this.willConnect();
    if (!this.enable) {
      return Promise.reject('Database disabled');
    }
    const db = this.getLib();
    const ps = new db.PreparedStatement(this.connectionPool);
    const values = {};

    fieldsArray.forEach((current) => {
      ps.input(current.name, current.type);
      values[current.name] = current.value;
    });

    let results = null;

    return connection.then(() => {
      return ps.prepare(query)
        .then(() => {
          results = ps.execute(values);
          return results;
        }, (reason) => {
          console.warn(reason);
        })
        .then(() => ps.unprepare(), () => ps.unprepare())
        .then(() => results)
        .catch((reason) => {
          console.warn(reason);
        });
    });
  }
}

Database.configKey = '';
Database.pool = null;
Database.connection = null;

module.exports = Database;
Wellington Rodriguez
@wrod7
const pool = new sql.ConnectionPool(config, (err) => {
  if (err) {
    console.error('DB Error callback:', err.message)
    throw new Error(err)
  }
})
I have this error callback in my connection pool. I changed my config so the connection doesn't actually log in so I can test the error handling. Why am I still getting these "UnhandledPromiseRejections"
[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.js`
Server is listening on 8080
DB Error callback: Login failed for user 'sas'.
(node:2732) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: ConnectionError: Login failed for user 'sas'.
(node:2732) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.(node:2732) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): ConnectionError: Login failed for user 'sas'.
David Gasperoni
@mcdado
well you're still throwing it…
it's a chain, even if you catch it, if you then throw and have no other mechanism for catching it, it will behave like that
either just log the error and don't rethrow it, or do whatever you might have to do about it
Wellington Rodriguez
@wrod7
ah that makes sense. thanks
is there a way i can log in the console overtime a connection is made and disconnected with ConnectionPool? is there a .on('close' or something I can use?
Chris Rutherford
@cjrutherford
Hey all, how should I form my query if there is a table I would like to join that should be an array on the total object?
Dai Nguyendo
@dainguyendo

Greetings! Does node-mssql support auto-incrementing id's during bulk upload? I have attempted multiple column configurations such as , table.columns.add('id', sql.Int, { primary: true identity: true }); - however I still require to input values for these columns which is not the desired effect.

To expand, TSQL's CREATE TABLE mytable ([id] INT IDENTITY(1,1) NOT NULL) will auto increment on each insert of a new row. Thoughts/suggestions?

David Gasperoni
@mcdado
You could create the raw statement, no?
Dai Nguyendo
@dainguyendo
@mcdado , apologies - could you explain further?
For context, I am creating tables on-the-fly based on the data we receive, however I have since learned I need to have primary keys to relate the data to another table. I am utilizing bulk uploads as the data to be inserted may be quite large - following the documentation, I need to first create the table (which continuously changes in number of columns however requires an ID), then implement table.rows.add() with the values for each column in order.
David Gasperoni
@mcdado
I see, then creating a raw statement might be problematic
What I meant is using a prepared statement and write a tsql query in it
Dai Nguyendo
@dainguyendo
Yeah, it would be great to hear if anyone else ever had to approach a problem such as this. The documentation gives clues such as those additional object properties to the method however nothing in plain text to auto-incrementing and PKs. Thanks for the assistance @mcdado !
PmoriartyPhoenix
@PmoriartyPhoenix
Was just wondering. In both the tedious driver and mssqlserverv8 there is no mention of 2016 allways on ag cluster support. Are they supported. (I know its your driver, not the wrapper question. Sorry)
davemeech
@davemeech

I'm getting pretty desperate here. I am looking for examples on how to properly perform transactions with looped inserts using mssql and I'm running into problems. patriksimek/node-mssql#550

If anyone can help I'd be eternally grateful.

trivedimehulk
@trivedimehulk

Guys.. I am facing a small issue here.
When I run to fetch big data from my table the call is blocking all other static content request to node server.

Have anybody faced this problem?
Ping me if need more details.

David Gasperoni
@mcdado
Can you paste the code where you’re fetching?
trivedimehulk
@trivedimehulk
yeah sure.
hold on

const sqlInstance = require('mssql');
const express = require('express');
const app = express();
app.get('/', (req, res) => {

if (req.query.p == 'sql') {

    var setUp = {
        server: 'myservername',
        database: 'Products',
        user: 'Products',
        password: 'Products',
        port: 1433,
        options: {
            encrypt: true
        }
    };

    sqlInstance.connect(setUp).then(function (connection) {
        var _sqlRequest = new sqlInstance.Request(connection)
            .query("[GetAllProducts]")
            .then(function (dbData) {
                if (dbData == null || dbData.length === 0)
                    res.send('No data boss!');
                res.send('Loaded big data');
                sqlInstance.close();
            })
            .catch(function (error) {
                console.dir(error);
            });
    })

} else {
    res.send('Responded to static request!!!');
}

})

var printLog = function(log){ console.log(log);};

app.listen(3000, () => console.log('Example app listening on port 3000!'))


David Gasperoni
@mcdado
You open a connection to db at every request? I would make a connection promise and reuse that at each request. I don’t think it will solve your issue but it might be faster
Connection would occur at app startup
trivedimehulk
@trivedimehulk
David
thia isnmy pic
David this is my poc code. I’ll take care of it.
David Gasperoni
@mcdado
Alright, I was just wondering. Because that definitely adds some delay. I’m not sure about blocking though, as you seem to always do the right thing and return promises/callbacks
Zheyi Zhu
@Voxis

hi im trying to dynamically add tvp data into tvp table. I need some help here…
I have already new the table and added the columns no problem there

let columns = _.map(tvpData.columns, 'name');
tvpData.data.forEach((item) => {
        tvp.rows.add.apply(null, columns.map((c) => item[c]));
});

but it seems stuck in this foreach. any help would be appreciated

Tim Oien
@toien44
Looking into tools to test against a DB and someone pointed me here. I need to test against SQL Management studio client I guess it's a GUI interface but should still be able to throw commands at it. Would this library work to verify that a job is set correctly and ran?
Tim Oien
@toien44
What tools do people use for using this on a mac? I need a GUI interface too to verify my tests/ steps.
Sean Kelly
@seank-com
I used to use MySQL Workbench. Don't know if it is compatible with MSSQL. Failing that you can always install Windows on a VirtualBox VM
Wellington Rodriguez
@wrod7
@toien44 SQL Operations Studio
dmanhaus
@dmanhaus
If you’re looking to issue SQL commands against a SQL DB on a Mac, I recommend using VS Code. It works well, includes intellisense and source control. Plus it’s good for just about any other language you need to develop in.
Tim Oien
@toien44
ok thanks all
dmanhaus
@dmanhaus
...just be sure to add the MSSQL extension after you install it.
Tim Oien
@toien44
I'm not looking for an editor as I have one I need a way to view the tables on a mac. I'd prefer to not use a VM
Sean Kelly
@seank-com
VSCode will display a table as a result of your SQL query. It's really pretty slick.
Tim Oien
@toien44
oh nice thanks
David Gasperoni
@mcdado
Sql operations Studio by Microsoft
It’s in alpha I think
It’s an electron-based app that’s multi-platform
Tim Oien
@toien44
I'm trying to set up a DB connection would host be the name of the database or a URL?
var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db'
});

connection.connect((err) => {
    if (err) {
        console.error(`error connecting: ${err.stack}`);

        return;
    }

    console.log(`connected as id ${connection.threadId}`);
});

connection.end();
Tim Oien
@toien44
I got the HOST figured out however, I can't get the console log to print out