You are on page 1of 142

User Guide and Reference

| TOC | 3

Contents
Part I: Quick Start.........................................................................................9
Run NuoDB.......................................................................................................................................... 9 Execute SQL Commands.................................................................................................................... 9 Run a Simple Java Sample Program................................................................................................. 10 Use NuoDB Console.......................................................................................................................... 10 How to Set Up a Chorus on One or More Hosts................................................................................ 11

Part II: Installation and Release Notes..................................................... 15


Release Notes................................................................................................................................... 15 Bug Fixes and Improvements..................................................................................................15 System Requirements........................................................................................................................18 Windows Installation.......................................................................................................................... 18 Linux Installation (rpm or deb installers)............................................................................................ 19 Sample Startup Script on UNIX......................................................................................................... 19 Mac OS X Installation........................................................................................................................ 20

Part III: Administration...............................................................................23


Launching a Chorus........................................................................................................................... 23 System Components..........................................................................................................................24 Client Connections............................................................................................................................. 28 Set Up A Pilot Project From The Command Line...............................................................................30 Using Amazon Web Services (AWS) Components............................................................................31 Troubleshooting NuoDB.....................................................................................................................33 ConfigurationTools............................................................................................................................. 33 nuodb...................................................................................................................................... 34 nuoloader (NuoDB Loader)..................................................................................................... 35 nuoagent................................................................................................................................. 37 Automate Configuration Scenarios.................................................................................................... 38 Configuration Using Command Line.................................................................................................. 38

Part IV: Programming With NuoDB.......................................................... 45


Programming..................................................................................................................................... 45 Connections....................................................................................................................................... 45 Use DbVisualizer.....................................................................................................................45 JDBC Connections.................................................................................................................. 47 JDBC Connection Properties.................................................................................................. 49 ODBC Connections on Windows............................................................................................ 50 Example: Using ODBC and MS Excel to Read a NuoDB Database....................................... 50 Using NuoDB SQL............................................................................................................................. 53 nuosql Command.................................................................................................................... 53 Using Parameterized Queries with NuoDB SQL..................................................................... 54 Batch Processing from the Command Line.............................................................................55 Working With Triggers.............................................................................................................55 Selecting from the DUAL Table...............................................................................................58 Metadata................................................................................................................................. 58 Troubleshooting NuoSQL........................................................................................................58

| Copyright 2012 NuoDB, Inc. All rights reserved. | 3

| TOC | 4

SQL Workbench/J................................................................................................................... 59 SQuirreL Universal SQL..........................................................................................................60 Sample Client Programs.................................................................................................................... 61 C++ Sample Program............................................................................................................. 62 Flights Sample Application...................................................................................................... 63 JRuby Sample Program.......................................................................................................... 63 Working with Hibernate........................................................................................................... 64

Part V: SQL Language Elements.............................................................. 67


Language Elements........................................................................................................................... 67 Data Types.............................................................................................................................. 67 Operators and Operations.......................................................................................................69 Expressions.............................................................................................................................75 Date and Time Functions........................................................................................................ 76 Object Privileges..................................................................................................................... 78 Transactions............................................................................................................................78 Clauses and Functions............................................................................................................82

Part VI: SQL Reference Pages.................................................................. 87


SQL Reference Pages....................................................................................................................... 87 ALTER DOMAIN..................................................................................................................... 87 ALTER SEQUENCE................................................................................................................89 ALTER TABLE........................................................................................................................ 89 ALTER TRIGGER................................................................................................................... 90 ALTER USER..........................................................................................................................90 COMMIT..................................................................................................................................91 CREATE DATABASE..............................................................................................................91 CREATE DOMAIN.................................................................................................................. 91 CREATE INDEX......................................................................................................................92 CREATE PROCEDURE..........................................................................................................93 CREATE ROLE....................................................................................................................... 93 CREATE SCHEMA................................................................................................................. 94 CREATE SEQUENCE.............................................................................................................95 CREATE TABLE..................................................................................................................... 95 CREATE TRIGGER................................................................................................................ 97 CREATE USER.......................................................................................................................99 CREATE VIEW..................................................................................................................... 100 DELETE................................................................................................................................ 101 DROP DATABASE................................................................................................................101 DROP DOMAIN.....................................................................................................................102 DROP INDEX........................................................................................................................ 102 DROP PROCEDURE............................................................................................................ 103 DROP ROLE......................................................................................................................... 103 DROP SCHEMA....................................................................................................................103 DROP SEQUENCE...............................................................................................................104 DROP TABLE....................................................................................................................... 104 DROP TRIGGER...................................................................................................................105 DROP USER......................................................................................................................... 105 DROP VIEW..........................................................................................................................106 GRANT..................................................................................................................................106 INSERT................................................................................................................................. 108 RELEASE..............................................................................................................................109 REPLACE............................................................................................................................. 110 REVOKE............................................................................................................................... 111

| Copyright 2012 NuoDB, Inc. All rights reserved. | 4

| TOC | 5

ROLLBACK........................................................................................................................... 112 SAVEPOINT..........................................................................................................................113 SELECT................................................................................................................................ 114 SET....................................................................................................................................... 119 SHOW................................................................................................................................... 120 START TRANSACTION........................................................................................................122 TRUNCATE...........................................................................................................................123 UPDATE................................................................................................................................123 UPGRADE............................................................................................................................ 124 USE....................................................................................................................................... 125

Glossary........................................................................................................................ 128 Appendix: Sample Client Application.........................................................................131


Start an agent and a chorus.............................................................................................................131 Install the Flights application............................................................................................................ 131 Load the Flights database and start the application........................................................................ 134 Understanding the Flights application.............................................................................................. 135 Flights Application Details................................................................................................................ 136 Optimize Performance of Flights Application................................................................................... 137 Add transaction engines to Flights application.................................................................................137 Add Updates.................................................................................................................................... 138 Add Client by Configuring a Flight Booker....................................................................................... 138 Benchmark Runtime........................................................................................................................ 139 Troubleshooting............................................................................................................................... 139 Restarting the tutorial....................................................................................................................... 140

Third Party Acknowledgments....................................................................................142

| Copyright 2012 NuoDB, Inc. All rights reserved. | 5

| TOC | 6

| Copyright 2012 NuoDB, Inc. All rights reserved. | 6

Quick Start
Topics: Run NuoDB Execute SQL Commands Run a Simple Java Sample Program Use NuoDB Console How to Set Up a Chorus on One or More Hosts

| Quick Start | 8

| Copyright 2012 NuoDB, Inc. All rights reserved. | 8

| Quick Start | 9

Quick Start
Run NuoDB
Procedure to get the product up and running 1. If you have not already done so, install NuoDB. 2. Start a command prompt or terminal window and go to the directory where you installed NuoDB. (The following examples show the default install directory.) On Windows: > cd C:\Program Files\NuoDB\ On Linux and MAC OS X > cd /opt/nuodb 3. Run the following script (on Mac and UNIX platforms "." must be in your path). > run-quickstart The script does the following: Configures your path Starts a NuoDB broker Creates, starts, and loads a NuoDB test database, as follows: 1. Starts a NuoDB storage manager with its repository in /tmp/test 2. Starts a NuoDB transaction engine 3. Creates sample schema. 4. Creates a sample database. 5. Imports data to the sample database from /install_dir/nuodb/samples/quickstart/bruins.csv Starts an interactive SQL session

Execute SQL Commands


Sample SQL Session Install the product and run the startup script (run-quickstart) in the install directory. An interactive SQL session starts in the window where you started NuoDB, as shown: Starting an interactive SQL session with nuosql SQL> 1. In the window where the SQL session is running issue the following command: SQL> show tables; HOCKEY is the sample table created when you started NuoDB. 2. To see what is in the table, run the following two commands: SQL> use hockey;

| Copyright 2012 NuoDB, Inc. All rights reserved. | 9

| Quick Start | 10

SQL> select * from hockey; 3. Try other commands as you like. Related Links Language Elements on page 67 Reference information about data types, operations, access, variables, indexes, and isolation levels. SQL Reference Pages on page 87 Syntax, descriptions, and examples for SQL statements

Run a Simple Java Sample Program


How to run a simple Java application against NuoDB The sample is in the following file: $NUODB_HOME/samples/java/HelloDB.java The following code fragment shows the first several lines of the sample:

public class HelloDB { /** The driver class provided by NuoDB. */ public static final String DRIVER_CLASS = "com.nuodb.jdbc.Driver"; /** The base URL for connecting to a local database server. */ public static final String DATABASE_URL = "jdbc:com.nuodb://localhost/"; // the established connection to a local server private final Connection dbConnection; } 1. Change directory to /nuodb/samples/java 2. Issue the following commands:

javac HelloDB.java java classpath ../../jar/nuodbjdbc.jar:.

HelloDB

You should see the following output: Name for ID=12 is: fred

Use NuoDB Console


How to start NuoDB Console and view the QuickStart processes. The specific examples in this procedure are based on the assumption that you have already performed the first step (Run NuoDB) in the Quick Start, which sets up a test chorus. 1. Start NuoDB Console by issuing the following from the prompt in a terminal shell or window. java -jar /opt/nuodb/jar/nuodbconsole.jar

| Copyright 2012 NuoDB, Inc. All rights reserved. | 10

| Quick Start | 11

2. When prompted for a password, enter hockey. 3. Click Discover Domains. 4. In the Results pane observe that there is a domain called hockey. This is the domain for the NuoDB database created by the Quick Start script. 5. If it is not already expanded, click the hockey domain to expand it on the Home page.

6. Observe that there is a chorus (named test) and a broker running on localhost in the hockey domain. A broker is indicated with a broker icon: 7. Select any item in the test chorus and select GO to open the Results pane, which displays several tabs: General, Monitor, and Logger. These tabs allow you to observe information about the domain, specify logging information, and monitor the behavior of a client program that is running against the chorus. 8. Click Home to get back to where you started. Use the NuoDB Console to start and stop processes, connect and disconnect to domains, monitor performance, and add new hosts and domains as required by your application. Related Links Overview of Configuration Tools on page 33 Using command-line tools as well as NuoDB Console to configure NuoDB Configuration Using Command Line on page 38 Describes some common configuration scenarios and the commands for enabling them on Linux or Mac OS X. nuosql Command on page 53 Start NuoDB SQL as a client against a specified chorus. Requires a chorus username and password.

How to Set Up a Chorus on One or More Hosts


Use NuoDB to start a broker and domain. Then use NuoDB Console to start agents, storage managers, and transaction engines. The concept of a chorus is a key feature of the support that NuoDB provides for elasticity and scalability. A chorus is a variable number of processes, running on a variable number of hosts, that serve a single database. Transaction engines and storage managers are part of the chorus. To manage the chorus each

| Copyright 2012 NuoDB, Inc. All rights reserved. | 11

| Quick Start | 12

host must run a NuoDB agent, and at least one of the hosts must run a NuoDB broker. An agent can run as a broker if required. To create a single chorus you must create the following: a broker, a transaction engine, and a storage manager. 1. On the host where you want to run NuoDB, start a NuoDB broker by issuing the following command. java -jar nuoagent.jar --broker --password domain_password This program is in /install_dir/bin. As soon as a broker is running you have created a NuoDB domain, even if there are not yet any choruses. 2. Start the NuoDB Console by running the following command: java -jar nuodbconsole.jar This program is in /install_dir/jar. When prompted for a password, enter the domain password you specified earlier. On the Home page of the console, discover the broker you just created by clicking Discover Domains... Starting the broker caused the creation of a NuoDB domain as well as a NuoDB broker. By default the domain is named test and is running on localhost, as shown in the Results pane on the Home page of the console. In the Results pane, select the test domain and click Add Process in the navigation pane. Create a transaction engine by clicking it on the list and entering a name. You are required to create a user name and password when you create the first transaction engine for a chorus. Similarly, create a storage manager by specifying a directory to use. Be sure to select the initialize option. In the Results pane, note that there is a storage manager as well as a transaction engine running in the test domain on localhost. To view the status of the chorus select the transaction engine and click Go. After you start a chorus you can connect and run your client application against the chorus and monitor performance using NuoDB Console. At first, performance may decrease as the new processes start up. You should be able to observe improved performance after this initial interval. Use NuoDB Console and other tools to manage and administer the system. You can perform administrative tasks, such as starting and stopping processes, finding and adding brokers. You can also specify and examine logging information and metrics. You can use NuoDB Loader to import and export data. You can use the interactive sessions with NuoDB SQL to issue SQL that you want to use as part of your client appliation.

3. 4.

5. 6.

7.

8.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 12

Installation and Release Notes


Topics: Release Notes System Requirements Windows Installation Linux Installation (rpm or deb installers) Sample Startup Script on UNIX Mac OS X Installation

| Installation and Release Notes | 14

| Copyright 2012 NuoDB, Inc. All rights reserved. | 14

| Installation and Release Notes | 15

Installation and Release Notes

Release Notes
The Beta 6 release is primarily a bug-fix release that also includes new features and substantial improvements to the overall stability of the platforms. Improvements and new features are as follows: NuoDB includes a license. The license supports up to 10 nodes and prevents starting new nodes after June 2012. Contact NuoDB Tech Support (support@nuodb.com) if more nodes are required. NuoDB Console provides an administrative hub for NuoDB databases. The console has been significantly improved since earlier releases, especially in terms of ease-of-use and breadth of features. An easy-to-use GUI provides rich graphical configuration and display capabilities. Management tools enable DBAs to manage multiple databases that are distributed and deployed at a customer site, in the cloud, or in a hybrid environment. Monitoring tools provide comprehensive real-time monitoring capabilities and assist in the management of the full lifecycle of NuoDB distributed database nodes. Security enhancements provide encryption of critical network communications between NuoDB transaction and storage nodes. NuoDB offers secure network communications and user access within an Administration Domain, which represents a set of associated NuoDB distributed databases. DBAs can define and manage user roles and access rules for the system. Product Performance, Quality and Usability The software includes Index maintenance bug fixes and performance improvements around load/ insert use cases. Failsafe shutdown of NuoDB transaction and storage nodes has been significantly improved. Signiificant progress has been made toward complete compliance with SWL. NuoDB documentation is now available as browser-based HTML documentation and NuoSQL online help has been added.

Bug Fixes and Improvements


Since the last release the following improvements have been made and bugs fixed. Indexes ADDED: Index improvements (DB-738, DB-724, DB-871, DB-1026, DB-739, DB-725) FIXED: Duplicate primary key after second update attempt (DB-567, DB-1082) FIXED: Index not cleaned up during ROLLBACK or Node Failover (DB-886) FIXED: Index not cleaned up during GC (DB-893) FIXED: Index insert failure during GC (DB-889) FIXED: Incomplete index support for blobs (DB-936) FIXED: Query returning 0 rows when expecting 2 (DB-1147) FIXED: Indexes on binary data (DB-988, DB-904, DB-902) FIXED: Uniqueness of values in a UNIQUE KEY not enforced at creation time (DB-950)

| Copyright 2012 NuoDB, Inc. All rights reserved. | 15

| Installation and Release Notes | 16

Security ADDED: All utilities require proper passwords to be accessed ADDED: Domain security using password model (DB-686) FIXED: All hardcoded/default passwords removed

Connection Drivers ADDED: ODBC and JDBC driver improvements (DB-884, DB-1154) ADDED: Implement getSchema in JDBC and ODBC (DB-1085) ADDED: Compatibility with JDK 1.7 confirmed (DB-1054) ADDED: activerecord-jdbcnuodb-adapter maps BOOLEAN to TINYINT (DB-891) FIXED: UTF8 handling could possibly corrupt data (DB-975) FIXED: Incorrect output printed when using the C++ API (DB-963) FIXED: ODBC: CLOB data not being written correctly (DB-915) FIXED: New connections always get the most recent commit sequence (DB-901) FIXED: JDBC large message handling (greater than 5120 bytes) sometimes fails (DB-899) FIXED: Missing C++ header files (DB-876) FIXED: Blob.setBinaryStream() not yet implemented (DB-834) FIXED: PreparedStatement.setObject() does not support VARBINARY (DB-816) FIXED: column created with type TINYINT has JDBC type 5 (SMALLINT) FIXED: TINYINT no longer supported (DB-765) FIXED: java.sql.Connection object isn't thread safe (DB-120)

SQL improvements ADDED: Operator in list is now implemented, select * from t1 where f1 in (1,3,5); (DB-549) ADDED: Select IN LIST supported (DB-150) ADDED: SQL LENGTH function (DB-635) ADDED: LOWER function (DB-565) ADDED: SQRT function (DB-594) ADDED: SUBSTR function (DB-593) ADDED: Support for DUAL table (DB-609) ADDED: Support for binary(n) (DB-139) FIXED: Using CAST(AS STRING) in various contexts causes errors (DB-832) FIXED: Select from view crashes transaction engine (DB-815) FIXED: Query returning fewer results than expected due to double conversion issue (DB-1118) FIXED: Hibernate test suite UnionSubclassFilterTest using derived tables and unions crashes (DB-1083) FIXED: Unions in derived tables do not work correctly (DB-1080) FIXED: Query optimization failed for IN LIST queries (DB-1053) FIXED: NULL results for joins with select list with '*' using derived tables / aliases (DB-1040) FIXED: CONSTRAINT "name" UNIQUE|PRIMARY is accepted but not actually enforced (DB-1027) FIXED: Some SYSTEM tables are case-sensitive (DB-1022) FIXED: Cannot select from SYSTEM.VIEW_TABLES (DB-1020) FIXED: COLLATION and CHARACTER SET are accepted in definitions even though not supported (DB-988) FIXED: SELECT 1 in (NULL) from ... fails (DB-964) FIXED: alter table add column + select * from table causes nuodb crash (DB-941) FIXED: Wrong result when casting strings into integers (DB-877) FIXED: AS is not optional when defining a column name (aka alias) in a select list (DB-843) FIXED: Cast from integer literal to float is not implemented (DB-836)

| Copyright 2012 NuoDB, Inc. All rights reserved. | 16

| Installation and Release Notes | 17

FIXED: Crash with GROUP BY .. ORDER BY COUNT(*) (DB-705) FIXED: Crash upon SELECT statement with LEFT join and "IS NOT NULL" condition used together (DB-682) FIXED: Problems joining derived tables (DB-676) FIXED: Support Table definitions with > 64K fields (DB-601, DB-602) FIXED: ALTER TABLE followed by SELECT * FROM <table> could crash if table has data in it. (DB-599) FIXED: null constraint is not yet implemented (DB-566) FIXED: insert causes "count mismatch between field list and value list" for generated column value (DB-534) FIXED: Adding a number to a string that's not a number should produce an error (DB-512) FIXED: Failures in DELETE after performing REPLACE INTO command (DB-435) FIXED: The SQL ESCAPE function doesn't work in queries with LIKE matching. (DB-383) FIXED: Using an alias to name a derived table (subquery) in the FROM clause is not accepted (DB-366)

NuoSQL improvements: ADDED: default statement ending mode is now semi-colon (DB-589, DB-973) ADDED: --user and --password arguments (DB-360) ADDED: interactive HELP (DB-974) ADDED: support history (DB-689) ADDED: !recall# should echo the command before execution (DB-906) ADDED: session saving (DB-591) ADDED: more complete show support (DB-587) ADDED: default schema support (DB-586) FIXED: automatic reconnect when connection to database is lost (DB-585) FIXED: nuosql crash with invalid command line switch (DB-757) FIXED: batch SQL on different lines creates annoying echoing (DB-294)

Failover improvements: FIXED: Unhandled SIGPIPE causes a crash on Socket:write (DB-961) FIXED: Multiple simultaneous node failure handling (DB-980) FIXED: Deadlock in MasterCatalog:newConnection (DB-946)

Performance FIXED: Shutdown issues (DB-726, DB-1106)

Agents, Brokers, and Administration ADDED: Need a way to forcibly remove a node from a broker (DB-794) ADDED: Remote(udp) syslog support (DB-559) ADDED: Simple license added for Beta6 that times out the product in June. FIXED: Agents do not always advertise alternate addresses correctly (DB-1024) FIXED: "recv failed: No error (10054)" error is printed by broker on node disconnection (DB-1018) FIXED: Brokers get stuck (DB-796)

Internal issues: FIXED: Unresolved internal deadlock (DB-743) FIXED: checkopen hang, multiple nodes in list (DB-736, DB-839) FIXED: premature relay teardown causes various issues (DB-880)

| Copyright 2012 NuoDB, Inc. All rights reserved. | 17

| Installation and Release Notes | 18

FIXED: Transaction Engine crash (DB-722) FIXED: Transaction Engine crash during open database call (DB-695, DB-698) FIXED: Misbehaving client applications cause SEGV during Connection destruction (DB-778)

Connection destruction (DB-778) FIXED: Transaction Engine hang (DB-1095, DB-848)) FIXED: Transaction Engine deadlock (DB-1079) FIXED: Transaction threads waiting on a txn that has already committed (DB-1041) FIXED: Sysbench: Nuodb transaction nodes fails under load with "Assertion `isActive()' failed" (DB-992) FIXED: SIGPIPE causes crash on socket write (DB-961) FIXED: Performance problem with full table scan concurrent to a flights workload (DB-849) FIXED: NuodDB fatal error messages are not printed to STDERR under default logging level (DB-848) FIXED: Various assertions (DB-744, DB-702, DB-408, DB-982, DB-762, DB-736) FIXED: Validation failures (DB-737, DB-692) FIXED: Various Memory leaks (DB-874)

Demo improvements: ADDED: Improve Flights Transaction Generator, write stats to file, exclude warm-up period stats (DB-663)

Documentation ADDED: add description of SQL Workbench J to documentation (DB-717) FIXED: inconsistent naming of product components (DB-659) FIXED: various SQL reference inconsistencies (DB-977)

Platform issue FIXED: Install Windows Visual Studio runtime (DB-1047) FIXED: Windows Installer is now signed with a code signing certificate.

System Requirements
NuoDB runs on Linux, MAC OS X, and Windows, and requires Java SDK. Operating Systems Supported Linux Mac OS X Windows

Additional Software Requirements NuoDB requires Java 1.6, and has been tested using the following software: Oracle Java MAC JDK Open JDK

