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
Aris Kemper
@ariskemper
Offcourse you could use node-mssql
Check node mssql documentation on how to connect to mssql server
Milan Willems
@Milanw2
Yeah I got that working in a Node console application
But now I'm getting the error: req.query is not a function
Aris Kemper
@ariskemper
This is something with express and sending params to endpoint.
Milan Willems
@Milanw2
Any idea how I can fix this?
Aris Kemper
@ariskemper
Debug your code
I cant give you direct answer
Milan Willems
@Milanw2
Do you know a tutorial I can follow for a new project? Not necessarily a MEAN stack application
I just need to build an Angular 2 app with data from an SQL server
Milan Willems
@Milanw2
router.get('/posts', (req, res) => {
conn.connect(function (err) {
if (err) {
console.log("connection error -->" +err);
return;
}
req.querySELECT TOP (10) u.* FROM [Alg].[User] AS u;, function (err, recordset) {
if (err) {
console.log("query error -->" + err);
return;
}
else {
console.log(recordset);
res.send(recordset);
}
conn.close();
};
});
});
this is the code which gives the error
any help?
crdil
@crdil
Hello. I'm trying to read queries from a file and run them, but I can't make it work. I'm reading the file with fs.readFile and utf8 into a buffer which I then try to run as query. Is this the wrong approach?
Sotirios Mantziaris
@mantzas
hi, i am trying to use the package inside a aws lambda. is there any walk through/example out there that shows how to get a connection, begin a transaction, commit/rollback transaction, close connection. etc. It seems that my code finds the connection open on subsequent calls to the lambda.
Ali Shaikh
@AliShaikh94
Hi, anyone here?
Selçuk GÜRAL
@selcukgural
hi, how can run query synchronous?
David Gasperoni
@mcdado
Is there a way to increase the connection pool?
dmanhaus
@dmanhaus
Basic question: I'm trying to refactor some code I wrote to use connection pooling asynchronously. The examples posted on the github repo are not sufficient for me to understand how to write the solution correctly. Are there any fully-featured example solutions in anyone's git repo I can look at? My app wants to open a sql connection pool and export execute methods for other modules to call upon. I am using koa wrapped around mssql to stand up an API backed by a sql database.
dmanhaus
@dmanhaus
Never mind. Worked it out.
snenp
@snenp
Hi,
anyone, knows if is it possible to mantain 2 connections to 2 different servers?
Wellington Rodriguez
@wrod7
anyone using mssql 2017 on linux? is it ready for production?
Paul
@karooga
dmanhaus: I have a similar issue, what was the work around that you used?
Paul
@karooga
Hi, anyone using mysql with promises, as per the documentation: https://www.npmjs.com/package/mssql
The examples don't seem to be correct from what I can see.
Javier Castro
@jacargentina
Hi! any chance to get a new release using tedious@next ?
Wellington Rodriguez
@wrod7
@jacargentina what is tedious next? node-mssql is using 2.0 I believe
Wellington Rodriguez
@wrod7
hello im trying to setup a single db file that exports a connection pool to it can be used throughout my entire web application (im new to mssql so please tell me if this isn't the right thing to do) any reason why this wouldn't work:
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 !