Git Product home page Git Product logo

node-sqlserver-v8's Introduction

msnodesqlv8

Build status GitHub stars GitHub issues npm npm

  1. new Ubuntu, Debian Node v18, v20 - install openssl 3.2 see WIKI
  2. docker images see WIKI
  3. new support always on encryption via tables and procedures.
  4. new support Node v20, v21
  5. new support electron v24, v25, v26
  6. new read numerics as strings - see WIKI
  7. Sybase Adaptive Server Enterprise support - see WIKI
  8. thread worker support - see WIKI
  9. manually register tables
  10. manually register and execute stored proc
  11. promises - see WIKI
  12. fast BCP bulk insert - see WIKI
  13. 64 bit x64 Linux
  14. includes MacOS support
  15. use object based named params for proc calls - see WIKI
  16. improved local date support via bound tables
  17. pause/resume long running query
  18. built in connection pool
  19. sequelize support directly included
  20. supports input/output parameters.
  21. captures return code from stored procedure.
  22. will obtain meta data describing parameters.
  23. compatible with Node versions greater 12.0
  24. electron version greater than 5.0
  25. includes 64 bit/ia32 precompiled libraries.
  26. npm install with npm install msnodesqlv8
  27. bulk table operations insert, delete, update
  28. prepared statements
  29. table value parameters
  30. native sequelize support

Ubuntu Debian SEGV on node v18, v20

please see appveyor which installs openssl 3.2 allowing this library to work for Node 18, 20. See test script tool\openssl.sh as potential installer, check for dependencies on your system first.

Node JS support for SQL server (and other databases with ODBC compliant driver)

This library has full compatibility with MS SQL Server using an MS ODBC driver. Many functions e.g. open, query, connection pool, prepare, transactions, close will work with any ODBC compatible driver with its repsective database.

Based on node-sqlserver, this version will compile in Visual Studio 2017/2019 and is built against the v8 node module API using the NAN abstraction. Releases include pre-compiled binaries for both x64 and x86 targets for Node and Electron.

This library only works with Node versions greater than 10.0 or electron greater than 5.0

BCP (odbc v17 / v18 only)

BCP allows fast insert speed from client to a designated table. This is achieved via allocating fixed positions in memory binding each column on that table and re-populating/sending each row to the server. It is in effect a memory copy from the client to the table.

a 16 column Employee table mixed with binary, varchar, date, int and decimal can insert over 50k rows in 3 seconds (vs 25 seconds using non bcp) over a network, smaller tables speeds can be over 100k a second.

    // see bcp.js unit tests - bind to a table
    async create () {
      const promisedQuery = util.promisify(theConnection.query)
      const tm = theConnection.tableMgr()
      const promisedGetTable = util.promisify(tm.getTable)
      await promisedQuery(this.dropTableSql)
      await promisedQuery(this.createTableSql)
      const table = await promisedGetTable(this.tableName)
      return table
    }
  }
 // set the flag to turn on bcp and send rows to server using fast memory copy.
 theConnection.setUseUTC(false)
        const table = await helper.create()
        table.setUseBcp(true)
        const promisedInsert = util.promisify(table.insertRows)
        const promisedQuery = util.promisify(theConnection.query)

This protocol is not part of the ODBC specification and its use therefore depends on using correct ODBC driver. For linux users, this should work out the box as ODBC 17, 18 are the only drivers supported. The feature has been tested on Ubuntu, MacOS, Debian and Alpine.

For windows users, older drivers can still be used on all non bcp functions just as before - however presently only ODBC 17 and 18 are supported for bcp. Hence you need to have installed ODBC data source "ODBC Driver 17 for SQL Server" or "ODBC Driver 18 for SQL Server". No other driver will work and attempts to do so will probably crash the node instance.

see wiki for more details or bcp unit tests - bcp is accessed via the table manager i.e. binding to a table and enabling bcp on that table returned.

Linux (x64 only)

if running on Linux, the odbc driver needs to be installed as outlined here ODBC 17. Please use version >= 17.5 which has been tested with this library. We are running test suite for Linux on AppVeyor which you can see via the badge at top of this page. Linux distros tested so far are Ubuntu 18.04, Alpine 3.12, Ubuntu 20.04, Debian 10.5, MacOS (see wiki) and Fedora 32. The driver also works under windows linux subsystem 2 (WLS).

Installing

Install the package from npm:

npm install msnodesqlv8 --save

Getting started

please see wiki for documentation.

JavaScript

Require the module, and write a simple program link this:

const sql = require("msnodesqlv8");

const connectionString = "server=.;Database=Master;Trusted_Connection=Yes;Driver={SQL Server Native Client 11.0}";
const query = "SELECT name FROM sys.databases";

sql.query(connectionString, query, (err, rows) => {
    console.log(rows);
});

See our JavaScript sample app for more details.

TypeScript

Typings are included in the package. Simply import the types you need, and require the module to get started:

import { SqlClient } from "msnodesqlv8/types";

const sql: SqlClient = require("msnodesqlv8");

const connectionString = "server=.;Database=Master;Trusted_Connection=Yes;Driver={SQL Server Native Client 11.0}";
const query = "SELECT name FROM sys.databases";

sql.query(connectionString, query, (err, rows) => {
    console.log(rows);
});

See our TypeScript sample app for more details.

Electron

Since this is a native module, you will likely need to run electron-rebuild to rebuild the module for your version of Electron.

Please see wiki for getting started with electron boilerplate with React.

Webpack

If you are using Webpack for your application, you need to:

  1. Add the node-loader as a dev dependency.
  2. Update your webpack.config.js to include the following under module.rules:
    {
        test: /\.node$/,
        use: 'node-loader'
    }

Pool

you can now submit queries through a native library connection pool. This pool creates a set of connections and queues work submitting items such that all connections are busy providing work exists. A keep alive is sent periodically to check connection integrity and idle connections beyond a threshold are closed and re-created when queries submitted at a later point in time. Queries can be cancelled and paused / resumed regardless of where they are in the work lifecycle

examples can be seen here and here

export interface PoolOptions {
    floor: number
    ceiling: number
    heartbeatSecs: number
    heartbeatSql: string
    inactivityTimeoutSecs: number
    connectionString: string
}

const pool = new sql.Pool(options)

the following example shows the pool being used.

const sql = require('msnodesqlv8')

const pool = new sql.Pool({
  connectionString: 'Driver={ODBC Driver 13 for SQL Server};Server=(localdb)\\node;Database=scratch;Trusted_Connection=yes;'
})

pool.on('open', (options) => {
  console.log(`ready options = ${JSON.stringify(options, null, 4)}`)
})