Windows Installation
The NuoDB installer on Windows is a self-extracting executable.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 18

| Installation and Release Notes | 19

1. Copy the NuoDB executable to your machine and run the executable. By default NuoDB is installed in: c:\Program Files\NuoDB The default location can be changed during the install process. 2. Configure your environment. Add c:\Program Files\NuoDB\bin to your systems PATH (Do this from Advanced System Settings on Windows.)

Linux Installation (rpm or deb installers)


To install and add new users you must have write access to the /opt directory. 1. For Linux distributions that support rpm:Run the RedHat Package Manager (RPM) using the NuoDB pack rpm -install nuodb-<build>.rpm By default NuoDB is installed in the /opt/nuodb directory. You can change this location during the installation process. 2. For Linux distributions that support dpkg: Run the Debian package utility, dpkg: dpkg i nuodb-<build>.deb Linux installation instructions apply to Amazon EC2 hosts as well. For Amazon EC2, we recommend installation of NuoDB on m1.large or m1.xlarge hosts. 3. Configure your environment. Add install_dir/nuodb/bin to the PATH, where install_dir is where you installed the product. 4. Optionally, use init.d scripts to start NuoDB processes. NuoDB provides a sample init.d script.

Sample Startup Script on UNIX


How to install and configure a sample NuoDB startup script for UNIX platforms The first set of steps are for LSB-compliant OS's such as RHEL, CentOS. 1. Copy the script to your /etc/init.d folder. sudo cp ${NUODB_HOME}/etc/nuoagent /etc/init.d/nuoagent 2. Perform these additional steps: chmod 755 /etc/init.d/nuoagent sudo chmod +x /etc/init.d/nuoagent sudo chkconfig --add nuoagent sudo chkconfig --level 2345 nuoagent on 3. Use the following commands to start and stop the service: service nuoagent start service nuoagent stop service nuoagent restart

| Copyright 2012 NuoDB, Inc. All rights reserved. | 19

| Installation and Release Notes | 20

service nuoagent status 4. Use the following command to delete the service: chkconfig --del nuoagent The following set of steps are for other LSB distributions such as Debian or Ubuntu. 5. Install the service sudo cp ${NUODB_HOME}/etc/nuoagent /etc/init.d/nuoagent chmod 755 /etc/init.d/nuoagent sudo update-rc.d nuoagent defaults 98 02 6. To delete the service update-rc.d -f nuoagent remove Related Links Overview of Configuration Tools on page 33 Using command-line tools as well as NuoDB Console to configure NuoDB Configuration Using Command Line on page 38 Describes some common configuration scenarios and the commands for enabling them on Linux or Mac OS X. nuosql Command on page 53 Start NuoDB SQL as a client against a specified chorus. Requires a chorus username and password.

Mac OS X Installation
The NuoDB installer on MAC OS X is a compressed file: .tar.gz file (tarball) or .zip file. 1. Extract the archive. 2. Move the contents to any location. 3. Configure your environment. Add install_dir/nuodb/bin to the PATH, where install_dir is where you installed the product.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 20

Administration
Topics: Launching a Chorus System Components Client Connections Set Up A Pilot Project From The Command Line Using Amazon Web Services (AWS) Components Troubleshooting NuoDB Overview of Configuration Tools Automate Configuration Scenarios Configuration Using Command Line

| Administration | 22

| Copyright 2012 NuoDB, Inc. All rights reserved. | 22

| Administration | 23

Administration
Launching a Chorus
To launch a chorus you must start a broker, a transaction engine, and a storage manager. Passwords are required for each of these NuoDB processes. A NuoDB broker process is part of the NuoDB management layer, and must be started before any other NuoDB processes. Starting a broker causes a domain to be defined. Starting any of the management processes (agent, broker, console) requires a domain password. This password must be specified by the first broker that is started for the domain and then used for each new management process. Similarly, starting any chorus processes (transaction engine, storage manager) requires a chorus password. You specify the chorus password when you start the first transaction engine for the chorus and then use the password evey time you start a chorus process. A password is also required for users of NuoDB SQL. The first user is known as the database administrator. Use the --dba-user and --dba-password option to make these specifications when you start the first transaction engine. After you launch the chorus, the last step is to start NuoDB SQL. Using NuoDB SQL the database administrator can create new users and privileges.

1. Start a broker java -jar nuoagent.jar --broker --password domainpwd & Note that this executable is in nuodb/bin, not in nuodb/jar. 2. Start the first transaction engine. nuodb --chorus demo --password choruspwd --dba-user admin --dbapassword adminpwd & In this example the chorus name is demo, the password for the chorus is choruspwd. The first user of NuoDB SQL is admin with a password of adminpwd. 3. Initialize the archive and start the storage manager. nuodb --chorus demo --password choruspwd --archive ./temp --initialize & 4. Start NuoDB SQL as a client of the chorus, and create a new user. nuosql demo@localhost --user admin --password adminpwd SQL> create user NewHire password 'Green'; SQL> commit; $ nuosql demo@localhost --user NewHire --password Green SQL> create table hockey (number integer, name string); SQL> show tables; Tables in schema HOCKEY HOCKEY SQL> create role admin; SQL> grant admin to NewHire default;

| Copyright 2012 NuoDB, Inc. All rights reserved. | 23

| Administration | 24

System Components
Management and chorus layers A NuoDB system is designed for the configuration, deployment, and management of one or more databases on a cloud. A NuoDB client is a user process that connects to NuoDB for the purpose of accessing data in a NuoDB system. From a conceptual point of view, a NuoDB system has two layers: a management layer and one or more NuoDB choruses. Each chorus is associated with a database. The following conceptual illustration shows a simple chorus and its relationship to the management layer for the chorus.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 24

| Administration | 25

A NuoDB system may contain multiple choruses, each associated with a database. A NuoDB domain is a collection of NuoDB hosts that have been provisioned to work together to support NuoDB processes. Choruses in a domain usually have common licensing and security specifications. By default, when you start a NuoDB agent, the agent becomes part of a NuoDB domain. A chorus has the following components:

| Copyright 2012 NuoDB, Inc. All rights reserved. | 25

| Administration | 26

A database is a collection of data that can be resolved by means of a unique name. A transaction engine is a process that provides access to a single database. It handles requests from clients, caches data, and coordinates transactions. There may be any number of transaction engines running on a single machine or across a cluster. A storage manager is a process that provides durability of the data that it handles (for example by writing to disk). There may be any number of storage managers running on a single machine or across a cluster. Each storage manager is associated with exactly one database.

The management layer has the following components: A broker is a server that manages access to transaction engines and storage managers, independent of any particular database (or chorus) in the NuoDB system. An agent is a process that manages NuoDB processes running on a particular computer. It starts and stops the NuoDB servers and communicates with the NuoDB broker about the state of the system. An agent can also act as a broker. NuoDB Console communicates and interacts with all the agents in a NuoDB system. It manages databases and choruses.

NuoDB makes use of external components such as Amazon EC2, Amazon EBS, and Amazon S3 to create virtual machines on the cloud. Overview of A Simple NuoDB System A NuoDB system designed for production typically has many hosts, which you can add and remove dynamically on the cloud according to the changing requirements of your system. The following conceptual illustration shows a simple NuoDB system with just four hosts.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 26

| Administration | 27

This example shows the following hosts: Part of the management layer (broker and NuoDB Console) runs on Host 1. An agent and a transaction engine run on Host 2. (The agent is part of the management layer.)

| Copyright 2012 NuoDB, Inc. All rights reserved. | 27

| Administration | 28

Another agent and transaction engine on Host 3. A storage manager for the chorus runs on Host 4, connects to Data Storage on disk, and maintains communications with an agent running on the same host.

Note that the components of the chorus (transaction engines and storage manager) do not run on the same host; performance is optimal if they run on separate hosts. Having just one transaction server on a host also enhances performance. Like the chorus, the components of the management layer do not have to run on the same host. That is, the agents running on Host 2 and Host 3 are part of the management layer, while other components of the management layer (NuoDB Console and the broker) are running on Host 1. An agent must run on every host in a NuoDB system. Related Links JDBC Connection Properties on page 49 Program fragment showing JDBC properties and sample connection URL

Client Connections
The following illustration shows a simple NuoDB chorus and a client that wants to connect to it.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 28

| Administration | 29

The steps in the process shown in this conceptual illustration are as follows:

| Copyright 2012 NuoDB, Inc. All rights reserved. | 29

| Administration | 30

1. A client that seeks to connect to the database connects to the broker on Host 1. Because it communicates with agents the broker can determine the existence of a host as well as its availability; it determines the best transaction engine for the client connection at any particular time. 2. The broker communicates back to the client that it should connect to the transaction server on Host 3. 3. The client connects to Host 3. Related Links SQL Reference Pages on page 87 Syntax, descriptions, and examples for SQL statements JDBC Connection Properties on page 49 Program fragment showing JDBC properties and sample connection URL

Set Up A Pilot Project From The Command Line


Description of a very simple NuoDB system (not intended for production). To get started you can set up a non-durable, non-production NuoDB system running on just one host, and add a second host to improve performance. Doing this as a prerequisite for building a NuoDB production environment helps you to: Evaluate and understand the requirements for a NuoDB system. Learn more about how to maximize performance when you eventually go live with a system that you use for production.

The goals of this simple system are to Run a broker, transaction engine, and a storage manager on a single host with local storage. Start a chorus on the same host, loading data, and running a client application against the chorus. Observe performance statistics (such as transactions per second) while running NuoDB on the single host. Add another host, run an agent and a transaction engine on this second host, reconnect the client application, and notice the performance change. Optionally add more hosts running agents and transaction engines for the same chorus and observe changes in performance. Optionally double the storage for the system by adding a host dedicated as an archive. Note: The following step-by-step instructions assume that you have a client application that you would like to run against a database, and that you have available a second host on which to run NuoDB. 1. Start a NuoDB broker on the machine to run a host of NuoDB: java -jar nuoagent.jar --broker --password domain_password 2. Create a local directory for storage (such as ./temp/archive-storage). 3. Start a chorus on the same host, and initialize a storage manager with local storage for the chorus. nuodb -chorus mychorus --password chorus_password archive ./temp/ archive-storage initialize where mychorus is the name of the database to be stored. 4. Run a client application against the chorus. Make sure the client connects to NuoDB and loads the database. 5. Configure another host with an agent and a transaction engine and connect it to the first host. On the new host:

| Copyright 2012 NuoDB, Inc. All rights reserved. | 30

| Administration | 31

a) Start a transaction engine for the chorus. nuodb -chorus --password chorus_password mychorus b) Start an agent and specify the host running the NuoDB broker (the first host you configured) as a peer: java -jar nuoagent.jar --password domain_password --peer <hostname or ip address of peer system> 6. Connect and run the client application. 7. Observe performance for each of two transaction engines running on separate hosts. You can monitor performance using NuoDB Console. At first, performance may decrease as the new processes start up. You should be able to observe improved performance after this initial interval. Note: Once you have NuoDB up and running you can use NuoDB the console and other tools to manage and administer the system. From NuoDB Console you can perform administrative tasks, such as starting and stopping processes, finding and adding brokers, and others. You can use NuoDB Loader to import and export data. You can use the interactive sessions with NuoDB SQL to issue SQL commands required by your application.

Using Amazon Web Services (AWS) Components


Suggestions for running NuoDB on the cloud You can integrate and deploy NuoDB by means of the following Amazon Web Services (AWS). Name of Service Purpose

You can launch an EC2 host using the AWS Management Console and then run Amazon Elastic Compute Cloud (EC2) a NuoDB broker on the host. Because EC2 has both an internal and external addressing scheme, you can configure connections with other brokers running on EC2 hosts in the cloud, as well as with clients outside the cloud. This feature is very useful for creating a cluster of externally-accessible brokers. Amazon Simple Storage Service (Amazon S3) Amazon Elastic Block Store (EBS) NuoDB supports archive storage of serialized atoms on Amazon S3. This makes it possible for you to run storage managers in an EC2 cloud without using EBS.

To support persistent storage as well as high availability and high reliability, you can run NuoDB on an instance of EC2 and attach EBS.

You can configure these services to work together, or independently, to support scalable cloud applications as well as persistence and reliability of a NuoDB system. NOTE See the NuoDB Forum for information about launching NuoDB on AWS. Overview To run NuoDB on Amazon Elastic Cloud (EC2) you launch hosts of EC2 using the AWS Management Console and then start NuoDB processes on each host as required for your particular deployment. You

| Copyright 2012 NuoDB, Inc. All rights reserved. | 31

| Administration | 32

can easily add and remove hosts using NuoDB management tools, such as NuoDB Console, and the elasticity features of Amazon EC2 and NuoDB. What is Amazon EC2 Amazon EC2 is a web service that provides resizeable compute capacity in the cloud. The NuoDB documentation assumes that you are familiar with setting up Amazon EC2. For help getting started see http://docs.amazonwebservices.com/AWSEC2/2011-07-15/GettingStartedGuide/. EC2 has both an internal and external addressing scheme, making it possible for you to configure the cloud to allow access among the agents and brokers (using the internal scheme) as well as access to clients (using the external scheme). In other words, each host on the cloud is essentially known by two names depending on context. You specify command-line arguments to configure the address when you start each agent and broker. The following figure shows the design of an initial system running on Amazon EC2 hosts:

As shown, this system runs a transaction engine and an agent as a broker on on instance of Amazon EC2, and a storage manager and an agent on a second instance of Amazon EC2. The storage manager connects to Amazon S3 for data storage on the cloud. (Because Amazon EC2 does not support persistent storage on disk, consider using Amazon S3 or Amazon EBS for storage. You could also put the archive on a physical rather than a virtual host.)

| Copyright 2012 NuoDB, Inc. All rights reserved. | 32

| Administration | 33

Troubleshooting NuoDB
Common problems and possible solutions Broker advertising a chorus node that no longer exists. Restart the broker. Cannot start a chorus. It is possible that the broker is advertising a chorus that no longer exists. Restart the broker Errors returned from JDBC Error Probable Cause What To Do Contact your NuoDB administrator for the correct connection URL.

The client was unable to "java.io.IOException: connect to the URL provided Connection timed for the broker within the out" specified timeout limit. "Unknown service: SQL2" The client connected to a NuoDB agent, but the agent is not specified as a broker. Only brokers (that is, agents running as brokers) can mediate NuoDB client connections. The database name provided in the URL does not correspond to a running chorus associated with a broker. The broker is unable to locate any running transaction engines for this chorus.

Start a broker if necessary and reconnect the client.

"No such database: DATABASE"

Contact your NuoDB administrator to determine the correct database name and start a chorus, including a broker.

"Fatal error: No nodes are available"

Contact your NuoDB administrator to restart the transaction engine and associate it with this broker.

Overview of Configuration Tools


Using command-line tools as well as NuoDB Console to configure NuoDB The basic building blocks for a NuoDB configuration are agents, brokers, transaction engines, and storage managers. This section tells you how to use two executables, nuoagent and nuodb to implement these building blocks. Using nuoagent One instance of a nuoagent executable must run on every host that runs NuoDB services. An agent can run in either of the following modes: Agent mode Keeps track of every NuoDB process running on a given machine and is the point of administration to

| Copyright 2012 NuoDB, Inc. All rights reserved. | 33

| Administration | 34

the system. Agents are responsible for starting and monitoring NuoDB processes. Broker and Agent mode At least one broker must run as part of a NuoDB configuration. A broker manages access (from both client and administrative connections) to the NuoDB transaction engines that are configured.

Using nuodb One or more instances of the nuodb executable can run on a host in a configuration. This command implements the following services: Name of Service transaction engine (TXE) storage manager Definition Runs SQL transactions on behalf of clients. Add more SQL transaction engines to scale the database. Storage managers provide durability and redundancy. To provide redundant durability, run a storage manager on more than one host using separate physical storage for each storage manager.

Related Links JDBC Connection Properties on page 49 Program fragment showing JDBC properties and sample connection URL Automate Configuration Scenarios on page 38 NuoDB configurations can be automated as follows. Sample Startup Script on UNIX on page 19 How to install and configure a sample NuoDB startup script for UNIX platforms Use NuoDB Console on page 10 How to start NuoDB Console and view the QuickStart processes. Configuration Using Command Line on page 38 Describes some common configuration scenarios and the commands for enabling them on Linux or Mac OS X. nuosql Command on page 53 Start NuoDB SQL as a client against a specified chorus. Requires a chorus username and password.

nuodb
Start a NuoDB chorus with two or more options. Requires a user name and password. Synopsis nuodb --chorus chorus_name --password password [ --dba-password DBA_account_password ] [ options ] nuodb --chorus chorus_name --password password Description Starts a NuoDB process, which can be a transaction engine or a storage manager, for a specified chorus. To launch a chorus (that is, when you start the first transaction engine for it) you must create a password for the NuoDB DBA (database administrator) account. The dba username and the password created with -dba-password are required to create new users and privileges in NuoDB SQL. To create additional transaction engines a chorus user name and password are required.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 34

| Administration | 35

Options Option --archive archive_name --chorus chorus_name --dba-password DBA_account_password --force --help --initialize Definition Archive directory for use by storage manager. Name of chorus. You must also initialize an archive if one does not exist. Password that must be created when the first transaction engine was started Overwrite existing archive Print information about this command Initialize archive. If the specified archive has already been initialized, NuoDB generates an error. Use --initialize --force to overwrite an existing archive. --log filename --mem --password password --verbose Log file name Memory threshold Chorus password. Report details such as the following: debug, info, warn, error, dump, stats, tx, net, records, atoms, archive, threads, gc, msgs, security, scheduler, sql, services, validate, flush Display the server version

--version

nuoloader (NuoDB Loader)


Import and export data to and from NuoDB nuoloader chorus_name [options]... Description NuoDB Loader is a command-line utility to import and export data to and from a NuoDB chorus. It supports comma-separated value (CSV) file formats. It runs as a client of NuoDB and requires a chorus user name and password. Options Option Connection Options --user user name --password password --schema database schema Import options --import from filename [,import file options] -to [SQL insert | update] Specifies a CSV file to be imported along with import options. The import options should follow the filename and be separated by comma. Definition Must be specified if required by the database. --user user_name --password chorus_password

| Copyright 2012 NuoDB, Inc. All rights reserved. | 35

| Administration | 36

Option

Definition If filename> is not provided, data is expected on stdin.

[import file options] --separator - printable character or word "tab" for horizontal tabulation; --skip - the number of lines to skip in the beginning of the file; --trim - may have value of leading, trailing, both or none, it controls stripping leading and trailing white spaces; --escape -backslash '\' is used to escape double quotes, new lines and tabulation.

Optionally specified list of attributes that indicate formatting conventions used in the input file. For an import operation, a valid prepared SQL INSERT/UPDATE statement is expected as the argument. Question mark '?' is used to specify a position of a parameter. For example: "insert into FOO values (?,?,?)" Specify an SQL SELECT statement to be exported into a file in CSV format, and specify an output file name for the export operation. If no filename is specified output is sent to stdout.

