GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • V11 Documentation
  • Privacy Statement
  • License Agreement
  • Contact Us

This view

  • Original page
  • New address

GeezerVison is showing docs.voltactivedata.com — 8.2. JSON HTTP Interface

  • Volt Active Data
  • Developer Hub
  • Books
    • VoltDB Tutorial
    • Using VoltDB
    • VoltDB Guide to Performance and Customization
    • VoltDB Administrator's Guide
    • Volt Kubernetes Administrator's Guide
    • VoltDB Quick Reference
  • Current docs ▶
  • VoltDB V11
    • VoltDB V16
    • VoltDB V15.3 LTS
    • VoltDB V14.3 LTS
    • VoltDB V13.3 LTS
    • VoltDB V12.3 LTS
    • VoltDB V11.4
    • VoltDB V10.2
    • VoltDB V9.3
8.2. JSON HTTP Interface

Using VoltDB

  • About This Book
  • 1. Overview▶
    • 1.1. What is VoltDB?
    • 1.2. Who Should Use VoltDB
    • 1.3. How VoltDB Works
      • 1.3.1. Partitioning
      • 1.3.2. Serialized (Single-Threaded) Processing
      • 1.3.3. Partitioned vs. Replicated Tables
      • 1.3.4. Ease of Scaling to Meet Application Needs
    • 1.4. Working with VoltDB Effectively
  • 2. Installing VoltDB▶
    • 2.1. Operating System and Software Requirements
    • 2.2. Installing VoltDB
      • 2.2.1. Upgrading From Older Versions
      • 2.2.2. Building a New VoltDB Distribution Kit
    • 2.3. Setting Up Your Environment
    • 2.4. What is Included in the VoltDB Distribution
    • 2.5. VoltDB in Action: Running the Sample Applications
  • 3. Starting the Database▶
    • 3.1. Initializing and Starting a VoltDB Database
    • 3.2. Initializing and Starting a VoltDB Database on a Cluster
    • 3.3. Stopping a VoltDB Database
    • 3.4. Saving the Data
    • 3.5. Restarting a VoltDB Database
    • 3.6. Updating Nodes on the Cluster
    • 3.7. Defining the Cluster Configuration
      • 3.7.1. Determining How Many Sites per Host
      • 3.7.2. Configuring Paths for Runtime Features
      • 3.7.3. Verifying your Hardware Configuration
  • 4. Designing the Database Schema▶
    • 4.1. How to Enter DDL Statements
    • 4.2. Creating Tables and Primary Keys
    • 4.3. Analyzing Data Volume and Workload
    • 4.4. Partitioning Database Tables
      • 4.4.1. Choosing a Column on which to Partition Table Rows
      • 4.4.2. Specifying Partitioned Tables
      • 4.4.3. Design Rules for Partitioning Tables
    • 4.5. Replicating Database Tables
      • 4.5.1. Choosing Replicated Tables
      • 4.5.2. Specifying Replicated Tables
    • 4.6. Modifying the Schema
      • 4.6.1. Effects of Schema Changes on Data and Clients
      • 4.6.2. Viewing the Schema
      • 4.6.3. Modifying Tables
      • 4.6.4. Adding and Dropping Indexes
      • 4.6.5. Modifying Partitioning for Tables and Stored Procedures
  • 5. Designing Stored Procedures to Access the Database▶
    • 5.1. How Stored Procedures Work
      • 5.1.1. VoltDB Stored Procedures are Transactional
      • 5.1.2. VoltDB Stored Procedures are Deterministic
    • 5.2. The Anatomy of a VoltDB Stored Procedure
      • 5.2.1. The Structure of the Stored Procedure
      • 5.2.2. Passing Arguments to a Stored Procedure
      • 5.2.3. Creating and Executing SQL Queries in Stored Procedures
      • 5.2.4. Interpreting the Results of SQL Queries
      • 5.2.5. Returning Results from a Stored Procedure
      • 5.2.6. Rolling Back a Transaction
    • 5.3. Installing Stored Procedures into the Database
      • 5.3.1. Compiling, Packaging, and Loading Stored Procedures
      • 5.3.2. Declaring Stored Procedures in the Schema
      • 5.3.3. Partitioning Stored Procedures in the Schema
  • 6. Designing VoltDB Client Applications▶
    • 6.1. Connecting to the VoltDB Database
      • 6.1.1. Connecting to Multiple Servers
      • 6.1.2. Using the Auto-Connecting Client
    • 6.2. Invoking Stored Procedures
    • 6.3. Invoking Stored Procedures Asynchronously
    • 6.4. Closing the Connection
    • 6.5. Handling Errors
      • 6.5.1. Interpreting Execution Errors
      • 6.5.2. Handling Timeouts
      • 6.5.3. Writing a Status Listener to Interpret Other Errors
    • 6.6. Compiling and Running Client Applications
      • 6.6.1. Starting the Client Application
      • 6.6.2. Running Clients from Outside the Cluster
  • 7. Simplifying Application Development▶
    • 7.1. Using Default Procedures
    • 7.2. Shortcut for Defining Simple Stored Procedures
    • 7.3. Verifying Expected Query Results
    • 7.4. Scheduling Stored Procedures as Tasks
    • 7.5. Directed Procedures: Distributing Transactions to Every Partition
  • 8. Using VoltDB with Other Programming Languages▶
    • 8.1. C++ Client Interface
      • 8.1.1. Writing VoltDB Client Applications in C++
      • 8.1.2. Creating a Connection to the Database Cluster
      • 8.1.3. Invoking Stored Procedures
      • 8.1.4. Invoking Stored Procedures Asynchronously
      • 8.1.5. Interpreting the Results
    • 8.2. JSON HTTP Interface
      • 8.2.1. How the JSON Interface Works
      • 8.2.2. Using the JSON Interface from Client Applications
      • 8.2.3. How Parameters Are Interpreted
      • 8.2.4. Interpreting the JSON Results
      • 8.2.5. Error Handling using the JSON Interface
    • 8.3. JDBC Interface
      • 8.3.1. Using JDBC to Connect to a VoltDB Database
      • 8.3.2. Using JDBC to Query a VoltDB Database
  • 9. Using VoltDB in a Cluster▶
    • 9.1. Starting a Database Cluster
    • 9.2. Updating the Cluster Configuration
    • 9.3. Elastic Scaling to Resize the Cluster
      • 9.3.1. Adding Nodes with Elastic Scaling
      • 9.3.2. Removing Nodes with Elastic Scaling
      • 9.3.3. Configuring How VoltDB Rebalances Nodes During Elastic Scaling
  • 10. Availability▶
    • 10.1. How K-Safety Works
    • 10.2. Enabling K-Safety
      • 10.2.1. What Happens When You Enable K-Safety
      • 10.2.2. Calculating the Appropriate Number of Nodes for K-Safety
    • 10.3. Recovering from System Failures
      • 10.3.1. What Happens When a Node Rejoins the Cluster
      • 10.3.2. Where and When Recovery May Fail
    • 10.4. Avoiding Network Partitions
      • 10.4.1. K-Safety and Network Partitions
      • 10.4.2. Using Network Fault Protection
  • 11. Database Replication▶
    • 11.1. How Database Replication Works
      • 11.1.1. Starting Database Replication
      • 11.1.2. Database Replication, Availability, and Disaster Recovery
      • 11.1.3. Database Replication and Completeness
    • 11.2. Using Passive Database Replication
      • 11.2.1. Specifying the DR Tables in the Schema
      • 11.2.2. Configuring the Clusters
      • 11.2.3. Starting the Clusters
      • 11.2.4. Loading the Schema and Starting Replication
      • 11.2.5. Updating the Schema During Replication
      • 11.2.6. Stopping Replication
      • 11.2.7. Database Replication and Read-only Clients
    • 11.3. Using Cross Datacenter Replication
      • 11.3.1. Designing Your Schema for Active Replication
      • 11.3.2. Configuring the Database Clusters
      • 11.3.3. Starting the Database Clusters
      • 11.3.4. Loading a Matching Schema and Starting Replication
      • 11.3.5. Updating the Schema During Active Replication
      • 11.3.6. Stopping Replication
      • 11.3.7. Example XDCR Configurations
      • 11.3.8. Understanding Conflict Resolution
    • 11.4. Monitoring Database Replication
  • 12. Security▶
    • 12.1. How Security Works in VoltDB
    • 12.2. Enabling Authentication and Authorization
    • 12.3. Defining Users and Roles
    • 12.4. Assigning Access to Stored Procedures
    • 12.5. Assigning Access by Function (System Procedures, SQL Queries, and Default Procedures)
    • 12.6. Using Built-in Roles
    • 12.7. Encrypting VoltDB Communication Using TLS/SSL
      • 12.7.1. Configuring TLS/SSL on the VoltDB Server
      • 12.7.2. Choosing What Ports to Encrypt with TLS/SSL
      • 12.7.3. Using the VoltDB Command Line Utilities with TLS/SSL
      • 12.7.4. Implementing TLS/SSL in the Java Client Applications
      • 12.7.5. Configuring Database Replication (DR) With TLS/SSL
    • 12.8. Integrating Kerberos Security with VoltDB
      • 12.8.1. Installing and Configuring Kerberos
      • 12.8.2. Installing and Configuring the Java Security Extensions
      • 12.8.3. Configuring the VoltDB Servers and Clients
      • 12.8.4. Accessing the Database from the Command Line and the Web
  • 13. Saving & Restoring a VoltDB Database▶
    • 13.1. Performing a Manual Save and Restore of a VoltDB Cluster
      • 13.1.1. How to Save the Contents of a VoltDB Database
      • 13.1.2. How to Restore the Contents of a VoltDB Database Manually
      • 13.1.3. Changing the Cluster Configuration Using Save and Restore
    • 13.2. Scheduling Automated Snapshots
    • 13.3. Managing Snapshots
    • 13.4. Special Notes Concerning Save and Restore
  • 14. Command Logging and Recovery▶
    • 14.1. How Command Logging Works
    • 14.2. Controlling Command Logging
    • 14.3. Configuring Command Logging for Optimal Performance
      • 14.3.1. Log Size
      • 14.3.2. Log Frequency
      • 14.3.3. Synchronous vs. Asynchronous Logging
      • 14.3.4. Hardware Considerations
  • 15. Streaming Data: Import, Export, and Migration▶
    • 15.1. How Data Streaming Works in VoltDB
      • 15.1.1. Understanding Import
      • 15.1.2. Understanding Export
      • 15.1.3. Understanding Migration
      • 15.1.4. Understanding Topics
    • 15.2. The Business Case for Streaming Data
      • 15.2.1. Extract, Transform, Load (ETL)
      • 15.2.2. Change Data Capture
      • 15.2.3. Streaming Data Validation
      • 15.2.4. Caching
      • 15.2.5. Archiving
    • 15.3. VoltDB Export Connectors
      • 15.3.1. How Export Works
      • 15.3.2. The File Export Connector
      • 15.3.3. The HTTP Export Connector
      • 15.3.4. The JDBC Export Connector
      • 15.3.5. The Kafka Export Connector
      • 15.3.6. The Elasticsearch Export Connector
    • 15.4. VoltDB Import Connectors
      • 15.4.1. Bulk Loading Data Using VoltDB Standalone Utilities
      • 15.4.2. Streaming Import Using Built-in Import Features
      • 15.4.3. The Kafka Importer
      • 15.4.4. The Kinesis Importer
    • 15.5. VoltDB Import Formatters
    • 15.6. VoltDB Topics
      • 15.6.1. Types of VoltDB Topics
      • 15.6.2. Declaring VoltDB Topics
      • 15.6.3. Configuring and Managing Topics
      • 15.6.4. Configuring the Topic Server
      • 15.6.5. Calling Topics from Consumers and Producers
      • 15.6.6. Using Opaque Topics
  • A. Supported SQL DDL Statements▶
    • ALTER STREAM
    • ALTER TABLE
    • ALTER TASK
    • ALTER VIEW
    • CREATE AGGREGATE FUNCTION
    • CREATE FUNCTION
    • CREATE INDEX
    • CREATE PROCEDURE AS
    • CREATE PROCEDURE FROM CLASS
    • CREATE ROLE
    • CREATE STREAM
    • CREATE TABLE
    • CREATE TASK
    • CREATE VIEW
    • DR TABLE
    • DROP FUNCTION
    • DROP INDEX
    • DROP PROCEDURE
    • DROP ROLE
    • DROP STREAM
    • DROP TABLE
    • DROP TASK
    • DROP VIEW
    • PARTITION TABLE
  • B. Supported SQL Statements▶
    • DELETE
    • INSERT
    • MIGRATE
    • SELECT
    • TRUNCATE TABLE
    • UPDATE
    • UPSERT
  • C. SQL Functions▶
    • ABS()
    • APPROX_COUNT_DISTINCT()
    • AREA()
    • ARRAY_ELEMENT()
    • ARRAY_LENGTH()
    • ASTEXT()
    • AVG()
    • BIN()
    • BIT_SHIFT_LEFT()
    • BIT_SHIFT_RIGHT()
    • BITAND()
    • BITNOT()
    • BITOR()
    • BITXOR()
    • CAST()
    • CEILING()
    • CENTROID()
    • CHAR()
    • CHAR_LENGTH()
    • COALESCE()
    • CONCAT()
    • CONTAINS()
    • COS()
    • COT()
    • COUNT()
    • CSC()
    • CURRENT_TIMESTAMP()
    • DATEADD()
    • DATEDIFF()
    • DAY(), DAYOFMONTH()
    • DAYOFWEEK()
    • DAYOFYEAR()
    • DECODE()
    • DEGREES()
    • DISTANCE()
    • DWITHIN()
    • EXP()
    • EXTRACT()
    • FIELD()
    • FLOOR()
    • FORMAT_CURRENCY()
    • FORMAT_TIMESTAMP()
    • FROM_UNIXTIME()
    • HEX()
    • HOUR()
    • INET6_ATON()
    • INET6_NTOA()
    • INET_ATON()
    • INET_NTOA()
    • ISINVALIDREASON()
    • ISVALID()
    • IS_VALID_TIMESTAMP()
    • LATITUDE()
    • LEFT()
    • LN(), LOG()
    • LOG10()
    • LONGITUDE()
    • LOWER()
    • MAKEVALIDPOLYGON()
    • MAX()
    • MAX_VALID_TIMESTAMP()
    • MIGRATING()
    • MIN()
    • MIN_VALID_TIMESTAMP()
    • MINUTE()
    • MOD()
    • MONTH()
    • NOW()
    • NUMINTERIORRINGS()
    • NUMPOINTS()
    • OCTET_LENGTH()
    • OVERLAY()
    • PI()
    • POINTFROMTEXT()
    • POLYGONFROMTEXT()
    • POSITION()
    • POWER()
    • QUARTER()
    • RADIANS()
    • REGEXP_POSITION()
    • REPEAT()
    • REPLACE()
    • RIGHT()
    • ROUND()
    • SEC()
    • SECOND()
    • SET_FIELD()
    • SIN()
    • SINCE_EPOCH()
    • SPACE()
    • SQRT()
    • STR()
    • SUBSTRING()
    • SUM()
    • TAN()
    • TIME_WINDOW()
    • TO_TIMESTAMP()
    • TRIM()
    • TRUNCATE()
    • UPPER()
    • VALIDPOLYGONFROMTEXT()
    • WEEK(), WEEKOFYEAR()
    • WEEKDAY()
    • YEAR()
  • D. VoltDB CLI Commands▶
    • csvloader
    • jdbcloader
    • kafkaloader
    • sqlcmd
    • voltadmin
    • voltdb
  • E. Configuration File (deployment.xml)▶
    • E.1. Understanding XML Syntax
    • E.2. The Structure of the Configuration File
  • F. VoltDB Datatype Compatibility▶
    • F.1. Java and VoltDB Datatype Compatibility
  • G. System Procedures▶
    • @AdHoc
    • @Explain
    • @ExplainProc
    • @ExplainView
    • @GetPartitionKeys
    • @Note
    • @Pause
    • @Ping
    • @Promote
    • @QueryStats
    • @Quiesce
    • @Resume
    • @Shutdown
    • @SnapshotDelete
    • @SnapshotRestore
    • @SnapshotSave
    • @SnapshotScan
    • @Statistics
    • @StopNode
    • @SwapTables
    • @SystemCatalog
    • @SystemInformation
    • @UpdateApplicationCatalog
    • @UpdateClasses
    • @UpdateLogging

