Giter Club home page Giter Club logo

node-sqlserver's Introduction

Archived

This repository is archived and no longer being maintained. If you are looking for a Node.js driver for SQL Server, please check out Tedious.

Note

This driver is a native C driver that uses the Microsoft ODBC driver under the hood. If you are looking for a pure javascript driver with no dependencies please check out Tedious.

Microsoft Driver for Node.js for SQL Server

The Microsoft Driver for Node.js for SQL Server allows Node.js applications on Microsoft Windows and Microsoft Windows Azure to access Microsoft SQL Server and Microsoft Windows Azure SQL Database.

This is an initial preview release, and is not production ready. We welcome any feedback, fixes and contributions from the community at this very early stage.

Prerequisites

The following prerequisites are necessary prior to using the driver:

Next install the msnodesql driver

  1. Download the msnodesql driver by using the command ‘npm install msnodesql’. This will install Microsoft’s NodeJS-SQL driver into your project. You should now have a folder called msnodesql inside node_modules. Note: This will only work with Node 0.8.9. If you had newer versions, you will have to downgrade.

  2. Next go to the file explorer and naviage to the the C:\NodeJSSampleProject\node_modules\msnodesql folder and run the executable(.msi file). Note: You will need Visual C++ 2010 Express before you run the executable. This can be downloaded from here.

Test

Included are a few unit tests. They require mocha, async, and assert to be installed via npm. Also, set the variables in test-config.js, then run the tests as follows:

cd test
node runtests.js

Known Issues

We are aware that many features are still not implemented, and are working to update these. Please visit the project on Github to view outstanding issues.

Usage

For now, please see the unit tests for usage examples.

Contribute Code

If you would like to become an active contributor to this project please follow the instructions provided in the Contribution Guidelines.

License

The Microsoft Driver for Node.js for SQL Server is licensed under the Apache 2.0 license. See the LICENSE file for more details.

node-sqlserver's People

Contributors

dmgambone avatar einaros avatar jkint avatar mathewc avatar meet-bhagdev avatar qbradley avatar salonisonpal avatar wread 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  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

node-sqlserver's Issues

Multiple Resultsets

This enhancement aims to implement multiple ResultSets support.

Currently, if you have a query which returns multiple ResultSets, you can't access the ones after the first. We want the the appropriate return mechanism to fire off for every returned ResultSet.

For the callback method, you'll get a callback per ResultSet.

For the events method, you'll get a new 'meta' event per ResultSet.

Unicode character issue

Attempting to insert the unicode character for NULL into a string column results in the character not being roundtripped correctly. When reading the character back, it comes back incorrectly as an empty string.

Might be issues with other unicode characters? I tried "caf\u00e9" (café) and that seems to work.

Rowsaffected

This enhancement aims to implement support for 'Rows Affected' for published ResultSets

node 0.8 compatibility

As Node.js upgraded to 0.8, sql-server cannot be used with this version. Could you please check it out?

Enhancement request: Add possibility to use named parameters

Since parameters to stored procedures can have default values, it would be great if named parameters could be sent when calling queries, My suggestion is either like this:

conn.query( 'SprocName', { '@param1': value1, '@Param2': value2 }, function ( err, result ) { ...

or:

conn.query( 'SprocName', [ { name: '@param1', value: value1, <dataType: dataType1>, <...more possible attributes...> }, { name: '@Param2', value: value2, <dataType: dataType2>, <...more possible attributes...> } ], function ( err, result ) { ...

great work by the way!

best regards J

Support core JS types in parameterization

Currently only string, number and buffer are supported as parameter types. It would be nice if the other core Javascript types like boolean (SQL BIT), Date (SQL DATETIME) and null (SQL NULL) were also supported. Without the latter, currently you cannot use a parameterized statement to set a column to null.

Closing Prematurely Doesn't Work

If a call to close is made before a result set is done processing, the extension will be ill behaved. See the code below for an example of the bug.

var sql=require('./lib/sql.js');
var assert=require('assert');
var config = require('./test/test-config.js' );

var conn_str = "Driver={SQL Server Native Client 11.0};Server=.\\SQL2008R2;Trusted_Connection={Yes};Database={test}";

sql.open( conn_str, function( err, conn ) {

  assert.ifError( err );

  var stmt = conn.queryRaw( "select * from sys.tables" );

  stmt.on( 'meta', function( m ) { console.log( 'meta' ); });
  stmt.on( 'done', function( ) { console.log( 'done' ); });
  stmt.on( 'error', function( e ) { console.log( e ); });
  stmt.on( 'row', function( r ) { console.log( 'row' ); conn.close(); });

});

insert 'null' into 'guid' column, fetches data as empty string instead of null

insert 'null' into 'guid' column, fetches data as empty string instead of null

INSERT INTO types_table (col2) VALUES (null)
INSERT INTO types_table (col2) VALUES ('0E984725-C51C-4BF4-9960-E1C80E27ABA0')
SELECT * FROM types_table ORDER BY id

Expected:

{ meta:
   [ { name: 'id', size: 10, nullable: false, type: 'number' },
     { name: 'col2', size: 0, nullable: true, type: 'text' } ],
  rows: [ [ 1, null ], [ 2, '0E984725-C51C-4BF4-9960-E1C80E27ABA0' ] ] }

Received:

{ meta:
   [ { name: 'id', size: 10, nullable: false, type: 'number' },
     { name: 'col2', size: 36, nullable: true, type: 'binary' } ],
  rows: [ [ 1, '' ], [ 2, '0E984725-C51C-4BF4-9960-E1C80E27ABA0' ] ] }

Bind Parameters

This enhancement aims to implement parameter support in the query API

The following data types should be supported:
NULL (as char)
String (as nchar)
Int32 (as int)
Uint32 (as bigint)
Number (as bigint if integer, as double if not integer)
Boolean (as bit)
Date Object (as datetime2)

Feature request: NPM Support

First, keep up the good work, guys! I'm already loving this module, even at this early stage.

I would like to ask that you please make this available in the NPM repository.

Error callback not called

In cases where consecutive errors occur, the node process is ending prematurely, preventing me from handling expected failures. What it looks like is after a certain number of errors, our error handler is no longer called and the process ends. Repro code below. Note that there is nothing special about the ALTER TABLE statement - if the SELECT statement is used instead with a syntax error injected, you'll get the same results. In this simple repro, the 20 expected errors aren’t written to the console - instead we only get a few of them.

var sql = require('node-sqlserver');

var connection = "Driver={SQL Server Native Client 11.0};Server={.\\SQLEXPRESS};Trusted_Connection={Yes};Database=TestDB";

// first setup the test_collection table
setupTestTable(connection, 'dbo', 'test_collection', function (err) {
    // When using this as the command text, all 20 iterations have their output correctly
    // written.
    //var cmdText = "SELECT * FROM [dbo].[test_collection];";

    // However, using the repro ALTER TABLE sql, the program will terminate an an unpredictable time,
    // without having written all results (mostly errors). Thus, the error handler isn't able to handle
    // all errors.
    var cmdText = "ALTER TABLE [dbo].[test_collection] ADD [col2] NVARCHAR(MAX) NULL, [col3] NVARCHAR(MAX) NULL, [col4] NVARCHAR(MAX);";
    var j = 1;
    for (var i = 0; i < 20; i++) {
        sql.query(connection, cmdText, function (err, results) {
            if (!err) {
                console.log('success (' + j++ + ')');
            } else {
                console.log('error (' + j++ + ') ' + err);
            }
        });
    }
});

function setupTestTable(connection, appName, collectionName, callback) {
    // first drop the test table if it exists
    var cmdText = 'DROP TABLE [' + appName + '].[' + collectionName + ']';

    sql.query(connection, cmdText, function (err) {
        // if an error occurs because the table doesn't exist,
        // ignore it
        if (err) {
            var errCode = err.message.substr(0, 5);
            if (errCode != '42S02') {
                callback(err);
            }
        }
        cmdText = 'CREATE TABLE ' + collectionName +
                    '([id] [int] IDENTITY(1,1) NOT NULL, [col1] [NVARCHAR](50) NULL, CONSTRAINT [pk_test_collection] PRIMARY KEY (id))';
        sql.query(connection, cmdText, function (err) {
            callback(err);
        });
    });
}

Provide executeNonQuery equivalent

It is a pretty common scenario to want to check the number of rows affected after executing an update or delete statement. When using an ODBC connection in .NET, there is an ExecuteNonQuery method that returns an integer representing the number of rows affected.

Please expose the same functionality. Thanks!

Surface native SQL errors when connection fails

Using the driver and encountering an issue when the firewall port is not enabled on SQL Azure. If I run SQL Mgmt studio I get this error which clearly indicates the problem.

However in node if I try to connect, I get this error from node in the console

events.js:3425: Uncaught Error: addListener only takes instances of Function

I have traced it and if I add logging of the error object in the callback from my invocation of the query function, the callback is never hit. It appears that the error occurs and node just exits out.

The error makes this hard to debug / unobvious. Would be great if the full error can be surfaced.

Serialization of queries

Currently, we only support having a single query active. This enhancement enables the developer to make multiple query requests, and they will be queued in the order they were called to be sent to the database server.

Prepare and Execute

This enhancement is to enable the ability for a developer to prepare a query and then execute it multiple times. Preparing a query which needs to be executed more than once will improve the performance of all requests, as the server will cache the prepared query.

Rollback does not rollback INSERT

connection.beginTransaction( function( e ) { } ); // Succeeds
connection.queryRaw( "INSERT INTO table1 (...) VALUES ( ... )", function( error, results, more ) { } ) // succeeds
connection.queryRaw( "INSERT INTO table2 (...) VALUES ( ... )", function( error, results, more ) { } ) // Fails w/ Foreign Key violation on table1
connection.queryRaw( "INSERT INTO table3 (...) VALUES ( ... )", function( error, results, more ) { } ) // succeeds
connection.queryRaw( "DELETE FROM table3 WHERE ..", function( error, results, more ) { } ) // succeeds, deletes previously inserted
connection.rollback( function( e ) { }); // Succeeds but does not rollback first insert into table 1

Can't insert empty strings

Attempting to insert an empty string into an nvarchar column produces error "Error: HY104: [Microsoft][SQL Server Native Client 11.0] Invalid precision"

Microsoft Visual C++ Runtime Library: Assertion failed!

this happends always when i trying to run query like "DELETE FROM Client WHERE ClientId = 123".
other queries like select, insert and update is working fine.
i have tried several versions of node.js (0.6.20, 0.8.1, 0.8.4)

and i get always this error:

Microsoft Visual C++ Runtime Library

Assertion failed!

Program: C:\Program Files\nodejs\node.exe
File: ..\src\OdbcException.cpp
Line: 34

Expression: false

For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts

(Press Retry to debug the application - JIT must be enabled)

Abort Retry Ignore

Datatype range issues and roundtripping

Values like double.MinValue, double.MaxValue, double.PositiveInfinity, double.NegativeInfinity, double.NaN, etc. In my case, I was sending these values from a .NET client (the above constants are .NET constants), but the issue is general if the corresponding json string values are sent.

For example, the .NET value Double.MinValue.ToString() yields “1.79769313486232E+308”. Calling parseFloat in JS on that string returns the JS constant -Infinity. Similarly Double.MaxValue yields Infinity. When -Infinity is passed to sql node as a parameter value on insert, the value roundtrips back as -9223372036854776000. Numbers outside of the range of JS Number (5e-324 (negative) to 1.7976931348623157e+308 (positive)) result in -Infinity/Infinity (overflow).

Seems like any values that cannot be stored/roundtripped properly should result in an error. Otherwise the truncation is silent.

NPM install issue

When installing the package from npm the build is successful
But when I run the sample from
http://blogs.msdn.com/b/sqlphp/archive/2012/06/08/introducing-the-microsoft-driver-for-node-js-for-sql-server.aspx

I got the following error:

node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Cannot find module './sqlserver.node'
at Function._resolveFilename (module.js:332:11)
at Function._load (module.js:279:25)
at Module.require (module.js:354:17)
at require (module.js:370:17)
at Object. (C:\Users\ANTON\Documents\GitHub\testproject\node_modules\node-sqlserver\lib\sql.js:20:11)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)
at Module.require (module.js:354:17)

I worked around it by copying sqlserver.node into the lib folder but thought I had better flag it.

insert 'null' into 'xml' column, fetches data as empty string instead of null

insert 'null' into 'xml' column, fetches data as empty string instead of null

Test log:

CREATE TABLE types_table (id int identity, col2  xml)
INSERT INTO types_table (col2) VALUES (null)
INSERT INTO types_table (col2) VALUES ('<data>zzzzz</data>')
SELECT * FROM types_table ORDER BY id

Expected:

{ meta:
   [ { name: 'id', size: 10, nullable: false, type: 'number' },
     { name: 'col2', size: 0, nullable: true, type: 'text' } ],
  rows: [ [ 1, null ], [ 2, '<data>zzzzz</data>' ] ] }

Received:

{ meta:
   [ { name: 'id', size: 10, nullable: false, type: 'number' },
     { name: 'col2', size: 0, nullable: true, type: 'binary' } ],
  rows: [ [ 1, '' ], [ 2, '<data>zzzzz</data>' ] ] }

Intermittent Failures

It appears there may be intermittent failures, and the pattern of doing one query to get results and doing another query using those results seems to make the failures far more frequent. The following code will reproduce the issue (requires a database):

var sql = require('node-sqlserver');
var connectionString = "Driver={SQL Server Native Client 11.0};Server={.\\sqlexpress};Trusted_Connection={Yes};Database=TestDB";

for(var i = 0; i < 10; i++) {
    useSQL(console.log);
}   

function useSQL(callback) {
    sql.query(connectionString, "SELECT TOP 3 [id] FROM [dbo].[blog_posts] WHERE ([showComments] = ?)", [1], function(err, results) {
        var params = [];
        for(var i = 0; i < results.length; i++)
        params.push(results[i].id);

        sql.query(connectionString, "SELECT TOP 10 * FROM [dbo].[blog_comments] WHERE (([postid] = ?) OR ([postid] = ?) OR ([postid] = ?))", params, function(err, results) {
            callback(err, results);
        });
    });
}

Retrieving Identity of inserted rows

It would be nice to provide in results the identity value of inserted rows.

I currently retrieve this value using the following query that returns both a count of inserted and identity if any:

INSERT INTO table1 () VALUES ()
SELECT @@ROWCOUNT AS '__record_count', @@IDENTITY AS '__identity'

insert maximum value into 'bigint' column fails - "Arithmetic overflow error converting expression to data type bigint"

insert maximum value into 'bigint' column fails - "Arithmetic overflow error converting expression to data type bigint"

from the test error log:

CREATE TABLE types_table (id int identity, col2 bigint)
INSERT INTO types_table (col2) VALUES (null)
INSERT INTO types_table (col2) VALUES (-9223372036854776000)
SELECT * FROM types_table ORDER BY id
assert.js:10444: Uncaught Error: 22003: [Microsoft][SQL Server Native Client 11.
0][SQL Server]Arithmetic overflow error converting expression to data type bigin
t.

Error on build

When ever I try and build I just get an error like this:

C:\github\temp\node_modules\node-sqlserver>node "C:\Program Files (x86)\nodejs\node_modules\npm\
bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild

Error: Command failed: 'C:\Program' is not recognized as an internal or external command, operable
 program or batch file.

That happens whether I build from source, or if I just install using npm install node-sqlserver

driver doesn't handle exception when queryRaw("SELECT...") causes an arithmetic overflow ... results in "assert.js:10444: Uncaught Error: 22003:..."

Using repro for issue # 37 or 38, the client application wraps the queryRaw call in a try/catch, but it can't catch the exception. I feel the client app should be able to catch the exception, and also be able to read error info when it's written thusly:

tsql = "SELECT * FROM types_table ORDER BY id";
c.queryRaw(tsql, function (e, r) {
// This should log any error information if an assert occurs
console.log(e);
assert.ifError(e);
try {
assert.deepEqual(r, expected, "Results do not match expected values");
}
catch (assert) {
console.log("\n****** TEST FAILED, Results do not match expected values, test note repro_vsts1008463_datatypes.js \n");
console.log("\nExpected: \n" + util.inspect(expected));
console.log("\nReceived: \n" + util.inspect(r));
done(new Error("\nxxxTEST FAILED, Results do not match expected values, Test Case: \n'" + testname + "' \n"));
return;
}
done();
});

Issuing a delete to an empty table fails

When attempting to issue a delete to a table that contains no rows, C++ assertions are thrown from the driver (C++ runtime libarary). Below is the delete I'm trying to execute - currently I have to use a guard query.

    sql.query(conn, 'SELECT COUNT(*) as [count] FROM foo', function (err, result) {
        if (!err && result[0].count > 0) {
            sql.query(conn, 'DELETE FROM foo', function (err) {
                if (callback) {
                    callback(err);
                }
            });
        } else {
            callback();
        }
    });

Installation problem - reference to sqlserver.node in sql.js

Hi,

I just compiled/installed node-sqlserver module on node 0.8.4.
When install done and try to use it in my app, I have this error message :

module.js:340
    throw err;
        ^
Error: Cannot find module './sqlserver.node'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:362:17)
    at require (module.js:378:17)
    at Object. (C:\workspace\transaction-manager\node_modules\node-sqlserver\lib\sql.js:20:11)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:362:17)

It seems that the path to sqlserver.node is wrong in sql.js.
It works if I replace the line 20 in by :

var sql = require('../build/RELEASE/sqlserver.node');

Rudy

insert 'null' into 'datetime2(7)' column (or other date/time types), fetches data as empty string instead of null

insert 'null' insto 'datetime2(7)' column, fetches data as empty string instead of null

Test log:

CREATE TABLE types_table (id int identity, col2 datetime2(7))
INSERT INTO types_table (col2) VALUES (null)
INSERT INTO types_table (col2) VALUES ('2001-04-10 10:12:59.1234567')
SELECT * FROM types_table ORDER BY id

Expected:
{ meta:
[ { name: 'id', size: 10, nullable: false, type: 'number' },
{ name: 'col2', size: 26, nullable: true, type: 'binary' } ],
rows: [ [ 1, null ], [ 2, '2001-04-10 10:12:59.1234567' ] ] }

Received:
{ meta:
[ { name: 'id', size: 10, nullable: false, type: 'number' },
{ name: 'col2', size: 27, nullable: true, type: 'binary' } ],
rows: [ [ 1, '' ], [ 2, '2001-04-10 10:12:59.1234567' ] ] }

Federations support?

Are Federations supported with the driver? I tried to make prepared query with "GO", and to chain the queries - it doesnt work. If Federations are supported please give example how to use. If not, please advise if support is in roadmap. Thanks!

Parameterized insert query fails.

I have 3 strings, some html, some markdown, and some more html... when I try to do an insert into the DB it fails...

example:

function insertIV(md,html,orightml) {
    sql.query(
        connectionstr
        ,"INSERT INTO [Table] ([MarkdownText],[HtmlText],[HtmlTextOriginal]) VALUES (?,?,?);SELECT 1;"
        ,[md,html,orightml]
        ,function(err,results){
            if (err) {
                console.error(err);
                console.log("\r\nEarly termination, insert failed.");
            }
            
            console.log(results);
            
            console.log("sql conn fin");
        }
    );
}

It doesn't get to the callback with the error.... I get:

events.js:2549: Uncaught Error: 08004: [Microsoft][SQL Server Native Client 11.0]
[SQL Server]Database 'THE' does not exist. Make sure that the name is entered correctly.

Is it the size of the strings? Not sure WTF... grab https://www.instavin.com/tosa.html use pandoc to convert to markdown, then from markdown back to clean html, and do said insert... total fail. :( I can do it in C#, but just didn't want all the boilerplate/build etc for what should be doable in a simple script.

Getting unexpected "Error: 24000 Invalid Cursor State" errors

The repro seems to be to execute one or more INSERT statements from withing the callback of a CREATE TABLE statement, where the create table statement is creating the table that is being inserted into. Even though the inserts actually succeeded (rows are added to the DB), there is an error returned to the callback: [Error: 24000: [Microsoft][SQL Server Native Client 10.0]Invalid cursor state].

Support returning JS types in results

Currently when results are returned, number and string properties are typed properly. However, in the case of SQL DATETIME, BIT, etc., these values are returned as strings. It would be nice if the json objects returned had these properties typed correctly as well (i.e. Date and Boolean properties).

Callbacks should always take error as first parameter

It looks like all of the on* functions which are crafted to be provided as callbacks take a "completed" value as the first parameter and "err" as the second parameter. The node convention is for err to be the first parameter provided to a callback.

Error codes and diags not returned on error, w/ workaround

On error, the error parameter in callbacks does not contain any useful information for debugging queries.

I currently work around this issue using TRY blocks:

BEGIN TRY
  <original statement>
END TRY BEGIN CATCH
  SELECT ERROR_NUMBER() AS '__error', ERROR_MESSAGE() AS 'message', ERROR_SEVERITY() AS 'severity', ERROR_STATE() AS 'state'
END CATCH

Improve Parameter Validation

If certain invalid parameters are passed to the query method, the containing node process will crash unexpectedly.

Two examples are:

  • Passing a null value as the query parameter.
  • Passing anything that is not an array as query parameters (ex: 1 instead of [1]).

These cases should be handled gracefully. The supplied error handler should be called with a validation error instead of crashing the entire process.

Connection has no method queryRaw ...?

I'm not sure if this is an issue or simply an error on my end. I have the driver installed correctly and I'm trying to run a query against an (empty) SQLAzure table. Here is my code:

var sql = require('node-sqlserver');

var server = "... my azure connection string ..."

sql.open(server, function(err, conn) {
  if (err) {
    console.dir(err);
  } else {
    console.dir(conn);
    conn.query('select * from mytable', function(err, results) {
      console.dir(results);
    });
  }
});

When I run this, I get this error:

C:\devtools\temp2\node_modules\node-sqlserver\lib\sql.js:8413: Uncaught TypeError: Object #<Connection> has no method 'queryRaw'

However, (a) when I print out the "conn" object it does show a queryRaw method and (b) when I change my "conn.query(...)" call to "conn.queryRaw(...)" it works.

Am I doing something wrong here that would cause this error? Any help is appreciated!

datetime conversion error

In a datetimeoffset(3) column, if I query for a row where the column contains date 2010-02-01 10:54:52.323 +00:00, I correctly get back { Mon, 01 Feb 2010 10:54:52 GMT nanosecondsDelta: 0 }.

However, it seems that if the data in the column doesn't contain a time component (2012-02-12 00:00:00.000 +00:00), I incorrectly get back { Mon, 13 Feb 2012 00:00:00 GMT nanosecondsDelta: 0 }. The day component is wrong - it has been incremented.

Connection Object

Currently, we use the the ODBC connection string to set up a connection:

var conn_str = "Driver={SQL Server Native Client 11.0};Server=(local);Database=AdventureWorks2012;Trusted_Connection={Yes}";
sql.open(conn_str, function (err, conn) {});

It would be nicer if we had a more JavaScript-oriented way of doing this, such as a ConnectionOptions object, or or array.

There's discussions about this going on at:
http://news.ycombinator.com/item?id=4082761
Example from this thread:

{server: 'localhost', database: 'AdventureWorks2012', trusted: true}

Uncaught TypeError: Object #<Connection> has no method 'queryRaw'

I'm getting this error on one of my recent queries. (I expect that query to return zero rows, which may be a factor in the problem. The error gets reported on sql.js:8413, which is slightly puzzling. (The file isn't that long.) However, some trial and error suggests that it's around line 320:

    this.query = function (query, paramsOrCallback, callback) {

        var chunky = getChunkyArgs(paramsOrCallback, callback);

        function onQueryRaw(completed, err, results) {

            if (!completed) {
                ext.queryRaw(query, chunky.params, onQueryRaw); // <<<< Pretty sure this is the line.
                return;
            }
            if (chunky.callback) {
                if (err) chunky.callback(err);
                else chunky.callback(err, objectify(results));
            }
        }

        return this.queryRaw(query, chunky.params, onQueryRaw);
    }

