Getting started with databases on Azure

The Azure cloud platform allows you to use any of the Azure databases (as services) or bring your own database. Once your server and database are set up, your existing code will only need to change the connection settings.

When you do use a database on Azure, there are several common tasks you need to accomplish to use the database from your JavaScript app. Learn more about getting and using your database on Azure.

Select a database to use on Azure

Microsoft provides managed services for the following databases:

Database Dev Guide Azure Service
Cassandra Azure Cosmos DB
Gremlin Azure Cosmos DB
MongoDB Azure Cosmos DB
MariaDB/MySQL Azure Database for MariaDB
PostgreSQL Azure Database for PostgreSQL
Redis Azure Cache for Redis
No-SQL Azure Cosmos DB
Tables Azure Cosmos DB

Select database type:

Didn't find your database? Bring your database as either a container or a virtual machine. You can bring any database type with these services and have high-availability and security to your other Azure resources. The trade-off is that you have to manage the infrastructure (container or VM) yourself. The rest of this document may help you with your container or VM but is more helpful when choosing an Azure database service.

Create the server

Creating a server is completed by creating a resource for the specific Azure service on your subscription where your database is hosted.

Creating a resource is accomplished with:

Tool Purpose
Azure portal Use for first or infrequently used database is the Azure portal.
Azure CLI Use for repeatable/scriptable scenarios.
Visual Studio Code extension (for that service) Use to stay within the development IDE.
npm Azure Resource Manager library (for that service) Use to stay within the JavaScript language.

Once you create the server, depending on the service, you may still need to:

  • Configure security settings such as firewall and SSL enforcement
  • Get your connection information
  • Create the database

Configure security settings for your database

Common security settings to configure for your service include:

  • Opening the firewall for your client IP address
  • Configuring SSL enforcement
  • Accepting public requests or requiring all requests to come from another Azure service

Create a database on the Azure server

You can get your connection information using the same tool as you created your server. Use the connection information to access your server. You still need to create your database specific to your application.

Access your server:

  • Use a tool specific to that database type such as pgAdmin, SQL Server Management Studio, and MySQL Workbench.
  • Continue to use Microsoft tools
    • Azure Cloud Shell includes many database CLIs such as psql and mysql.
    • Visual Studio Code extensions
    • npm packages for JavaScript
    • Azure portal

Programmatically access the server and database with JavaScript

Once you have your connection information, you can access your server with industry-standard npm packages and JavaScript.

After you create or migrate a database, only your connection information to the new server and database should need to change.

Configure an Azure web app's connection to database

If your Azure web app connects to your database, you need to change the App setting for the connection information.

Database-agnostic query languages

Data query languages, agnostic of a specific database, allow you to use the query languages features with your data. Database-agnostic query languages can be used on Azure and require you to bring the translation layer.

GraphQL data layer

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

Static Web apps with GraphQL

Azure Functions with GraphQL

Azure API Management with GraphQL

Cassandra on Azure

To create, move, or use a Cassandra DB database to Azure, you need an Azure Cosmos DB resource.

Create a resource for Azure Cosmos DB for Apache Cassandra

Use the following Azure CLI az cosmosdb create command in the Azure Cloud Shell to create a new resource for your Cassandra database.

az cosmosdb create \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOUR-RESOURCE_NAME \
    --capabilities EnableCassandra

This command may take a couple of minutes to complete and creates a publicly available resource. You don't need to configure firewall rules to allow your client IP address through.

View and use your Cassandra DB on Azure Cosmos DB

While developing your Cassandra DB database with JavaScript, use Azure Cosmos DB explorer to work with your database.

Use the Azure Cosmos DB explorer, found at `https://cosmos.azure.com/`, to view and work with your Cassandra DB database.

The Azure Cosmos DB explorer is also available in the Azure portal, for your resource, as the Data Explorer.

Create a keyspace on the server with Azure CLI

Use the following Azure CLI az cosmosdb cassandra keyspace create command in the Azure Cloud Shell to create a new Cassandra keyspace on your server.

az cosmosdb cassandra keyspace create \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --account-name YOUR-RESOURCE_NAME \
    --name YOUR-KEYSPACE-NAME

Create a table on the keyspace with Azure CLI

Use the following Azure CLI az cosmosdb cassandra table create command in the Azure Cloud Shell to create a new Cassandra keyspace on your server.

az cosmosdb cassandra table create \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --account-name YOUR-RESOURCE_NAME \
    --keyspace-name YOUR-KEYSPACE-NAME \
    --name YOUR-TABLE-NAME \
    --schema @schema.json

Get the Cassandra connection string with Azure CLI

Retrieve the MongoDB connection string for this instance with the az cosmosdb keys list command:

az cosmosdb keys list \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOUR-RESOURCE-NAME \
    --type connection-strings 

Connect to the Cassandra database with a connection string. Your Cassandra user name is the resource name.

Use native SDK packages to connect to Cassandra DB on Azure