Export options --export [SQL SELECT statement] to options] [export file

[export file options] separator Printable character or word "tab" for horizontal tabulation; titles If specified, columns names are written in the first line; escape Backslash '\' is used to escape double quotes, new lines and tabulation enclose All fields are enclosed in double quotes; Batching options batch-size Size of a batch in bytes, default is 64KB batch-count Size of a batch in the number of rows, default is 5000 batch-commit Performs commit after batch execution

An optional comma separated list of modifiers to the output file format.

For better performance data can be imported using batches. Options control the size of single batch and whether or not each batch should be processed as a separate transaction. Batching can be turned off by setting either --batch-size or -batch-count to zero. -

Reporting options --verbose Reports progress for each executed batch. --log Redirects error and verbose output into a file.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 36

| Administration | 37

Option Miscellaneous options

Definition By default, an erroneous line is reported and execution continues.

--strict Halts execution on any error. --help Prints the list of options. --version Prints the version.

nuoagent
Starts a NuoDB agent or broker. Requires a domain password. Synopsis java -jar nuoagent.jar --broker --password password [options] java -jar nuoagent.jar --peer hostname --password password [options] Command Line Options Name --broker Usage Start the agent as a connection broker. If not started as a broker, either the peer or broadcast option is required to specify an entry to an existing domain. You must create a password the first time you create a broker. --password --peer host[:port] Domain password, which is specified the first time a broker runs. Specifies host to use as a peer connection for entering the domain. Requires domain user name and password. Alternatively you can specify --broadcast but there might be a performance impact. Use the specified port (instead of the default port, which is 48004) Directory containing the nuodb executable. If the bin-dir flag is not specified, the agent looks in the directory that contains the jar file. If no executable is found the command fails. --advertise-alt --alt-addr address --domain name --port-range start[,end] --broadcast number_of_seconds --help --verbose --version Advertise alternate addresses. Associate an address with the specified peer Name of the domain to support Range of allowable port numbers for NuoDB hosts. Enable broadcast advertisement and discovery of NuoDB hosts at intervals specified by number_of_seconds. May degrade perfomance compared to use of --peer option. Display information about the command Enable logging Display the agent version

--port [:port] --bin-dir directory

| Copyright 2012 NuoDB, Inc. All rights reserved. | 37

| Administration | 38

Description A nuoagent process must run (as either an agent or a broker) on any instance where NuoDB choruses are hosted. Examples Provision a domain with two hosts. $ java -jar nuoagent.jar --broker --password domainpassword $ java -jar nuoagent.jar --peer host1 -password domain-password

Automate Configuration Scenarios


NuoDB configurations can be automated as follows. 1. Configure a host to start nuoagent at boot time. On UNIX you can run an init.d script by using a sample provide in /install_dir/etc/ nuoagent. 2. Use options with nuodb commands in a script to set up the required nuodb processes across all machines. Related Links Overview of Configuration Tools on page 33 Using command-line tools as well as NuoDB Console to configure NuoDB Configuration Using Command Line on page 38 Describes some common configuration scenarios and the commands for enabling them on Linux or Mac OS X. nuosql Command on page 53 Start NuoDB SQL as a client against a specified chorus. Requires a chorus username and password.

Configuration Using Command Line


Describes some common configuration scenarios and the commands for enabling them on Linux or Mac OS X. NOTE Keep in mind that you must start brokers and agents on the command line, but transaction engines and storage managers can be started more conveniently using NuoDB Console. Also note use of passwords with all NuoDB processes. Minimal single host configuration with durability This configuration does the following: Starts an agent running as a broker on Host1. Initializes a storage manager on the same host. Starts a transaction engine for the chorus on the same host.

The nuosql client connects to the test database/chorus through the broker running on Host1. Host1 > java -jar nuoagent.jar -broker --password domain_password & Host1 > nuodb --chorus test --password chorus_password --archive /archive/ test_data -initialize & Host1 > nuodb chorus test --password chorus_password &

| Copyright 2012 NuoDB, Inc. All rights reserved. | 38

| Administration | 39

Host1 > nuosql test@Host1 --user dba-username --password dba_password & Note: The initialize option for the storage manager is specified only the first time a database is configured. The rest of the examples assume the initialize option has been used. Multi-host configuration with durability and transactional scalability This configuration does the following: Starts an agent running as broker on Host1 Starts a storage manager on Host1 to store data for the test@Host1 chorus in the /archive/test_data directory. Transaction engines run on Host1, Host2, and Host3 managing transactions against the chorus named test. Agents also run on Host2 and Host3. The -peer option is required when adding hosts to the system, so that additional agents can connect to the broker. Host1 > java -jar nuoagent.jar -broker --password domain_password & Host1 > nuodb --chorus --password chorus_password test --archive /archive/ test_data & Host1 > nuodb -chorus --password chorus_password test & Host2 > java -jar nuoagent.jar -peer Host1 --password domain_password & Host2 > nuodb -chorus --password chorus_password test & Host3 > java -jar nuoagent.jar -peer --password domain_password Host1 &Host3 > nuodb chorus --password chorus_password test & Multi-host configuration with durability, data redundancy, and transactional scalability This configuration is similar to the previous one except that it runs more than one archive manager. It does the following: Starts an agent running as broker on Host1 On both Host1 and Host2, a storage manager stores data for the test chorus to the /archive/test_data directory. It is important that the /archive/test_data directory is not shared in any way by multiple storage managers. Transaction engines run on Host1, Host2, and Host3 managing transactions against the chorus named test. Agents also run on Host2 and Host3. Host1 > java -jar nuoagent.jar -broker --password domain_password & Host1 > nuodb --chorus --password chorus_password test --archive /archive/ test_data Host1 > nuodb -chorus --password chorus_password test Host2 > java -jar nuoagent.jar -peer Host1 --password domain_password Host2 > nuodb --chorus --password chorus_password test --archive /archive/ test_data Host2 > nuodb -chorus --password chorus_password testHost3 > java -jar nuoagent.jar -peer Host1 Host3 > nuodb -chorus --password chorus_passwordtest@Host1 Multi-host configuration with broker redundancy, durability, data redundancy and transactional scalability This is exactly the same configuration as the previous one but also demonstrates how to specify multiple brokers . Note that the redundant broker runs on the same host as the redundant storage manager. Host1 > java -jar nuoagent.jar -broker Host1 --password domain_password &

| Copyright 2012 NuoDB, Inc. All rights reserved. | 39

| Administration | 40

> nuodb --chorus --password chorus_password test --archive /archive/ testdataHost1 > nuodb -chorus --password chorus_password test Host2 > nuoagent -broker -peer Host1Host2 --password domain_password > nuodb --chorus --password chorus_password test --archive /archive/ testdataHost2 > nuodb -chorus --password chorus_password testHost3 > > java -jar nuoagent.jar -peer Host2Host3 --password domain_password > nuodb -chorus --password chorus_password test In this configuration a client can get a transactional and consistent view of the database by using either the test@Host1 or test@Host2 path as the connect string from the client. For example: Host D > nuosql test@Host1 Host D > nuosql test@Host2 Multiple data center and cloud region configuration You can use NuoDB in a deployment that spans multiple data centers or cloud regions. A typical scenario is a web application deployment that runs in two or more geographies. In this scenario clients can be globally load-balanced to a specific data center based on their location. The following deployment scenario has hosts in the UK (uk-host1 and uk-host2) and the US (us-host1 and us-host2). The steps for this deployment are as follows: 1. Provision the four hosts by running an agent on each, starting some of them to act as brokers as well: uk-host1 uk-host2 password us-host1 us-host2 password > java -jar nuoagent.jar > java -jar nuoagent.jar domain_password& > java -jar nuoagent.jar > java -jar nuoagent.jar domain_password& -broker --password domain_password & -peer uk-host1 --broker --password domain_password & -peer us-host1 --

2. Configure the transaction and storage managers: uk-host2 > nuodb archive/testdata uk-host1 > nuodb us-host2 > nuodb archive/testdata us-host1 > nuodb -chorus & -chorus -chorus & -chorus --password chorus_password test -archive / --password chorus_password test & --password chorus_password test -archive / --password chorus_password test &

3. Connect a client such as nuosql by specifying the chorus as follows: chorusnname-@brokerhost For example test@uk-host1 or test@us-host1 Some modifications may be required for this format to work in an Amazon cloud deployment. For example, with Amazon you have to accommodate the complexities of the private/public IP model that is used. Related Links Overview of Configuration Tools on page 33

| Copyright 2012 NuoDB, Inc. All rights reserved. | 40

| Administration | 41

Using command-line tools as well as NuoDB Console to configure NuoDB Automate Configuration Scenarios on page 38 NuoDB configurations can be automated as follows. Sample Startup Script on UNIX on page 19 How to install and configure a sample NuoDB startup script for UNIX platforms Use NuoDB Console on page 10 How to start NuoDB Console and view the QuickStart processes.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 41

| Administration | 42

| Copyright 2012 NuoDB, Inc. All rights reserved. | 42

Programming With NuoDB


Topics: Programming Connections Using NuoDB SQL Sample Client Programs

| Programming With NuoDB | 44

| Copyright 2012 NuoDB, Inc. All rights reserved. | 44

| Programming With NuoDB | 45

Programming With NuoDB

Programming
Introduction to programming with NuoDB Programming with NuoDB is like programming with any other database: you write your client program and connect the client executable to NuoDB using a database connection tool such as JDBC. NuoDB provides nuosql, an interactive interpreter for NuoSQL, which you can use to test out your client code. NuoDB supports the use of external programming tools, such as Hibernate, SQuirreL, and DbVisualizer. Related Links SQL Reference Pages on page 87 Syntax, descriptions, and examples for SQL statements

Connections
NuoDB automatically installs drivers and supports database connections by means of JDBC and ODBC. NuoDB supports the following drivers: Name of Driver JDBC Driver ODBC Driver Usage The JDBC driver is installed automatically in the $NUODB_HOME/jar directory, where $NUODB_HOME is the folder where you installed NuoDB. The NuoDB installer automatically installs the a 32-bit driver for ODBC connections on Windows platforms. NOTE: 64bit Windows applications will not work properly with the 32-bit NuoDB ODBC driver.

Use DbVisualizer
How to configure DbVisualizer for NuoDB JDBC driver Since NuoDB has full JDBC support, you can use tools such as DbVisualizer with minimal configuration. The most important task is to configure DbVisualizer to use the NuoDB JDBC driver. 1. Download DbVisualizer from their website: http://www.dbvis.com 2. Copy the NuoDB JDBC driver into the DbVisualizer installation directory. For example, on Linux, use commands like the following: cd ~/DbVisualizer-8.0.4/jdbc mkdir nuodb cp /opt/nuodb/jar/nuodbjdbc.jar nuodb 3. Setup DbVisualizer to use the NuoDB driver a) Open the Driver Manager b) Specify the items in the screen as shown:

| Copyright 2012 NuoDB, Inc. All rights reserved. | 45

| Programming With NuoDB | 46

4. Open a database by creating a connection using the DbVisualizer connection wizard: Database > Create Database Connection 5. Follow the steps in the wizard. Choose the NuoDB driver

6. Connect to the database using the connection form:

7. Browse/Interact with the NuoDB database as you like.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 46

| Programming With NuoDB | 47

JDBC Connections
NuoDB automatically installs drivers and supports database connections by means of JDBC and ODBC. Drivers Driver JDBC Driver ODBC Driver Definition The JDBC driver is installed automatically in the $NUODB_HOME/jar directory, where $NUODB_HOME is the folder where you installed NuoDB. The NuoDB installer automatically installs the a 32-bit driver for ODBC connections on Windows platforms. NOTE: 64bit Windows applications will not work properly with the 32-bit NuoDB ODBC driver.

JDBC Connections JDBC provides RDBMS access by allowing you to embed SQL inside Java code. The correct URL syntax for a NuoDB JDBC client is as follows: jdbc:com.nuodb://{BROKER}:{PORT}/{DATABASE} where BROKER is the tcp/ip address for the NuoDB Broker agent, as IP address or DNS name string. PORT is the configured port for that broker; if not defined it is assumed to be 48004. DATABASE is the name of the NuoDB chorus database you are connecting to and is required. The following fragment is from the Java sample; it shows how to connect to the local database server.

/** An example program for connecting to a NuoDB database server. */ public class HelloDB { /** The driver class provided by NuoDB. */ public static final String DRIVER_CLASS = "com.nuodb.jdbc.Driver"; /** The base URL for connecting to a local database server. */ public static final String DATABASE_URL = "jdbc:com.nuodb://localhost/"; // the established connection to a local server private final Connection dbConnection;

| Copyright 2012 NuoDB, Inc. All rights reserved. | 47

| Programming With NuoDB | 48

/** * Creates an instance of HelloDB and connects to a local server, * as the given user, to work with the given named database * * @param user the user name for the connection * @param password the password for the given user * @param dbName the name of the database at the server to use */ public HelloDB(String user, String password, String dbName) throws SQLException { Properties properties = new Properties(); properties.put("user", user); properties.put("password", password); properties.put("schema", "hello"); dbConnection = DriverManager.getConnection(DATABASE_URL + dbName, properties); } /** Closes the connection to the server. */ public void close() throws SQLException { dbConnection.close(); } /** Creates a simple two-column table: id->name. */ public void createNameTable() throws SQLException { try { Statement stmt = dbConnection.createStatement(); stmt.execute("create table names (id int primary key, name string)"); stmt.close(); dbConnection.commit(); } catch(Exception exception) { System.out.println("Skipping table creation: " + exception.getMessage()); } } /** * Inserts a row into the table. The id must be unique. * * @param id a unique numeric identifier * @param name a name associated with the given id */ public void insertName(int id, String name) throws SQLException { try { PreparedStatement stmt = dbConnection. prepareStatement("insert into names (id, name) values (?, ?)"); stmt.setInt(1, id); stmt.setString(2, name); stmt.addBatch(); stmt.executeBatch(); dbConnection.commit(); } catch(Exception exception) { System.out.println("Skipping insert..."); } } Related Links

| Copyright 2012 NuoDB, Inc. All rights reserved. | 48

| Programming With NuoDB | 49

Example: Using ODBC and MS Excel to Read a NuoDB Database on page 50 Step-by-step example using Flights application JDBC Connection Properties on page 49 Program fragment showing JDBC properties and sample connection URL

JDBC Connection Properties


Program fragment showing JDBC properties and sample connection URL String connectURL = "jdbc:com.nuodb://broker_host:48004/ my_chorus"; Properties connectProperties = new Properties(); connectProperties.put("user", DB_USER); connectProperties.put("password", DB_PASSWORD); connectProperties.put("schema", "test"); connectProperties.put("isolation", "write_committed"); try { connection = DriverManager.getConnection(connectURL, connectProperties); connection.setAutoCommit(false); } catch (SQLException e) { throw new RuntimeException("TestConnection: cannot open chorus "+chorus+" at "+connectURL + "; check user credentials and broker status.", e); } Related Links Run a Simple Java Sample Program on page 10 How to run a simple Java application against NuoDB C++ Sample Program on page 62 Simple Hello program in C++ JRuby Sample Program on page 63 How to run a sample JRuby application and Gems Working with Hibernate on page 64 Information about the Hibernate sample System Components on page 24 Management and chorus layers Client Connections on page 28 The following illustration shows a simple NuoDB chorus and a client that wants to connect to it. Using Amazon Web Services (AWS) Components on page 31 Suggestions for running NuoDB on the cloud Overview of Configuration Tools on page 33 Using command-line tools as well as NuoDB Console to configure NuoDB Connections on page 45 NuoDB automatically installs drivers and supports database connections by means of JDBC and ODBC. JDBC Connections on page 47 ODBC Connections on Windows on page 50 NuoDB supports connections by means of ODBC, which is an open specification that provides a predictable API for accessing SQL servers and any data source with an ODBC connection. Example: Using ODBC and MS Excel to Read a NuoDB Database on page 50 Step-by-step example using Flights application

| Copyright 2012 NuoDB, Inc. All rights reserved. | 49

| Programming With NuoDB | 50

ODBC Connections on Windows


NuoDB supports connections by means of ODBC, which is an open specification that provides a predictable API for accessing SQL servers and any data source with an ODBC connection. The transaction modes defined by ODBC and supported by NuoDB are shown in the following table. ODBC Constant SQL_TXN_READ_UNCOMMITTED SQL_TXN_READ_COMMITTED SQL_TXN_REPEATABLE_READ SQL_TXN_SERIALIZABLE Notes Dirty reads, non-repeatable reads and phantom reads can occur. Dirty reads are prevented; non-repeatable reads and phantom reads can occur. Dirty reads are prevented; non-repeatable reads happen after writes; phantom reads can occur. Dirty reads, non-repeatable reads and phantom reads are prevented.

Related Links Example: Using ODBC and MS Excel to Read a NuoDB Database on page 50 Step-by-step example using Flights application JDBC Connection Properties on page 49 Program fragment showing JDBC properties and sample connection URL

Example: Using ODBC and MS Excel to Read a NuoDB Database


Step-by-step example using Flights application 1. Set up and run the Flight Reservation program as described in Flights Tutorial. 2. Open the ODBC Data Source Administrator from the MS Windows Start menu (search for ODBC in the Search programs and files area, and choose Data Sources (ODBC)). a) From the ODBC Data Source dialog select NuoODBC. b) In the NuoDB ODBC Setup dialog specify Flights as the schema. (This is the schema used in the Flights Tutorial database.) 3. Start MS Excel. a) Select the Data tab b) Select From Other Sources c) Select From Microsoft Query. Do not select From Data Connection Wizard.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 50

| Programming With NuoDB | 51

d) Select FlightsDemo DSN

e) Choose the FLIGHTS table.

f) Open the FLIGHTS tree and select all of the columns using the > button:

g) Click Next until you get to the Query Wizard-Finish dialog. (Optionally select a different sorting option for the table.) h) Select Return Data to Microsoft Excel.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 51

| Programming With NuoDB | 52

i) Click Finish. j) In the Import Data dialog click OK.

k) Click Refresh The Flights Tutorial data should be displayed in the spreadsheet.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 52

| Programming With NuoDB | 53

Using NuoDB SQL


Step-by-step instructions to use NuoDB SQL NuoDB provides nuosql, an interactive interpreter for NuoSQL, which you can use to test out your client code. 1. If you have not already done so, start a broker, a chorus, and an archive. 2. Invoke nuosql specifying the name of the database, which is the name of the chorus including the host where the broker was started, and using your password. 3. Issue NuoSQL statements at the SQL> prompt. The following example creates a table, inserts some data, then selects it. SQL> create schema xyzzy; SQL> use xyzzy; SQL> create table foo (f1 integer, f2 string); SQL> insert into foo (f1, f2) values (123, 'abc'); SQL> select * from foo --- --123 abc 4. Commit changes nuosql does not commit changes to the database automatically. a) To commit changes, use the commit statement. SQL> commit b) To undo a change that has not been committed, use the rollback statement. >SQL> rollback Related Links Language Elements on page 67 Reference information about data types, operations, access, variables, indexes, and isolation levels. SQL Reference Pages on page 87 Syntax, descriptions, and examples for SQL statements

nuosql Command
Start NuoDB SQL as a client against a specified chorus. Requires a chorus username and password. Synopsis nuosql chorus_name --user username --password password [options] Description Options Name Of Option --user --password --schema Description User name Password Default schema

| Copyright 2012 NuoDB, Inc. All rights reserved. | 53

| Programming With NuoDB | 54

Name Of Option --encrypt --config --file --nosemicolon --help --version

Description Encryption algorithm name Configuration file Command file Do not require semicolon command terminator Display this information Display the agent version

Related Links Overview of Configuration Tools on page 33 Using command-line tools as well as NuoDB Console to configure NuoDB Automate Configuration Scenarios on page 38 NuoDB configurations can be automated as follows. Sample Startup Script on UNIX on page 19 How to install and configure a sample NuoDB startup script for UNIX platforms Use NuoDB Console on page 10 How to start NuoDB Console and view the QuickStart processes.

Using Parameterized Queries with NuoDB SQL


Improving performance and security by using parameterized queries A parameterized query is a query in which placeholders are used for parameters and the parameter values are supplied at execution time. NuoDB recommends that you use parameterized queries to improve performance as well as security. Because NuoDSB saves SQL statements as they are compiled, parameterized queries are available for reuse with new SQL statements without having to recompile the code that specifies the parameter. For example, suppose you want to present a list of the sequences defined in a particular schema named schemaName. The following code fragment shows how you might approach this without parameterized queries: char buffer [256]; int len = sizeof (buffer); snprintf (buffer, len, "select sequenceName from system.sequences where schema = '%s' ", schemaName); statement = prepareStatement (buffer); Parameterized queries are both safer and faster. In the following alternative, statement represents a parameterized query: statement = prepareStatement( "select sequenceName from system.sequences where schema=?"); statement->setString(1, schemaName); Using parameterized queries improves security because the literal field names in the database are not used in every statement. Using parameters also helps you avoid issues around string length. NuoDB implements object names (table, column, view, constraint, sequence) as almost unbounded UTF8 character strings. Moreover, index and constraint names can be built automatically by concatenating something to another object name. As a result a buffer may not be long enough to hold even a very simple query.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 54

| Programming With NuoDB | 55

Batch Processing from the Command Line


Using commands and writing scripts for batch processing of NuoDB SQL The nuosql interpreter accepts SQL commands from redirected standard input (stdin) or directly by means of a file directly using the command <file> argument. When redirecting input, nuosql suppresses the SQL > prompt on output and automatically exits on EOF. The following example redirects input of SQL commands and sends the output of all operations to an output file: nuosql --password dba_password test@localhost < my_application_ddl.sql &> output.txt This example executes the commands in filename: nuosql --file command_filename --password dba_password Note: When you specify the --command option, nuosql executes all the commands in the specified file, and then runs interactively. You can change this behavior by specifying an explicit exit at the end of the specified file.

Working With Triggers


Examples of creating, altering, and dropping triggers in NuoDB A trigger is a named database object that is associated with a table. It is executed when a particular event occurs for the table. For example, you can use triggers to check values before they are inserted into a table, or to perform calculations on values that are part of an update. How NuoSQL Triggers Work INSERT, DELETE, or UPDATE statements that execute for a table can activate a trigger for the table. You can set the trigger to activate either before or after the triggering statement. For example, you can have a trigger activate before each row that is inserted into a table or after each row that is updated. NOTE NuoSQL triggers are non-standard. See the ALTER TRIGGER, CREATE TRIGGER, and DROP TRIGGER topics for the exact syntax for NuoSQL triggers. Example: Creating Triggers This code fragment shows two triggers: test1A and test1B. One of the triggers fails because of a mismatch of type definitions for a column. Create three tables (test1, test2, test3). Each of the tables has one cell (a1, a2, a3, respectively). SQL> use test; SQL> create table test1(a1 int); SQL> create table test2 (a2 int); SQL> create table test3 (a3 int not null primary key);

Define a trigger that inserts 200 as the value of a2 in test2 whenever any value is inserted into test1.

SQL> > > >

create trigger test1A for test1 before insert as insert into test2(a2) values(200);

| Copyright 2012 NuoDB, Inc. All rights reserved. | 55

| Programming With NuoDB | 56

> end_trigger; To show the results of the trigger, specify an INSERT to test1 as 100.

SQL> insert into test1(a1) values (100); SQL> select * from test1; A1 --100 SQL> select * from test2; A2 --200

Define another trigger on test1 to insert 200 as the value of a2 in test2, and also to insert 300 as the value of a3, whenever any value is inserted into test1. To show the results of the trigger, specify an INSERT to test1 as 100. Note that test2 has two rows added, because of two triggers that fired before the insert to test1.

SQL> > > > > >

create trigger test1B for test1 before insert as insert into test2(a2) values(400); insert into test3(a3) values(300); end_trigger;

SQL> insert into test1(a1) values(100); SQL> select * from test1; A1 --100 100 SQL> select * from test2; A2 --200 200 400 SQL> select * from test3; A3 --300

Example: Altering A Trigger The following code fragment depends on the code in the previous section (Example: Creating Triggers). An error occurs on the next insert into test1. Trigger test1B attempted to add a row to table test3 but failed because of SQL> insert into test1(a1) values(100); duplicate value in unique index TEST3..PRIMARY_KEY

| Copyright 2012 NuoDB, Inc. All rights reserved. | 56

| Programming With NuoDB | 57

a mismatch in the definition of test3(a3). (The value of test3(a3) is defined as a primary key and must be unique.) To avoid the error until you can fix the problem, deactivate the trigger that causes it, namely test1B. Show the results when you do the insert. Only the first trigger (test1A) fires. SQL> alter trigger test1b for test1 inactive;

SQL> insert into test1(a1) values(100); SQL> A1 --100 100 100 SQL> select * from test2; A2 --200 200 400 200 SQL> select * from test3; A3 --300

Example: Dropping A Trigger The following code fragment depends on the code in the previous section (Example: Altering A Trigger). To fix the problem with test1B you must remove it and define it again. You cannot use ALTER TRIGGER to redefine it. SQL> drop trigger test1B;