The ext.queryRaw line looks suspicious because I don't see a queryRaw function in the header for it. (ext is a sql.Connection, not the Connection being declared, if I'm reading it right.) I'm not sure what the right thing for it to do is, however.

Problems with multi-statement queries or temporary table or table variables

I am trying to execute a multi-line query statement using node-sqlserver which uses table variables -


declare @UserCounts table (
NumberOfUsers int,
NumberOfUsersOnRequestAccessList int,
NumberOfUsersOnRequestAccessListHandled int,
NumberOfUsersOnRequestAccessListNotHandled int,
NumberOfUsersOnWhitelist int)

insert into @UserCounts (NumberOfUsers)
select count(*) from [User]
where IsDeleted = 0

update @UserCounts set NumberOfUsersOnRequestAccessList =
(select count(*) from RequestAccess)

update @UserCounts set NumberOfUsersOnRequestAccessListHandled =
(select count(*) from RequestAccess
where IsHandled = 1)

update @UserCounts set NumberOfUsersOnRequestAccessListNotHandled =
(select count(*) from RequestAccess
where IsHandled = 0)

update @UserCounts set NumberOfUsersOnWhitelist =
(select count(*) from UserWhitelist)

select * from @UserCounts

If I execute this from SQL Management Studio it works fine.

What I have tried -