The Cassandra DB database on Azure Cosmos DB uses npm packages already available, such as:

localDataCenter using cassandra-driver:

  • V3, use the default of dataCenter1
  • V4, you must specify the data center, such as Central US in the following code block.
  let client = new cassandra.Client({
    contactPoints: [`${config.contactPoint}:10350`],
    authProvider: authProvider,
    localDataCenter: 'Central US',
    sslOptions: {
      secureProtocol: 'TLSv1_2_method',
      rejectUnauthorized: false,
    },
  });

If you're unsure of your localDataCenter, remove the property, run the sample code, and the value of the property is returned in the error text.

NoHostAvailableError: All host(s) tried for query failed. First host tried, xxx.xxx.xxx.xxx:10350: ArgumentError: localDataCenter was configured as 'dataCenter1', but only found hosts in data centers: [Central US]

Use cassandra-driver SDK to connect to Cassandra DB on Azure

To connect and use your Cassandra DB on Azure Cosmos DB with JavaScript and cassandra-driver, use the following procedure.

  1. Make sure Node.js LTS and npm are installed.

  2. Create a Node.js project in a new folder:

    mkdir DataDemo && \
        cd DataDemo && \
        npm init -y && \
        npm install cassandra-driver && \
        touch index.js && \
        code .
    

    The command:

    • creates a project folder named DataDemo
    • changes the Bash terminal into that folder
    • initializes the project, which creates the package.json file
    • adds the cassandra-driver npm SDK to the project
    • creates the index.js script file
    • opens the project in Visual Studio Code
  3. Copy the following JavaScript code into index.js:

    // install cassandra-driver SDK
    // run at command line
    // npm install cassandra-driver
    
    const cassandra = require('cassandra-driver');
    
    const config = {
      username: 'YOUR-USERNAME', // Your Cassandra user name is the resource name 
      password:
        'YOUR-PASSWORD',
      contactPoint: 'YOUR-RESOURCE-NAME.cassandra.cosmos.azure.com',
    };
    
    let client = null;
    
    const callCassandra = async () => {
    
      // authentication 
      const authProvider = new cassandra.auth.PlainTextAuthProvider(
        config.username,
        config.password
      );
    
      // create client
      client = new cassandra.Client({
        contactPoints: [`${config.contactPoint}:10350`],
        authProvider: authProvider,
        localDataCenter: 'Central US',
        sslOptions: {
          secureProtocol: 'TLSv1_2_method',
          rejectUnauthorized: false,
        },
      });
    
      await client.connect();
      console.log("connected");
      
      // create keyspace
      let query =
        "CREATE KEYSPACE IF NOT EXISTS uprofile WITH replication = {\'class\': \'NetworkTopologyStrategy\', \'datacenter\' : \'1\' }";
      await client.execute(query);
      console.log('created keyspace');
    
      // create table
      query =
        'CREATE TABLE IF NOT EXISTS uprofile.user (name text, alias text, region text Primary Key)';
      await client.execute(query);
      console.log('created table');
    
      // insert 3 rows
      console.log('insert');
      const arr = [
        "INSERT INTO uprofile.user (name, alias , region) VALUES ('Tim Jones', 'TJones', 'centralus')",
        "INSERT INTO uprofile.user (name, alias , region) VALUES ('Joan Smith', 'JSmith', 'northus')",
        "INSERT INTO uprofile.user (name, alias , region) VALUES ('Bob Wright', 'BWright', 'westus')"
      ];
      for (const element of arr) {
        await client.execute(element);
      }
    
      // get all rows
      query = 'SELECT * FROM uprofile.user';
      const resultSelect = await client.execute(query);
    
      for (const row of resultSelect.rows) {
        console.log(
          'Obtained row: %s | %s | %s ',
          row.name,
          row.alias,
          row.region
        );
      }
    
      // get filtered row
      console.log('Getting by region');
      query = 'SELECT * FROM uprofile.user where region=\'westus\'';
      const resultSelectWhere = await client.execute(query);
    
      for (const row of resultSelectWhere.rows) {
        console.log(
          'Obtained row: %s | %s | %s ',
          row.name,
          row.alias,
          row.region
        );
      }
    
      client.shutdown();
    };
    
    callCassandra()
      .then(() => {
        console.log('done');
      })
      .catch((err) => {
        if (client) {
          client.shutdown();
        }
        console.log(err);
      });
    
  4. Replace the following in the script with your Azure Cosmos DB for Apache Cassandra connection information:

    • YOUR-RESOURCE-NAME
    • YOUR-USERNAME - replace with YOUR-RESOURCE-NAME
    • YOUR-PASSWORD
  5. Run the script.

    node index.js
    

    The results are:

    connected
    created keyspace
    created table
    insert
    Obtained row: Joan Smith | JSmith | northus 
    Obtained row: Tim Jones | TJones | centralus 
    Obtained row: Bob Wright | BWright | westus
    Getting by region
    Obtained row: Bob Wright | BWright | westus 
    done
    