8.2. JSON HTTP Interface

JSON (JavaScript Object Notation) is not a programming language; it is a data format. The JSON "interface" to VoltDB is actually a web interface that the VoltDB database server makes available for processing requests and returning data in JSON format.

The JSON interface lets you invoke VoltDB stored procedures and receive their results through HTTP requests. To invoke a stored procedure, you pass VoltDB the procedure name and parameters as a querystring to the HTTP request, using either the GET or POST method.

Although many programming languages provide methods to simplify the encoding and decoding of JSON strings, you still need to understand the data structures that are created. So if you are not familiar with JSON encoding, you may want to read more about it at http://www.json.org.

8.2.1. How the JSON Interface Works

When a VoltDB database starts, it opens port 8080 on each server as a simple web server. You have complete control over this feature through the configuration file and the voltdb start command, including:

  • Disabling just the JSON interface, or the HTTP port entirely using the <httpd> element in the configuration file.

  • Enabling TLS encryption on the port using the <ssl> element.

  • Changing the port number using the --http flag on the voltdb start command.

See the section on the "Web Interface Port" in the VoltDB Administrator's Guide for more information on configuring the HTTP port.

This section assumes the database is using the default httpd configuration. In which case, any HTTP requests sent to the location /api/2.0/ on that port are interpreted as JSON requests to run a stored procedure. The structure of the request is:

URLhttp://<server>:8080/api/2.0/
Arguments

Procedure=<procedure-name>
Parameters=<procedure-parameters>
User=<username for authentication>
Password=<password for authentication>
Hashedpassword=<Hashed password for authentication>
admin=<true|false>
jsonp=<function-name>

The arguments can be passed either using the GET or the POST method. For example, the following URL uses the GET method (where the arguments are appended to the URL) to execute the system procedure @SystemInformation on the VoltDB database running on node voltsvr.mycompany.com:

http://voltsvr.mycompany.com:8080/api/2.0/?Procedure=@SystemInformation

Note that only the Procedure argument is required. You can authenticate using the User and Password (or Hashedpassword) arguments if security is enabled for the database. Use Password to send the password as plain text or Hashedpassword to send the password as an encoded string. (The hashed password must be either a 40-byte hex-encoding of the 20-byte SHA-1 hash or a 64-byte hex-encoding of the 32-byte SHA-256 hash.)[2]

You can also include the parameters on the request. However, it is important to note that the parameters — and the response returned by the stored procedure — are JSON encoded. The parameters are an array (even if there is only one element to that array) and therefore must be enclosed in square brackets. Also, although there is an upper limit of 2 megabytes for the entire length of the parameter string, large parameter sets must be sent using POST to avoid stricter limitations on allowable URL lengths.