Example: Using A Sequence Number In A Trigger The following code fragment depends on the code in the previous section. Fix the problem by defining the trigger using a sequence instead of an integer. SQL> create sequence test3key; SQL> create trigger test1B for test1 >before insert >as >insert into test2(a2) values (400); >insert into test3(a3) values (next value for test3key); >end_trigger; SQL> insert into test1(a1) values (100); SQL> select * from test3; A3 --300

| Copyright 2012 NuoDB, Inc. All rights reserved. | 57

| Programming With NuoDB | 58

1 SQL> insert into test1(a1) values (100); SQL> select * from test3; A3 --300 1 2

Selecting from the DUAL Table


DUAL is a table automatically created by NuoDB. The DUAL table is accessible by the name DUAL to all users. It resolves to a table with a single row. It appears to be in whatever schema you are using, as well as in the system schema. Selecting from the DUAL table is useful for computing a constant expression with the SELECT statement. Because DUAL has only one row, the constant is returned only once. Alternatively, you can select a constant, pseudocolumn, or expression from any table, but the value will be returned as many times as there are rows in the table. You cannot qualify DUAL with any schema other than the system schema. See the following example select 'test' from dual; select 'system' from system.dual; create schema foo; use foo; select 'foo' from dual; use test; drop schema foo;

Metadata
Schema for describing NuoDB database objects (such as tables, columns, indexes, and others) The schema that has metadata information is the SYSTEM schema. The table that has metadata information is system.tables. To list all the non-system tables in the database, use the following: SQL> select * from system.tables where type <> SYSTEM TABLE The system schema also contains tables that describe columns (system.fields), indexes, views, and others.

Troubleshooting NuoSQL
How to deal with NuoSQL errors Query Connection Closed If you get an SQL error indicating that the query failed because a remote connection closed, restart the chorus and try again. For example, using the Flights database, you get the following message:

SQL> insert into tickets (address) values ('703 main street') remote connection closed

| Copyright 2012 NuoDB, Inc. All rights reserved. | 58

| Programming With NuoDB | 59

remote connection closed socket is broken Restart the chorus as follows:

$ nuodb --chorus Flights &[2] 4051

SQL Workbench/J
How to use SQL Workbench/J with NuoDB 1. To use the SQL Workbench/J Universal SQL client with NuoDB, download and configure SQL Workbench/J a) Download SQL Workbench/J from: http://www.sql-workbench.net b) Install SQL Workbench/J according to the instructions on the website. Note that the steps differ according to platform. 2. Add a driver using the Manage Drivers dialog and configure as required with the following settings as needed: Name Example URL Website URL Extra Class Path Class Name NuoDB jdbc:com.nuodb://localhost/test http://www.nuodb.com /opt/nuodb/li /nuodbjdbc.jar com.nuodb.jdbc.Driver

3. On the Select Connection Profile dialog, use the settings shown:

| Copyright 2012 NuoDB, Inc. All rights reserved. | 59

| Programming With NuoDB | 60

4. Start working with your database. You can browse tables, insert rows, and edit values.

SQuirreL Universal SQL


How to use SQuirreL tool For Java users NuoDB supports both a Hibernate dialect and sample application that makes use of Hibernate and the NuoDB Hibernate dialect. 1. To use the SQuirreL Universal SQL client with NuoDB, download and configure SQuirreL a) Download SQuirreL from: http://sourceforge.net/projects/squirrel-sql b) Install SQuirreL by running the following command java jar <downloaded install file> c) Choose the Base, Standard and Optional Plugin Data Import packs 2. Run SQuirreL using the script that the installer created (typically as a menu or desktop shortcut) 3. Click the Drivers tab, add a new driver, and configure with the following settings: Name Example URL NuoDB jdbc:com.nuodb://localhost/test

| Copyright 2012 NuoDB, Inc. All rights reserved. | 60

| Programming With NuoDB | 61

Website URL Extra Class Path Class Name

http://www.nuodb.com /opt/nuodb/li /nuodbjdbc.jar com.nuodb.jdbc.Driver

4. Create an Alias for NuoDB by clicking the Aliases tab and then clicking Create New Alias. 5. Fill out the Add New Alias dialog. (Note: NuoDB is pre-configured with a UserName/Password of cloud/user): Select Auto logon and Connect at Startup 6. Start working with your database. The following screen capture shows a graphical view of the Flights schema that is part of the NuoDB

installation:

Sample Client Programs


You can find most of the programming samples in the $NUODB_HOME/samples folder. The following table lists the samples. Directory flights Description Simple but comprehensive program showing GUI and other important features of NuoDB. Simple Hello program. Simple Hello program. Sample application that makes use of Hibernate and the NuoDB Hibernate dialect. Include sample application and Gems Language Java

java cpp hibernate

Java C++ Java dialect

jruby

JRuby

Related Links

| Copyright 2012 NuoDB, Inc. All rights reserved. | 61

| Programming With NuoDB | 62

Programming on page 45 Introduction to programming with NuoDB Connections on page 45 NuoDB automatically installs drivers and supports database connections by means of JDBC and ODBC. Client Connections on page 28 The following illustration shows a simple NuoDB chorus and a client that wants to connect to it. SQL Reference Pages on page 87 Syntax, descriptions, and examples for SQL statements JDBC Connection Properties on page 49 Program fragment showing JDBC properties and sample connection URL

C++ Sample Program


Simple Hello program in C++ The sample is in the following file: $NUODB_HOME/samples/cpp 1. Set up libraries as required Options On Linux Description Ensure that LD_LIBRARY_PATH includes /nuodb/ lib64. Go to the /samples/cpp directory and issue the following command: g++ -I../../include HelloDB.cpp ../../lib64/ libNuoRemote.so -o HelloDB NuoDB also requires libuuid.so.1 and libncurses.so.5. On Windows: cd C:\Program Files\NuoDB\samples \cpp copy "C:\program files\NuoDB\bin \NuoRemote.dll" cl/EHsc HelloDB.cpp "c:\program files\NuoDB\lib \NuoRemote.lib" Ensure that DYLD_LIBRARY_PATH includes /nuodb/lib64. Go to the /samples/cpp directory and issue the following command: g++ -I../../include HelloDB.cpp ../../lib64/ libNuoRemote.dylib -o HelloDB

On MAC OS X:

2. Run the built executable > ./HelloDB test@localhost You should see the following output: Name with id of 12: Fred # 12

| Copyright 2012 NuoDB, Inc. All rights reserved. | 62

| Programming With NuoDB | 63

Flights Sample Application


Simple but comprehensive program showing GUI and other important features See the /nuodb/sample/flights directory in the installation area.

JRuby Sample Program


How to run a sample JRuby application and Gems The sample is in the following file: $NUODB_HOME/samples/jruby/sample.rb The following code fragment shows the first several lines of sample.rb: require 'rubygems' require 'active_record' puts "Connecting to database..." ActiveRecord::Base.establish_connection( :adapter => 'nuodb', :database => 'test', :username => 'cloud', :password => 'user' ) The application creates a schema, creates several records using the schema definition, and reads them back. 1. Download and install JRuby (this sample has been tested with JRuby 1.6.5) 2. Set your search path to include the jruby executable. For example: /Library/Frameworks/JRuby.framework/Versions/Current/bin/jruby) 3. In a directory other than the samples directory, install Gems that are required by the sample > gem install activerecord 4. Change your working directory to the samples/jruby subdirectory 5. Install the Gems that are provided by the sample: > gem install jdbc-nuodb-1.0.gem > gem install activerecord-jdbcnuodbadapter-1.0.gem 6. Start up a nuodb chorus (archive node and transaction engine with a "test" database). >java -jar nuoagent.jar --broker --password domain_password &[1] 8236 >nuodb --chorus --password chorus_password test@localhost &[2] 8237 7. Run the sample: jruby sample.rb The results should be as follows: Connecting to database... Create tables... -- drop_table(:sample_users) -- create_table(:sample_users) -> 0.0190s -> -2 rows

| Copyright 2012 NuoDB, Inc. All rights reserved. | 63

| Programming With NuoDB | 64

Create user records... Print user records... Found 2 records: User(1), Username: fred, Name: Fred Flintstone, admin Street: 301 Cobblestone Way City: Bedrock Zip: 00001 User(2), Username: barney, Name: Barney Rubble, member Street: 303 Cobblestone Way City: Bedrock Zip: 00001 Modify user records... Print user records... Found 2 records: User(1), Username: fred, Name: FRED FLINTSTONE, member Street: 301 Cobblestone Way City: Bedrock Zip: 00001 User(2), Username: barney, Name: Barney Rubble, member Street: 303 Cobblestone Way City: Bedrock Zip: 00001 How To Install JRuby Active Record Driver for NuoDB Active Record supports object-relational mapping (ORM), which makes it possible to focus on the business logic of your client application rather than the underlying details of a database. Using the Active Record adapter allows you to use any JDBC-compliant database with a JRuby application. These instructions are for Linux and MAC OS X; use similar steps for Windows. Download, install, and configure RVM (Ruby Version Manager) implemented for JRuby. RVM allows you to install and manage several different versions and implementations of JRuby on one computer, and supports the ability to manage different sets of RubyGems on each. For more information, see About Ruby Version Manager

Working with Hibernate


Information about the Hibernate sample For Java users NuoDB supports both a Hibernate dialect and sample application that makes use of Hibernate and the NuoDB Hibernate dialect. The sample is in the installation area as follows: /samples/hibernate Instructions for building and running the sample are in a file in the same folder: /samples/hibernate/readme.txt file. The hibernate dialect jar file is found in /samples/jar. $NUODB_HOME/jar/nuodb-hibernate-1.0.jar

| Copyright 2012 NuoDB, Inc. All rights reserved. | 64

SQL Language Elements


Topics: Language Elements

| SQL Language Elements | 66

| Copyright 2012 NuoDB, Inc. All rights reserved. | 66

| SQL Language Elements | 67

SQL Language Elements

Language Elements
Reference information about data types, operations, access, variables, indexes, and isolation levels.

Data Types Supported By NuoDB


Describes NuoDB extensions, how character and numeric types are handled, as well as standard data types and domains. NuoDB Extensions Types supported as extensions to the standard. NuoDB supports the following types as extensions to the standard: String is a character string of arbitrary length. Number is a numeric value of arbitrary length and scale. Binary with no length is an arbitrarily long string of bytes. (The standard specifies Binary with no length as a single byte.)

Character and Numeric Types NuoDB handles String types as potentially unlimited in length. NuoDB recommends that you use String instead of char types. There is no storage penalty for using String, so most application developers should use String rather than char or varchar. For varchar character types, NuoDB checks and supports the defined length. NuoDB allows both decimal and numeric values to exceed their defined size. NuoDB does not check the size of a number when performing numeric operations. (According to SQL 2008 standard, numeric values cannot hold more than the number of digits defined.) Characters are all stored in UTF8. NuoDB supports numeric and decimal values up to 19 digits, for any decimal or numeric defined as larger than 9 places, and up to 9 places for anything smaller. Standard Data Types List of keywords of the predefined data types that are supported by SQL 2008 as well as those supported by NuoDB. NOTE TO BETA CUSTOMERS Row types, interval types, explicit precision on time types, and timezone are not supported. NuoDB does not support constructed types, and user-defined types Kind of data type Character string types Basic types CHARACTER CHARACTER VARYING CHARACTER LARGE OBJECT SQL 2008 Keywords supported by NuoSQL character [(<n> [characters])] character varying (<n> [characters]) varchar (<n> [characters])

| Copyright 2012 NuoDB, Inc. All rights reserved. | 67

| SQL Language Elements | 68

Kind of data type

Basic types

SQL 2008 Keywords supported by NuoSQL Character Large Object [(<n>{K | M | G}]) Char Large Object [(<n>{K | M | G}]) CLOB [(<n>{K | M | G}]) National Character [(<n> [characters])] National Char[(<n> [characters])] NChar [(<n> [characters])] National Character Varying (<n> [characters]) National Char Varying (<n> [characters]) National Character Large Object [(<n>{K | M | G})] NChar Large Object [(<n>{K | M | G})] NCLOB [(<n>{K | M | G})]

Binary string types

BINARY BINARY VARYING BINARY LARGE OBJECT

Binary [(<n>)] Binary Varying [(<n>)] Binary Large Object [(<n>{K | M | G})] BLOB [(<n>{K | M | G})]

Exact numeric types

NUMERIC DECIMAL SMALLINT INTEGER BIGINT

number Numeric (<n> [,<n>]) Decimal (<n> [,<n>]) DEC (<n> [,<n>]) SmallInt Integer Int BigInt

Approximate numeric types

REAL DOUBLE PRECISION

Real Double Precision NOTE: NuoDB recommends the use of Double Precision rather than Float.

Boolean type Datetime types

BOOLEAN DATE TIME

boolean date

| Copyright 2012 NuoDB, Inc. All rights reserved. | 68

| SQL Language Elements | 69

Kind of data type

Basic types TIMESTAMP

SQL 2008 Keywords supported by NuoSQL time [(<n>)] [WITH[OUT] TIME ZONE] timestamp [(<n>)] [WITH[OUT] TIME ZONE]

Interval type

INTERVAL