Cassandra resources

MariaDB and MySQL on Azure

MariaDB and MySQL share a common ancestry and maintain compatibility via the MySQL protocol. MySQL clients can connect to MariaDB and vice versa.

To create, move, or use a MySQL or MariaDB database, you need an Azure resource. Learn how to create the resource and use your database.

Create an Azure Database for MySQL resource

You can create a resource with:

Create an Azure Database for MySQL resource with Azure CLI

Use the following Azure CLI az mysql server create command in the Azure Cloud Shell to create a new MySQL resource for your database.

az mysql server create \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOURRESOURCENAME \
    --location eastus \
    --admin-user YOUR-ADMIN-NAME \
    --ssl-enforcement Disabled \
    --enable-public-network Enabled 

This command may take a couple of minutes to complete and creates a publicly available resource in the eastus region.

The response includes your server's configuration details including:

  • the autogenerated password for the admin account
  • the command to connect to the server with mysql CLI

Before you can connect to the server programmatically, you need to configure your firewall rules to allow your client IP address through.

Add firewall rule for your client IP address to MySQL resource

By default, the firewall rules aren't configured. You should add your client IP address so your client connection to the server with JavaScript is successful.

az mysql server firewall-rule create \
--resource-group YOUR-RESOURCE-GROUP \
--server YOURRESOURCENAME \
--name AllowMyIP --start-ip-address 123.123.123.123 \
--end-ip-address 123.123.123.123

If you don't know your client IP address, use one of these methods:

  • Use the Azure portal to view and change your firewall rules, which include adding your detected client IP
  • Run your Node.js code, the error about your firewall rules violation includes your client IP address

While you can add the full range of internet addresses as a firewall rule, 0.0.0.0-255.255.255.255, this leaves your server open to attacks.

Create a database on the server with Azure CLI

Use the following Azure CLI az mysql db create command in the Azure Cloud Shell to create a new MySQL database on your server.

az mysql db create \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --server-name YOURRESOURCENAME \
    --name YOURDATABASENAME

Get the MySql connection string with Azure CLI

Retrieve the MySql connection string for this instance with the az mysql server show-connection-string command:

az mysql server show-connection-string \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --server-name YOURRESOURCENAME

This returns the connection strings for the popular languages as a JSON object. You need to replace {database}, {username}, and {password} with your own values before using the connection string.

View and use your MySQL on Azure

While developing your MySQL database with JavaScript, use one of the following tools:

Use SDK packages to develop your MySQL on Azure

The Azure MySQL uses npm packages already available, such as:

Use Promise-mysql SDK to connect to MySQL on Azure

To connect and use your MySQL on Azure with JavaScript, use the following procedure.

Note

This article contains references to the term slave, a term that Microsoft no longer uses. When the term is removed from the software, we’ll remove it from this article.

  1. Make sure Node.js and npm are installed.

  2. Create a Node.js project in a new folder:

    mkdir MySQLDemo && \
        cd MySQLDemo && \
        npm init -y && \
        npm install promise-mysql && \
        touch index.js && \
        code .
    

    The command:

    • creates a project folder named MySQLDemo
    • changes the Bash terminal into that folder
    • initializes the project, which creates the package.json file
    • installs the promise-mysql npm package - to use async/await
    • creates the index.js script file
    • opens the project in Visual Studio Code
  3. Copy the following JavaScript code into index.js:

    // To install npm package,
    // run following command at terminal
    // npm install promise-mysql
    
    // get MySQL SDK
    const MySQL = require('promise-mysql');
    
    // query server and close connection
    const query = async (config) => {
      // creation connection
      const connection = await MySQL.createConnection(config);
    
      // show databases on server
      const databases = await connection.query('SHOW DATABASES;');
      console.log(databases);
    
      // show tables in the mysql database
      const tables = await connection.query('SHOW TABLES FROM mysql;');
      console.log(tables);
    
      // show users configured for the server
      const rows = await connection.query('select User from mysql.user;');
      console.log(rows);
    
      // close connection
      connection.end();
    };
    
    const config = {
      host: 'YOUR-RESOURCE_NAME.mysql.database.azure.com',
      user: 'YOUR-ADMIN-NAME@YOUR-RESOURCE_NAME',
      password: 'YOUR-ADMIN-PASSWORD',
      port: 3306,
    };
    
    query(config)
      .then(() => console.log('done'))
      .catch((err) => console.log(err));
    
  4. Replace the host, user, and password with your values in the script for your connection configuration object, config.

  5. Run the script.

MySql resources

MongoDB on Azure

To create, move, or use a mongoDB database to Azure, you need an Azure Cosmos DB resource. Learn how to create the resource and use your database.

Create a resource for Azure Cosmos DB for MongoDB via the Azure CLI