The admin argument specifies whether the request is submitted on the standard client port (the default) or the admin port (when you specify admin=true). When the database is in admin mode, the client port is read-only; so you must submit write requests with admin=true or else the request is rejected by the server.

The jsonp argument is provided as a convenience for browser-based applications (such as Javascript) where cross-domain browsing is disabled. When you include the jsonp argument, the entire response is wrapped as a function call using the function name you specify. Using this technique, the response is a complete and valid Javascript statement and can be executed to create the appropriate language-specific object. For example, calling the @Statistics system procedure in Javascript using the jQuery library looks like this:

$.getJSON('http://myserver:8080/api/1.0/?Procedure=@Statistics' +
          '&Parameters=["MANAGEMENT",0]&jsonp=?',
          {},MyCallBack);

Perhaps the best way to understand the JSON interface is to see it in action. If you build and start the Hello World example application that is provided in the VoltDB distribution kit (including the client that loads data into the database), you can then open a web browser and connect to the local system through port 8080, to retrieve the French translation of "Hello World". For example:

http://localhost:8080/api/1.0/?Procedure=Select&Parameters=["French"]

The query returns the following results:

{"status":1,"appstatus":-128,"statusstring":null,"appstatusstring":null,
"results":{"0":[{ "HELLO":"Bonjour","WORLD":"Monde"}]}}