Domains There is a distinction between a NuoDB administrative domain that contains choruses and NuoDB SQL domain Administrative domain A NuoDB administrative domain is a collection of hosts that have been provisioned to work together to support NuoDB processes. The hosts are a set of machines that are under the same physical management. A database runs on a chorus (also a set of machines), which can cross domains. You can have a chorus that is partially local and partially in a cloud. A chorus can span domains and a domain can run all or part of several choruses. Our expectation is that there will be one group of people who are responsible for physically provisioning the domain (e.g the IT staff) and another group who manage databases (DBA's). SQL domain NuoDB SQL supports SQL domains, which support a type of abstraction that can be referenced in many tables. A change to the domain causes a corresponding change in the tables.

Operators and Operations


Describes NuoDB logical and comparison operators. Logical Operators NuoDB supports the following logical operators: AND, OR, NOT. NuoDB uses a three-valued logic system with true, false, and null, which represents unknown. See the following tables. a TRUE TRUE TRUE FALSE FALSE NULL a TRUE FALSE NULL b TRUE FALSE NULL FALSE NULL NULL a AND b TRUE FALSE NULL FALSE FALSE NULL NOT a FALSE TRUE NULL a OR b TRUE TRUE TRUE FALSE NULL NULL

| Copyright 2012 NuoDB, Inc. All rights reserved. | 69

| SQL Language Elements | 70

The operators AND and OR are commutative, that is, you can switch the left and right operand without affecting the result. Comparison Operators Comparison operators are supported for all supported data types. All comparison operators are binary operators that return values of type boolean; expressions like 1 < 2 < 3 are not valid (because there is no < operator to compare a Boolean value with 3). NuoDB supports the comparison operators described in the following table: Operator < > <= >= = BETWEEN In addition to the comparison operators, the special BETWEEN construct is available: a BETWEEN x AND y is equivalent to a >= x AND a <= y Description less than greater than less than or equal to greater than or equal to equal

Notice that BETWEEN treats the endpoint values as included in the range. NOT BETWEEN does the opposite comparison: a NOT BETWEEN x AND y is equivalent to a < x OR a > y To check whether a value is or is not null, use the constructs: expression IS NULL expression IS NOT NULL NOTE: Do not write expression = NULL because NULL is not "equal to" NULL. (The null value represents an unknown value, and it is not known whether two unknown values are equal.) This behavior conforms to the SQL standard. BETWEEN Conditional Expression Specify fields based on values within a specified range Synopsis [NOT] BETWEEN startpoint AND endpoint where startpoint defines the first value in the range and endpoint defines the last value in the range.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 70

| SQL Language Elements | 71

Description The BETWEEN conditional expression is true if the first value expression is between the second and third value expression, or equal to one of them. If you precede the BETWEEN expression with the optional NOT qualifier, the condition is true if there are no fields with values within the range you specify (with the second and third value expression). Examples The following example demonstrates the use of the BETWEEN conditional expression with a numeric field. Select rows from the hockey table, choosing numbers where the value for number contains a value greater than or equal to 10 and less than or equal to 20. SQL> select number from hockey where number between 10 and 20; NUMBER ------11 18 17 20 19 14

Character String Comparison Character string comparison operators are described in the following table: Operator = Usage 'string' = 'comparison' Description A comparison returning true if string matches comparison identically Identical to the != operator A comparison returning true if string should be sorted alphabetically before comparison A comparison returning true if string should be sorted alphabetically before comparison, or if the values are identical A comparison returning true if string should be sorted alphabetically after comparison A comparison returning true if string should be sorted alphabetically after comparison, or if the values are identical

<> <

'string' <> 'comparison' 'string' < 'comparison'

<=

'string' <= 'comparison'

>

'string' > 'comparison'

>=

'string' >= 'comparison'

NOTE: NuoDB does not support the != comparison operator NuoDB supports the LIKE and ILIKE keywords, which call the like() function, and are sometimes referred to as string comparison operators.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 71

| SQL Language Elements | 72

LIKE | NOT LIKECondition Perform pattern matching. The LIKE condition allows you to use wild cards in the WHERE clause of SELECT, INSERT, UPDATE, or DELETE statements. This allows you to perform pattern matching. The LIKE condition can be used in any valid SQL statement. The patterns that you can choose from are: % (percent sign) allows you to match any string of any length (including zero length) _ (underscore) allows you to match on a single character

Examples How to find all team members who play defense.

SQL> select * from hockey where position like 'D%'; NUMBER NAME POSITION TEAM ------- ----------------- --------- -----43 55 33 14 21 47 54 44 MATT BARTKOWSKI JOHNNY BOYCHUK ZDENO CHARA JOE CORVO ANDREW FERENCE STEVEN KAMPFER ADAM MCQUAID DENNIS SEIDENBERG Defense Defense Defense Defense Defense Defense Defense Defense Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins

Find team members who are not forwards.

SQL> select * from hockey where position not like 'Forward'; NUMBER NAME POSITION TEAM ------- ----------------- --------- -----43 55 33 14 21 47 54 44 40 30 1 MATT BARTKOWSKI JOHNNY BOYCHUK ZDENO CHARA JOE CORVO ANDREW FERENCE STEVEN KAMPFER ADAM MCQUAID DENNIS SEIDENBERG TUUKKA RASK TIM THOMAS MAX SUMMIT Defense Defense Defense Defense Defense Defense Defense Defense Goalie Goalie Fan Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins

Find team members with numbers in the 40's.

SQL> select * from hockey where number like '4_'; NUMBER NAME POSITION TEAM ------- ----------------- --------- -----46 49 43 47 DAVID KREJCI RICH PEVERLEY MATT BARTKOWSKI STEVEN KAMPFER Forward Forward Defense Defense Bruins Bruins Bruins Bruins

| Copyright 2012 NuoDB, Inc. All rights reserved. | 72

| SQL Language Elements | 73

44 40

DENNIS SEIDENBERG TUUKKA RASK

Defense Goalie

Bruins Bruins

CONTAINING Operator String comparison Synopsis string CONTAINING | NOT CONTAINING pattern

Description Generates a case-insensitive search for a partial match. Examples Select names that contain a specific letter. SQL> use hockey; SQL> select * from hockey; NUMBER NAME POSITION TEAM ------- ----------------- --------- -----37 11 38 18 23 46 17 63 20 49 67 91 19 22 43 55 33 14 21 47 54 44 40 30 1 PATRICE BERGERON GREGORY CAMPBELL JORDAN CARON NATHAN HORTON CHRIS KELLY DAVID KREJCI MILAN LUCIC BRAD MARCHAND DANIEL PAILLE RICH PEVERLEY BENOIT POULIOT MARC SAVARD TYLER SEGUIN SHAWN THORNTON MATT BARTKOWSKI JOHNNY BOYCHUK ZDENO CHARA JOE CORVO ANDREW FERENCE STEVEN KAMPFER ADAM MCQUAID DENNIS SEIDENBERG TUUKKA RASK TIM THOMAS MAX SUMMIT Forward Forward Forward Forward Forward Forward Forward Forward Forward Forward Forward Forward Forward Forward Defense Defense Defense Defense Defense Defense Defense Defense Goalie Goalie Fan Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins Bruins

SQL> select name from hockey where name containing 'O'; NAME ---------------PATRICE BERGERON GREGORY CAMPBELL JORDAN CARON NATHAN HORTON BENOIT POULIOT SHAWN THORNTON

| Copyright 2012 NuoDB, Inc. All rights reserved. | 73

| SQL Language Elements | 74

MATT BARTKOWSKI JOHNNY BOYCHUK ZDENO CHARA JOE CORVO TIM THOMAS

String Concatenation

Function string || string

Return Type string

Description String concatenation. Use the text concatenation operator (||) to format output results. Use it anywhere a constant value is allowed in an SQL statement. Values may be repeatedly concatenated in a single statement by appending the || operator after each appended string constant or identifier.

Numeric Operations Describes NuoDB extensions, how character and numeric types are handled, as well as standard data types and domains. NuoDB supports the following kinds of numeric operators:: Mathematical operators Numeric comparison operators Mathematical operators affect one or two values, perform a mathematical operation, and return a value of a numeric data type. Numeric comparison operators draw a conclusion based on two numeric values (such as whether one is larger than the other) and returns a value of type boolean, set to either true or false.

Mathematical operators You can use mathematical operators in the target list, in the WHERE clause of a SELECT statement, or anywhere else a numeric result may be appropriate. This sometimes will include the ORDER BY clause, a JOIN qualifier, or a GROUP BY clause. See the following table for a list of the mathematical operators supported by NuoDB. Operator + * / % Usage a +b a -b a *b a /b a %b Description Addition of numeric quantities a and b Subtraction of numeric quantity b from a Multiplication of numeric quantities a and b Division of numeric quantity a by b Modulus, or remainder, from dividing a by b

Numeric comparison operators Use comparison operators to compare values of types such as integer to one another. They always return a value of type boolean.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 74

| SQL Language Elements | 75

These operators are most commonly used in the WHERE clause, but may be used anywhere in a SQL statement where a value of type boolean would be valid. Operator < > <= >= = != Description Less-than, returns true if the value to the left is smaller than the value to the right Greater-than, returns true if the value to the left is greater than the value to the right Less-than or equal-to, returns true if the value to the left is smaller, or equal to, in quantity than the value to the right Greater-than or equal-to, returns true if the value to the left is greater, or equal to, in quantity than the value to the right Equal-to, returns true if the values to the left and right of the operator are equivalent Not equal-to

Expressions
Describes value and conditional expressions. Value Expressions A type cast specifies a conversion from one data type to another. NuoDB supports type cast according to the following syntax: CAST (expression AS type) CAST value AS data_type CAST (arrivalDate AS string) Conditional Expressions NuoDB supports CASE, COALESCE, NULLIF, and IN as described in the following table: CASE CASE WHEN condition THEN result [WHEN ...] [ELSE result] END Use a CASE clause wherever an expression is valid. condition is an expression that returns a boolean result. If the result is true, then the value of the CASE expression is the result that follows the condition. If the result is false, any subsequent WHEN clauses are searched in the same manner. If no WHEN condition is true then the value of the case expression is the result in the ELSE clause. If the ELSE clause is omitted and no condition matches, the result is null. COALESCE COALESCE(value [, ...]) Returns the first of its arguments that is not null.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 75

| SQL Language Elements | 76

Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display. Like a CASE expression, COALESCE will not evaluate arguments that are not needed to determine the result (that is, arguments to the right of the first non-null argument are not evaluated). NULLIF NULLIF(value1, value2) Returns a null value if value1 and value2 are equal; otherwise it returns value1 Checks if the specified column data is a member of the specified list. It can be used with WHERE, CHECK, and creation of views.

IN

WHERE coldata IN (x1,x2,x3,...) is equivalent to the following: WHERE (coldata=x1 or coldata=x2 or coldata=x3).

Date and Time Functions


Syntax and examples of date and time functions. The following table describes support for date and time functions Purpose of function Implementation Example of Usage in NuoDB

Current date Implemented as 'today' SQL> create table BirthDates (Name string, BirthDate date); 'yesterday' SQL> insert into BirthDates values and ('Glenn','today'sele); 'tomorrow' SQL> select * from BirthDates are also ; supported NAME BIRTHDATE ----- ---------Glenn 2012-02-28 Implemented SQL> create table T1 (f1 date, f2 date, f3 date, f4 Difference integer, f5 integer, f6 integer); between two as date SQL> insert into T1 (f1, f2, f3) values ('today', arithmetic. dates. 'tomorrow', 'yesterday'); SQL> select * from T1; F1 F2 F3 F4 F5 F6 ---------- ---------- ---------- ------ ------ -----2012-02-28 2012-02-29 2012-02-27 <null> <null> <null>

| Copyright 2012 NuoDB, Inc. All rights reserved. | 76

| SQL Language Elements | 77

Purpose of function

Implementation Example of Usage in NuoDB SQL> update T1 set f4=f2-f1; SQL> select f4, f5, f6 from T1; F4 F5 F6 --- ------ -----1 <null> <null>

Calculate a Use new date by arithmetic adding an symbols interval to an existing date Current Timestamp Implemented as now'.

SQL> select f1, f1+4 as FourDaysFromNow from T1; F1 FOURDAYSFROMNOW ---------- ---------------2012-02-28 2012-03-03

SQL> create table ChangeLog (Name string, Change string, When timestamp); SQL> insert into ChangeLog values ('me', 'everything', 'now'); SQL> select * from ChangeLog; NAME CHANGE WHEN ----- ---------- ------------------me everything 2012-02-28 13:23:02

Calculate a new timestamp using cast function

SQL> select cast('now' as timestamp) from dual; ------------------2012-02-28 13:30:37

QUARTER(date), Not Return standard. quarter for Not date. supported WEEK(date), Return week of year for date. Not standard. Not supported

DAYNAME(date) Not Return day supported of week for date. DAYOFMONTH(date) Not Return day supported of month for date. DAYOFYEAR(date) Not Return day supported

| Copyright 2012 NuoDB, Inc. All rights reserved. | 77

| SQL Language Elements | 78

Purpose of function of year for date.

Implementation Example of Usage in NuoDB

MONTH(date), Not Return standard. month of Not year for supported date. NOTE TO BETA USERS NuoDB SQL does not yet implement the interval data type and does not accept numbers with fractional components with time/data arithmetic.

Object Privileges
Become the administrator (owner) of a database when you create the first transaction engine for it. A password is required for users of NuoDB SQL. The first user is known as the database administrator. Use the --dba-user and --dba-password option to make these specifications when you start the first transaction engine and then use them as needed. After you launch the first transaction engine, start NuoDB SQL as the database administrator to create new users and privileges.

Transactions
NuoDB supports several levels of transaction isolation and is based on Multi-Version Concurrency (MVCC). Multi-Version Concurrency (MVCC) is a form of concurrency control that uses multiple versions of records to provide a consistent view of the data to each transaction and to prevent concurrent transactions from overwriting each other's changes. Under MVCC, readers do not block writers, and vice-versa. NuoDB supports the following isolation levels. Note that READ_WRITE and READ_ONLY must be specified explicitly by the transaction statement. Name of Isolation Level CONSISTENT_READ Description Each transaction sees the state of the database as it was when the transaction started, plus changes made by that transaction. Each transaction sees the state of the database as it was when the transaction started, plus its own changes, except in the case of a SELECT FOR UPDATE. Performance Tradoffs and Comments CONSISTENT_READ produces more update conflicts, but provides complete isolation from changes made by other transactions. WRITE_COMMITTED maintains the complete isolation of each transaction for simple SELECT statements, but can breach the isolation for SELECT FOR UPDATE, update, and delete statements. In an update intensive application, WRITE_COMMITTED transactions get fewer errors on update than CONSISTENT_READ transactions. READ_COMMITTED transactions offer no guarantee of isolation, but are very familiar to users of database systems that do not implement concurrency through

WRITE_COMMITTED

READ_COMMITTED

A transaction always reads the most recently committed version of a record.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 78

| SQL Language Elements | 79

Name of Isolation Level

Description

Performance Tradoffs and Comments MVCC. For applications that must run on multiple database systems, including those that are not based on MVCC, the READ_COMMITTED level provides compatible behavior.

AUTOCOMMIT

For JDBC connections, NuoDB automatically issues a commit at the end of each statement. A transaction may select, insert, update, and delete records, subject to the privileges granted to the user for that table A transaction may select only records; it cannot insert, update, or delete records, regardless of the privileges granted to the user.

If your JDBC application requires that several changes succeed or fail as a group, you must explicitly set AUTOCOMMIT off.

READ_WRITE

May be specified explicitly for a transaction.

READ_ONLY

May be specified explicitly for a transaction.

CONSISTENT_READ When a transaction running at the CONSISTENT_READ isolation level attempts to update or delete a record that has been changed by a concurrent transaction, it waits for the other transaction to complete. When it completes, the waiting transaction succeeds in its update only if the previous transaction rolled back. Otherwise, the waiting transaction gets an error. How the waiting transaction handles the error depends on the logic of the application. If the logic requires updating that particular record, then the application must rollback the transaction that got the error and retry it. If not, then the transaction can succeed. For example, at the CONSISTENT_READ isolation level, the following transaction query gets the same value back, even if other transactions have updated the value of seatsAvailable. select seatsAvailable from flights where flightNumber = 23 and flightDate = 'today' Note: The CONSISTENT_READ isolation level is the same as SERIALIZABLE, a name that is used in the SQL standard. WRITE_COMMITTED Applications that depend on updating the same record repeatedly are difficult to run at CONSISTENT_READ isolation level because there are frequent failures because of conflicting updates. For example, an application that assigns unique part numbers by incrementing a master part number generator gets frequent update conflicts. NuoDB offers WRITE_COMMITTED, which is a lower level of transaction isolation that avoids update conflicts at the expense of read consistency. When a transaction in WRITE_COMMITTED isolation level executes a SELECT FOR UPDATE statement and the record being selected has been updated by a concurrent transaction, it waits for the first transaction to complete, then, if the transaction commits, it reads the newest version of the record.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 79

| SQL Language Elements | 80

So, for example, the NuoDB sample flights application could keep a single value for the number of seats available on a flight and reduce it by one each time a seat is booked. Suppose the following query returns a value of 45 for a particular transaction. select seatsAvailable from flights where flightNumber = 23 and flightDate = 'today' Suppose the same transaction runs the same query except it adds a "for update" qualifier. select seatsAvailable from flights where flightNumber = 23 and flightDate = 'today' for update In this case the query might return 44, that is, the FOR UPDATE leads to a different result. Here's why the results differ: At the CONSISTENT_READ isolation level, when a transaction issues the same query more than once, it gets the same results, unless the transaction itself has made change that affects the query. At the WRITE_COMMITTED isolation level, SELECT queries in a transaction also return consistent results aside from changes that it made, except if SELECT queries have a FOR UPDATE qualifier. If FOR UPDATE is specified as part of the transaction, and there is a record that has been changed by a concurrent transaction, the reader waits for the update to complete, then reads the most recently committed record version. In other words, it "looks ahead" and finds a value it depends on and waits for that value to be updated.

For example, at the WRITE_COMMITTED level, the following update statement waits for any concurrent changes to be committed, then applies the update to the most recent version of the record. l update flights set seatsAvailable = seatsAvailable - 1 where flightNumber = 23 and flightDate = 'today' In the same situation, a CONSISTENT_READ transaction would get an update conflict error. The WRITE_COMMITTED level trades absolute consistency for higher throughput in update-intensive applications. Note: NuoDB supports an alternative method of creating unique values, called SEQUENCES, which is defined by the SQL standard. READ_COMMITTED NuoDB also supports a transaction isolation level called READ_COMMITTED. At this level, a transaction always reads the most recently committed version of a record. The following query could return 45 the first time it is run in a transaction, 43 the next time, and 25 the third time, depending on the number of times the record was updated between the running of the statement. select seatsAvailable from flights where flightNumber = 23 and flightDate ='today' For data such as seats available in a flight-booking application, these results are good. For a different application, such as one that reconciles financial accounts, having values change during the life span of a transaction makes it almost impossible to generate consistent results. At the READ_COMMITTED isolation level, NuoDB handles update conflicts in the same way that it handles them at the WRITE_COMMITTED level. That is, when a transaction attempts to update a record that was updated by a concurrent transaction, it waits for that transaction to commit, then updates the most recent version of the record.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 80

| SQL Language Elements | 81

AUTOCOMMIT The JDBC Specification requires that default transactions be executed at the AUTOCOMMIT level, meaning that each statement ends in an implicit commit. At this level, update conflicts and deadlocks are less frequent than when a transaction must be explicitly ended. However, an autocommit transaction can not guarantee that two related changes succeed or fail together. If the application requires that a deposit in one account matches with a withdrawal from another account, it should set AUTOCOMMIT off or risk inconsistent results. Note: Use SHOW AUTOCOMMIT to display the current status of AUTOCOMMIT as an isolation level. READ_WRITE and READ_ONLY NuoDB accepts qualifiers that specify the operations allowed by a transaction, such as READ_WRITE and READ_ONLY. Errors In all three isolation levels, errors on the database side are returned to the application, which decides whether to rollback the transaction. As long as the application maintains its connection with the NuoDB database, it maintains control of its transactions. If NuoDB discovers that it has lost its connection with an application, changes made by uncommitted transactions belonging to that application are rolled back. Defaults NuoSQL statements execute only in the context of a transaction. If there is no active transaction when an application issues a statement to NuoDB, it creates a transaction at the CONSISTENT_READ isolation level with a qualifier of READ_WRITE: this means that the transaction can both read and change records. For applications that use the JDBC interface, the transaction is also in AUTOCOMMIT level, meaning that NuoDB automatically issues a commit at the end of each statement. If your JDBC application requires that several changes succeed or fail as a group, you must explicitly set autocommit level off. Performance Tradeoffs The performance of the three isolation levels is approximately equivalent. Related Links SHOW on page 120 Display information about schemas, tables, domains, and status of AUTOCOMMIT isolation level.

Domains
There is a distinction between a NuoDB administrative domain that contains choruses and NuoDB SQL domain Administrative domain A NuoDB administrative domain is a collection of hosts that have been provisioned to work together to support NuoDB processes. The hosts are a set of machines that are under the same physical management. A database runs on a chorus (also a set of machines), which can cross domains. You can have a chorus that is partially local and partially in a cloud. A chorus can span domains and a domain can run all or part of several choruses. Our expectation is that there will be one group of people who are responsible for physically provisioning the domain (e.g the IT staff) and another group who manage databases (DBA's).

| Copyright 2012 NuoDB, Inc. All rights reserved. | 81

| SQL Language Elements | 82

SQL domain NuoDB SQL supports SQL domains, which support a type of abstraction that can be referenced in many tables. A change to the domain causes a corresponding change in the tables.

Clauses and Functions


CHAR_LENGTH Function Returns the number of characters or bytes in a specified string Synopsis CHAR[ACTER]_LENGTH (string[USING [CHARACTERS|OCTETS]]) Parameters string USING CHARACTERS USING OCTETS Examples Discover rows in hockey table that do not have names specified. SQL> select number, name from hockey where (CHAR_LENGTH(name)=0); NUMBER NAME ------- ----0 52 Either a quoted string or a column of string type (such as CHAR, VARCHAR, or others) Returns the number of characters in the string () Returns number of bytes in the string.

SUBSTR Function Selects all characters beginning at a specified position until the end of the string (or for an optionally provided length). Synopsis SUBSTR(str, pos [,len]) Description SUBSTR(str, pos) SUBSTR(str, pos, len) Examples Select names of hockey players who are goalies. SQL> select name from hockey where (substr(position,1)='Goalie'); NAME ----------Select all characters in the string starting at position pos. Select all characters in the string starting at pos and continuing len number of characters.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 82

| SQL Language Elements | 83

TUUKKA RASK TIM THOMAS

| Copyright 2012 NuoDB, Inc. All rights reserved. | 83

| SQL Language Elements | 84

| Copyright 2012 NuoDB, Inc. All rights reserved. | 84

SQL Reference Pages


Topics: SQL Reference Pages

| SQL Reference Pages | 86

| Copyright 2012 NuoDB, Inc. All rights reserved. | 86

| SQL Reference Pages | 87

SQL Reference Pages


SQL Reference Pages
Syntax, descriptions, and examples for SQL statements Related Links Programming on page 45 Introduction to programming with NuoDB Connections on page 45 NuoDB automatically installs drivers and supports database connections by means of JDBC and ODBC. Client Connections on page 28 The following illustration shows a simple NuoDB chorus and a client that wants to connect to it.

ALTER DOMAIN
Change definition of a domain (not yet implemented) Synopsis ALTER DOMAIN name { SET DEFAULT expression | DROP DEFAULT } ALTER DOMAIN name { SET | DROP } NOT NULL ALTER DOMAIN name ADD domain_constraint [ NOT VALID ] ALTER DOMAIN name DROP CONSTRAINT constraint_name [ RESTRICT | CASCADE ] ALTER DOMAIN name VALIDATE CONSTRAINT constraint_name ALTER DOMAIN name OWNER TO new_owner ALTER DOMAIN name SET SCHEMA new_schema NOTE TO BETA CUSTOMERS ALTER DOMAIN has not yet been fully implemented. Description ALTER DOMAIN changes the definition of an existing domain. You must own the domain to use ALTER DOMAIN. To alter the owner, you must also be a direct or indirect member of the new owning role, and that role must have CREATE privilege on the domain's schema. These restrictions enforce that altering the owner does not do anything you would not be able to do by dropping and recreating the domain. NuoDB supports the following forms: SET | DROP DEFAULT Sets or removes the default value for a domain. Defaults only apply to subsequent INSERT commands; they do not affect rows that are already in a table using the domain.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 87

| SQL Reference Pages | 88

SET |DROP NOT NULL

Changes whether or not a domain is specified to allow NULL values or to reject NULL values. You can only use SET NOT NULL if the columns using the domain contain no null values. Adds a new constraint to a domain using the same syntax as CREATE DOMAIN.

ADD domain_constraint [ NOT VALID ]

You can suppress the checks NuoDB always checks newly inserted or updated rows against all by adding the new constraint constraints, even those marked NOT VALID. NOT VALID is only (domain_constraint) using the NOT accepted for CHECK constraints. VALID option. Later you can make it valid using ALTER DOMAIN ... VALIDATE CONSTRAINT. DROP CONSTRAINT VALIDATE CONSTRAINT Drops constraints on a domain. Validates a constraint previously added as NOT VALID, that is, verifies that all data in columns that use the domain satisfy the specified constraint. Changes the owner of the domain to the specified user. Changes the schema of the domain. Also moves any constraints associated with the domain into the new schema.

OWNER SET SCHEMA

Parameters name domain_constraint constraint_name NOT VALID CASCADE RESTRICT new_owner new_schema Notes ALTER DOMAIN, ADD CONSTRAINT , and ALTER DOMAIN SET NOT NULL fail if the named domain (or any derived domain) is used within a composite-type column of any table in the database. Examples To add a NOT NULL constraint to a domain To remove a NOT NULL constraint from a domain To add a check constraint to a domain ALTER DOMAIN zipcode SET NOT NULL; ALTER DOMAIN zipcode DROP NOT NULL; ALTER DOMAIN zipcode ADD CONSTRAINT zipchk CHECK (char_length(VALUE) = 5); The name (possibly schema-qualified) of an existing domain to alter. New domain constraint for the domain. Name of an existing constraint to drop. Do not verify existing column data for constraint validity. Automatically drop objects that depend on the constraint. Refuse to drop the constraint if there are any dependent objects. This is the default behavior. The user name of the new owner of the domain. The new schema for the domain.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 88

| SQL Reference Pages | 89

To remove a check constraint from a domain To move the domain into a different schema

ALTER DOMAIN zipcode DROP CONSTRAINT zipchk; ALTER DOMAIN zipcode SET SCHEMA customers;

ALTER SEQUENCE
Change definition of a sequence Synopsis ALTER SEQUENCE sequence START [WITH] value Parameters sequence value Description ALTER SEQUENCE changes the starting value of an existing sequence. Refer to CREATE SEQUENCE for a further description of valid arguments. NOTE TO BETA CUSTOMERS ALTER SEQUENCE does not work in Beta 6. Examples To change the starting value for an existing sequence alter sequence nextCustomer start with 300; The name of an existing sequence to alter. New starting value for sequence.

ALTER TABLE
Change definition of a table Synopsis ALTER TABLE name ADD PRIMARY KEY column_name... Description ALTER TABLE changes the definition of an existing table. To change the schema of a domain, you must also have CREATE privilege on the new schema. Use ALTER TABLE to add a new PRIMARY KEY to a table. If PRIMARY KEY is specified, and the columns are not already marked NOT NULL, then ALTER TABLE attempts to do set them to NOT NULL. IMPORTANT You can use ALTER TABLE DROP COLUMN to drop a column, but only if you drop all constraints that include the column. Otherwise the column is dropped but the constraints are not dropped, and further operations on the table fail. You cannot drop a column that is part of an index unless the index has been removed.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 89

| SQL Reference Pages | 90

Parameters name column_name The name (possibly schema-qualified) of an existing table to alter. Name of a new or existing column.

ALTER TRIGGER
Change definition of a trigger Synopsis ALTER TRIGGER trigger_name for table_name [ ACTIVE ] | Parameters trigger_name table_name Description Use ALTER TRIGGER to specify whether a trigger should be activated or not. You must own the table to enable or disable triggers associated with it. ACTIVE enables a trigger, and INACTIVE disables a trigger. Refer to CREATE TRIGGER for a further description of valid arguments. Examples Disable a trigger alter trigger customer_audit_trigger for customer inactive; The name of an existing trigger to alter. The name of the table on which this trigger acts. [ INACTIVE ]

ALTER USER
Change definition of a user Synopsis ALTER USER username PASSWORD password Use ALTER USER to change the attributes of a NuoDB user account. Attributes that are not specified in the command retain their previous settings. Only a database owner can change privileges and password expiration with this command. NOTE TO BETA USERS Users are not currently allowed to change their own passwords. Parameters username password The name of the user whose attributes are to be altered. The new password to be used for this account.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 90

| SQL Reference Pages | 91

Notes Use CREATE USER to add new users, and DROP USER to remove a user. Examples Change a user password ALTER USER davide PASSWORD 'hu8jmn3';

COMMIT
Commit the current transaction Synopsis COMMIT [ WORK ] Parameters WORK is an optional keyword that has no effect. Description COMMIT commits the current transaction. All changes made by the transaction become visible to others and are guaranteed to be durable if a crash occurs. Use ROLLBACK to stop and undo a transaction. You can rollback to a save point, but you cannot commit a save point. A COMMIT implicitly releases all named save points. See SAVEPOINT for more information. Examples To make all changes permanent commit work;

Related Links Transactions on page 78 NuoDB supports several levels of transaction isolation and is based on Multi-Version Concurrency (MVCC).

CREATE DATABASE
Use NuoDB Console to create and drop databases; you cannot use NuoSQL for this purpose. Related Links What is NuoDB Console? Overview of Configuration Tools on page 33 Using command-line tools as well as NuoDB Console to configure NuoDB Use NuoDB Console on page 10 How to start NuoDB Console and view the QuickStart processes.

CREATE DOMAIN
Define a new domain Synopsis CREATE DOMAIN domain_name [AS] data_type

| Copyright 2012 NuoDB, Inc. All rights reserved. | 91

| SQL Reference Pages | 92

[ [NOT] NULL ] [ DEFAULT default_value ] Parameters domain_name data_type DEFAULT default_value The name (optionally schema-qualified) of a domain to be created. The underlying data type of the domain. The DEFAULT clause specifies a default value for columns of the domain data type. The value is any variable-free expression (but subselects are not allowed). The data type of the default expression must match the data type of the domain. NuoDB uses the default expression in any insert operation that does not specify a value for the column. If there is no default for a domain, then the default is NULL. Note: If a default value is specified for a particular column, it overrides any default associated with the domain. In turn, the domain default overrides any default value associated with the underlying data type.

Description Use CREATE DOMAIN to register a new data domain for use in the current database. The user who defines a domain becomes its owner. Usage Domains are useful for specifying as an abstraction common columns between tables into a single location for maintenance. Examples Create two domains that are used in the flight example. Create and use a domain for product names. create domain airport_code string; create domain airline_code string; create domain Identifier number; create domain name_type char(50) default 'NuoDB'; create table company (name name_type, product name_type); insert into company (product) values ('one'),('two'); select * from company; name ----'NuoDB' 'NuoDB' product -------one two

CREATE INDEX
Define a new index Synopsis CREATE [ UNIQUE ] INDEX index_name ON table ( column [, ...] )

| Copyright 2012 NuoDB, Inc. All rights reserved. | 92

| SQL Reference Pages | 93

Parameters index_name The name of the index to be created. No schema name can be included here; the index is always created in the same schema as its parent table. The name (possibly schema-qualified) of the table to be indexed. Causes the system to check for duplicate values in the table when the index is created (if data already exist) and each time data is added. Attempts to insert or update data which would result in duplicate entries generates an error. The name of a column of the table.

table UNIQUE

column Description

CREATE INDEX constructs an index index_name on the specified table. NuoDB provides B-tree access for indexes. Use DROP INDEX to remove an index. Examples`` Define an index based on five columns of the flights table. create index flt_idx on flights (origin, destination, flight_date, scheduled_departure);

CREATE PROCEDURE
Return the exact string to use to recreate a stored procedure (Not Yet Implemented) NOTE TO BETA CUSTOMERS CREATE PROCEDURE is not implemented. Synopsis CREATE PROCEDURE proc_name Description Examples

CREATE ROLE
Define a new database role Synopsis CREATE ROLE name Description A user gains privileges by assuming one or more roles, as permitted by the DBA.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 93

| SQL Reference Pages | 94

CREATE ROLE adds a new role to a NuoDB database. A role is an entity that can own database objects and have database privileges. It is recommended that you create roles with privileges and assign roles to users, rather than assign privileges directly to users. You must be a database owner to use the CREATE ROLE command. Parameters name Notes To change the attributes of a role, use DROP ROLE to remove a role and create a new one. The recommended approach to add and remove members of roles that are being used as groups is to use GRANT and REVOKE. Examples Create a role for data base administrator. create role dba; The name of the new role.

CREATE SCHEMA
Define a new schema Synopsis CREATE SCHEMA [schemaname] Parameters schemaname The name of a schema to be created. If not specified, by default the name is USER.

Description CREATE SCHEMA enters a new schema into the current database. The schema name must be distinct from the name of any existing schema in the current database. If you create a table, view, domain, or sequence, and you wish to use the current schema you do not have to specify the schema explicitly. A schema is essentially a namespace; it contains named objects (tables, data types, functions, and operators) whose names may duplicate those of other objects existing in other schemas. Named objects are accessed either by "qualifying" their names with the schema name as a prefix, or by setting a search path that includes the desired schema(s). Unqualified objects are created in the current schema. Notes To create a schema, the you must have CREATE privilege for the current database. Owners of the database bypass this requirement. Use DROP SCHEMA to remove a schema.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 94

| SQL Reference Pages | 95

Examples Create a schema create schema newSchema

CREATE SEQUENCE
Define a new sequence Synopsis CREATE SEQUENCE seqname Description CREATE SEQUENCE enters a new sequence number into the current database starting with a specified value. A sequence is a source of unique values. This command supports a mechanism in the database that creates unique numbers automatically, a mechanism which is called a SEQUENCE in the SQL Standard. To avoid interference between transactions, sequences are outside transaction control. You can also use the GENERATED ALWAYS AS IDENTITY clause to create a sequence for a table when you create it. In this case NuoDB creates a sequence for the table and assigns the next value for the sequence regardless of the value passed in the INSERT statement. Dropping the table makes the sequence go away. Examples Create a sequence called customerUpdate starting at 101 Get the next value for a sequence named customerUpdate to use in an update operation create sequence customerUpdate start with 101; [ START WITH value]

update customers set address = '13 Main Street', updateTag = next value for customerUpdate where lastName = 'Joe Smith';

Create Tickets table using GENERATED ALWAYS AS IDENTITY clause for the ticket_id

create table Tickets ( ticket_id Identifier not null generated always as identity primary key, trip_id Identifier references Trips, flight_id references Flights, sequence number ); Identifier

CREATE TABLE
Define a new table Synopsis CREATE TABLE [schema_name.]table_name ( { column_name {

| Copyright 2012 NuoDB, Inc. All rights reserved. | 95

| SQL Reference Pages | 96

data_type | domain } [ DEFAULT default_expr ] [ column_constraint [, ... ] ] } [, ... ] ) where column_constraint is: { GENERATED ALWAYS AS IDENTITY | NOT NULL | NULL | CHECK (expression) | REFERENCES reftable [ ( refcolumn ) ] [ ON DELETE action ] } Description CREATE TABLE creates a new, initially empty table in the current database. The table is owned by the user issuing the command. If a schema name is specified (for example, CREATE TABLE myschema.mytable ...) then the table is created in the specified schema. Otherwise it is created in the default schema. A table cannot have more than 32000 columns. (In practice, the effective limit is lower because of recordlength constraints). GENERATED ALWAYS AS IDENTITY clause You can use the GENERATED ALWAYS AS IDENTITY clause to create a sequence for a table when you create it. In this case NuoDB creates a sequence for the table and assigns the next value for the sequence regardless of the value passed in on the INSERT statement. Dropping the table makes the sequence go away. You can also specify an identity name, as shown: SQL> create table t1 (f1 integer generated always as identity (i1)); SQL> select * from system.sequences; SCHEMA SEQUENCENAME ------- ------------AWH I1

Parameters table_name column_name data_type domain DEFAULT default_expr The name (optionally schema-qualified) of the table to be created. The name of a column to be created in the new table. The data type of the column. The data type specifies the length and scale factor for the column. The name of a domain that defines the characteristics of this column The DEFAULT clause assigns a default value for the column. The value expression, default_expr, cannot include a variable,

| Copyright 2012 NuoDB, Inc. All rights reserved. | 96

| SQL Reference Pages | 97

subselect or cross-references to other columns in the current table. The data type of the default expression must be comparable with the data type of the column. For example, the default expression for a numeric value must evaluate to a number, and the default expression for a timestamp must evaluate to a timestamp. The default expression is used in any insert operation that does not specify a value for the column. If there is no default for a column, then the default is NULL, unless the column is constrained to be NOT NULL, in which case a value must be supplied for the column. NOT NULL NULL CHECK (expression) The column is not allowed to contain NULL values. The column is allowed to contain NULL values. This is the default. CHECK clauses specify integrity constraints or tests that must be satisfied by new or updated rows to enable an insert or update operation to succeed. CHECK constraints are satisfied if they resolve to 'true' or 'unknown'. Each constraint must be an expression producing a Boolean result. A condition appearing within a column definition should reference that column's value only, while a condition appearing as a table constraint may reference multiple columns. CHECK expressions cannot contain sub-selects nor refer to variables other than columns of the current row.

CREATE TRIGGER
Define a new trigger Synopsis CREATE TRIGGER name [FOR] table { [ BEFORE | AFTER ] event } [ POSITION number ] [ ACTIVE | INACTIVE ] AS [ statements ] END_TRIGGER NOTE TO BETA CUSTOMERS POSITION number is not implemented. If multiple triggers of the same kind are defined for the same event, they are fired in random order. Parameters name The name to give the new trigger. This must be distinct from the name of any other trigger for the same table. The name of the table the trigger is for.

table

| Copyright 2012 NuoDB, Inc. All rights reserved. | 97

| SQL Reference Pages | 98

event number statements

The operation that causes the trigger to fire. One of INSERT, DELETE or UPDATE. Specifies the order in which a trigger executes on a given table. Definition of actions to perform as part of the trigger. One or more of the following: INSERT UPDATE DELETE IF ( boolean_expression ) statements [ ELSE statements ] END_IF THROW string_expression

SELECT does not modify any rows so you can not create SELECT triggers. Use views instead of triggers. ACTIVE enables a trigger, and INACTIVE disables a trigger. Description CREATE TRIGGER enters a new trigger into the current database. A trigger is a database object that is attached to a table. It is fired only when an INSERT, UPDATE or DELETE occurs. You specify the modification action(s) that fire the trigger when it is created. NuoDB automatically executes a batch of SQL code when the trigger is fired. The trigger can be specified to fire before the specified action is attempted, or after the specified action (event) has occurred: Before the operation is attempted Before an operation means before constraints are checked, as well as before an INSERT, UPDATE or DELETE is attempted. For INSERT and UPDATE operations, the trigger either skips the operation for the current row, or changes the row being inserted. After the operation has been attempted After the event means after constraints are checked and after the INSERT, UPDATE or DELETE has completed. If the trigger fires after the event, all changes, including the last insertion, update, or deletion, are "visible" to the trigger. Notes Triggers make use of two special tables: The OLD table contains the data referenced in an INSERT before it is actually committed to the database. The NEW table contains the data in the underlying table referenced in a DELETE before it is actually removed from the database.

When an UPDATE is issued both tables are used. More specifically, the new data referenced in the UPDATE statement is contained in the first table, and the data that is being updated is contained in the second table. An UPDATE trigger is used to perform an action after an update is made on a table. Refer to the DROP TRIGGER command for information on how to remove triggers. Examples Specify a trigger (named customer_audit_trigger) for a table named customer. The trigger updates SQL> create table customer(name char(40)) SQL> create table customer_audit(name char(50), updated datetime)

| Copyright 2012 NuoDB, Inc. All rights reserved. | 98

| SQL Reference Pages | 99

the name and time in another table (ccustomer_audit) after the name is updated in the customer table.

SQL> create trigger customer_audit_trigger for customer AFTER update SQL> as SQL> insert into customer_audit(name, updated) values (NEW.name,'now'); SQL> end_trigger

Use the trigger and get results. SQL> insert into customer values ('adam'); SQL> select * from customer; NAME ----adam SQL> update customer set name='adam'; SQL> select * from customer_audit; NAME UPDATED ----- ------------------adam 2011-10-26 13:27:28 Create a trigger that tracks the value of SQL> create table t (n int, trail string); updates SQL> create trigger insert_t for t before insert as > trail = n;; > end_trigger; SQL> create trigger update_t for t before update as > trail = trail || ',' || n;; > end_trigger; SQL> insert into t (n) values(1); SQL> update t set n = 2; SQL> update t set n = 3; SQL> update t set n = 4; SQL> update t set n = 5; SQL> select * from t; N TRAIL -- --------5 1,2,3,4,5

CREATE USER
Define a new database user account Synopsis CREATE USER username PASSWORD 'password' Description CREATE USER adds a new user to a NuoDB database. Use DROP USER to remove a user. Use CREATE ROLE to grant privileges to users. Parameters username The name of the user.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 99

| SQL Reference Pages | 100

password

Sets the user's password. The password can be set or changed later, using ALTER USER.

Examples Create a user with no password Create a user with a password CREATE USER jonathan; CREATE USER davide WITH PASSWORD 'jw8s0F4';

CREATE VIEW
Define a new view. Note limitations with SELECT. Synopsis CREATE VIEW [schema.]view [ ( column name list ) ] AS SELECT query Parameters view column name list The name (optionally schema-qualified) of a view to be created. An optional list of names to be used for columns of the view. If specified, these names override the column names that would be based on the SQL query. An SQL query (that is, a SELECT statement) which provides the columns and rows of the view.

query

NOTE TO BETA CUSTOMERS Although you can specify GROUP BY with CREATE VIEW, it does not return correct results. The SELECT clause for a view cannot contain a HAVING clause or UNION clause. You cannot use AS SELECT * FROM when creating a view. You cannot update a view. Support for the optional list of column names is not yet implemented. Description CREATE VIEW defines a view of a query. The view is not physically materialized. Instead, a query rewrite rule (an ON SELECT rule) is automatically generated to support SELECT operations on views. If a schema name is specified (for example, CREATE VIEW myschema.myview ...) then the view is created in the specified schema. Otherwise it is created in the current schema. The view name can be the same as names for sequences and indexes. It must be distinct from the name of any other view or table. Use DROP VIEW to drop views. To change a view, drop and recreate it.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 100

| SQL Reference Pages | 101

Examples Creates a view that has particular data from a particular state. CREATE VIEW MaineAirports (airport_name, city, airport_code, altitude) AS SELECT airport_name, city, airport_code, altitude from Airports WHERE state IN(SELECT state FROM airports WHERE code = 'RKD');

DELETE
Remove table rows as specified by WHERE. See also TRUNCATE. Synopsis DELETE FROM [schema].table [ WHERE condition ]; Parameters table condition The name (optionally schema-qualified) of an existing table. A selection query that returns the rows to be deleted.

Description DELETE removes rows from the specified table as specified by the WHERE clause. If the condition (WHERE clause) is absent, the effect is to delete all rows in the table. The result is a valid, but empty table. NOTE: TRUNCATE provides a faster mechanism to remove all rows from a table. You must have write access to the table in order to modify it, as well as read access to any table whose values are read in the condition. Examples Delete any flights that do not leave from, or arrive at, known airports, and also delete flights that are not part of a known airline. delete from flights where not exists (select airport_code from airports a where a.airport_code = destination) or not exists (select airport_code from airports a where a.airport_code = origin) or not exists (select airline_code from airlines al where al.airline_code = airline_code);

DROP DATABASE
Use NuoDB Console to create and drop databases; you cannot use NuoSQL for this purpose. Related Links What is NuoDB Console?

| Copyright 2012 NuoDB, Inc. All rights reserved. | 101

| SQL Reference Pages | 102

Overview of Configuration Tools on page 33 Using command-line tools as well as NuoDB Console to configure NuoDB Use NuoDB Console on page 10 How to start NuoDB Console and view the QuickStart processes.

DROP DOMAIN
Remove a domain from the database Synopsis DROP DOMAIN [IF EXISTS] [SCHEMA. ] [ name ] DROP DOMAIN [SCHEMA.] [name ] [IF EXISTS] Description If you do not specify the name of the domain, the default domain is removed. If the domain does not exist and you specify IF EXISTS, NuoDB does not generate an error. Otherwise, if the domain does not exist, an error is generated. Dropping a domain does not cascade to dropping columns defined in terms of that domain. That is, if any column in any table is defined in terms of the domain specified to be dropped, the definition of that column remains valid and includes all attributes of the dropped domain. This behavior complies with SQL2008. Examples Removes the Identifier domain drop domain Identifier

DROP INDEX
Remove an index Synopsis DROP INDEX index_name [IF EXISTS] Parameters index_name Description DROP INDEX drops an existing index from the database system. To execute this command you must be the owner of the index. If the index does not exist and you specify IF EXISTS, NuoDB does not generate an error. Otherwise an error is generated if the index does not exist. Refer to CREATE INDEX for information on how to create indexes. Examples Remove the title_idx index drop index title_idx; The name of an index to remove.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 102

| SQL Reference Pages | 103

DROP PROCEDURE
Remove a specified procedure or function from storage NOTE TO BETA CUSTOMERS DROP PROCEDURE is not implemented. Synopsis DROP PROCEDURE Description Use the DROP PROCEDURE statement to remove a standalone stored procedure from the database. procedure_name [ CASCADE | RESTRICT]

DROP ROLE
Remove a role from the database Synopsis DROP ROLE role_name [ IF EXISTS ] DROP ROLE [ IF EXISTS ] Description Use the DROP ROLE statement to remove a role from the database. When you drop a role, NuoDB revokes it from all users and roles to whom it has been granted and removes it from the database. User sessions in which the role is already enabled are not affected. If the role does not exist and you specify IF EXISTS, NuoDB does not generate an error. Otherwise, if the role does not exist, an error is generated. Examples Drop the dba role drop role dba; role_name

Notes New user sessions cannot enable the role after it is dropped.

DROP SCHEMA
Remove a schema Synopsis DROP SCHEMA name [ CASCADE | RESTRICT ] [ IF EXISTS ] name

DROP SCHEMA [ CASCADE | RESTRICT] [IF EXISTS ] Parameters name CASCADE RESTRICT

The name of a schema. Automatically drop objects (tables, functions, and others) that are contained in the schema. Refuse to drop the schema if it contains any objects. This is the default.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 103

| SQL Reference Pages | 104

IF EXISTS

If the schema does not exist and you specify IF EXISTS, NuoDB does not generate an error. Otherwise, if the schema does not exist, an error is generated. An empty schema is treated as if it does not exist.

Description DROP SCHEMA removes schemas from the data base. A schema can only be dropped by its owner. Note that the owner can drop the schema (and thereby all contained objects) even if he does not own some of the objects within the schema. Refer to the CREATE SCHEMA statement for information on how to create a schema.

DROP SEQUENCE
Remove a sequence Synopsis DROP SEQUENCE [ IF EXISTS ] [SCHEMA. ] sequence_name [IF EXISTS ] Parameters sequence_name IF EXISTS The name (optionally schema-qualified) of a sequence. If the sequence does not exist and you specify IF EXISTS, NuoDB does not generate an error. Otherwise, if the sequence does not exist, an error is generated.

Description Use the DROP SEQUENCE statement to remove a sequence from the database. You can also use this statement to restart a sequence by dropping and then re-creating it.

DROP TABLE
Remove a table. See also TRUNCATE. Synopsis DROP TABLE [IF EXISTS] [CASCADE | RESTRICT] [SCHEMA.] tablename [IF EXISTS] [CASCADE | RESTRICT]

Parameters tablename CASCADE RESTRICT The name (optionally schema-qualified) of an existing table to drop. Automatically drop objects that depend on the table (such as views). Refuse to drop the table if there are any dependent objects. This is the default.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 104

| SQL Reference Pages | 105

IF EXISTS

If the table does not exist and you specify IF EXISTS, NuoDB does not generate an error. Otherwise, if the table does not exist, an error is generated.

Description Use the DROP TABLE statement to remove the table and all its data from the database entirely. DROP TABLE removes tables from the database. Only its owner may destroy a table. A table may be emptied of rows, but not destroyed, by using DELETE. You can also use TRUNCATE. DROP TABLE always removes any indexes, triggers, and constraints that exist for the target table.

DROP TRIGGER
Remove a trigger Synopsis DROP TRIGGER trigger_name [ IF EXISTS ] DROP TRIGGER trigger_name [IF EXISTS ] Parameters trigger_name table IF EXISTS The name of an existing trigger. The name (optionally schema-qualified) of a table. If the trigger does not exist, and you specify IF EXISTS, NuoDB does not generate an error. Otherwise, if the trigger does not exist, an error is generated.

Description Use the DROP TRIGGER statement to remove a database trigger from the database. The trigger must be in your own schema, or you must have the DROP ANY TRIGGER system privilege. DROP TRIGGER removes an existing trigger definition. To execute this command the current user must be the owner of the table for which the trigger is defined. Examples Avoid generating an error when deleting a trigger in the case where it does not exist. drop customer_audit_trigger if exists;

DROP USER
Remove a database user account Synopsis DROP USER name [ IF EXISTS ]

| Copyright 2012 NuoDB, Inc. All rights reserved. | 105

| SQL Reference Pages | 106

Description Use the DROP USER statement to remove a database. When you drop a user, NuoDB purges all of that user's schema objects from the recycle bin. Parameters name IF EXISTS The name of a user. If the user does not exist and you specify IF EXISTS, NuoDB does not generate an error. Otherwise, if the user does not exist, an error is generated.

Examples To drop a user account drop user jonathan;

DROP VIEW
Remove a view Synopsis DROP VIEW [IF EXISTS] [CASCADE | RESTRICT] [SCHEMA.] viewname [IF EXISTS] [CASCADE | RESTRICT] Parameters viewname CASCADE RESTRICT IF EXISTS The name (optionally schema-qualified) of an existing view. Automatically drop objects that depend on the view (such as other views). Refuse to drop the view if there are any dependent objects. This is the default. If the view does not exist and you specify IF EXISTS, NuoDB does not generate an error. Otherwise, if the view does not exist, an error is generated.

Description DROP VIEW drops an existing view from the database. To execute this command you must be the owner of the view. You can change the definition of a view by dropping and re-creating it. Notes Refer to CREATE VIEW for information on how to create views.

GRANT
Define access

| Copyright 2012 NuoDB, Inc. All rights reserved. | 106

| SQL Reference Pages | 107

Synopsis GRANT rolename [, ...] TO username DEFAULT GRANT { SELECT | INSERT | UPDATE | DELETE |EXECUTE | ALTER | GRANT | ALL [ PRIVILEGES ] } ON [ TABLE ] tablename TO ROLE rolename [, ...] GRANT { SELECT | INSERT | UPDATE | DELETE |EXECUTE | ALTER | GRANT | ALL [ PRIVILEGES ] } ON [ TABLE ] tablename TO username [, ...]

NOTE TO BETA CUSTOMERS REFERENCES is not yet implemented. You cannot yet specify multiple database objects in a single statement when specifying or revoking privileges. Description Use the GRANT statement to grant privileges to roles (rather than users) and then assign roles to users. Users can have several roles, each of which, by default, are active or inactive at any point in time. Active roles are the only roles available to a user at a given time. To specify that a user should have a role as active by default, use the DEFAULT keyword when specifying the role. The GRANT command gives specific permissions on an object (table, view, sequence, database, function, procedural language, or schema) to one or more users or groups of users. These permissions are added to those already granted, if any. You do not have to grant privileges to the creator of an object, because the creator has all privileges by default. (The creator could, however, choose to revoke some of his own privileges for safety.) The ability to grant and revoke privileges is inherent in the creator and cannot be lost. The right to drop an object, or to alter it in any way not described by a grantable right, is likewise inherent in the creator, and cannot be granted or revoked. The possible privileges are described in the following table. The privileges required by other commands are listed on the reference page describing that command. SELECT INSERT UPDATE Allows SELECT from any column of the specified table, view, or sequence. Allows INSERT of a new row into the specified table. Allows UPDATE of any column of the specified table. SELECT ... FOR UPDATE also requires this privilege (besides the SELECT privilege). Allows DELETE of a row from the specified table.

DELETE EXECUTE ALTER GRANT

| Copyright 2012 NuoDB, Inc. All rights reserved. | 107

| SQL Reference Pages | 108

ALL PRIVILEGES

Grant all of the privileges applicable to the object without specifying them individually.

NuoDB Administration NuoDB defines a special user, named DBA, as the administrator of the database, who has all rights. When a new user account is created, it has no rights. Either the creator or DBA must grant rights to new users, using the DEFAULT qualifier to indicate that a specified role is active by default. A new role has no rights until someone grants rights to it. Although the SQL standard says that a user's role is established at connection time, NuoDB allows users to add and drop roles under application control, possibly as often as they look up new tables. This flexibility can be helpful in developing a client application to run against NuoDB. Notes Use the REVOKE command to revoke access privileges. Database owners can access all objects regardless of object privilege settings. To grant privileges to only a few columns, you must create a view having the desired columns and then grant privileges to that view. NuoDB supports {WITH GRANT OPTION}, which specifies permission inheritance. Examples Assign the admin role to a new user. By default all privileges are active. SQL> show tables; Tables in schema HOCKEY ENGINEERS HOCKEY SQL> create role admin; SQL> grant all on hockey to role admin; SQL> create user esther password 'esther22'; SQL> grant admin to esther default; Grant SELECT privileges to a new user.

SQL> create user alta password 'glenn'; SQL> grant select on hockey to alta;

INSERT
Create new rows in a table Synopsis INSERT INTO table [ ( column [, ...] ) ] VALUES ( expression [, ...] )[, (expression [, ...]) | SELECT query ] INSERT INTO table DEFAULT VALUES Parameters table column The name (optionally schema-qualified) of an existing table. The name of a column in table.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 108

| SQL Reference Pages | 109

expression query

A valid expression or value to assign to column. A valid query. Refer to the SELECT statement for a further description of valid arguments.

Description Use the INSERT statement to add rows to a table. INSERT allows you to insert new rows into a table. You can insert a single row at a time or several rows as a result of a query. The columns in the target list may be listed in any order. Each column not present in the target list is inserted using a default value, either a declared DEFAULT value or NULL. NuoDB rejects the new column if a NULL is inserted into a column declared NOT NULL. If the expression for each column is not of the correct data type, automatic type coercion is attempted. DEFAULT Use the DEFAULT keyword to insert a default value that you have defined for a column. Prerequisites For you to insert rows into a table, you must have the INSERT object privilege on the table. You must have INSERT privilege to a table in order to append to it, as well as SELECT privilege on any table specified in a WHERE clause. Examples Add a column for addresses to the tickets table, and insert a value Define a table with a default value for the dayweather column and insert this value to the table. SQL> alter table tickets add column address varchar(30); SQL> insert into tickets (address) values ('703 main street') SQL> create table days (daynumber bigint generated by default primary key, dayweather string default 'partly cloudy'); SQL> insert into days (daynumber, dayweather) values (); SQL> insert into days (daynumber) values (); SQL> insert into days (dayweather) values ('sunny'); SQL> insert into days values (); SQL> insert into days default values; SQL> insert into days (daynumber, dayweather) values (432, default); SQL> select * from days; DAYNUMBER DAYWEATHER ---------- ------------9 10 11 12 13 432 partly partly sunny partly partly partly cloudy cloudy cloudy cloudy cloudy

RELEASE
Release a save point. See SAVEPOINT.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 109

| SQL Reference Pages | 110

Synopsis RELEASE SAVEPOINT savepoint_name; Related Links Transactions on page 78 NuoDB supports several levels of transaction isolation and is based on Multi-Version Concurrency (MVCC).

REPLACE
Replace one or more values in a table with new values Synopsis REPLACE [INTO] [schema.]table_name [ ( column [, ...] ) ] VALUES ( expression [, ...] ) [, (expression [, ...]) | SELECT query Parameters table_name column The name (optionally schema-qualified) of an existing table. The name of a column in table_name. Must include the primary key if replacing values in an existing row. A valid expression or value to replace the current value. A valid query. Refer to the SELECT statement for a description of valid arguments.

expression query

Description Use the REPLACE statement to update or replace values in a table. If you specify a value with a a primary key NuoDB attempts to update an existing row. If the row does not exist, the replacement values are inserted as a new row. (Primary keys are always NOT NULL.) You can replace a single row at a time, or replace several rows as a result of a query. The columns in the target list may be specified in any order. If the expression for each column is not of the correct data type, automatic type coercion is attempted. Examples Change the value for AS in the airlines table. In this example AIRLINE_CODE is a primary key. SQL> select * from airlines AIRLINE_CODE AIRLINE_NAME ------------- -------------------------AS Alaska Airlines Inc.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 110

| SQL Reference Pages | 111

AA CO DL F9 HA OH OO UA US WN

American Airlines Inc. Continental Air Lines Inc. Delta Air Lines Inc. Frontier Airlines Inc. Hawaiian Airlines Inc. Comair Inc. SkyWest Airlines Inc. United Air Lines Inc. US Airways Inc. Southwest Airlines Co.

YV Mesa Airlines Inc. SQL> replace into airlines (AIRLINE_CODE, AIRLINE_NAME) VALUES ('AS', 'AAA Airlines'); SQL> select * from airlines AIRLINE_CODE AIRLINE_NAME ------------- -------------------------AS AA CO DL F9 HA OH OO UA US WN YV AAA Airlines American Airlines Inc. Continental Air Lines Inc. Delta Air Lines Inc. Frontier Airlines Inc. Hawaiian Airlines Inc. Comair Inc. SkyWest Airlines Inc. United Air Lines Inc. US Airways Inc. Southwest Airlines Co. Mesa Airlines Inc.

REVOKE
Remove access privileges Synopsis REVOKE ROLE rolename ON [ TABLE ] tablename FROM { username | ROLE rolename} [, ...] REVOKE privileges ON [ TABLE ] tablename FROM { username | ROLE rolename} [, ...]

| Copyright 2012 NuoDB, Inc. All rights reserved. | 111

| SQL Reference Pages | 112

NOTE TO BETA CUSTOMERS REFERENCES is not yet implemented. REVOKE FROM username has no effect if you specify an invalid user name. Description Use the REVOKE statement to remove roles and privileges from users and roles. IMPORTANT You must specify a tablename. Using REVOKE without specifying a table name has no effect. Examples Remove admin role privileges for a user SQL> SQL> SQL> SQL> SQL> SQL> create user alta password '1922'; create user admin password '0724'; create role admin; grant admin to admin; grant admin to alta; revoke admin from alta;

ROLLBACK
Stop and end the current transaction Synopsis ROLLBACK [ WORK | TRANSACTION ] ROLLBACK TO SAVEPOINT savepoint_name Parameters savepoint_name Name of save point that you want to be able to specify with ROLLBACK

Description Use the ROLLBACK statement to undo work done in the current transaction, or to manually undo the work done at a specified save point. ROLLBACK rolls back the current transaction and causes all the updates made by the transaction to be discarded. Notes NuoDB recommends that you explicitly end transactions in application programs using either a COMMIT or ROLLBACK statement. If you do not explicitly commit the transaction and the program terminates abnormally, then NuoDB rolls back the last uncommitted transaction. To roll back your current transaction, no privileges are necessary. Use COMMIT to successfully terminate a transaction. See SAVEPOINT for more information about save points. Examples To stop and end all changes ROLLBACK WORK;

| Copyright 2012 NuoDB, Inc. All rights reserved. | 112

| SQL Reference Pages | 113

Related Links Transactions on page 78 NuoDB supports several levels of transaction isolation and is based on Multi-Version Concurrency (MVCC).

SAVEPOINT
Mark and name a point within a transaction to use with ROLLBACK and RELEASE Synopsis SAVEPOINT savepoint_name RELEASE savepoint_name ROLLBACK TO SAVEPOINT savepoint_name Parameters savepoint_name Name of save point that you want to be able to specify with ROLLBACK

Description Use SAVEPOINT to mark a point (that is, a save point) within a transaction and specify a name for it. You can use ROLLBACK TO SAVEPOINT to undo NuoDB operations to the specified save point. Use RELEASE to explicitly release the specified save point. A COMMIT implicitly releases all named save points and commits all uncommitted data. ROLLBACK to a named save point releases all save points back to that named save point. (A ROLLBACK with no arguments releases all named save points within the transaction. ) Examples Create several save points in a table (t) and rollback to each. SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> N -1 2 3 4 SQL> SQL> N -1 2 SQL> SQL> SQL> N insert into t values savepoint first; insert into t values savepoint second; insert into t values savepoint third; insert into t values select * from t; (1) (2); (3); (4);

rollback to savepoint second; select * from t;

insert into t values (3); insert into t values (4); select * from t;

Related Links

| Copyright 2012 NuoDB, Inc. All rights reserved. | 113

| SQL Reference Pages | 114

Transactions on page 78 NuoDB supports several levels of transaction isolation and is based on Multi-Version Concurrency (MVCC).

SELECT
Retrieve rows from a table or view Synopsis SELECT * | select_item [, ...] FROM from_list [ WHERE condition ] [ GROUP BY group_list [, ...] [ HAVING condition [, ...] ]] [ UNION [ ALL | DISTINCT ] select ] [ ORDER BY order_list] [ OFFSET start [ROW[S]]] [ FETCH [{FIRST | NEXT}] count [ROW[S]] [ONLY] [ FOR UPDATE ]

Parameters select_item column source_name source_alias column_name expression item_alias column | expression | literal [[as] item_alias] [{source_name | source_alias}.]column_name Name of a table, view or procedure directly listed in the from_list. Alternate name for a data source Name of a column from a data source string_expression | numeric_expression | boolean_expression Alternate name for select_item that can differentiate it from other select_items that have the same name, or give a name to an expression. { qualified_data_source [,...] | qualified_data_source [join_clause qualified_data_source [on_clause] ...] data_source [AS] source_alias [schema.]base_table | [schema.]view | [schema.]procedure | derived_table ( select ) [AS] source_alias Select statement with all features except ORDER BY, OFFSET/FETCH, and FOR UPDATE clauses. Name of the schema that contains the data source Boolean expression giving a result of true or false. See WHERE and HAVING clauses.

from_list qualified_data_source data_source derived_table select schema condition

Outputs rows The complete set of rows resulting from the query specification.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 114

| SQL Reference Pages | 115

Description SELECT retrieves rows from zero or more tables. An abstract version of the processing steps for a SELECT statement is as follows: 1. All elements in the FROM list are computed. If more than one element is specified in the FROM list, they are joined together. 2. If the WHERE clause is specified, all rows that do not satisfy the condition are eliminated from the output. 3. If the GROUP BY clause is specified, the output is aggregated into groups of rows that match on one or more values. If the HAVING clause is present, NuoDB eliminates groups that do not satisfy the given condition. 4. The actual output rows are computed using the SELECT output expressions for each selected row. 5. The UNION operator combines the output of multiple SELECT statements to form a single result set. The UNION operator returns all rows that are in one or both of the result sets. Duplicate rows are eliminated unless ALL is specified. 6. If the ORDER BY clause is specified, the returned rows are sorted in the specified order. If ORDER BY is not given, the rows are returned in whatever order the system finds fastest to produce. 7. DISTINCT eliminates duplicate rows from the result. ALL (the default) returns all candidate rows, including duplicates. 8. If the OFFSET or FETCH clause is specified, the SELECT statement returns a subset of the result rows. 9. If FOR UPDATE is specified, the SELECT statement locks the selected rows against concurrent updates. Note: You must have SELECT privilege on a table to read its values. The use of FOR UPDATE requires UPDATE privilege as well. FROM Clause The FROM clause specifies one or more data sources for the SELECT. If the select statement contains no restrictions in its ON or WHERE clause, the result is the full cross product (Cartesian join) of all the sources. Typically, qualification conditions are added to restrict the returned rows to a small subset of the Cartesian join. The FROM clause can contain the following elements: from_list Data source. Sources can be joined with explicit join_types, or in a comma separated list. (The comma separated list was deprecated in SQL-92.) Either a derived ta,ble or the name of a table or view. The name of the view or table can be qualified with a schema name. select statement enclosed in parentheses. The data sources within the derived table can be qualified with a schema name. Substitute name for the FROM item containing the alias. An alias is used for brevity or to eliminate ambiguity for self-joins (where the same table is scanned multiple times). When an alias is provided, it completely hides the actual name of the table or function.

data_source

derived_table

alias

| Copyright 2012 NuoDB, Inc. All rights reserved. | 115

| SQL Reference Pages | 116

For example given FROM foo AS f, the remainder of the SELECT must refer to this FROM item as f not foo. A column alias list can be written to provide substitute names for one or more columns of the table. join_type One of the following: [ [ [ [ INNER OUTER OUTER OUTER ] ] ] ] JOIN LEFT JOIN RIGHT JOIN FULL JOIN

For the INNER and OUTER join types, a join condition may be specified in an ON join_condition, or in the WHERE clause. A JOIN clause combines two data sources. INNER JOIN produces pairs or records from the two data sources, matched by the conditions in the WHERE clause and ON clause. LEFT OUTER JOIN returns all rows from the data source before it, and matching rows from the data source that follows. Matching is again based on the contents of the ON clause. Rows from the first data source that have no matching rows in the following data source represent the values that would have come from that source as nulls. If a matching condition is specified in the WHERE clause only rows from first data source that do not match that condition will not be included in the result. Conversely, RIGHT OUTER JOIN returns all the joined rows, plus one row for each unmatched righthand row (extended with nulls on the left). This is just a notational convenience, since you could convert it to a LEFT OUTER JOIN by switching the left and right inputs. FULL OUTER JOIN returns all the joined rows, plus one row for each unmatched left-hand row (extended with nulls on the right), plus one row for each unmatched right-hand row (extended with nulls on the left). ON join_condition An expression resulting in a value of type boolean (similar to a WHERE clause) that specifies which rows in a join are considered to match. The join_condition in the ON clause should include only Boolean values that describe the relationship between the data sources being joined.

WHERE Clause The optional WHERE clause has the general form:

| Copyright 2012 NuoDB, Inc. All rights reserved. | 116

| SQL Reference Pages | 117

WHERE condition where condition is any expression that evaluates to a result of type boolean. Any row that does not satisfy this condition is eliminated from the output. A row satisfies the condition if it returns true when the actual row values are substituted for any variable references. GROUP BY Clause The optional GROUP BY clause has the general form GROUP BY expression [, ...] GROUP BY condenses into a single row all selected rows that share the same values for the grouped expressions. expression can be a column name, or the alias or ordinal number of an output column (SELECT list item). Aggregate functions, if any are used, are computed across all rows making up each group, producing a separate value for each group. Without GROUP BY, an aggregate produces a single value computed across all the selected rows. When GROUP BY is present, the expressions on a SELECT list cannot refer to ungrouped columns, except within aggregate functions. Otherwise there would be more than one possible value to return for an ungrouped column. HAVING Clause The optional HAVING clause has the following general form, where condition is the same as specified for the WHERE clause. HAVING condition HAVING eliminates group rows that do not satisfy the condition. HAVING is different from WHERE as follows: WHERE filters individual rows before the application of GROUP BY, while HAVING filters group rows created by GROUP BY. Unless the reference appears within an aggregate function each column referenced in condition must unambiguously reference a grouping column SELECT List The SELECT list is specified between the key words SELECT and FROM. The list specifies expressions that form the output rows of the SELECT statement. The expressions can (and usually do) refer to columns computed in the FROM clause. Instead of an expression, you can use an asterisk ( * ) in the output list as a shorthand for all the columns of the selected rows. Also, you can write table_name.* as a shorthand for the columns coming from just that table. UNION Clause The UNION clause has this general form: select_statement UNION [ ALL | DISTINCT ] select_statement NOTE TO BETA CUSTOMERS In Beta 6, the Union clause does not support WHERE, GROUP BY, or other useful clauses. ORDER BY Clause The optional ORDER BY clause has the following general form, where expression can be the name or ordinal number of a column (SELECT list item). :

| Copyright 2012 NuoDB, Inc. All rights reserved. | 117

| SQL Reference Pages | 118

ORDER BY expression [ ASC | DESC] [, ...] The ORDER BY clause causes the result rows to be sorted according to the specified expressions. If two rows are equal according to the leftmost expression, they are compared according to the next expression and so on. If they are equal according to all specified expressions, they are returned in an implementationdependent order. The ordinal number refers to the ordinal (left-to-right) position of the result column. This feature makes it possible to define an ordering on the basis of a column that does not have a unique name. This is never absolutely necessary because it is always possible to assign a name to a result column using the AS clause. It is also possible to use columns that do not appear in the SELECT result list. Thus the following statement is valid: SELECT name FROM distributors ORDER BY code; A limitation of this feature is that an ORDER BY clause applying to the result of a UNION clause may specify only an output column name or number, not an expression. One may add the key word ASC (ascending) or DESC (descending) after any expression in the ORDER BY clause. If not specified, ASC is assumed by default. DISTINCT Clause If DISTINCT is specified, all duplicate rows are removed from the result set (one row is kept from each group of duplicates). ALL specifies the opposite: all rows are kept; that is the default. FETCH Clause The FETCH clause consists of two independent sub-clauses: FETCH [FIRST | NEXT count [ROW[S]] [ONLY] OFFSET start [ROW[S]]

count specifies the maximum number of rows to return, while start specifies the number of rows to skip before starting to return rows. When both are specified, start rows are skipped before starting to count the count rows to be returned. When using FETCH, it is a good idea to use an ORDER BY clause that constrains the result rows into a unique order. Otherwise you get an unpredictable subset of the query's rows. For example you intend to ask for the tenth through twentieth rows, but without ORDER BY the order of the results is unpredictable. FOR UPDATE Clause The FOR UPDATE clause has the following form: FOR UPDATE FOR UPDATE causes the rows retrieved by the SELECT statement to be locked as though for update. This prevents them from being modified or deleted by other transactions until the current transaction ends. That is, other transactions that attempt UPDATE, DELETE, or SELECT FOR UPDATE of these rows are blocked until the current transaction ends. Also, if an UPDATE, DELETE, or SELECT FOR UPDATE from another transaction has already locked a selected row or rows, SELECT FOR UPDATE waits for the other transaction to complete. When the other transaction completes, the waiting transaction will proceed if the other transaction rolled back, otherwise it will get an error message in the default isolation mode. In write-committed or read-committed isolation modes, the waiting transaction will read the most recently committed version of the record and can proceed with its update. FOR UPDATE cannot be used in contexts, such as aggregation, where returned rows cannot be clearly identified with individual table rows.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 118

| SQL Reference Pages | 119

Examples Retrieve rows from system table and arrange according to tablename column. Retrieve rows from aircraft table and arrange according to tablename column. select tablename, field, datatype, length, scale from system.fields where schema ='SYSTEM' order by tablename; select tablename, field, datatype, length, scale from system.fields where tablename = 'AIRCRAFT' order by tablename;

SET
Set variables that define system behavior Synopsis SET {CONSISTENT_READ | WRITE_COMMITTED | READ_COMMITTED}; Description Use the SET command to change run-time configuration parameters. NOTE TO BETA CUSTOMERS Support for setting additional run-time parameters is not yet implemented. The isolation level of a transaction determines the data that the transaction can see when other transactions are running concurrently. The setting is in effect with the start of the next transaction, and stays in effect until the level is reset with another SET command. The following settings are supported: CONSISTENT_READ (the default) Same as SERIALIZABLE. At this level a transaction that tries to update or delete a record that was updated by a concurrent transaction waits for the concurrent transaction to end. If the concurrent transaction fails, NuoDB automatically retries the update for the waiting transaction, and, in the absence of other conflicts, succeeds. If the concurrent transaction is committed, NuoDB generates an update conflict error for the waiting transaction. The waiting transaction can then either roll back and retry its operations, or continue. If it continues and retries the change of the conflicting record NuoDB generates an error. WRITE_COMMITTED At this level every update or delete statement is preceded by a SELECT..FOR UPDATE that operates differently from an ordinary SELECT. Ordinarily, a SELECT returns the most recent version of the record that was committed when the transaction started. If you set WRITE_COMMITTED, a SELECT..FOR UPDATE

| Copyright 2012 NuoDB, Inc. All rights reserved. | 119

| SQL Reference Pages | 120

returns the most recent version of the record and creates a new version without changing any values. If the most recent version of the record is not yet committed, the SELECT..FOR UPDATE waits until the transaction that created it finishes, then returns the most recent committed version. Note: At the level of WRITE_COMMITTED, NuoDB operates in both READ_COMMITTED as well as WRITE_COMMITTED. If you want only READ_COMMITTED, use the READ_COMMITTED instead of WRITE_COMMITTED. READ_COMMITTED At this level NuoDB allows a running transaction to see the most recently committed version of each record, regardless of whether that record was visible at the time the transaction started. As a result, running the same query twice can produce different results. Note: With one exception the behavior of NuoDB at the READ_COMMITTED level is like READ_COMMITTED isolation in other relational databases. The exception is the handling of conflicts between transactions that update or delete the same record. A NuoDB transaction that attempts to update or delete a record that was updated by a concurrent transaction generates an update conflict error, just as if the isolation level were set to the default (CONSISTENT_READ).

SHOW
Display information about schemas, tables, domains, and status of AUTOCOMMIT isolation level. Synopsis SHOW SHOW SHOW SHOW SHOW SHOW [ SCHEMAS | TABLES |DOMAINS | SEQUENCES | AUTOCOMMIT ] name TABLE [schema.]name DOMAIN [schema.]name SEQUENCE [schema.]name SCHEMA name

Parameters and Options Name SHOW What Is Displayed Current settings Example

SQL> show autocommit state is off semicolon completion is required

| Copyright 2012 NuoDB, Inc. All rights reserved. | 120

| SQL Reference Pages | 121

Name

What Is Displayed

Example current schema is ENGINEERS

SHOW SCHEMAS

All schemas containing tables

SQL> show schemas; Schemas containing tables ENGINEERS HOCKEY SYSTEM

SHOW TABLES

Tables in current schema

SQL> show tables Tables in schema ENGINEERS ENGINEERS

SHOW DOMAINS

Domains in current schema

SQL> SHOW domains No domains found in schema ENGINEERS

SHOW SEQUENCES SHOW AUTOCOMMIT

Sequences in current schema Status of AUTOCOMMIT isolation level (off or on)l SQL> show AUTOCOMMIT Autocommit is off

SHOW name SHOW TABLE [schema.]name Schema and columns of the table specified SQL> show table hockey; Schema HOCKEY Table HOCKEY NUMBER integer NAME string POSITION string TEAM string SHOW DOMAIN [schema.]name SHOW SEQUENCE [schema.]name SHOW SCHEMA name Description Use SHOW to get information about schemas, tables, sequences, and domains. You can also use SHOW to determine the status of the setting for AUTOCOMMIT. Specified domain Specified sequence Specified schema

| Copyright 2012 NuoDB, Inc. All rights reserved. | 121

| SQL Reference Pages | 122

By default SHOW uses the current schema if none is specified. If NuoDB cannot find a table with the exact name that is specified it performs as follows: 1. Searches for tables with similar names in the current schema, and then in all schemas. 2. Searches for tables that match the first few characters of the specified name, in the current schema, and then in all schemas. 3. Generates a list of tables with same initial letter as the specified name. Note: Keep in mind that an SQL domain is not the same as a NuoDB administrative domain. An SQL domain is a set of types that are named and can be used as a group as if they are one type.

START TRANSACTION
Start a transaction block Synopsis START TRANSACTION { [ READ ONLY ] [ READ WRITE ] [ ISOLATION LEVEL { READ COMMITTED | WRITE COMMITTED | SERIALIZABLE }] }

NOTE TO BETA CUSTOMERS REPEATABLE READ is not implemented. READ UNCOMMITTED is not implemented. Parameters None. Description If the first statement you submit is START TRANSACTION, NuoDB starts a transaction using the specified isolation level. If you execute a select, insert, update or other command and there is no transaction running, NuoDB starts a transaction as READ WRITE SERIALIZABLE. Example Start a transaction as read only, do an update, and the transaction fails. Then start a transaction as read write and the update succeeds.

SQL> start transaction; SQL> use foo; SQL> create table t1 (n1 integer); SQL> insert into t1 (n1) values (1), (2), (3); SQL> select * from t1; N1 ---

| Copyright 2012 NuoDB, Inc. All rights reserved. | 122

| SQL Reference Pages | 123

1 2 3 SQL> commit; SQL> start transaction read only; SQL> update t1 set n1=n1+10; Read only transactions cannot change data SQL> commit; SQL> start transaction read write; SQL> update t1 set n1=n1+10; SQL> select * from t1; N1 --11 12 13

Related Links Transactions on page 78 NuoDB supports several levels of transaction isolation and is based on Multi-Version Concurrency (MVCC).

TRUNCATE
Empty a table Synopsis TRUNCATE [ TABLE ] name Parameters name The name (optionally schema-qualified) of the table to be truncated.

Description TRUNCATE quickly removes all rows from a table. It has the same effect as an unqualified DELETE but since it does not actually scan the table it is faster. This can be useful on large tables. Although TRUNCATE can be executed inside a transaction block, there is no way to roll it back. Examples Truncate the table bigtable TRUNCATE TABLE bigtable;

UPDATE
Update rows of a table Synopsis UPDATE [schema.] table SET column = expression [, ...] [WHERE condition ]

| Copyright 2012 NuoDB, Inc. All rights reserved. | 123

| SQL Reference Pages | 124

Parameters table column expression condition The name (optionally schema-qualified) of an existing table. The name of a column in table. A valid expression or value to assign to column. Refer to the SELECT statement for a further description of the WHERE clause.

Description UPDATE changes the values of the columns specified for all rows that meet the requirements specified by the WHERE condition clause. You are required only to specify the columns to be modified. Columns not specified by SET remain unchanged. You must have write access to the table in order to modify it, as well as read access to any table whose values are specified in the WHERE condition. Examples Establish a ticket number for a particular seat on a particular flight update Seats set ticket_id = 346 where flight_id = 844 and seat_number = 24

UPGRADE
Change or create tables and indexes. (NuoDB extension) Synopsis UPGRADE TABLE [schema_name.]table_name ( { column_name { data_type | domain } [ DEFAULT default_expr ] [ column_constraint [, ... ] ] | table_constraint } [, ... ] ) UPGRADE [UNIQUE ] INDEX index_name ON table ( column [, ...] )

Description Use UPGRADE TABLE to change an existing table or, if the named table does not exist, create a new table. See the syntax for CREATE TABLE for more details. UPGRADE TABLE does not drop existing fields. You can use UPGRADE on a single table.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 124

| SQL Reference Pages | 125

Similarly use UPGRADE INDEX to change an existing index or create a new one. You can also convert an index from non-unique to unique, but you cannot make a unique index non-unique. It will add columns to an index. UPGRADE is a NuoDB extension to the SQL standard. Examples Create a table, pet, using UPGRADE, and insert values. Create an index based on the age column for the pets table. SQL> upgrade table pets (name string, age number, weight integer); SQL> show tables; Tables in schema AWH PETS SQL> insert into pets (name,age, weight) values ('Amanda',6,26); SQL> select * from pets; NAME AGE WEIGHT ------ ---- ------Amanda 6 26

SQL> upgrade index petAge on pets(age); SQL> insert into pets (name, age, weight) values ('Wryly',10,40); SQL> select * from pets; NAME AGE WEIGHT ------ ---- ------Amanda Wryly 6 10 26 40

SQL> show table pets; Schema AWH Table PETS NAME string AGE number WEIGHT integer Index: PETAGE AGE

USE
Specify a schema as the default for the current connection to NuoDB SQL Synopsis USE name_of_schema NOTE TO BETA USERS NuoDB does not generate an error if you specify a schema or database that does not exist.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 125

| SQL Reference Pages | 126

Description A NuoDB database has one or more schemas. Each table, view, domain, index, and sequence is part of a particular schema. While you are using the default schema specified by the USE command, you can reference these objects with an unqualified name. Use a qualified name to reference entities in schemas other than the default. Examples Make hockey the default schema. SQL> use hockey; SQL> select number from hockey where number >40; NUMBER ------46 63 49 67 91 43 55 47 54 44

Use common schema instead of the default.

SQL> use common; SQL> select number from hockey where number >40; can't find table "HOCKEY" SQL> select number from hockey.hockey where number >40; NUMBER ------46 63 49 67 91 43 55 47 54 44

| Copyright 2012 NuoDB, Inc. All rights reserved. | 126

| Glossary | 128

Glossary
This glossary defines terms as used in the context of NuoDB. agent Part of the NuoDB management layer. Running an agent on a host makes it available as a NuoDB host. The agent starts and stops the NuoDB processes and communicates with the broker about the state of the system. Every host must have an agent and every chorus must have at least one broker. An agent can also run as a broker if necessary. archive Provides durability of the data handled by the storage manager, for example by writing to disk. Holds a copy of the state of a NuoDB database at any given moment. broker Part of the NuoDB management layer. Manages access and control of transaction engines and storage managers, independent of any particular database (or chorus) in a NuoDB system. chorus A set of processes that at any one moment are collaborating on a database. A chorus is a variable number of processes running on a variable number of computers that serve a single database. Transaction engines and storage managers are part of the chorus. A chorus can span domains. For example, half a chorus could run on Amazon and half on machines at the customer site, each with separate administration of the physical machines. console Part of the NuoDB management layer. Can find and manage NuoDB components that are known to brokers. The purpose of the console is to help you manage databases and choruses in a NuoDB system. For example, from the console you can start and stop NuoDB processes across all instances of NuoDB. database object Any defined object in a database that is used to store or reference data. Some examples of database objects include tables, views, sequences, and indexes. DBA (database administrator) account The NuoDB DBA username and password are required to create new users and privileges in NuoDB SQL. domain (NuoDB) A collection of NuoDB hosts that have been provisioned to work together to support NuoDB processes. You provision a host to run NuoDB by starting an agent. At that point the host is part of a domain, regardless of whether there are any choruses running. domain (NuoDB SQL) A kind of user-defined field type defined by NuoDB SQL For example, define a domain named money as numeric(15,2). You can define fields as being of type money: create table employee (id integer, name string, salary money); launch a chorus To launch a chorus you must start a broker, a transaction engine, and a storage manager. Passwords are required for each of these NuoDB processes. Multiple Active Result Sets (MARS) Allows you to run more than one NuoDB SQL batch on an open connection at the same time. A result set is active until it is either closed or the statement that created it is closed. nuodb

| Copyright 2012 NuoDB, Inc. All rights reserved. | 128

| Glossary | 129

Part of the NuoDB chorus layer. Process that runs on each NuoDB host. NuoDB SQL ACID, transactional, and elastically scalable client/cloud relational database. NuoDB has chorus components, management components, and standalone components. NuoDB Loader Loads data to and from NuoDB NuoDB SQL Set of SQL language elements supported by NuoDB storage manager Process that maintains the archive for a chorus. There can be any number of storage managers running in a NuoDB domain. Each storage manager is associated with exactly one database. transaction engine Process that provides access to a single database. It handles requests from clients, caches data, and coordinates transactions. There may be any number of transaction engines running in a NuoDB chorus. Each transaction engine is associated with exactly one database.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 129

| Glossary | 130

| Copyright 2012 NuoDB, Inc. All rights reserved. | 130

Introduction To Flights Demo


Guides you through the steps to run a sample application against a NuoDB database system. The application simulates a flight reservation system; it includes simulated flight data among airports and generates client reservations. Some of the actions you can perform with the tutorial: Vary the amount of data in the database. Dynamically change load on the database (reads and writes) to see the effect on the transactions per second (TPS) handled by NuoDB. Add transaction engines to your database chorus to increase the transactions per second.

Start an agent and a chorus


Getting started with the Flights program. These commands start a NuoDB storage manager and then a transaction engine for a chorus named Flights. (These steps must be in this exact order). 1. Make sure you have installed and configured NuoDB on your system. 2. Choose a host to run the application. 3. On the host, on the command line, start a nuoagent running as a broker as well as an agent, as follows: java -jar nuoagent.jar --broker --password domain_password 4. Create an empty directory anywhere, to use as storage, such as (on MAC OS X) mkdir ./FlightsArchive 5. Start up two additional terminal windows or command prompts. 6. Start up each of the following processes at separate command prompts or terminal windows: nuodb -chorus Flights --password chorus_password --archive /temp/ FlightsArchive --initialize & nuodb -chorus Flights --password chorus_password &

Install the Flights application


How to start the Flights application. Make sure you have set up NuoDB correctly. 1. Start the Flights program, which is a Java application, according to your platform requirements: On Windows cd c:\Program Files\NuoDB\samples\flights java jar flights.jar&

On Linux and Mac OS X: cd /install_dir/nuodb/samples/flights java jar flights.jar &

| Introduction To Flights Demo | 132

The NuoDB Load Driver Dashboard opens as shown:

The NuoDB Load Driver Dashboard has the following functions: Loads data from a CSV file into a database Generates client threads that read and change the data Provides a graphic interface that controls the application and reports its performance. 2. Click the Settings tab

| Copyright 2012 NuoDB, Inc. All rights reserved. | 132

| Introduction To Flights Demo | 133

The following dialog appears:

3. If necessary, change the database URL to specify the Database URL as follows:

jdbc.com.nuodb://localhost/Flights 4. Make sure the Schema is specified as Flights The correct settings for the Flight application are as shown:

| Copyright 2012 NuoDB, Inc. All rights reserved. | 133

| Introduction To Flights Demo | 134

5. Click Save. The application saves all its current settings in your home directory in an XML file called session.dashboard. (To begin the tutorial from a blank slate, delete this file.)

Load the Flights database and start the application


How to load the database for the Flights chorus and start the application Make sure you have the Flights Load Driver Dashboard application running. 1. Select the Data tab on the Load Driver Dashboard.

The Flights database is loaded with the following data: Airports (hubs and connections Airlines that fly between the airports selected Specific flights Seats on the flights

| Copyright 2012 NuoDB, Inc. All rights reserved. | 134

| Introduction To Flights Demo | 135

Note: Before you run the Flights application you must specify a number of hub airports. Based on what you specify, the data about those airports and every airport they connect is stored in the database. Selecting a large hub like Chicago or Atlanta generates a large database. Selecting an obscure hub like Adak Island generates a much smaller database. Also, when you first open the Data dialog, the left-hand column has one airport name (Adak Island in Alaska) with a check mark. Do not deselect Adak. This would mean there are no hubs. If there are no hubs there are no connections, and you cannot enter any data. If there are no connections, exit the application, and restart the flights program without initializing the archive. The right hand column has one airport listed (Anchorage), which is the only destination available from Adak Island. The fields in the center of the window show the number of hubs and connections, and the number of airlines, flights, and seats that can be booked on those connections in one week. 2. Select an airport in the Connections column to transfer it to the Hubs column. 3. Use the Data dialog to specify how much data to use. Select Anchorage in the Connections list. Anchorage appears in the Hubs list, along with Adak, and more choices appear in the Connections list. The connections list has changed to include all the airports accessible from Adak and Anchorage. (More hubs typically result in more connections and flights.) 4. Select just one or two small hubs (ADC and ANC) to minimize load time required. (For example if you choose Boston and Chicago, which are large hubs, loading all the data can take several minutes.) 5. Click the Run tab. 6. Click Load. A message on the status line at the bottom of the dialog shows that the database has been loaded.

(Data comes from the CSV files in flights dir>\src\main\resources\data.) 7. After the database is loaded, click Start to run the Flights program.

Understanding the Flights application


When you start the Flights application the dashboard shows information about transactions and lets you control and balance the transaction processes.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 135

| Introduction To Flights Demo | 136

While the application runs, one or more Flights clients send many transactions to the Flights database. The dashboard provides sliders that you can use to control and balance the following factors that affect performance (transactions per second (TPS): Number of client threads Percent of transactions that change the database (updates and inserts as distinguished from reads and writes) Frequency at which clients connect to the chorus.

As you adjust these factors, using the sliders on the dashboard, a real-time display of TPS shows the effect of the adjustments. At this point, a single Flights client is making queries to the Flights database at a certain rate, which is shown as transactions per second (TPS) in the window. With the first slider (number of client threads) set to 1, there is only one client operating against the database. At the time of this screen capture the TPS is 1,127 with a target of 10,000. As shown, the target number of client threads is 1, the percent update is 0, and the reconnect interval is also 0. Shortly after the application starts running it generates a message similar to the following in the terminal window where you started the program: Next flight leaves at 16:20 in 178 minutes

Flights Application Details


Definitions of controls and statistics in the Flights application. Sliders Number of client threads allows you to control the number of concurrent clients interacting with the database. Percent Update defines the percentage of transactions that actually change the database (as opposed to just reading) during the running phase of the application (next section). Reconnect Interval allows you to specify the frequency (in milliseconds) at which clients reconnect to NuoDB hosts. This is important when adding additional transaction engines or storage managers, to force new clients to connect to new hosts. Database statistics You can graphically display up to four database statistics simultaneously in the center sub-window. Each graphic has a different color. o Database Transactions per Second (TPS ) total and local. Local TPS shows the transaction rate of the local client for all threads.

o Total TPS represents all database transactions, across all clients ( See more about this in the section on bookers). Latency at Queue represents the round-trip time for a transaction to return from the server.

Latency at Client represents the average time a request is forced to wait on the client in its own queue. Buttons for application operation Load loads the database with all the flight data as specified in the Data window. During this phase, all buttons are disabled (grayed out). Start initiates the simulation of searches against (and possibly updates to) the Flights database.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 136

| Introduction To Flights Demo | 137

Pause halts all transactions against the database. A subsequent Start will continue the transactions. Benchmark allows you to create a file with benchmark data. See Benchmark section for more. NOTE Reset is not working at this time. Do not select this button or you may have to restart the dashboard.

Optimize Performance of Flights Application


You can use the UI controls on the Flights dashboard to experiment with factors that can optimize performance of the application. 1. While the Flights application is running, observe that the TIPS is about 1,277 with one client thread. 2. Change the setting for the number of client threads from the default (1) to 4:

3. Observe a change in the TPS as four clients generate transactions. With four clients, the TPS increases to about 2200 TPS. 4. Experiment with the slider and see how many clients maximize the TPS. At some point (100 in this example), you see a reduction in TPS and a corresponding increase in server latency (latency at queue) and client latency At this setting, performance of the application is at a maximum. The next step is to add more resources; a second NuoDB transaction engine running on another host is required.

Add transaction engines to Flights application


Adding transaction engines on additional hosts directly reduces the latency of the client and server. The NuoDB broker distributes load across the servers. 1. Find another host to add to the NuoDB system for Flights. 2. Make sure that NuoDB is installed on the new host.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 137

| Introduction To Flights Demo | 138

3. Start a NuoDB transaction engine on the new host (if one is not already running). Be sure to specify the host running the NuoDB broker (the first host you configured) as a peer: java -jar nuoagent.jar --peer <hostname or ip address of peer system>

4. Make sure that your firewall does not block traffic on the private network. (For example, on Windows, select Windows Firewall in the Control Panel. In the navigation pane, select Turn Windows Firewall on or off. Turn off Windows Firewall for the private network.) 5. Enable connection for Flights clients on the new host: nuodb chorus Flights 6. Move the slider labeled Reconnect Interval up from zero to a higher setting. This setting determines the frequency (in milliseconds) at which the client asks the NuoDB broker for a new connection to a transaction engine. NOTE Currently NuoDB brokers distribute connections using a round-robin approach. Other approaches have not yet been implemented. 7. Observe the TPS as shown on the dashboard. As soon as the broker begins distributing transaction load across multiple transaction engines, the TPS dips briefly as the new server acquires data, then the TPS goes up and the latencies go down.

Add Updates
By default, Flights clients read flight information from the database, not performing updates. For this activity you use the Percent Update slider on the dashboard. 1. To add updates to the kinds of transactions performed by the application, slide the Percent Update slider up to a percentage of 50%. This setting specifies that up to 50% of all database read transactions may generate write transactions, as clients reserve seats on flights. 2. Observe that this increase in updates leads to transaction update conflict messages, such as the following, as threads conflict over access to records: SqlException: update conflict in table FLIGHTS.SEATS

Add Client by Configuring a Flight Booker


You can add a client to the Flights application by specifying flight bookers from the Flights dashboard. At some point, the Flights application that generates client requests may be unable to generate enough requests to load all the NuoDB transaction engines that are available. At that point, you can increase load on the database by running additional hosts of the Flights client generator (referred to as a flight booker). Typically you configure an additional host to handle increasing the load. The following script listens for requests on port 48005, and starts up a flight booker when it is called from the dashboard. It appears on the dashboard as a tab labeled Bookers. You can integrate new flight bookers from the dashboard by specifying the new booker and clicking Add. Also, the flight bookers report their statistics to the Flights dashboard. The dashboard displays the information graphically, providing a clear performance picture across the NuoDB system.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 138

| Introduction To Flights Demo | 139

NOTE A flight booker is supported only on Linux as an xinetd service. 1. Put the following script in a file in /etc/xinetd.d on the host where you want to run the broker:

# default: off # description: This is the NuoDB Flights load driver client. service NuoDB-driver { type = UNLISTED port = 48005 socket_type = stream protocol = tcp wait = no user = cloud server = /usr/bin/java server_args = -cp /opt/nuodb/samples/flights/flights.jar com.nuodb.loaddriver.TransactionGenerator --agent disable = no } 2. Start the Flights Dashboard. 3. In the field labeled New Booker, enter the hostname or ip address of the host where the booker script is located. 4. Select Add to add the booker to the list of remote bookers. 5. Click Run 6. Click Start on the dashboard. All the specified bookers start up on their remote servers, passing them their configuration information so they are able to operate against the NuoDB database. 7. Go to the Settings tab and click Save. The next time you bring up the dashboard, the bookers will be listed as part of the Flights reservation system. NOTE Viewing the TPS rate of remote bookers in the dashboard is not yet supported.

Benchmark Runtime
Run tests to determine the maximum TPS with specific settings. 1. Open the Flights dashboard if it is not already open. 2. Click Settings to set warm-up time and benchmark run time (both in seconds). 3. Click Benchmark to run a time-bounded test with the current settings and report on the maximum TPS attained. The Flights database loads (if not already loaded), warms up, and benchmark is launched. At the end of the benchmark, the results are posted in the status bar at the bottom of the Run window.

Troubleshooting
If all of the buttons in the Run window are disabled, save your settings in the Settings window, exit the dashboard and restart the Flights application.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 139

| Introduction To Flights Demo | 140

Restarting the tutorial


How to start the tutorial with all new data 1. Stop all NuoDB processes. (You can manually shut down the processes, or use the NuoDB Console to show all running servers in a chorus and shut them down.) 2. Remove the session.dashboard file. 3. Delete the archive directory for the database. cd c:\temp\nuodb rm r flights 4. Be sure to use the initialize argument with the nuodb archive command to create new storage for the NuoDB system.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 140

| Third Party Acknowledgments | 142

Third Party Acknowledgments


EditLine Library Parts of NuoDB use the EditLine library that is: Copyright (c) 1992, 1993 The Regents of the University of California. All rights reserved. This code is derived from software contributed to Berkeley by Christos Zoulas of Cornell University. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. PostgreSQL NuoDB SQL Reference documentation is partially based on PostgreSQL documentation. PostgreSQL is released under the PostgreSQL License , a liberal Open Source license, similar to the BSD or MIT licenses. PostgreSQL Database Management System (formerly known as Postgres, then as Postgres95) Portions Copyright (c) 1996-2010, The PostgreSQL Global Development Group Portions Copyright (c) 1994, The Regents of the University of California Permission to use, copy, modify, and distribute this software and its documentation for any purpose, without fee, and without a written agreement is hereby granted, provided that the above copyright notice and this paragraph and the following two paragraphs appear in all copies. IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

| Copyright 2012 NuoDB, Inc. All rights reserved. | 142

You might also like