Use the following Azure CLI az cosmosdb create command in the Azure Cloud Shell to create a new Azure Cosmos DB resource for a mongoDB database.

az cosmosdb create \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOUR-RESOURCE_NAME \
    --locations regionName=eastus \
    --kind MongoDB \
    --enable-public-network true \
    --ip-range-filter 123.123.123.123 

Replace 123.123.123.123 with your own client IP or remove the parameter entirely.

This command may take a couple of minutes to complete and creates a publicly available resource in the eastus region.

{
  "apiProperties": {
    "serverVersion": "3.6"
  },
  "capabilities": [
    {
      "name": "EnableMongo"
    }
  ],
  "connectorOffer": null,
  "consistencyPolicy": {
    "defaultConsistencyLevel": "Session",
    "maxIntervalInSeconds": 5,
    "maxStalenessPrefix": 100
  },
  "cors": [],
  "databaseAccountOfferType": "Standard",
  "disableKeyBasedMetadataWriteAccess": false,
  "documentEndpoint": "https://mongo-2.documents.azure.com:443/",
  "enableAnalyticalStorage": false,
  "enableAutomaticFailover": false,
  "enableCassandraConnector": null,
  "enableFreeTier": false,
  "enableMultipleWriteLocations": false,
  "failoverPolicies": [
    {
      "failoverPriority": 0,
      "id": "mongodb-2",
      "locationName": "East US"
    }
  ],
  "id": "/subscriptions/.../resourceGroups/my-resource-group/providers/Microsoft.DocumentDB/databaseAccounts/mongo-2",
  "ipRules": [
    {
      "ipAddressOrRange": "123.123.123.123"
    }
  ],
  "isVirtualNetworkFilterEnabled": false,
  "keyVaultKeyUri": null,
  "kind": "MongoDB",
  "location": "Central US",
  "locations": [
    {
      "documentEndpoint": "https://mongodb-2.documents.azure.com:443/",
      "failoverPriority": 0,
      "id": "mongodb-2",
      "isZoneRedundant": false,
      "locationName": "East US",
      "provisioningState": "Succeeded"
    }
  ],
  "name": "mongo-2",
  "privateEndpointConnections": null,
  "provisioningState": "Succeeded",
  "publicNetworkAccess": "Enabled",
  "readLocations": [
    {
      "documentEndpoint": "https://mongodb-2.documents.azure.com:443/",
      "failoverPriority": 0,
      "id": "mongodb-2",
      "isZoneRedundant": false,
      "locationName": "East US",
      "provisioningState": "Succeeded"
    }
  ],
  "resourceGroup": "my-resource-group",
  "systemData": {
    "createdAt": "2021-02-08T20:21:05.9519342Z"
  },
  "tags": {},
  "type": "Microsoft.DocumentDB/databaseAccounts",
  "virtualNetworkRules": [],
  "writeLocations": [
    {
      "documentEndpoint": "https://mongodb-2.documents.azure.com:443/",
      "failoverPriority": 0,
      "id": "mongodb-2",
      "isZoneRedundant": false,
      "locationName": "East US",
      "provisioningState": "Succeeded"
    }
  ]
}

Add firewall rule for your client IP address with Azure CLI

By default, the firewall rules aren't configured. You should add your client IP address so your client connection to the server with JavaScript is successful.

Use the az cosmosdb update command to update the firewall rules.

az cosmosdb update \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOUR-RESOURCE_NAME \
    --ip-range-filter 123.123.123.123

To configure multiple IP addresses, use a comma-separated list.

az cosmosdb update \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOUR-RESOURCE_NAME \
    --ip-range-filter 123.123.123.123,456.456.456.456

Get the MongoDB connection string for your resource with Azure CLI

Retrieve the MongoDB connection string for this instance with the az cosmosdb keys list command:

az cosmosdb keys list \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOUR-RESOURCE-NAME \
    --type connection-strings 

This returns 4 connection strings, 2 read-write and 2 read-only. There are two so that you can give 2 different systems or developers a connection string to use individually.

Connect to the mongoDB database with a connection string. Make sure your service is available with one of the following:

  • publicly available
  • firewall settings for your client's IP address

Configure your Azure web app with the connection string with Azure CLI

Add an Azure web app MONGODB_URL environment variable with the az webapp config appsettings set so the web app connects to the Azure Cosmos DB resource:

az webapp config appsettings set \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOUR-RESOURCE_NAME \
    --settings MONGODB_URL=YOUR-CONNECTION-STRING

Use the Azure Cosmos DB emulator for local development

Learn more about the Azure Cosmos DB emulator:

Use native SDK packages to connect to MongoDB on Azure

The mongoDB database on Azure Cosmos DB uses npm packages already available, such as:

Mongo DB resources

NoSQL on Azure

To create or use Azure Cosmos DB for NoSQL, create an Azure Cosmos DB resource. Learn how to create the Azure Cosmos DB resource and use your database.

Locally develop with the Azure Cosmos DB emulator