pool.on('debug', msg => {
  console.log(`\t\t\t\t\t\t${new Date().toLocaleTimeString()} <pool.debug> ${msg}`)
})

pool.on('status', s => {
  console.log(`status = ${JSON.stringify(s, null, 4)}`)
})

pool.on('error', e => {
  console.log(e)
})

const testSql = 'waitfor delay \'00:00:10\';'

function submit (sql) {
  const q = pool.query(sql)
  console.log(`send ${new Date().toLocaleTimeString()}, sql = ${sql}`)
  q.on('submitted', d => {
    console.log(`query submitted ${new Date().toLocaleTimeString()}, sql = ${d.query_str}`)
    q.on('done', () => console.log(`query done ${new Date().toLocaleTimeString()}`))
  })
  return q
}

for (let i = 0; i < 7; ++i) {
  const q = submit(testSql)
  switch (i) {
    case 5:
      console.log('cancel a query')
      q.cancelQuery()
      break
    case 6:
      q.pauseQuery()
      setTimeout(() => {
        console.log('resume a paused query')
        q.resumeQuery()
      }, 50000)
      break
    default:
      break
  }
}

setInterval(() => {
  submit(testSql)
}, 60000)

pool.open()

Prepared Statements

It is now possible to prepare one or more statements which can then be invoked over and over with different parameters. There are a few examples in the prepared unit tests. Please note that prepared statements must be closed as shown below when they are no longer required. Each prepared statement utilises server resources so the application should open and close appropriately.

Prepared Statements can be useful when there is a requirement to run the same SQL with different parameters many times. This saves overhead from constantly submitting the same SQL to the server.

    function employeePrepare(done) {

    var query =
        `SELECT [ModifiedDate]
        ,[BusinessEntityID]
        ,[OrganizationNode]
        ,[ModifiedDate]
        FROM [scratch].[dbo].[Employee]
        WHERE BusinessEntityID = ?`;

    // open connection
    sql.open(connStr, function (err, conn) {
        assert.ifError(err);
        // prepare a statement which can be re-used
        conn.prepare(query, function (e, ps) {
            // called back with a prepared statement
            console.log(ps.getMeta());
            // prepared query meta data avaialble to view
            assert.ifError(err);
            // execute with expected paramater
            ps.preparedQuery([1], function(err, fetched) {
                console.log(fetched);
                // can call again with new parameters.
                // note - free the statement when no longer used,
                // else resources will be leaked.
                ps.free(function() {
                    done();
                })
            });
        });
    });
    }

Connect Timeout

