Thursday, January 25, 2018

Access Db2 from IBM Cloud Functions the Easy Way (Node.js)

Db2 access via IBM Cloud Functions
Recently, I have been experimenting with the IBM Watson Conversation service and Db2. With a new feature in the conversation service it is possible to perform programmatic calls from a dialog node. Why not query Db2? I implemented both a Db2 SELECT and INSERT statement wrapped into actions of IBM Cloud Functions. It is quite easy and here is what you need to know.

The conversation service supports client-side and service-side calls. This means, either the application driving the chat can be instructed to make an outside call or the conversation service itself is invoking an action. That is, IBM Cloud Function actions can be called. For my experiment I coded up two actions, one to fetch data from a Db2 database, the other to insert new data. I chose Node.js 8 runtime platform because the Db2 driver for Node.js is already part of the runtime environment. The sources for the Db2-related actions are in this Github repository.

Passing the right values to the functions shouldn't be a problem for you. Obtaining the credentials for Db2 and making them available inside the action got simplified recently. The CLI plugin for IBM Cloud Functions allows to bind a service to an action as show here:

bx wsk service bind dashDB /hloeser/ConferenceFetch --instance henrikDB2 --keyname henriksKey2

In the example I am binding credentials for the dashDB service (that is Db2 Warehouse on Cloud) to one of my actions named "ConferenceFetch". Because I have multiple service instances and possibly multiple keys (credentials) I make use of the optional parameters "instance" and "keyname". Thereafter, the Db2 configuration including username and password is available in the action metadata. In the action code I am using this syntax to obtain the "dsn" information. The dsn is used by the Db2 driver to connect to the database.

__bx_creds: {dashDB:{dsn}}

With this rough outline you should be able to get your IBM Cloud Functions connected to Db2. Those actions can then directly be called from within a dialog node of Watson Conversation. I will post details on how that works in another blog entry.

If you have feedback, suggestions, or questions about this post, please reach out to me on Twitter (@data_henrik) or LinkedIn.