Learn how to install the Azure Cosmos DB emulator and start the emulator for Azure Cosmos DB for NoSQL development.

Create a resource for an Azure Cosmos DB for NoSQL database

You can create a resource with:

Create a resource for Azure Cosmos DB for NoSQL

Use the following Azure CLI az cosmosdb create command in the Azure Cloud Shell to create a new Azure Cosmos DB resource. This command may take a couple of minutes to complete.

az cosmosdb create \
--subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
--resource-group YOUR-RESOURCE-GROUP \
--name YOUR-RESOURCE-NAME \
--kind YOUR-DB-KIND \
--ip-range-filter YOUR-CLIENT-IP

To enable firewall access from your local computer to your resource, replace 123.123.123.123 with your own client IP. To configure multiple IP addresses, use a comma-separated list.

Add firewall rule for your client IP address

If you need to add a client IP address to your resource after it's created so your client connection to the server with JavaScript is successful, use this procedure. Use the az cosmosdb update command to update the firewall rules.

az cosmosdb update \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOUR-RESOURCE_NAME \
    --ip-range-filter 123.123.123.123

To configure multiple IP addresses, use a comma-separated list.

az cosmosdb update \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOUR-RESOURCE_NAME \
    --ip-range-filter 123.123.123.123,456.456.456.456

Get the Azure Cosmos DB keys for your resource

Retrieve the keys for this instance with the az cosmosdb keys list command:

az cosmosdb keys list \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOUR-RESOURCE-NAME

This returns 4 keys, 2 read-write and 2 read-only. There are two so that you can give 2 different systems or developers a key to use and recycle individually.

Use @azure/cosmos SDK to connect to database

Connect to your Azure Cosmos DB for NoSQL database using the following Azure SDK:

To connect and use your Azure Cosmos DB for NoSQL database with JavaScript, use the following procedure.

  1. Make sure Node.js and npm are installed.

  2. Create a Node.js project in a new folder:

    mkdir dataDemo && \
        cd dataDemo && \
        npm init -y && \
        npm install @azure/cosmos && \
        touch index.js && \
        code .
    

    The command:

    • creates a project folder named dataDemo
    • changes the Bash terminal into that folder
    • initializes the project, which creates the package.json file
    • creates the index.js script file
    • opens the project in Visual Studio Code
  3. Copy the following JavaScript code into index.js:

    const CosmosClient = require("@azure/cosmos").CosmosClient;
    
    // CHANGE THESE VALUES
    const COSMOS_DB_RESOURCE_NAME = "YOUR-RESOURCE-NAME";
    const COSMOS_DB_RESOURCE_KEY = "YOUR-RESOURCE-KEY";
    
    let client = null;      // Azure Cosmos DB connection object
    let db = null;          // DB object
    let container = null;   // Container object
    
    // data
    const DATABASE_DOCS = [
        { name: "Joe", job: "banking" },
        { name: "Jack", job: "security" },
        { name: "Jill", job: "pilot" }];
    
    const ALL_DOCS = null;
    
    // Azure Cosmos DB config
    const config = {
        COSMOSDB_SQL_API_URI: `https://${COSMOS_DB_RESOURCE_NAME}.documents.azure.com:443/`,
        COSMOSDB_SQL_API_KEY: COSMOS_DB_RESOURCE_KEY,
        COSMOSDB_SQL_API_DATABASE_NAME: "DemoDb",
        COSMOSDB_SQL_API_CONTAINER_NAME: "DemoContainer"
    }
    
    // Unique Id = Guid
    const newGuid = () => {
        const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
        return `${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4() + s4() + s4()}`;
    }
    
    // insert array
    const insert = async (newItems) => {
    
        const results = [];
        for (const item of newItems) {
    
            item.id = newGuid();
            const result = await container.items.create(item);
            results.push(result.item);
        }
        return results;
    };
    // find all or by id
    const find = async (query) => {
    
        if (query == null) {
            query = "SELECT * from c"
        } else {
            query = `SELECT * from c where c.id = ${query}`
        }
    
        const result = await container.items
            .query(query)
            .fetchAll();
    
        return result && result.resources ? result.resources : [];
    }
    // remove all or by id
    const remove = async (id) => {
    
        // remove 1
        if (id) {
            await container.item(id).delete();
        } else {
    
            // get all items
            const items = await find();
    
            // remove all
            for await (const item of items) {
                await container.item(item.id).delete();
            }
        }
    
        return;
    }
    // connection with SDK
    const connect = () => {
        try {
    
            const connectToCosmosDB = {
                endpoint: config.COSMOSDB_SQL_API_URI,
                key: config.COSMOSDB_SQL_API_KEY
            }
    
            return new CosmosClient(connectToCosmosDB);
    
        } catch (err) {
            console.log('Azure Cosmos DB - can\'t connect - err');
            console.log(err);
        }
    }
    const connectToDatabase = async () => {
    
        client = connect();
    
        if (client) {
    
            // get DB
            const databaseResult = await client.databases.createIfNotExists({ id: config.COSMOSDB_SQL_API_DATABASE_NAME });
            db = databaseResult.database;
    
            if (db) {
                // get Container
                const containerResult = await db.containers.createIfNotExists({ id: config.COSMOSDB_SQL_API_CONTAINER_NAME });
                container = containerResult.container;
                return !!db;
            }
        } else {
            throw new Error("can't connect to database");
        }
    
    
    }
    
    // use Database
    const dbProcess = async (docs) => {
    
        // connect
        const db = await connectToDatabase();
        if (!db) throw Error("db not working")
        console.log("connected to " + config.COSMOSDB_SQL_API_DATABASE_NAME + "/" + config.COSMOSDB_SQL_API_CONTAINER_NAME)
    
        // insert new docs
        const insertResult = await insert(docs);
        console.log("inserted " + insertResult.length)
    
        // get all docs
        const findResult = await find(ALL_DOCS);
        console.log("found " + findResult.length);
    
        // remove all then make sure they are gone
        await remove(ALL_DOCS);
        const findResult3 = await find(ALL_DOCS);
        console.log("removed all, now have " + findResult3.length);
    
        return;
    
    }
    
    dbProcess(DATABASE_DOCS)
    .then(() => {
        console.log("done")
    }).catch(err => {
        console.log(err)
    })
    
  4. Replace the following variables in the script:

    • YOUR-RESOURCE-NAME - the name you used when creating your Azure Cosmos DB resource
    • YOUR-RESOURCE-KEY - one of the read/write keys for your resource
  5. Run the script.

    node index.js
    

    The results are:

    connected to DemoDb/DemoContainer4
    inserted 3
    found 3
    removed all, now have 0
    done
    

