Showing posts with label SQL Server. Show all posts
Showing posts with label SQL Server. Show all posts

Thursday, January 12, 2017

Node.js 7.x async/await example with express and mssql

Async/await has finally found its home in node 7.x and it’s just great, we’ve been waiting for ages. Not only it works great, with Visual Studio Code you can write and debug async/await like any other code. Just make sure you have runtimeArgs in your launch.json as a temporary fix until it’s not required somewhere in future:

{
    // Use IntelliSense to learn about possible Node.js debug attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceRoot}/app.js",
            "cwd": "${workspaceRoot}",
            "runtimeArgs": [
                "--harmony"
            ]
        },
        {
            "type": "node",
            "request": "attach",
            "name": "Attach to Process",
            "port": 5858
        }
    ]
}

Async/await could possibly sound like a ephemeral alien until you realize that a lot of good code has already been written with Promises async/await is a sugar over. In an example below I read the data from a simple Sql Server table using node’s mssql module:

CREATE TABLE [dbo].[Parent](
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [ParentName] [nvarchar](150) NOT NULL,
 CONSTRAINT [PK_Parent] PRIMARY KEY CLUSTERED
(
 [ID] ASC
)
) ON [PRIMARY]

I also need a connection string somewhere

// settings.js
module.exports.connectionString = 'server=.\\sql2012;database=databasename;user id=user;password=password';

Note that since tedious doesn't support integrated auth at the moment, you are stuck with sql's username/pwd authentication. The mssql on the other hand uses tedious internally.

Here goes an example of the "old-style" code, written with promises  
   var conn = new sql.Connection(settings.connectionString);
   conn.connect()
     .then( () => {

         var request = new sql.Request(conn);

         request.query('select * from Parent')
              .then( recordset => {

                  recordset.forEach( r => {
     // do something with single record
                  });

    conn.close();
              })
              .catch( err => {
                  console.log( err );
              });
     })
     .catch( err => {
         console.log(err);
     });  
(note that you could possibly avoid nesting thens by just returing the request.query promise so that the next, chained then would refer to it.) However, with async/await the same becomes
try {
 var conn = new sql.Connection(settings.connectionString);
 await conn.connect();
 
 var request = new sql.Request(conn);
 var recordset = await request.query('select * from Parent') 
 
 recordset.forEach( r => {
  // do something with single record
 });
 
 conn.close();
}
catch ( err ) {
 console.log( err );
}
Pretty impressive, if you ask me. If you don't mind occasional awaits, the code is clean, no .thens, no .catches. Remember that express middlewares can be async too
var app = express();

app.get('/', async (req, res) => {

      // code that awaits

});
All this means the callback hell is hopefully gone forever.

Monday, July 13, 2009

Breaking backward compatibility - oh, please!

Most of our SQL Server applications are developed in a way so that they work with any version of the SQL Sever. However users are encouraged to use SQL Sever 2005 just because this particular version has been thoroughly tested.

As one can expect, few users install and use SQL Sever 2008 and usually they do not observe any major issues.

At least not until yesterday.

It turns out that one of our scripts, intended to allow users to select a SQL Server account and assign it to a employee row in a employee table, is based on sp_helpuser stored procedure.

And guess what? Someone from Microsoft has decided to change the names of columns returned by sp_helpuser!

The change is described here

http://msdn.microsoft.com/en-us/library/ms143179.aspx

among few other much more subtle changes.

Does the rename clears up any confusion or introduces a new value to the procedure results?

No!

It's just "GroupName" has been renamed to "RoleName" and three other columns named with "group..." have been renamed to "role...".

Does such change breaks your scripts?

YES!

It's just beautiful BOOM and the application does not work as expected!

I've been talking to few developers from Microsoft and what they always emphasise very firmly is that the backward compatibility for the client-code written by us, developers, is very, very important for them. They are not allowed to just rename "CreateWindow" to "CreateNewWindow" or "sp_helpuser" to "sp_userdata" just because thousands of people probably use previously released artifacts in their own code.

Apparently, this time someone has decided that there are really some lifetime reasons which would consider RoleName more correct that GroupName so that breaking the backward compatibility is somehow justified.

I really, really wonder what these reasons would be....

Thursday, November 15, 2007

Three typical maintenance queries for SQL Server vs Oracle

1. How to get the name of user currently connected to the engine?

MSSQL: SELECT SYSTEM_USER

Oracle: select user from dual

2. How to list schemas/databases available to user currently connected to the engine?

MSSQL: sp_helpdb

Oracle: SELECT * FROM ALL_USERS

3. How to retrieve the size of selected schema/database?

MSSQL: look at the column [db_size] returned by sp_helpdb

Oracle: select Sum(bytes) from dba_segments where owner=SCHEMANAME group by tablespace_name,owner