As you can see, the JSON-encoded results are not particularly easy to read. But they do provide a simple, generic interface accessible from almost any programming language, most of which provide methods for encoding and decoding JSON strings and interpreting their results.

8.2.2. Using the JSON Interface from Client Applications

The general process for using the JSON interface from within a program is:

  1. Encode the parameters for the stored procedure as a JSON-encoded string

  2. Instantiate and execute an HTTP request, passing the name of the procedure and the parameters as arguments using either GET or POST.

  3. Decode the resulting JSON string into a language-specific data structure and interpret the results.

The following are examples of invoking the Hello World Insert stored procedure from several different languages. In each case, the three arguments (the name of the language and the words for "Hello" and "World") are encoded as a JSON string.

PHP

<?php
// Construct the procedure name, parameter list, and URL.
 
   $voltdbserver = "http://myserver:8080/api/2.0/";
   $proc = "Insert";
   $a = array("Croatian","Pozdrav","Svijet");
   $params = json_encode($a);
   $params = urlencode($params);
   $querystring = "Procedure=$proc&Parameters=$params";

// create a new cURL resource and set options
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $voltdbserver);
   curl_setopt($ch, CURLOPT_HEADER, 0);
   curl_setopt($ch, CURLOPT_FAILONERROR, 1);
   curl_setopt($ch, CURLOPT_POST, 1);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $querystring);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the request
   $resultstring = curl_exec($ch);