NoSQL resources

PostgreSQL on Azure

To create, move, or use a PostgreSQL database to Azure, you need an Azure Database for PostgreSQL server resource. Learn how to create the resource and use your database.

Create an Azure Database for PostgreSQL resource

Create a resource with:

Create an Azure Database for PostgreSQL server resource with Azure CLI

Use the following Azure CLI az postgres server create command in the Azure Cloud Shell to create a new PostgreSQL server resource for your database.

az postgres server create \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --location eastus \
    --name YOURRESOURCENAME \
    --admin-user YOUR-ADMIN-USER \
    --ssl-enforcement Disabled \
    --enable-public-network Enabled 

This command may take a couple of minutes to complete and creates a publicly available resource in the eastus region.

The response includes your server's configuration details including:

  • Autogenerated password for the admin account
  • Connection string

Before you can connect to the server, you need to configure your firewall rules to allow your client IP address through.

Add a firewall rule for your client IP address to PostgreSQL resource

By default, the firewall rules aren't configured. You should add your client IP address so your client connection to the server with JavaScript is successful.

Use the following Azure CLI az postgres server firewall-rule create command in the Azure Cloud Shell to create a new firewall rule for your database.

az postgres server firewall-rule create \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --server YOURRESOURCENAME \
    --name AllowMyIP \
    --start-ip-address 123.123.123.123 \
    --end-ip-address 123.123.123.123

If you don't know your client IP address, use one of these methods:

  • Use the Azure portal to view and change your firewall rules, which include adding your detected client IP
  • Run your Node.js code, the error about your firewall rules violation includes your client IP address

While you can add the full range of internet addresses as a firewall rule, 0.0.0.0-255.255.255.255, this leaves your server open to attacks.

Create a PostgreSQL database on the server with Azure CLI

Use the following Azure CLI az postgres db create command in the Azure Cloud Shell to create a new PostgreSQL database on your server.

az postgres db create \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --server-name YOURRESOURCENAME \
    --name YOURDATABASENAME

Get the PostgreSQL connection string with Azure CLI

Retrieve the PostgreSQL connection string for this instance with the az postgres server show-connection-string command:

az postgres server show-connection-string \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --server-name YOURRESOURCENAME

This returns the connection strings for the popular languages as a JSON object. You need to replace {database}, {username}, and {password} with your own values before using the connection string. Replace YOURRESOURCENAME with your resource name.

View and use your PostgreSQL server on Azure

While developing your PostgreSQL database with JavaScript, use one of the following tools:

Use SDK packages to develop your PostgreSQL server on Azure

The Azure PostgreSQL uses npm packages already available, such as:

Use pg SDK to connect to PostgreSQL on Azure