send in a connect object to pass a timeout to the driver for connect request

    function connect_timeout() {
        var co = {
            conn_str : connStr,
            conn_timeout : 2
        };
        var start = new Date().getTime();
        console.log ('connect ' + start);
        sql.open(co, function(err, conn) {
            var end = new Date().getTime();
            var elapsed = end - start;
            console.log ('callback ..... ' + elapsed );
            if (err) {
                console.log(err);
                return;
            }
            var ts = new Date().getTime();
            conn.query("declare @v time = ?; select @v as v", [sql.Time(ts)], function (err, res) {
                assert.ifError(err);
                console.log(res);
            });
        });

Query Timeout

send in a query object such as that shown below to set a timeout for a particular query. Note usual semantics of using a sql string parameter will result in no timeout being set

        open(function(conn) {
            var queryObj = {
                query_str : "waitfor delay \'00:00:10\';",
                query_timeout : 2
            };

            conn.query(queryObj, function (err, res) {
                assert(err != null);
                assert(err.message.indexOf('Query timeout expired') > 0)
                test_done();
            });
        });

A timeout can also be used with a stored procedure call as follows :-

        function go() {
            var pm = c.procedureMgr();
            pm.setTimeout(2);
            pm.callproc(sp_name, ['0:0:5'], function(err, results, output) {
                assert(err != null);
                assert(err.message.indexOf('Query timeout expired') > 0)
                test_done();
            });
        }

User Binding Of Parameters

In many cases letting the driver decide on the parameter type is sufficient. There are occasions however where more control is required. The API now includes some methods which explicitly set the type alongside the value. The driver will in this case use the type as provided. For example, to set column type as binary and pass in null value, use the sql.VarBinary as shown below. There are more examples in test harness file userbind.js.

     sql.open(connStr, function(err, conn) {
         conn.query("declare @bin binary(4) = ?; select @bin as bin", [sql.VarBinary(null)], function (err, res) {
             var expected = [ {
                 'bin' : null
             }];
             assert.ifError(err);
             assert.deepEqual(expected, res);
         });
     });

Stored Procedure Support

Included in this module is support for stored procedures in SQL server. Simple input/output parameters and return value can be bound.

open a connection, and get an instance of procedureMgr

        sql.open(conn_str, function (err, conn) {
                var pm = conn.procedureMgr();
                pm.callproc('my_proc', [10], function(err, results, output) {
            });
        });

in above example a call is issued to the stored procedure my_proc which takes one input integer parameter. results will contain rows selected within the procedure and output parameters are inserted into output vector. Note the [0] element in output will be the return result of the procedure. If no return exists in the procedure, this value will be 0. Any further elements in the array will be output parameters populated by the execution of the procedure.

Note the manager will issue a select to the database to obtain meta data about the procedure. This is cached by the manager. It is possible to obtain this information for inspection.

    pm.describe(name, function (meta) {
        console.log(JSON.stringify(meta));
        pm.callproc('my_proc', [10], function (err, results, output) {
        });
    });

meta will contain the parameter array associated with the procedure, the type, size and call signature required.

the test folder includes some simple unit tests for stored procedures. If you discover any problems with using this new feature please include a simple example, preferably a unit test illustrating the issue. I will endeavour to fix the issue promptly.

Further enhancements will be made to the library over the coming months - please leave feedback or suggestions for required features.

Bulk Table Operations

Bulk insert/delete/modify is now supported through a helper class. The underlying c++ driver will reserve vectors containing the column data and submit in bulk to the database which will reduce network overhead. It is possible to configure in the java script a batch size which will break the master vector of objects down into batches each of which is prepared and sent by the driver. Most of the effort for this update was spent in getting the c++ driver to work, the js API still needs a little refinement, so please use the feature and make suggestions for improvements.

If issues are found, please provide the exact table definition being used and ideally a unit test illustrating the problem.

take a look at the unit test file bulk.js to get an idea of how to use these new functions.

once a connection is opened, first get the table manager :-

            var tm = c.tableMgr();
            tm.bind('Employee', cb);

the table manager will fetch some meta data describing the table 'Employee' and make a callback providing a manager for that particular table :-

            function cb(bulkMgr) {
              // bulkMgr is now ready to accept bulk operations for table 'Employee'
              // see employee.json and employee.sql in test.
              var parsedJSON = getJSON(); // see bulk.js
              bulkMgr.insertRows(parsedJSON, insertDone);
            }

you can look at the signatures, columns and other interesting information by asking for a summary :-

             var summary = bulkMgr.getSummary();

by default the primary key of the table is assigned to the where condition for select which gives a convenient way of selecting a set of rows based on knowing the keys. Note this operation is not yet optimized with bulk fetch, which will be enhanced in the next update addressing cursors.

             keys = [];
             keys.push(
                 {
                     BusinessEntityID : 1  
                 }
             );
             bulkMgr.selectRows(keys, function(err, results) {
                 // results will contain the full object i.e. all columns,
             }
             );

it is possible to change the where clause by using a different column signature - for example, LoginID

            var whereCols = [];
            whereCols.push({
                name : 'LoginID'
            });
            // as above keys now needs to contain a vector of LoginID
            bulkMgr.setWhereCols(whereCols);
            bulkMgr.selectRows(keys, bulkDone);

Amends can be made to a sub set of columns, for example to bulk update the modified date, prepare a set of objects with the primary keys to satisfy the where clause and of course the column to be updated. By default all assignable columns are used for the update signature so the entire object would need to be presented. Where performance is within acceptable limits, this is probably the easiest pattern i.e. select the entire object, amend as required and commit the amended vector back to the database.

                var newDate = new Date("2015-01-01T00:00:00.000Z");
                var modifications = [];
                parsedJSON.forEach(function(emp) {
                    emp.ModifiedDate = newDate;
                    modifications.push( {
                        BusinessEntityID : emp.BusinessEntityID,
                        ModifiedDate : newDate
                    });
                });

tell the bulkMgr which columns to use for the update and send in the modification :-

                var updateCols = [];
                updateCols.push({
                    name : 'ModifiedDate'
                });

                bulkMgr.setUpdateCols(updateCols);
                bulkMgr.updateRows(modifications, updateDone);

the manager can also delete rows - the where clause is used in binding signature so by default this will be the primary key. Similar to the select examples above :-

                 bulkMgr.deleteRows(keys, function (err, res) {
                 })

of course keys can be the original objects as fetched with select - the driver only needs all columns that satisfy the where condition of the signature.

finally, to reset the signatures the summary can help :-

                 var summary = bulkMgr.getSummary();
                 bulkMgr.setWhereCols(summary.primaryColumns);
                 bulkMgr.setUpdateCols(summary.assignableColumns);

Further enhancements will be made to the library over the coming months - please leave feedback or suggestions for required features.

Use with Sequelize

This library now has direct support for sequelize v6, the popular ORM:

const Sequelize = require('sequelize')

const sequelize = new Sequelize({
  dialect: 'mssql',
  dialectModulePath: 'msnodesqlv8/lib/sequelize',
  dialectOptions: {
    user: '',
    password: '',
    database: 'node',
    options: {
      driver: '',
      connectionString: 'Driver={ODBC Driver 17 for SQL Server};Server=(localdb)\\node;Database=scratch;Trusted_Connection=yes;',
      trustedConnection: true,
      instanceName: ''
    }
  },
  pool: {
    min: 0,
    max: 5,
    idle: 10000
  }
})

Building

Pre-compiled binaries are provided for each release. If you are running a version of Node or Electron that a pre-compiled binary has not been provided for, you can build your own module using node-gyp.

cd node_modules\msnodesqlv8
node-gyp

Test

Included are a few unit tests. They require mocha, async, and assert to be installed via npm install.

The unit test suite uses the SQLLocalDB utility provided by SQL Server Express.

To run the tests:

  1. Install SQL Server Express with the LocalDB option (it is not included in the default installation).
  2. From the command-line, run the following commands to create a SQL Server instance called "node":
sqllocaldb create node
sqllocaldb start node
sqllocaldb info node
  1. Copy the "Instance pipe name" value from the output of sqllocaldb info node. The format will be like np:\\.\pipe\LOCALDB#<hash>\tsql\query.
  2. Open SQL Server Management Studio.
  3. In the "Connect to Server" dialog, paste the "Instance pipe name" you copied above and connect using "Windows Authentication".
  4. Create a new database, called scratch.

You will now be able to run the tests using the following command:

npm run test

You must ensure the node SQLLocalDB instance is running before running the test command.

Note if you wish to run the code through an IDE such as PHPStorm, the following fragment may help :-

    function runTest() {

    var mocha = new Mocha(
        {
            ui : 'tdd'
        });

    -- change path as required to unit test file, set breakpoint and run via IDE

    mocha.addFile('node_modules/node-sqlserver-v8/test/query.js');

    mocha.run(function (failures) {
        process.on('exit', function () {
            process.exit(failures);
        });
    });

Known Issues

node-sqlserver-v8's People

Contributors

brbeaird avatar dependabot[bot] avatar dhensby avatar egmen avatar gulshan avatar kevinkuszyk avatar m-hoffmann avatar milenkovyua avatar mtriff avatar pellejacobs avatar thething avatar timelorduk avatar xueenda 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

node-sqlserver-v8's Issues

Getting Binary/Image Type as a Buffer

Is there a way to get an Binary/Image column as actual binary data or better as a buffer?

For example we have some pdf's stored in an old database as the sql "image" type and when I do a raw query the metadata confirms it as the "image" type but the data returned from the query is already decoded and in a string.... while this would normally be ok something is not being decoded properly and the PDF's are not showing up right.

so instead of this:
%PDF-1.4 %๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ 1 0 obj<</Producer(DynamicPDF Generator v3.0.3 for .NET)/CreationDate(D:20080721130746)>> endobj ..........

so is there a way to get the actual raw data like this:
0x255044462D312E340A25E2E3CFD30A312030206F626A3C3C2F50726F64756365722844.......

I think the underling issue is with the characters used in a pdf file and JavaScript native encoding/decoding being used, I had a similar issue when writing our new pdf file uploader and as a workaround/fix I kept the files in binary/base64 and they were left intact both in and out of the database.

Thanks,
Jeff

"None of the binaries loaded successfully." on Windows Server 2008 SP2, Node v4

While trying to require the library I'm receiving an error loading the binaires:

Error: None of the binaries loaded successfully. Is your node version either >= 0.12.7 or >= 4.2.x or >= 5.1.1 or >= 6.1.0
    at failIfNoBinaryExported (...dir\node_modules\msnodesqlv8\lib\sqlserver.native.js:64:13)
    at liveLoad (...dir\node_modules\msnodesqlv8\lib\sqlserver.native.js:51:3)
    at Object.<anonymous> (...dir\node_modules\msnodesqlv8\lib\sqlserver.native.js:24:1)

I'm trying to get script to run in an environment with:

  • Windows Server 2008 SP2 (x64)
  • Node v4.8.4 x86, npm v2.15.11
  • VS C++ 2015 Redistributable installed (x86, x64)
  • SQL Native Client 11
  • [email protected]

Adding logging in the attemptToExportBinary (filename) function in sqlserver.native.js lists the expected binaries, but suppresses an error:

sqlserverv8.node.v4.8.4.ia32.node
[Error: The specified procedure could not be found.
\\?\c:\...dir\node_modules\msnodesqlv8\lib\bin\sqlserverv8.node.v4.8.4.ia32.node]

sqlserverv8.node.v4.8.4.x64.node
[Error: %1 is not a valid Win32 application.
\\?\c:\...dir\node_modules\msnodesqlv8\lib\bin\sqlserverv8.node.v4.8.4.x64.node]

Any suggestions what to try?

Passing XML over 2000 characters long to stored procedure results in "[Microsoft][SQL Server Native Client 11.0]Invalid precision value"

Hey there,

I have noticed that trying to pass a XML string of over 2000 characters to a stored procedure as a parameter results in SQL returning "[Microsoft][SQL Server Native Client 11.0]Invalid precision value".

I suppose it's being truncated, but I can't find a way to stop this happening?

I'm just using:

procManager.callproc('SEL_GetDataByXml', parameters, function (err, result) {

Any advice?

Thanks!

Dave

Problem with concurrent connections

Hi, first of all thanks for your efforts on making this lib up to date with latest node releases. I'm in the process of implementing support into node-mssql and during that I found some glitches. I'm going to create a separate issues for each of them.

var msnodesql = require('msnodesqlv8');
msnodesql.open("Driver={SQL Server Native Client 11.0};Server=localhost;Database=xsp;Uid=xsp_test;Pwd=...;Trusted_Connection=No;", function(err, conn1) {
    if (err) return console.error(err);

    msnodesql.open("Driver={SQL Server Native Client 11.0};Server=localhost;Database=xsp;Uid=xsp_test2;Pwd=...;Trusted_Connection=No;", function(err, conn2) {
        if (err) return console.error(err);

        conn1.query("select @@SPID as id, CURRENT_USER as name", function(err, res) {
            if (err) return console.error(err);

            console.log('CONN1', res);
        });

        conn2.query("select @@SPID as id, CURRENT_USER as name", function(err, res) {
            if (err) return console.error(err);

            console.log('CONN2', res);
        });
    });
});

Got:

CONN1 [ { id: 56, name: 'xsp_test2' } ]
CONN2 [ { id: 56, name: 'xsp_test2' } ]

Expected:

CONN1 [ { id: 56, name: 'xsp_test' } ]
CONN2 [ { id: 57, name: 'xsp_test2' } ]

This problem was not present in original msnodesql.

Bulk insert doesn't understand table names wrapped in brackets

tm = connection.tableMgr();
tm.bind("bulk_table", function(mgr) {
    assert(mgr.columns.length > 0); // OK
});
tm = connection.tableMgr();
tm.bind("[bulk_table]", function(mgr) {
    assert(mgr.columns.length > 0); // Fails
});

Temporary tables are not recognized regardless if they're in brackets or not.

tm = connection.tableMgr();
tm.bind("#mytemptable", function(mgr) {
    assert(mgr.columns.length > 0); // Fails
});

bulk insert - some records don't enter the db

Hi,

I don't know the exact cause of this, but we encountered a problem with using the bulk insert feature of this library. The standard query option that we fell back to works like a charm.

We had a CSV file with 13.8m rows in it that we streamed in batches of 25,000 into the tableMgr.insertRows function. At the end of the run we found that the script exited with 13.5m records inserted into the database (SQL Server 2008 R2). We then used a standard query to run through the csv again, and the missing records were inserted into the database.

The strange thing was that records in the very early parts of the csv file had been missed by the bulk insert, which wasn't what I expected.

I can provide supporting files (db schema, csv file, the script I ran) if that would help, with the caveat that the data is representative of the data inserted, but not the actual data.

ConnectionError: [Microsoft][ODBC Driver Manager] Data source name not found

Greetings,

Just moved our app to production and suddenly getting the following error (abbreviated) This works just fine on the dev side of our app.

Error { ConnectionError: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified at msnodesql.open (c:\apps\vim\node_modules\mssql\lib\msnodesqlv8.js:174:17)

Anyone ever run into this issue?
Thanks

Stored proc with BigInt output parameter does not work

As a simple test case:
create PROCEDURE bigint_test
@A bigint = 0,
@b bigint = 0 output
AS
BEGIN
set @b = @A
select @b as b
END
GO

When you call this via the stored proc manager:
pm.callproc("bigint_test", [1234567890], function (err, results, output) {
console.log("err", err);
console.log("results", results);
console.log("output", output);
});

You get the following:
err null
results [ { b: 1234567890 } ]
output [ 0, null ]

So the "b" output parameter does not get assigned correctly

"COUNT field incorrect or syntax error" when string reaches a certain length during an insert?

Is there a byte length limit for values in an insert, or for the entire array during an insert? The following loop fails when value.length > 2000...

/* table structure:

USE [bn_dev]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[ntextTest](
  [testme] [ntext] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
*/

var sql = require('msnodesqlv8');
var conn_str = "Driver={SQL Server Native Client 11.0};Server=(local);Database=bn_dev;Trusted_Connection={Yes}";

value = 'x';
q='insert into ntextTest values ( ? )';
didIFail=false;
times=0;
while(times<335) {
   sql.query(conn_str, q, [value], function (err, results) { if(err){ console.log(err); } });
   value = value + '+x+x+x';
   times = times+1;
}

/* output:

$ node load_test.js
{ Error: [Microsoft][SQL Server Native Client 11.0]COUNT field incorrect or syntax error
    at Error (native) sqlstate: '07002', code: 0 }

*/

`

A dynamic link library (DLL) initialization routine failed

Hi,

I'm trying to make a standalone app with electron.
If use electron i get following error: A dynamic link library (DLL) initialization routine failed
Without electron everything works fine.
I've already used electron-rebuild but still the same error.
What do i have to do to get it working?

Incorrect values for DateTimeOffset

Originally posted here: Azure/node-sqlserver#160

var msnodesql = require('msnodesqlv8');
msnodesql.open(connectionString, function(err, conn) {
    if (err) return console.error(err);

    conn.query("select convert(datetimeoffset(7), '2014-02-14 22:59:59.9999999 +05:00') as dto1, convert(datetimeoffset(7), '2014-02-14 17:59:59.9999999 +00:00') as dto2", function(err, res) {
        console.log(res);
    });
});

Got:

[ { dto1: { Sat, 15 Feb 2014 03:59:59 GMT nanosecondsDelta: 0.0009999 },
    dto2: { Fri, 14 Feb 2014 17:59:59 GMT nanosecondsDelta: 0.0009999 } } ]

Expected:

[ { dto1: { Fri, 14 Feb 2014 17:59:59 GMT nanosecondsDelta: 0.0009999 },
    dto2: { Fri, 14 Feb 2014 17:59:59 GMT nanosecondsDelta: 0.0009999 } } ]

Connection close callback hangs occasionally

Hi,

Version: 0.1.35, node version 4.4.3

Firstly thanks for the work on this.

We've recently looked at replacing the original node-sqlserver with your v8 version and have run into a small issue. The code we have for connecting to SQL Server looks like this:

new Promise(function (resolve, reject) {

    // Open the connection
    nodesqlv8.open('connectionString', function (error, con) {

        // Execute the query
        con.query('SELECT * FROM foo.bar', undefined, function (error, results, hasMore) {

            // Close the connection.
            con.close(function (closeError) {

                // Resolve result
                resolve(results);
            });
        });
    });
});

This bit of code was working correctly in the original node-sqlserver, but in the v8 version it hangs occasionally. Stepping into the code I see that the resolve(results) line gets executed, but control flow never reaches the outer world. I have not been able to reproduce this consistently, but have found that the following two workarounds get rid of the hang:

Workaround 1: Add a setTimeout

  // Execute the query
  con.query('SELECT * FROM foo.bar', undefined, function (error, results, hasMore) {

            // Close the connection.
            con.close(function (closeError) {

                // Resolve with setTimeout
                setTimeout(function () { resolve(results); });
            });
});

Workaround 2: Do not wait for the connection close callback

        // Execute the query
        con.query('SELECT * FROM foo.bar', undefined, function (error, results, hasMore) {

            // Resolve
            resolve(results);

            // Close the connection.
            con.close(function () { });
        });

This is a bit strange and is probably related to #5.

Count of affected rows is somehow broken

var msnodesql = require('msnodesqlv8');
msnodesql.open(connectionString, function(err, conn) {
    if (err) return console.error(err);

    cmd = [
        'create table rowsAffectedTest (id int)',
        'insert into rowsAffectedTest values (1)',
        'insert into rowsAffectedTest values (1)',
        'insert into rowsAffectedTest values (1)',
        'update rowsAffectedTest set id = 1',
        'drop table rowsAffectedTest'
    ];

    var q = conn.query(cmd.join(';'));
    q.on('rowcount', function(count) {
        console.log(count);
    })
});

Result:

1
1
3
3

Expected:

1
1
1
3

"Invalid precision value" in QueryOperation::bindString

Maybe varchar(0) is a invalid type in sqlserver. So if input string is empty, it will throw "Error: [Microsoft][ODBC SQL Server Driver]Invalid precision value".
So change the code like:

binding.param_size = str_len==0?1:str_len;

Invalid precision value when inserting a long string (> 2000 chars) to a NVARCHAR(MAX) column

I seem to be getting an Invalid precision value error when attempting to insert a long string. The string is just over 2000 chars long, and the column is an NVARCHAR(MAX), which is plenty big enough to hold it. The query works fine when running in a tool (e.g. Visual Studio / SQL Server Management Studio), but falls over when using this library.

My research led me here:

http://stackoverflow.com/questions/15007721/sqlbindparameter-invalid-precision-value-on-a-nvarcharmax-column

which suggests that we need to use SQL_WLONGVARCHAR rather than SQL_WVARCHAR when binding long strings. Looking through the code, my best guess is in src/BoundDatum.cpp, should we set sql_type to SQL_WLONGVARCHAR rather than SQL_WVARCHAR if it's over a certain length? Does that sound plausible, or am I barking up the wrong tree?

msnodesqlv8 not supporting on linux

Not able to install msnodesqlv8 on linux. Getting the below error.
Unsupported platform for [email protected]: Wanted {"os":"win32", "arch":"any"} (Current:{"OS":"linux","arch":"x64"
Could you please give a work around for this.

please give node-sqlserver-v8 a try!

greetings. I hope you find some use in this module. I intend to add additional features which hopefully will be based on the community feedback. So please feel free to make suggestions for improvements or issues with the new stored procedure feature.

Issue while inserting long strings

Using this driver when i try to insert long strings in sql server tables whose columns set to nvarchar(max) through stored procedures via mssql client and setting input type to sql.NVarChar(sql.MAX), for long wkt text it gets:

Error:  String or binary would be truncated

and for other long strings it gets:

Error: Invalid precision value

and no insertion; But using tedious driver it works flawlessly with the same values.
I use your driver because of windows auth support but i have to make a sql login to use tedious.

PRINT 1 + 1 or USE Database Throws Error

This code throws error on the last version (0.2.16) of node-sqlserver-v8. In 0.2.15 everything is OK.
const connStr = 'Driver={SQL Server Native Client 11.0};Server=Server;Trusted_Connection=Yes;'
const sql = require('msnodesqlv8')
var co = {
conn_str : connStr,
conn_timeout : 2
}
sql.open(co, (err, conn) => {
if (err) {
console.log(err)
return
}
conn.query('print 'print error'; select 1 as cnt', [], (err, res) => {
if (err) {
console.log(err)
} else {
console.log(res)
}
})
})

Problem with passing null values into Binary, VarBinary and Image

var msnodesql = require('msnodesqlv8');
msnodesql.open("Driver={SQL Server Native Client 11.0};Server=localhost;Database=xsp;Uid=xsp_test;Pwd=...;Trusted_Connection=No;", function(err, conn) {
    if (err) return console.error(err);

    conn.query("declare @bin binary(4) = ?; select @bin as bin", [null], function(err, res) {
        console.error(err);
    });
});

Results in:

[Error: [Microsoft][SQL Server Native Client 11.0][SQL Server]Implicit conversion from data type char to binary is not allowed. Use the CONVERT function to run this query.]

I had a workaround for original msnodesql - sending an empty buffer to the argument (new Buffer(0)) but this doesn't work anymore. Any ideas?

Question: Connections don't appear to be closing after query?

(I'm not sure if this is the right place for these questions and how much pertains to the original node-sqlserver)

I have essentially the following code:

var sql = require('msnodesqlv8');

function doQuery() {
    sql.open(this.connectionString, function (err, conn) {
        if (err) {
            console.log("Error opening the SQL connection: " + err);
            self.emit('error', err);
            conn.close();
            return;
        }

        var q = conn.queryRaw(query, values, function (err, results) {
            if (err) {
                self.emit('error', err);
                conn.close();
                return;
            }
            callback(null, true, results.rowcount);
        });

        q.on('rowcount', function (count) {
            console.log('rowcount = ' + count);
        }); 

        q.on('closed', function () {
            console.log('closed');
        });

        q.on('done', function () {
            console.log('done');
        });

        q.on('error', function (err) {
            console.log('error: ' + err);
        });
    });

}

I'm noticing log messages for 'rowcount' and 'done' but not 'closed'.
Unless I'm misunderstanding, under the hood the queryRaw() method calls queryCloseOnDone() which upon a 'complete' callback calls thisConn.close() which does a notify.emit('closed'). Since there's no 'closed' event, why isn't this connection being automatically closed?

If I do a conn.close() within the queryRaw() callback it seems that the 'closed' event is not emitted either.

As an additional question, is there any way to read the state of a connection object? e.g. to determine if it is still open/valid or if it has been closed.

Could not catch error

This code block throws error, but I could not catch it from my code (only by uncaughtException): msnodesqlv8\lib\reader.js:29

const sql = require('msnodesqlv8')
const server = 'server'
const connStr = `Driver={SQL Server Native Client 11.0};Server=${server};Trusted_Connection=Yes`
const query = `PRINT 1`

sql.open(connStr, function (err, conn) {
  console.error('First ERROR', err)
  conn.query(query, function (err, fetched) {
    console.error('Second ERROR', err)
  })
})

process.on('uncaughtException', (err) => {
  console.error('Caught exception: ' + err)
})

"done" fires before last result?

I am not sure if this is a bug, or a misunderstanding.

I have a query (actually a stored proc) which I can't change. I can't run it as a stored proc because it's one of many queries that I'm retrieving from a datastore - I don't know what it's going to be when I load it, except that it's SQL.

Unfortunately, whoever wrote the proc didn't add NOCOUNT ON, so for everything the proc does which affects any rows, the handler fires.

I know that eventually the proc returns a single table (which might be empty), so I thought perhaps I could do something like this -

let results: any = [];

let q = conn.query(loadedQuery, (err, res) => {
  results = res;
  console.log(`Result from query: ${JSON.stringify(results)}`)
});

q.on('done', () => {
  console.log(`Completed: ${JSON.stringify(results)}`)
});

But the output for this is -

... 
Result from query: []
Result from query: []
Completed: []
Result from query: [ /* things in here */ ]

So, is this normal behaviour? If so, how can I get the last result and know it's the last result? (especially if the last result is actually empty) If not, well...consider this a bug report ๐Ÿ˜ƒ

Developer Usage Survey

Hello!

I'm trying to learn more about Node.js developers using SQL Server. I created a survey to gather some data: https://www.surveybuilder.com/s/VjJ3Z

Questions include types of projects, drivers, Node.js frameworks and versions. I will share the results back to satisfy your curiosity :)

Error: "None of the binaries loaded successfully. Is your node version either >= 0.12.7 or >= 4.2.x or >= 5.1.1 or >= 6.1.0"

{ "errorMessage": "None of the binaries loaded successfully. Is your node version either >= 0.12.7 or >= 4.2.x or >= 5.1.1 or >= 6.1.0", "errorType": "Error", "stackTrace": [ "Object.<anonymous> (/var/task/node_modules/msnodesqlv8/lib/sqlserver.native.js:24:1)", "Module._compile (module.js:409:26)", "Object.Module._extensions..js (module.js:416:10)", "Module.load (module.js:343:32)", "Function.Module._load (module.js:300:12)", "Module.require (module.js:353:17)", "require (internal/module.js:12:17)", "Object.<anonymous> (/var/task/node_modules/msnodesqlv8/lib/ConnectionWrapper.js:5:11)" ] }

I am run on Amazon Lambda.
Please help me. Thank you!

Compatibility with the new ODBC Driver

Hello @TimelordUK
Hope you are doing well :) Thanks for all the great work you are doing on this driver. We recently released a new ODBC Driver. Will node-sqlserver-v8 work with Microsoft ODBC Driver 13 for SQL Server?

"None of the binaries loaded" error when using --asar=true option during packaging stage

Ok i lost 1-2 days until i realized where the problem is. I am posting this issue in hopes of saving somebody time in searching.
To replicate the issue
in project directory
npm init npm install electron-prebuilt --save-dev npm install electron-packager --save-dev npm install mssql --save npm install msnodesqlv8 --save
then setup project to run and use msnodesqlv8 as a driver for mssql, when you run the project with
npm run test
where test in package.json is "test": "electron main.js" everything is ok. Now here is the tricky part, when you package your application with the command
"electron-packager . \"App Name\" --version=1.4.10 --overwrite --platform=win32 --arch=ia32 --asar=true

the asar=true options creates app.asar archive in the resources folder within the release folder, and when you run the from there it can't load the binaries for the msnodesqlv8 driver.
BTW i use asar archives to ensure that "path too long in windows" error doesn't happen.

Hope i have helped some one.

procedureMgr.bindParams never increments the current param id (j)

Hey there,

There's a bug inside procedureMgr.bindParams where the 'j' variable is never updated; this means that parameters with more than one input parameter won't work properly.

I have altered the function to:

function bindParams(meta, params) {
        var j = 0;
        for (var i = 0; i < params.length; ++i) {
            while (j < meta.params.length && meta.params[j].is_output === true) {
                ++j;
            }
            if (j < meta.params.length) meta.params[j++].val = params[i];
        }
    }

Looks good?

Date Off By One Day

I'm having an issue pulling the correct datetime value. For example, the value in the database is 2009-05-27 00:00:00.000 but when I view the query results, the value is Tue May 26 2009 20:00:00 GMT-0400 (Eastern Daylight Time). How can I pull exactly what is in the database?

Callback firing twice

Hi,
I'm running into an issue with a nested connection callback running twice. What is returned in the console is:
x is 0
x is 1
y is 0
y is 1

And my code is:

x = 0;

y = 0;

sql.open(sqlConnectionString, function(err, conn) {
  if(err){
    return;
  }
  conn.queryRaw("USE master CREATE DATABASE [db_" + guid + "]", function(err, results) {
    //the function below's callback runs twice
    conn.queryRaw("USE BuilderCatalog; insert into Events (Guid, Name, Edited, Date) VALUES('" + guid + "', '" + name + "', GETDATE(), '" + date.format() + "' )", function(err, results) {
      console.log("x is " + x);
      x++;
      conn.queryRaw("USE db_" + guid + "]; " + createTableString, function(err, results) {
        console.log("y is " + y);
        y++;
      }
    }
  }
});

Maybe I'm missing something, but any help would be appreciated!

Node Version 9.2.0 Issue

When the package is used in Node 9.2.0 there is an issue that crops up as below.

Please is there any work around this. This is surely not the expected behaviour.

Unhandled rejection Error: None of the binaries loaded successfully. Is your node version either latest 4, 5, 6, 7 or 8 ?
at failIfNoBinaryExported (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\msnodesqlv8\lib\bootstrap.js:61:15)
at Object.liveLoad (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\msnodesqlv8\lib\bootstrap.js:48:5)
at Object. (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\msnodesqlv8\lib\bootstrap.js:77:12)
at Module._compile (module.js:641:30)
at Object.Module._extensions..js (module.js:652:10)
at Module.load (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\coffee-script\lib\coffee-script\register.js:45:36)
at tryModuleLoad (module.js:503:12)
at Function.Module._load (module.js:495:3)
at Module.require (module.js:585:17)
at require (internal/module.js:11:18)
at D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\msnodesqlv8\lib\connection.js:10:19
at Object. (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\msnodesqlv8\lib\connection.js:449:2)
at Module._compile (module.js:641:30)
at Object.Module._extensions..js (module.js:652:10)
at Module.load (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\coffee-script\lib\coffee-script\register.js:45:36)
at tryModuleLoad (module.js:503:12)
at Function.Module._load (module.js:495:3)
at Module.require (module.js:585:17)
at require (internal/module.js:11:18)
at Object. (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\msnodesqlv8\lib\sql.js:20:10)
at Module._compile (module.js:641:30)
at Object.Module._extensions..js (module.js:652:10)
at Module.load (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\coffee-script\lib\coffee-script\register.js:45:36)
at tryModuleLoad (module.js:503:12)
at Function.Module._load (module.js:495:3)
at Module.require (module.js:585:17)
at require (internal/module.js:11:18)
at Object. (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\mssql\lib\msnodesqlv8.js:3:19)
at Module._compile (module.js:641:30)
at Object.Module._extensions..js (module.js:652:10)
at Module.load (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\coffee-script\lib\coffee-script\register.js:45:36)
at tryModuleLoad (module.js:503:12)
at Function.Module._load (module.js:495:3)
at Module.require (module.js:585:17)
at require (internal/module.js:11:18)
at Object. (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\mssql\msnodesqlv8.js:1:18)
at Module._compile (module.js:641:30)
at Object.Module._extensions..js (module.js:652:10)
at Module.load (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\coffee-script\lib\coffee-script\register.js:45:36)
at tryModuleLoad (module.js:503:12)
at Function.Module._load (module.js:495:3)
at Module.require (module.js:585:17)
at require (internal/module.js:11:18)
at Object. (D:\development\iViewPlus\iViewPlus.External.Web.v2\e2e\pages\utils\databaseabstraction\iViewPlus-database-helper.ts:2:13)
at Module._compile (module.js:641:30)
at Module.m._compile (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\ts-node\src\index.ts:392:23)
at Module._extensions..js (module.js:652:10)
at Object.require.extensions.(anonymous function) [as .ts] (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\ts-node\src\index.ts:395:12)
at Module.load (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\coffee-script\lib\coffee-script\register.js:45:36)
at tryModuleLoad (module.js:503:12)
at Function.Module._load (module.js:495:3)
at Module.require (module.js:585:17)
at require (internal/module.js:11:18)
at Object. (D:\development\iViewPlus\iViewPlus.External.Web.v2\e2e\pages\utils\databaseabstraction\query-manager-database-helper.ts:1:1)
at Module._compile (module.js:641:30)
at Module.m._compile (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\ts-node\src\index.ts:392:23)
at Module._extensions..js (module.js:652:10)
at Object.require.extensions.(anonymous function) [as .ts] (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\ts-node\src\index.ts:395:12)
at Module.load (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\coffee-script\lib\coffee-script\register.js:45:36)
at tryModuleLoad (module.js:503:12)
at Function.Module._load (module.js:495:3)
at Module.require (module.js:585:17)
at require (internal/module.js:11:18)
at Object. (D:\development\iViewPlus\iViewPlus.External.Web.v2\e2e\stepdefinitions\querymanagerStep.ts:3:1)
at Module._compile (module.js:641:30)
at Module.m._compile (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\ts-node\src\index.ts:392:23)
at Module._extensions..js (module.js:652:10)
at Object.require.extensions.(anonymous function) [as .ts] (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\ts-node\src\index.ts:395:12)
at Module.load (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\coffee-script\lib\coffee-script\register.js:45:36)
at tryModuleLoad (module.js:503:12)
at Function.Module._load (module.js:495:3)
at Module.require (module.js:585:17)
at require (internal/module.js:11:18)
at D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\cucumber\src\cli\index.js:61:42
at Array.forEach ()
at Cli.getSupportCodeLibrary (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\cucumber\src\cli\index.js:61:22)
at Cli. (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\cucumber\src\cli\index.js:76:37)
at Generator.next ()
at Generator.tryCatcher (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\bluebird\js\release\util.js:16:23)
at PromiseSpawn._promiseFulfilled (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\bluebird\js\release\generators.js:97:49)
at Promise._settlePromise (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\bluebird\js\release\promise.js:574:26)
at Promise._settlePromise0 (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\bluebird\js\release\promise.js:614:10)
at Promise._settlePromises (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\bluebird\js\release\promise.js:693:18)
at Async._drainQueue (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\bluebird\js\release\async.js:133:16)
at Async._drainQueues (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\bluebird\js\release\async.js:143:10)
at Immediate.Async.drainQueues [as _onImmediate] (D:\development\iViewPlus\iViewPlus.External.Web.v2\node_modules\bluebird\js\release\async.js:17:14)
at runCallback (timers.js:800:20)
at tryOnImmediate (timers.js:762:5)
at processImmediate [as _immediateCallback] (timers.js:733:5)

Empty string parameter results in NULL value in column

It seems that when binding an empty string, the resulting value in my column is NULL, not the empty string. This has come in recently - between 0.1.35 (where this doesn't occur) and the latest (0.1.44):

UPDATE [mytable] SET [textfield] = ?', ['']

Results in textfield being NULL, not the empty string

msnodesqlv8 version 0.1.28 tries to run 'node-gyp rebuild' during 'npm install'

While any other versions up to 0.1.28 allowed to install binaries without 'node-gyp rebuild'

Log is below:

C:\app\test_npm_install>npm install
npm WARN package.json [email protected] No README data
npm WARN package.json [email protected] license should be a valid SPDX lic
ense expression
/
> [email protected] install C:\app\test_npm_install\node_modules\msnodesqlv8
> node-gyp rebuild


C:\app\test_npm_install\node_modules\msnodesqlv8>if not defined npm_config_node_
gyp (node "C:\Users\Administrator\AppData\Roaming\npm\node_modules\npm\bin\node-
gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node  reb
uild )
gyp WARN install got an error, rolling back install
gyp ERR! configure error
gyp ERR! stack Error: 404 status code downloading 32-bit node.lib
gyp ERR! stack     at Request.<anonymous> (C:\Users\Administrator\AppData\Roamin
g\npm\node_modules\npm\node_modules\node-gyp\lib\install.js:377:20)
gyp ERR! stack     at emitOne (events.js:82:20)
gyp ERR! stack     at Request.emit (events.js:169:7)
gyp ERR! stack     at Request.onRequestResponse (C:\Users\Administrator\AppData\
Roaming\npm\node_modules\npm\node_modules\request\request.js:992:10)
gyp ERR! stack     at emitOne (events.js:77:13)
gyp ERR! stack     at ClientRequest.emit (events.js:169:7)
gyp ERR! stack     at HTTPParser.parserOnIncomingClient (_http_client.js:415:21)

gyp ERR! stack     at HTTPParser.parserOnHeadersComplete (_http_common.js:88:23)

gyp ERR! stack     at TLSSocket.socketOnData (_http_client.js:305:20)
gyp ERR! stack     at emitOne (events.js:77:13)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Administrator
\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gy
p.js" "rebuild"
gyp ERR! cwd C:\app\test_npm_install\node_modules\msnodesqlv8
gyp ERR! node -v v4.2.2
gyp ERR! node-gyp -v v2.0.2
gyp ERR! not ok
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Administrator\\A
ppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install"
npm ERR! node v4.2.2
npm ERR! npm  v2.13.4
npm ERR! code ELIFECYCLE

npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'.
npm ERR! This is most likely a problem with the msnodesqlv8 package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls msnodesqlv8
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\app\test_npm_install\npm-debug.log

C:\app\test_npm_install>

How to handle errors/warnings based on severity level

Hi,

I am moving across to this driver from tedious as tedious has severe issues when in streaming mode and causing the entire node app to be blocked. This package/driver does not cause those issues :)

However we have some warning messages in SQL that we cant always suppress. In tedious these warnings did not cause errors, however in this driver the warnings such as "Warning: Null value is eliminated by an aggregate or other SET operation" or "Warning: The join order has been enforced because a local join hint is used" are throwing errors, even though these warnings do not stop or prevent the queries from actually running and returning results.

I commented out some of the error callbacks and the issue went away of course, but I am wondering if there is already a way to handle these cases.

I think it would be best tied to severity levels. E.g severity levels 10 and below (https://docs.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-error-severities) of which my two examples above are included, do not actually prevent the code from running and are just informational messages. I would like to find a solution where informational messages do not cause errors to be thrown please. Could you point me in the correct place in the code to implement something like this if it is not already possible.

Thanks,

Using node-sqlserver-v8 inside electron 1.2.4

I would like to use this module in my electron (v1.2.4) application, but unfortunately the module is not able to require the precompiled ".node" file (sqlserverv8.v6.1.0.x64.node).

Electron (v1.2.4) is using the following versions:

image

I think that i have to build the c++ node addon for the correct electron version. But i have no idea if this is correct and how i have to do it.

Can someone help me please?

Memory Leak

I've been trying to find the cause of a memory leak in my application that uses msnodesqlv8 and it seems to be caused by msnodesqlv8. I have the following test code:

const msnodesqlv8 = require('msnodesqlv8');

msnodesqlv8.open('Driver={SQL Server Native Client 11.0};Server=localhost\\SQLEXPRESS;Trusted_Connection=yes;', (err, conn) => {
	if (err) {
		throw err;
	}
	setInterval(() => {
		conn.queryRaw('select 1+1', (err, results) => {
			if (err) {
				throw err;
			}
			console.log(results);
		});
	}, 100);
});

The query executes successfully, but when monitoring the memory usage, the usage just keeps going up until it uses so much the process has to be killed. It does not look like queries are being cleaned up properly.

I took a look into the code and think it might have to do with SQL handles not being freed. I noticed that in the Free method of the OdbcHandle class, handle is set to nullptr before the call to SQLFreeHandle. This would cause the handle to not be freed. (Reference)

String legth from 2001 to 4000 bytes Throws error

This code throws error "Invalid precision value" for STR_LEN from 2001 to 4000.
const connStr = 'Driver={SQL Server Native Client 11.0};Server=Database;Trusted_Connection=Yes;'

const sql = require('msnodesqlv8')

var co = {
conn_str : connStr,
conn_timeout : 2
}

const STR_LEN = 2001

const str = '1'.repeat(STR_LEN)
sql.open(co, (err, conn) => {
if (err) {
console.log(err)
return
}
conn.query('select ? as cnt', [str], (err, res) => {
if (err) {
console.log(err)
} else {
console.log(res)
}
})
})

Build for node v8.0.0

Hi,
Is there any guide for building the binary for specific Node version like v8.0.0 ?

Thanks!

Passing table value parameter to Store Proc

I'm having an issue when I try to pass a table value parameter to Store proc.

const tvp= new sql.Table();
tvp.columns.add('x',sql.TYPES.Int);
tvp.columns.add('y', sql.TYPES.SmallInt);

When I try to pass this tvp to store proc
await db
.request()
.input("tvpTable", tvp) i'm getting this error RequestError: IMNOD: [msnodesql] Parameter 1: Invalid parameter type.

But the same call works with MSSQL node module. Is table value parameter not supported in node-sqlserver-v8?

Feature proposal

Just a small withlist. You know... it's Christmas :)

  • Connection timeout (documentation says it can't be set via connection string)
  • Request cancellation (required to support request timeouts)
  • Multiple errors handling (atm only the first error that occurs is reported)

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.