?>

Python

import urllib
import urllib2
import json

# Construct the procedure name, parameter list, and URL.
url = 'http://myserver:8080/api/2.0/'
voltparams = json.dumps(["Croatian","Pozdrav","Svijet"])
httpparams = urllib.urlencode({
    'Procedure': 'Insert',
    'Parameters' : voltparams
})
print httpparams
# Execute the request
data = urllib2.urlopen(url, httpparams).read()

# Decode the results
result = json.loads(data)

Perl

use LWP::Simple;

my $server = 'http://myserver:8080/api/2.0/';

# Insert "Hello World" in Croatian
my $proc = 'Insert';
my $params = '["Croatian","Pozdrav","Svijet"]';
my $url = $server . "?Procedure=$proc&Parameters=$params";
my $content = get $url;
die "Couldn't get $url" unless defined $content;

C#

using System;
using System.Text;
using System.Net;
using System.IO;

namespace hellovolt

{
  class Program
  {
    static void Main(string[] args)
    {
      string VoltDBServer = "http://myserver:8080/api/2.0/";
      string VoltDBProc = "Insert";
      string VoltDBParams = "[\"Croatian\",\"Pozdrav\",\"Svijet\"]";
      string Url = VoltDBServer + "?Procedure=" + VoltDBProc 
                   + "&Parameters=" + VoltDBParams;
 
      string result = null;
      WebResponse response = null;
      StreamReader reader = null;

      try
      {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
        request.Method = "GET";
        response = request.GetResponse();
        reader = new StreamReader(response.GetResponseStream(),Encoding.UTF8 );
        result = reader.ReadToEnd();

      }
      catch (Exception ex)

      {     // handle error
        Console.WriteLine( ex.Message );
      }
      finally
      { 
        if (reader != null)reader.Close();
        if (response != null) response.Close();

      }
    }
  }
}

8.2.3. How Parameters Are Interpreted

When you pass arguments to the stored procedure through the JSON interface, VoltDB does its best to map the data to the datatype required by the stored procedure. This is important to make sure partitioning values are interpreted correctly.

For integer values, the JSON interface maps the parameter to the smallest possible integer type capable of holding the value. (For example, BYTE for values less than 128). Any values containing a decimal point are interpreted as DOUBLE.

String values (those that are quoted) are handled in several different ways. If the stored procedure is expecting a BIGDECIMAL, the JSON interface will try to interpret the quoted string as a decimal value. If the stored procedure is expecting a TIMESTAMP, the JSON interface will try to interpret the quoted string as a JDBC-encoded timestamp value. (You can alternately pass the argument as an integer value representing the number of microseconds from the epoch.) Otherwise, quoted strings are interpreted as a string datatype.

Table 8.1, “Datatypes in the JSON Interface” summarizes how to pass different datatypes in the JSON interface.

Table 8.1. Datatypes in the JSON Interface