To connect and use your PostgreSQL on Azure with JavaScript, use the following procedure.

  1. Make sure Node.js and npm are installed.

  2. Create a Node.js project in a new folder:

    mkdir DbDemo && \
        cd DbDemo && \
        npm init -y && \
        npm install pg && \
        touch index.js && \
        code .
    

    The command:

    • Creates a project folder named DbDemo
    • Changes the Bash terminal into that folder
    • Initializes the project, which creates the package.json file
    • Installs the pg npm package - to use async/await
    • Creates the index.js script file
    • Opens the project in Visual Studio Code
  3. Copy the following JavaScript code into index.js:

    const { Client } = require('pg')
        
    const query = async (connectionString) => {
        
        // create connection
        const connection = new Client(connectionString);
        connection.connect();
        
        // show tables in the postgres database
        const tables = await connection.query('SELECT table_name FROM information_schema.tables where table_type=\'BASE TABLE\';');
        console.log(tables.rows);
    
        // show users configured for the server
        const users = await connection.query('select pg_user.usename FROM pg_catalog.pg_user;');
        console.log(users.rows);
        
        // close connection
        connection.end();
    }
    
    const server='YOURRESOURCENAME';
    const user='YOUR-ADMIN-USER';
    const password='YOUR-PASSWORD';
    const database='postgres';
    
    const connectionString = `postgres://${user}@${server}:${password}@${server}.postgres.database.azure.com:5432/${database}`;
    
    query(connectionString)
    .then(() => console.log('done'))
    .catch((err) => console.log(err));
    
  4. Replace the YOUR-ADMIN-USER, YOURRESOURCENAME, and YOUR-PASSWORD with your values in the script for your connection string.

  5. Run the script to connect to the postgres server and see the base tables and users.

    node index.js
    
  6. View the results.

    [
      { table_name: 'pg_statistic' },
      { table_name: 'pg_type' },
      { table_name: 'pg_authid' },
      { table_name: 'pg_user_mapping' },
      ...removed for brevity
      { table_name: 'sql_languages' },
      { table_name: 'sql_packages' },
      { table_name: 'sql_parts' },
      { table_name: 'sql_sizing' },
      { table_name: 'sql_sizing_profiles' }
    ]
    [ { usename: 'azure_superuser' }, { usename: 'YOUR-ADMIN-USER' } ]
    done
    

PostgreSQL resources

Redis on Azure

To create, move, or use a Redis database to Azure, you need an Azure Cache for Redis resource. Learn how to create the resource and use your database.

Create a resource for a Redis database

You can create a resource with:

Create an Azure Cache for Redis resource with Azure CLI

Use the following Azure CLI az redis create command in the Azure Cloud Shell to create a new Redis resource for your database.

az redis create \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOUR-RESOURCE-NAME \
    --location eastus \
    --sku Basic \
    --vm-size c0 \
    --enable-non-ssl-port

This command may take a couple of minutes to complete and creates a publicly available resource in the eastus region.

The response includes your server's configuration details including:

  • the version of Redis: redisVersion
  • ports: sslPort and port

Add firewall rule for your client IP address to Redis resource

Add firewall rules with az redis firewall-rules create command to define access to your cache from your client IP or your app's IP.

az redis firewall-rules create \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOUR-RESOURCE-NAME \
    --rule-name AllowMyIP \
    --start-ip 123.123.123.123 \
    --end-ip 123.123.123.123

If you don't know your client IP address, use one of these methods:

  • Use the Azure portal to view and change your firewall rules, which include adding your detected client IP.
  • When you run your Node.js code, your receive an error about your firewall rules violation, which includes your client IP address. Copy the IP address and use it to set your firewall rule.

Get the Redis keys with Azure CLI

Retrieve the Redis connection string for this instance with the az redis list-keys command:

az redis list-keys \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOUR-RESOURCE-NAME

This returns the two keys:

{
    "primaryKey": "5Uey0GHWtCs9yr1FMUMcu1Sv17AJA2QMqPm9CyNKjAA=",
    "secondaryKey": "DEPr+3zWbL6d5XwxPajAriXKgoSeCqraN8SLSoiMWhM="
  }

Connect Azure Cache for Redis to your App service web app

Add connection information to your App service web app with az webapp config appsettings set command.

az webapp config appsettings set \
--subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
--resource-group YOUR-RESOURCE-GROUP \
--name YOUR-APP-SERVICE-RESOURCE-NAME \
--settings "REDIS_URL=YOUR-REDIS-HOST-NAME" "REDIS_PORT=YOUR-REDIS-PORT" "REDIS_KEY=YOUR-REDIS-KEY"

Replace the following settings in the preceding code:

  • YOUR-SUBSCRIPTION-ID-OR-NAME
  • YOUR-RESOURCE-GROUP
  • YOUR-APP-SERVICE-RESOURCE-NAME
  • YOUR-REDIS-HOST-NAME
  • YOUR-REDIS-PORT
  • YOUR-REDIS-KEY

Use native SDK packages to connect to Redis on Azure

The Redis database uses npm packages such as:

Install ioredis SDK