1/ I loaded the above text from a file and ran it in sql.query and sql.queryRaw - no output was returned.
I tried lots of combinations - putting begin/ed around it etc - nothing worked. I have had simple queries working fine from Node.

2/ I put the above text into a stored procedure and ran that - no output was returned (but from SQL Studio - works fine).
I tried putting a single "select count(*) from [User]" into the stored proc, that worked fine. If I added the "declare" before the select, then it still worked, but as soon as I got the first "insert" in there - no output.

3/ I changed my query to user temporary tables (#UserCounts) - same problem.

I am on SQL Server 2008 R2 on Win7.

events.js:2549: Uncaught Error: The connection is in an invalid state

I try to use last src from dev benchmark cda03f8 with node v0.6.5 and v0.8.4

I try to write a simple provider of mssql for ueberDB git module.
This error is happend when I start a benchmark that include in ueberDB.
Seems that this benchmark insert asynchronous many records, and after different time I got this error, for example here is log of this benchmark.

d:\...\node_modules\ueberDB>node benchmark.js mssql
generating random data, to fill database...
done
initalize database...
done
do the first writings to fill the database...
done
values;read_time;write_time;update_time;delete_time;memory_mb
200;0;24;24;22;23
rows: 200
400;0;82;84;82;23
rows: 400
600;0;67;68;68;24
rows: 600
800;0;84;84;83;24
rows: 800
1000;64;71;71;72;25
rows: 1000
events.js:2549: Uncaught Error: The connection is in an invalid state
events.js:2549: Uncaught Error: The connection is in an invalid state
events.js:2549: Uncaught Error: The connection is in an invalid state
events.js:2549: Uncaught Error: The connection is in an invalid state
^C

d:\...\node_modules\ueberDB>node benchmark.js mssql
generating random data, to fill database...
done
initalize database...
done
do the first writings to fill the database...
done
values;read_time;write_time;update_time;delete_time;memory_mb
200;0;37;35;34;23
rows: 200
400;0;85;84;84;23
rows: 400
600;0;73;72;73;24
rows: 600
events.js:2549: Uncaught Error: The connection is in an invalid state
^C

d:\...\node_modules\ueberDB>node benchmark.js mssql
generating random data, to fill database...
done
initalize database...
done
do the first writings to fill the database...
done
values;read_time;write_time;update_time;delete_time;memory_mb
200;0;38;35;35;23
rows: 200
400;0;86;85;87;23
rows: 400
600;0;74;75;74;24
rows: 600
events.js:2549: Uncaught Error: The connection is in an invalid state
^C

d:\...\node_modules\ueberDB>node benchmark.js mssql
generating random data, to fill database...
done
initalize database...
done
do the first writings to fill the database...
done
values;read_time;write_time;update_time;delete_time;memory_mb
200;0;23;22;22;23
rows: 200
400;0;84;85;84;23
rows: 400
600;0;77;76;76;24
rows: 600
800;1;71;71;71;24
rows: 800
events.js:2549: Uncaught Error: The connection is in an invalid state
events.js:2549: Uncaught Error: The connection is in an invalid state

In one of provider method building very long(seems about 5600 sql commands) sql string which include many delete/insert/select commands in format "select * from aaa; delete from aaa where ...; select * from aaa ; ....." and after this string is executing.
If I try to get from profiler this long generated string and execute without many asynchronous executes all executing fine.

I think you can reproduce it.
You need:

  1. npm install ueberDB
  2. in database create table:
CREATE TABLE [dbo].[test] (
  [Key] varchar(800) NULL,
  [Value] varchar(1200) NULL
)
  1. In ueberDB folder create a new file with name mssql_db.js and put this simple code(need change connection string )
var sql = require('node-sqlserver');
var async = require("async");
var conn_str = "Driver={SQL Server Native Client 11.0};Server={xxx};Database={xxx};Trusted_Connection={Yes};";

exports.database = function(settings)
{
  this.db=null; 
}

exports.database.prototype.init = function(callback)
{
  callback();
}

exports.database.prototype.get = function (key, callback)
{
sql.open(conn_str, function (err, conn) {
    if (err) {
        console.log("Error opening the connection!");
        return;
    }
    conn.queryRaw("select [value] from dbo.test where [key] = '" + key + "'", function (err, results) {
        if (err) {
            console.log("Error running query!");
            return;
        }
        if (results.rows.length > 0)
        {
            callback(null, results.rows[0][0]);
        }
        else
        {
            callback(null, null);
        }
    });
});
}

exports.database.prototype.set = function (key, value, callback)
{

sql.open(conn_str, function (err, conn) {
    if (err) {
        console.log("Error opening the connection!");
        return;
    }
    conn.queryRaw("insert into dbo.test ([key], [value]) values('"+key+"', '"+values+"')", function (err, results) {
        if (err) {
            console.log("Error running query!");
            return;
        }
        callback(null);
    });
});

}

exports.database.prototype.remove = function (key, callback)
{

sql.open(conn_str, function (err, conn) {
    if (err) {
        console.log("Error opening the connection!");
        return;
    }
    conn.queryRaw("delete from dbo.test where [key] = '"+key+"'", function (err, results) {
        if (err) {
            console.log("Error running query!");
            return;
        }
        callback(null);
    });
});

}

exports.database.prototype.doBulk = function (bulk, callback)
{ 

//console.log(bulk);
  var sql_q = "";
  for(var i in bulk)
  {
    if(bulk[i].type == "set")
    {
      sql_q+="INSERT INTO dbo.test ([key], [value]) VALUES (" + escape(bulk[i].key) + ", " + escape(bulk[i].value) + "); ";
    }
    else if(bulk[i].type == "remove")
    {
      sql_q+="delete from dbo.test where [key] = " + escape(bulk[i].key) + "; ";
    }
  }

  var stmt = sql.query(conn_str, sql_q);
  callback(null);

}

exports.database.prototype.close = function(callback)
{
  if(callback) callback();
}

function escape (val) 
{
  var res = val.replace(/'/g, "''");
  res = res.replace(/"/g, "");
  return "'"+res+"'";
};  
  1. run benchmark in ueberDB folder
    node benchmark.js mssql

Cannot Read Column Values Longer than 4096 Characters

If a value longer than 4096 characters is read from a column of type NVARCHAR(MAX), the node process will terminate with a Visual C++ assertion failed dialog box.

The dialog box expression is: ret != SQL_NO_DATA.

Note that values of length greater than 4096 can be inserted and updated without any issues.

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.