DatatypeHow to PassExample
Integers (Byte, Short, Integer, Long)An integer value12345
DOUBLEA value with a decimal point123.45
BIGDECIMALA quoted string containing a value with a decimal point"123.45"
TIMESTAMPEither an integer value or a quoted string containing a JDBC-encoded date and time

12345

"2010-07-01 12:30:21"

StringA quoted string"I am a string"

8.2.4. Interpreting the JSON Results

Making the request and decoding the result string are only the first steps. Once the request is completed, your application needs to interpret the results.

When you decode a JSON string, it is converted into a language-specific structure within your application, composed of objects and arrays. If your request is successful, VoltDB returns a JSON-encoded string that represents the same ClientResponse object returned by calls to the callProcedure method in the Java client interface. Figure 8.1, “The Structure of the VoltDB JSON Response” shows the structure of the object returned by the JSON interface.

Figure 8.1. The Structure of the VoltDB JSON Response

{  status                   (integer)
   appstatus                (integer)
   statusstring             (string)
   appstatusstring          (string)
   results                  (list)
     {  result-index        (array)
          [ 
             { column-name  (any type)  ,...
             }
          ]
     }
}

The key components of the JSON response are the following:

status

Indicates the success or failure of the stored procedure. If status is false, statusstring contains the text of the status message..

appstatus

Returns additional information, provided by the application developer, about the success or failure of the stored procedure. The values of appstatus and appstatusstring can be set programmatically in the stored procedure. (See Section 6.5.1, “Interpreting Execution Errors” for details.)

results

A list of objects representing the VoltTables returned by the stored procedure. Each element of the list is one set of results, identified by an index value ("0", "1", "2" and so on). Within each set is an array of rows. And within each row is a list of columns represented by the column name and value. If the stored procedure does not return any results (i.e. is void or null), then the results object will be null.

It is possible to create a generic procedure for testing and evaluating the result values from any VoltDB stored procedure. However, in most cases it is far more expedient to evaluate the values that you know the individual procedures return.

For example, again using the Hello World example that is provided with the VoltDB software, it is possible to use the JSON interface to call the Select stored procedure and return the values for "Hello" and "World" in a specific language. Rather than evaluate the entire results array (including the name and type fields), we know we are only receiving one result object with two column values. So we can simplify the code, as in the following python example:

import urllib
import urllib2
import json
import pprint

# Construct the procedure name, parameter list, and URL.
url = 'http://localhost:8080/api/2.0/'
voltparams = json.dumps(["French"])
httpparams = urllib.urlencode({
    'Procedure': 'Select',
    'Parameters' : voltparams
})

# Execute the request
data = urllib2.urlopen(url, httpparams).read()

# Decode the results
results = json.loads(data)[u'results']
volttable = results[u'0']
row = volttable[0]

# Get the data by column name and display them
hello = row[u'HELLO']
world = row[u'WORLD']

print hello, world

8.2.5. Error Handling using the JSON Interface

There are a number of different reasons why a stored procedure request using the JSON interface may fail: the VoltDB server may be unreachable, the database may not be started yet, the stored procedure name may be misspelled, the stored procedure itself may fail... When using the standard Java client interface, these different situations are handled at different times. (For example, server and database access issues are addressed when instantiating the client, whereas stored procedure errors can be handled when the procedures themselves are called.) The JSON interface simplifies the programming by rolling all of these activities into a single call. But you must be more organized in how you handle errors as a consequence.

When using the JSON interface, you should check for errors in the following order:

  1. First check to see that the HTTP request was submitted without errors. How this is done depends on what language-specific methods you use for submitting the request. In most cases, you can use the appropriate programming language error handlers (such as try-catch) to catch and interpret HTTP request errors.

  2. Next check to see if VoltDB successfully invoked the stored procedure. You can do this by verifying that the HTTP request returned a valid JSON-encoded string and that its status is set to true.

  3. If the VoltDB server successfully invoked the stored procedure, then check to see if the stored procedure itself succeeded, by checking to see if appstatus is true.

  4. Finally, check to see that the results are what you expect. (For example, that the data array is non-empty and contains the values you need.)



[2] Hashing the password stops the text of your password from being detectable from network traffic. However, it does not make the database access any more secure. To secure the transmission of credentials and data between client applications and VoltDB, enable TLS encryption for the HTTP port using the configuration file.

You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.