Use the following procedure to install the ioredis package and initialize your project.

  1. Make sure Node.js and npm are installed.

  2. Create a Node.js project in a new folder:

    mkdir DataDemo && \
        cd DataDemo && \
        npm init -y && \
        npm install ioredis \
        code .
    

    The command:

    • Creates a project folder named DataDemo
    • Changes the Bash terminal into that folder
    • Initializes the project, which creates the package.json file
    • Adds the ioredis npm SDK to the project
    • Opens the project in Visual Studio Code

Create JavaScript file to bulk insert data into Redis

  1. In Visual Studio Code, create a bulk_insert.js file.

  2. Download the MOCK_DATA.csv file and place it in the same directory as bulk_insert.js.

  3. Copy the following JavaScript code into bulk_insert.js:

    const Redis = require('ioredis');
    const fs = require('fs');
    const parse = require('csv-parser')
    const { finished } = require('stream/promises');
    const { config } = require('./config')
    
    // Create Redis config object
    const configuration = {
        host: config.HOST,
        port: 6380,
        password: config.KEY,
        tls: {
            servername: config.HOST
        },
        database: 0,
        keyPrefix: config.KEY_PREFIX
    }
    var redis = new Redis(configuration);
    
    // insert each row into Redis
    async function insertData(readable) {
        for await (const row of readable) {
            await redis.set(`bar2:${row.id}`, JSON.stringify(row))
        }
    }
    
    /* 
    id,first_name,last_name,email,gender,ip_address
    1,Rodrigo,Lock,rlock0@eventbrite.com,Agender,73.93.61.37
    2,Nikos,Gutierrez,ngutierrez1@yahoo.com,Genderfluid,213.54.40.210
    3,Eada,Sotham,esotham2@yellowpages.com,Bigender,28.236.183.89
    4,Ana,Brazil,abrazil3@who.int,Polygender,142.30.140.225
    5,Roman,Rohmer,rrohmer4@admin.ch,Genderqueer,235.197.52.85
    6,Elyn,Sute,esute5@ftc.gov,Genderqueer,171.151.109.188
    7,Omero,Childers,ochilders6@stanford.edu,Bigender,133.21.192.66
    8,Stephana,Pipet,spipet7@parallels.com,Genderfluid,177.48.129.213
    9,Anthiathia,Ulster,aulster8@weebly.com,Genderfluid,175.1.59.106
    10,Yard,Pyson,ypyson9@jalbum.net,Non-binary,0.8.135.151
    */
    
    // read file, parse CSV, each row is a chunck
    const readable = fs
        .createReadStream('./MOCK_DATA.csv')
        .pipe(parse());
    
    // Pipe rows to insert function
    insertData(readable)
        .then(() => {
            console.log('succeeded');
            redis.disconnect();
        })
        .catch(console.error);
    
  4. Replace the following in the script with your Redis resource information:

    • YOUR-RESOURCE-NAME
    • YOUR-AZURE-REDIS-RESOURCE-KEY
  5. Run the script.

    node bulk_insert.js
    

Create JavaScript code to use Redis

  1. In Visual Studio Code, create a index.js file.

  2. Copy the following JavaScript code into index.js:

    const redis = require('ioredis');
    const { config } = require('./config')
    
    // Create Redis config object
    const configuration = {
        host: config.HOST,
        port: 6380,
        password: config.KEY,
        timeout: config.TIMEOUT,
        tls: {
            servername: config.HOST
        },
        database: 0,
        keyPrefix: config.KEY_PREFIX
    }
    
    const connect = () => {
        return redis.createClient(configuration);
    }
    
    const set = async (client, key, expiresInSeconds=configuration.timeout, stringify=true, data) => {
        return await client.setex(key, expiresInSeconds, stringify? JSON.stringify(data): data);
    }
    
    const get = async (client, key, stringParse=true) => {
        const value = await client.get(key);
        return stringParse ? JSON.parse(value) : value;
    }
    
    const remove = async (client, key) => {
          return await client.del(key);
    }
    
    const disconnect = (client) => {
        client.disconnect();
    }
    
    const test = async () => {
        
        // connect
        const dbConnection = await connect();
        
        // set
        const setResult1 = await set(dbConnection, "r1", "1000000", false, "record 1");
        const setResult2 = await set(dbConnection, "r2", "1000000", false, "record 2");
        const setResult3 = await set(dbConnection, "r3", "1000000", false, "record 3");
    
        // get
        const val2 = await get(dbConnection, "r2", false);
        console.log(val2);
        
        // delete
        const remove2 = await remove(dbConnection, "r2");
        
        // get again = won't be there
        const val2Again = await get(dbConnection, "r2", false);
        console.log(val2Again);
        
        // done
        disconnect(dbConnection)
    }
    
    test()
    .then(() => console.log("done"))
    .catch(err => console.log(err))
    
  3. Replace the following in the script with your Redis resource information:

    • YOUR-RESOURCE-NAME
    • YOUR-RESOURCE-PASSWORD
  4. Run the script.

    node index.js
    

    The script inserts 3 keys then deletes the middle key. The console results are:

    record 2
    null
    done
    

Redis resources