This document provides an overview of the H2 database engine and how to use its console application. It discusses installation, requirements, supported platforms, directory structure, starting the console, login process, executing queries, and disconnecting. It also covers using H2 with JDBC, servers, frameworks like Hibernate and Glassfish, databases in web applications, and CSV support for import, export, and reading files.
This document provides an overview of the H2 database engine and how to use its console application. It discusses installation, requirements, supported platforms, directory structure, starting the console, login process, executing queries, and disconnecting. It also covers using H2 with JDBC, servers, frameworks like Hibernate and Glassfish, databases in web applications, and CSV support for import, export, and reading files.
This document provides an overview of the H2 database engine and how to use its console application. It discusses installation, requirements, supported platforms, directory structure, starting the console, login process, executing queries, and disconnecting. It also covers using H2 with JDBC, servers, frameworks like Hibernate and Glassfish, databases in web applications, and CSV support for import, export, and reading files.
This document provides an overview of the H2 database engine and how to use its console application. It discusses installation, requirements, supported platforms, directory structure, starting the console, login process, executing queries, and disconnecting. It also covers using H2 with JDBC, servers, frameworks like Hibernate and Glassfish, databases in web applications, and CSV support for import, export, and reading files.
1 of 180 Table of Contents Embedding H2 in an Application.....................................................................................................................................12 The H2 Console Application...........................................................................................................................................12 Step-by-Step...........................................................................................................................................................12 !nstallation.........................................................................................................................................................12 Start the Console................................................................................................................................................12 Login.................................................................................................................................................................13 Sample..............................................................................................................................................................1+ Execute..............................................................................................................................................................15 Disconnect.........................................................................................................................................................16 End....................................................................................................................................................................16 Requirements...............................................................................................................................................................17 Database Engine......................................................................................................................................................17 H2 Console..............................................................................................................................................................17 Supported Platforms......................................................................................................................................................17 !nstalling the Software..................................................................................................................................................17 Directory Structure........................................................................................................................................................17 Starting and Using the H2 Console.................................................................................................................................18 Firewall...................................................................................................................................................................19 Testing Java............................................................................................................................................................19 Error Nessage 'Port may be in use'...........................................................................................................................19 Using another Port...................................................................................................................................................19 Connecting to the Server using a Browser.................................................................................................................19 Nultiple Concurrent Sessions....................................................................................................................................19 Login......................................................................................................................................................................20 Error Nessages........................................................................................................................................................20 Adding Database Drivers..........................................................................................................................................20 Using the H2 Console...............................................................................................................................................20 !nserting Table Names or Column Names..................................................................................................................20 Disconnecting and Stopping the Application...............................................................................................................20 Special H2 Console Syntax.............................................................................................................................................20 Settings of the H2 Console............................................................................................................................................21 Connecting to a Database using JDBC............................................................................................................................21 Creating New Databases................................................................................................................................................22 Using the Server...........................................................................................................................................................22 Starting the Server Tool from Command Line............................................................................................................22 Connecting to the TCP Server...................................................................................................................................22 Starting the TCP Server within an Application............................................................................................................22 Stopping a TCP Server from Another Process.............................................................................................................22 Using Hibernate............................................................................................................................................................23 Using TopLink and Glassfish..........................................................................................................................................23 Using EclipseLink..........................................................................................................................................................23 Using Apache ActiveNQ.................................................................................................................................................23 Using H2 within NetBeans..............................................................................................................................................2+ Using H2 with jOOQ......................................................................................................................................................2+ Using Databases in Web Applications.............................................................................................................................2+ Embedded Node......................................................................................................................................................25 Server Node............................................................................................................................................................25 Using a Servlet Listener to Start and Stop a Database................................................................................................25 Using the H2 Console Servlet....................................................................................................................................25 Android........................................................................................................................................................................26 CSv (Comma Separated values) Support........................................................................................................................27 Reading a CSv File from Within a Database...............................................................................................................27 !mporting Data from a CSv File................................................................................................................................27 Writing a CSv File from Within a Database................................................................................................................27 Writing a CSv File from a Java Application.................................................................................................................27 Reading a CSv File from a Java Application...............................................................................................................28 Upgrade, Backup, and Restore.......................................................................................................................................28 Database Upgrade...................................................................................................................................................28 Backup using the Script Tool....................................................................................................................................28 Restore from a Script...............................................................................................................................................28 Online Backup.........................................................................................................................................................28 Command Line Tools.....................................................................................................................................................29 The Shell Tool...............................................................................................................................................................29 Using OpenOffice Base..................................................................................................................................................30 Java Web Start f JNLP...................................................................................................................................................30 Using a Connection Pool................................................................................................................................................30 2 of 180 Fulltext Search..............................................................................................................................................................31 Using the Native Fulltext Search...............................................................................................................................31 Using the Lucene Fulltext Search..............................................................................................................................31 User-Defined variables..................................................................................................................................................32 Date and Time..............................................................................................................................................................33 Using Spring.................................................................................................................................................................33 Using the TCP Server...............................................................................................................................................33 Error Code !ncompatibility........................................................................................................................................33 OSGi............................................................................................................................................................................3+ Java Nanagement Extension (JNX)................................................................................................................................3+ Feature List..................................................................................................................................................................35 Nain Features..........................................................................................................................................................35 Additional Features..................................................................................................................................................35 SQL Support............................................................................................................................................................35 Security Features.....................................................................................................................................................36 Other Features and Tools.........................................................................................................................................36 Comparison to Other Database Engines..........................................................................................................................36 DaffodilDb and One$Db............................................................................................................................................37 NcKoi......................................................................................................................................................................37 H2 in Use.....................................................................................................................................................................37 Connection Nodes.........................................................................................................................................................37 Embedded Node......................................................................................................................................................37 Server Node............................................................................................................................................................38 Nixed Node.............................................................................................................................................................38 Database URL Overview................................................................................................................................................39 Connecting to an Embedded (Local) Database................................................................................................................+0 !n-Nemory Databases...................................................................................................................................................+0 Database Files Encryption..............................................................................................................................................+0 Creating a New Database with File Encryption...........................................................................................................+0 Connecting to an Encrypted Database.......................................................................................................................+0 Encrypting or Decrypting a Database........................................................................................................................+1 Database File Locking....................................................................................................................................................+1 Opening a Database Only if it Already Exists...................................................................................................................+1 Closing a Database........................................................................................................................................................+1 Delayed Database Closing........................................................................................................................................+1 Don't Close a Database when the vN Exits................................................................................................................+2 Execute SQL on Connection...........................................................................................................................................+2 !gnore Unknown Settings..............................................................................................................................................+2 Changing Other Settings when Opening a Connection.....................................................................................................+2 Custom File Access Node...............................................................................................................................................+2 Nultiple Connections.....................................................................................................................................................+3 Opening Nultiple Databases at the Same Time..........................................................................................................+3 Nultiple Connections to the Same Database: ClientfServer.........................................................................................+3 Nultithreading Support.............................................................................................................................................+3 Locking, Lock-Timeout, Deadlocks............................................................................................................................+3 Avoiding Deadlocks..................................................................................................................................................++ Database File Layout.....................................................................................................................................................++ Noving and Renaming Database Files.......................................................................................................................++ Backup....................................................................................................................................................................++ Logging and Recovery...................................................................................................................................................++ Compatibility.................................................................................................................................................................++ Compatibility Nodes.................................................................................................................................................+5 DB2 Compatibility Node...........................................................................................................................................+5 Derby Compatibility Node.........................................................................................................................................+5 HSQLDB Compatibility Node.....................................................................................................................................+5 NS SQL Server Compatibility Node............................................................................................................................+5 NySQL Compatibility Node.......................................................................................................................................+5 Oracle Compatibility Node........................................................................................................................................+6 PostgreSQL Compatibility Node................................................................................................................................+6 Auto-Reconnect............................................................................................................................................................+6 Automatic Nixed Node..................................................................................................................................................+6 Page Size......................................................................................................................................................................+7 Using the Trace Options................................................................................................................................................+7 Trace Options..........................................................................................................................................................+7 Setting the Naximum Size of the Trace File...............................................................................................................+7 Java Code Generation..............................................................................................................................................+8 Using Other Logging AP!s..............................................................................................................................................+8 Read Only Databases....................................................................................................................................................+8 Read Only Databases in Zip or Jar File............................................................................................................................+8 Opening a Corrupted Database.................................................................................................................................+9 Computed Columns f Function Based !ndex....................................................................................................................+9 3 of 180 Nulti-Dimensional !ndexes.............................................................................................................................................+9 User-Defined Functions and Stored Procedures...............................................................................................................50 Referencing a Compiled Nethod................................................................................................................................50 Declaring Functions as Source Code..........................................................................................................................50 Nethod Overloading.................................................................................................................................................51 Function Data Type Napping....................................................................................................................................51 Functions That Require a Connection........................................................................................................................51 Functions Throwing an Exception..............................................................................................................................51 Functions Returning a Result Set..............................................................................................................................51 Using SimpleResultSet..............................................................................................................................................51 Using a Function as a Table......................................................................................................................................52 Pluggable or User-Defined Tables...................................................................................................................................52 Triggers........................................................................................................................................................................53 Compacting a Database.................................................................................................................................................53 Cache Settings..............................................................................................................................................................5+ Performance Comparison...............................................................................................................................................55 Embedded...............................................................................................................................................................55 Client-Server...........................................................................................................................................................55 Benchmark Results and Comments...........................................................................................................................56 H2.....................................................................................................................................................................56 HSQLDB.............................................................................................................................................................56 Derby................................................................................................................................................................56 PostgreSQL........................................................................................................................................................56 NySQL...............................................................................................................................................................56 Firebird..............................................................................................................................................................56 Why Oracle f NS SQL Server f DB2 are Not Listed................................................................................................57 About this Benchmark..............................................................................................................................................57 How to Run........................................................................................................................................................57 Separate Process per Database...........................................................................................................................57 Number of Connections.......................................................................................................................................57 Real-World Tests................................................................................................................................................57 Comparing Embedded with Server Databases.......................................................................................................57 Test Platform.....................................................................................................................................................57 Nultiple Runs.....................................................................................................................................................57 Nemory Usage...................................................................................................................................................57 Delayed Operations............................................................................................................................................58 Transaction Commit f Durability..........................................................................................................................58 Using Prepared Statements.................................................................................................................................58 Currently Not Tested: Startup Time.....................................................................................................................58 PolePosition Benchmark.................................................................................................................................................58 Database Performance Tuning.......................................................................................................................................59 Keep Connections Open or Use a Connection Pool.....................................................................................................59 Use a Nodern JvN...................................................................................................................................................59 virus Scanners.........................................................................................................................................................59 Using the Trace Options...........................................................................................................................................59 !ndex Usage............................................................................................................................................................59 How Data is Stored !nternally...................................................................................................................................59 Optimizer................................................................................................................................................................60 Expression Optimization...........................................................................................................................................60 COUNT(*) Optimization............................................................................................................................................60 Updating Optimizer Statistics f Column Selectivity......................................................................................................60 !n-Nemory (Hash) !ndexes.......................................................................................................................................60 Use Prepared Statements.........................................................................................................................................61 Prepared Statements and !N(...)...............................................................................................................................61 Optimization Examples.............................................................................................................................................61 Cache Size and Type................................................................................................................................................61 Data Types..............................................................................................................................................................61 Sorted !nsert Optimization........................................................................................................................................61 Using the Built-!n Profiler..............................................................................................................................................61 Application Profiling.......................................................................................................................................................62 Analyze First............................................................................................................................................................62 Database Profiling.........................................................................................................................................................62 Statement Execution Plans............................................................................................................................................63 Displaying the Scan Count........................................................................................................................................63 Special Optimizations...............................................................................................................................................6+ How Data is Stored and How !ndexes Work....................................................................................................................6+ !ndexes...................................................................................................................................................................6+ Using Nultiple !ndexes.............................................................................................................................................65 Fast Database !mport....................................................................................................................................................66 Result Sets...................................................................................................................................................................67 Statements that Return a Result Set.........................................................................................................................67 + of 180 Limiting the Number of Rows....................................................................................................................................67 Large Result Sets and External Sorting......................................................................................................................67 Large Objects...............................................................................................................................................................68 Storing and Reading Large Objects...........................................................................................................................68 When to use CLOBfBLOB..........................................................................................................................................68 Large Object Compression........................................................................................................................................68 Linked Tables...............................................................................................................................................................68 Updatable views...........................................................................................................................................................68 Transaction !solation.....................................................................................................................................................69 Table Level Locking..................................................................................................................................................69 Lock Timeout...........................................................................................................................................................69 Nulti-version Concurrency Control (NvCC).....................................................................................................................70 Clustering f High Availability..........................................................................................................................................70 Using the CreateCluster Tool....................................................................................................................................70 Detect Which Cluster !nstances are Running..............................................................................................................71 Clustering Algorithm and Limitations.........................................................................................................................71 Two Phase Commit.......................................................................................................................................................71 Compatibility.................................................................................................................................................................72 Transaction Commit when Autocommit is On.............................................................................................................72 Keywords f Reserved Words.....................................................................................................................................72 Standards Compliance...................................................................................................................................................72 Supported Character Sets, Character Encoding, and Unicode......................................................................................72 Run as Windows Service................................................................................................................................................72 !nstall the Service....................................................................................................................................................72 Start the Service......................................................................................................................................................73 Connect to the H2 Console.......................................................................................................................................73 Stop the Service......................................................................................................................................................73 Uninstall the Service................................................................................................................................................73 Additional JDBC drivers............................................................................................................................................73 ODBC Driver.................................................................................................................................................................73 ODBC !nstallation....................................................................................................................................................73 Starting the Server...................................................................................................................................................73 ODBC Configuration.................................................................................................................................................7+ PG Protocol Support Limitations................................................................................................................................7+ Security Considerations............................................................................................................................................7+ Using Nicrosoft Access.............................................................................................................................................75 Using H2 in Nicrosoft .NET............................................................................................................................................75 Using the ADO.NET AP! on .NET...............................................................................................................................75 Using the JDBC AP! on .NET.....................................................................................................................................75 AC!D............................................................................................................................................................................75 Atomicity.................................................................................................................................................................75 Consistency.............................................................................................................................................................76 !solation..................................................................................................................................................................76 Durability................................................................................................................................................................76 Durability Problems.......................................................................................................................................................76 Ways to (Not) Achieve Durability..............................................................................................................................76 Running the Durability Test......................................................................................................................................77 Using the Recover Tool..................................................................................................................................................77 File Locking Protocols....................................................................................................................................................77 File Locking Nethod 'File'..........................................................................................................................................77 File Locking Nethod 'Socket'.....................................................................................................................................78 File Locking Nethod 'FS'...........................................................................................................................................78 Using Passwords...........................................................................................................................................................78 Using Secure Passwords...........................................................................................................................................78 Passwords: Using Char Arrays instead of Strings........................................................................................................79 Passing the User Name andfor Password in the URL..................................................................................................79 Password Hash.............................................................................................................................................................79 Protection against SQL !njection....................................................................................................................................80 What is SQL !njection...............................................................................................................................................80 Disabling Literals......................................................................................................................................................80 Using Constants.......................................................................................................................................................80 Using the ZERO() Function.......................................................................................................................................81 Protection against Remote Access..................................................................................................................................81 Restricting Class Loading and Usage..............................................................................................................................81 Security Protocols.........................................................................................................................................................81 User Password Encryption........................................................................................................................................81 File Encryption.........................................................................................................................................................82 Wrong Password f User Name Delay.........................................................................................................................82 HTTPS Connections..................................................................................................................................................82 SSLfTLS Connections.....................................................................................................................................................82 Universally Unique !dentifiers (UU!D).............................................................................................................................83 5 of 180 Recursive Queries.........................................................................................................................................................83 Settings Read from System Properties............................................................................................................................8+ Setting the Server Bind Address.....................................................................................................................................8+ Pluggable File System....................................................................................................................................................8+ Split File System...........................................................................................................................................................85 Database Upgrade........................................................................................................................................................85 Java Objects Serialization..............................................................................................................................................85 Limits and Limitations....................................................................................................................................................86 Glossary and Links........................................................................................................................................................86 !ndex...........................................................................................................................................................................87 Commands (Data Nanipulation)................................................................................................................................87 Commands (Data Definition).....................................................................................................................................87 Commands (Other)..................................................................................................................................................88 Other Grammar.......................................................................................................................................................88 System Tables.........................................................................................................................................................89 SELECT...................................................................................................................................................................89 !NSERT...................................................................................................................................................................90 UPDATE..................................................................................................................................................................90 DELETE...................................................................................................................................................................90 BACKUP..................................................................................................................................................................90 CALL.......................................................................................................................................................................91 EXPLA!N..................................................................................................................................................................91 NERGE....................................................................................................................................................................91 RUNSCR!PT.............................................................................................................................................................91 SCR!PT...................................................................................................................................................................92 SHOW.....................................................................................................................................................................92 ALTER !NDEX RENANE.............................................................................................................................................92 ALTER SCHENA RENANE..........................................................................................................................................93 ALTER SEQUENCE....................................................................................................................................................93 ALTER TABLE ADD...................................................................................................................................................93 ALTER TABLE ADD CONSTRA!NT..............................................................................................................................93 ALTER TABLE ALTER COLUNN..................................................................................................................................93 ALTER TABLE DROP COLUNN...................................................................................................................................9+ ALTER TABLE DROP CONSTRA!NT............................................................................................................................9+ ALTER TABLE SET....................................................................................................................................................95 ALTER TABLE RENANE.............................................................................................................................................95 ALTER USER ADN!N................................................................................................................................................95 ALTER USER RENANE..............................................................................................................................................95 ALTER USER SET PASSWORD...................................................................................................................................95 ALTER v!EW............................................................................................................................................................96 ANALYZE.................................................................................................................................................................96 CONNENT...............................................................................................................................................................96 CREATE AGGREGATE...............................................................................................................................................96 CREATE AL!AS.........................................................................................................................................................97 CREATE CONSTANT.................................................................................................................................................97 CREATE DONA!N.....................................................................................................................................................98 CREATE !NDEX........................................................................................................................................................98 CREATE L!NKED TABLE............................................................................................................................................98 CREATE ROLE..........................................................................................................................................................99 CREATE SCHENA.....................................................................................................................................................99 CREATE SEQUENCE.................................................................................................................................................99 CREATE TABLE......................................................................................................................................................100 CREATE TR!GGER..................................................................................................................................................100 CREATE USER........................................................................................................................................................101 CREATE v!EW........................................................................................................................................................101 DROP AGGREGATE.................................................................................................................................................101 DROP AL!AS..........................................................................................................................................................102 DROP ALL OBJECTS...............................................................................................................................................102 DROP CONSTANT..................................................................................................................................................102 DROP DONA!N......................................................................................................................................................102 DROP !NDEX.........................................................................................................................................................102 DROP ROLE...........................................................................................................................................................103 DROP SCHENA......................................................................................................................................................103 DROP SEQUENCE...................................................................................................................................................103 DROP TABLE..........................................................................................................................................................103 DROP TR!GGER.....................................................................................................................................................103 DROP USER...........................................................................................................................................................10+ DROP v!EW...........................................................................................................................................................10+ TRUNCATE TABLE..................................................................................................................................................10+ CHECKPO!NT.........................................................................................................................................................10+ CHECKPO!NT SYNC................................................................................................................................................105 6 of 180 CONN!T................................................................................................................................................................105 CONN!T TRANSACT!ON.........................................................................................................................................105 GRANT R!GHT.......................................................................................................................................................105 GRANT ALTER ANY SCHENA...................................................................................................................................105 GRANT ROLE.........................................................................................................................................................106 HELP.....................................................................................................................................................................106 PREPARE CONN!T.................................................................................................................................................106 REvOKE R!GHT......................................................................................................................................................106 REvOKE ROLE.......................................................................................................................................................106 ROLLBACK.............................................................................................................................................................107 ROLLBACK TRANSACT!ON......................................................................................................................................107 SAvEPO!NT...........................................................................................................................................................107 SET @...................................................................................................................................................................107 SET ALLOW_L!TERALS...........................................................................................................................................108 SET AUTOCONN!T.................................................................................................................................................108 SET CACHE_S!ZE...................................................................................................................................................108 SET CLUSTER........................................................................................................................................................108 SET B!NARY_COLLAT!ON.......................................................................................................................................109 SET COLLAT!ON....................................................................................................................................................109 SET CONPRESS_LOB..............................................................................................................................................109 SET DATABASE_EvENT_L!STENER..........................................................................................................................110 SET DB_CLOSE_DELAY...........................................................................................................................................110 SET DEFAULT_LOCK_T!NEOUT..............................................................................................................................110 SET DEFAULT_TABLE_TYPE....................................................................................................................................110 SET EXCLUS!vE.....................................................................................................................................................111 SET !GNORECASE..................................................................................................................................................111 SET JAvA_OBJECT_SER!AL!ZER..............................................................................................................................111 SET LOG................................................................................................................................................................111 SET LOCK_NODE...................................................................................................................................................112 SET LOCK_T!NEOUT..............................................................................................................................................112 SET NAX_LENGTH_!NPLACE_LOB...........................................................................................................................113 SET NAX_LOG_S!ZE...............................................................................................................................................113 SET NAX_NENORY_ROWS.....................................................................................................................................113 SET NAX_NENORY_UNDO.....................................................................................................................................113 SET NAX_OPERAT!ON_NENORY............................................................................................................................11+ SET NODE.............................................................................................................................................................11+ SET NULT!_THREADED..........................................................................................................................................11+ SET OPT!N!ZE_REUSE_RESULTS............................................................................................................................11+ SET PASSWORD.....................................................................................................................................................115 SET QUERY_STAT!ST!CS........................................................................................................................................115 SET QUERY_T!NEOUT...........................................................................................................................................115 SET REFERENT!AL_!NTEGR!TY...............................................................................................................................115 SET RETENT!ON_T!NE...........................................................................................................................................116 SET SALT HASH.....................................................................................................................................................116 SET SCHENA.........................................................................................................................................................116 SET SCHENA_SEARCH_PATH..................................................................................................................................116 SET THROTTLE......................................................................................................................................................117 SET TRACE_LEvEL.................................................................................................................................................117 SET TRACE_NAX_F!LE_S!ZE...................................................................................................................................117 SET UNDO_LOG.....................................................................................................................................................117 SET WR!TE_DELAY................................................................................................................................................118 SHUTDOWN..........................................................................................................................................................118 Alias......................................................................................................................................................................118 And Condition........................................................................................................................................................118 Array.....................................................................................................................................................................119 Boolean.................................................................................................................................................................119 Bytes.....................................................................................................................................................................119 Case......................................................................................................................................................................119 Case When............................................................................................................................................................119 Cipher...................................................................................................................................................................120 Column Definition..................................................................................................................................................120 Comments.............................................................................................................................................................120 Compare...............................................................................................................................................................120 Condition...............................................................................................................................................................121 Condition Right Hand Side......................................................................................................................................121 Constraint..............................................................................................................................................................121 Constraint Name Definition.....................................................................................................................................122 Csv Options...........................................................................................................................................................122 Data Type.............................................................................................................................................................122 Date......................................................................................................................................................................123 Decimal.................................................................................................................................................................123 7 of 180 Digit......................................................................................................................................................................123 Dollar Quoted String...............................................................................................................................................123 Expression.............................................................................................................................................................123 Factor...................................................................................................................................................................12+ Hex.......................................................................................................................................................................12+ Hex Number..........................................................................................................................................................12+ !ndex Column........................................................................................................................................................12+ !nt........................................................................................................................................................................12+ Long.....................................................................................................................................................................125 Name....................................................................................................................................................................125 Null.......................................................................................................................................................................125 Number.................................................................................................................................................................125 Numeric................................................................................................................................................................125 Operand................................................................................................................................................................126 Order....................................................................................................................................................................126 Quoted Name........................................................................................................................................................126 Referential Constraint.............................................................................................................................................126 Referential Action...................................................................................................................................................126 Script Compression Encryption................................................................................................................................127 Select Expression...................................................................................................................................................127 String....................................................................................................................................................................127 Summand..............................................................................................................................................................127 Table Expression....................................................................................................................................................128 values Expression..................................................................................................................................................128 Term.....................................................................................................................................................................128 Time.....................................................................................................................................................................128 Timestamp............................................................................................................................................................129 value....................................................................................................................................................................129 !nformation Schema...............................................................................................................................................129 Range Table..........................................................................................................................................................130 !ndex.........................................................................................................................................................................131 Aggregate Functions..............................................................................................................................................131 Numeric Functions.................................................................................................................................................131 String Functions.....................................................................................................................................................132 Time and Date Functions........................................................................................................................................132 System Functions...................................................................................................................................................133 AvG......................................................................................................................................................................133 BOOL_AND............................................................................................................................................................133 BOOL_OR..............................................................................................................................................................13+ COUNT..................................................................................................................................................................13+ GROUP_CONCAT....................................................................................................................................................13+ NAX......................................................................................................................................................................13+ N!N.......................................................................................................................................................................13+ SUN......................................................................................................................................................................135 SELECT!v!TY.........................................................................................................................................................135 STDDEv_POP.........................................................................................................................................................135 STDDEv_SANP......................................................................................................................................................135 vAR_POP...............................................................................................................................................................135 vAR_SANP............................................................................................................................................................136 ABS.......................................................................................................................................................................136 ACOS....................................................................................................................................................................136 AS!N.....................................................................................................................................................................136 ATAN....................................................................................................................................................................136 COS......................................................................................................................................................................137 COSH....................................................................................................................................................................137 COT......................................................................................................................................................................137 S!N.......................................................................................................................................................................137 S!NH.....................................................................................................................................................................137 TAN......................................................................................................................................................................138 TANH....................................................................................................................................................................138 ATAN2...................................................................................................................................................................138 B!TAND.................................................................................................................................................................138 B!TOR...................................................................................................................................................................138 B!TXOR.................................................................................................................................................................139 NOD.....................................................................................................................................................................139 CE!L!NG................................................................................................................................................................139 DEGREES...............................................................................................................................................................139 EXP.......................................................................................................................................................................139 FLOOR..................................................................................................................................................................139 LOG......................................................................................................................................................................1+0 LOG10...................................................................................................................................................................1+0 8 of 180 RAD!ANS...............................................................................................................................................................1+0 SQRT....................................................................................................................................................................1+0 P!.........................................................................................................................................................................1+0 POWER.................................................................................................................................................................1+1 RAND....................................................................................................................................................................1+1 RANDON_UU!D.....................................................................................................................................................1+1 ROUND.................................................................................................................................................................1+1 ROUNDNAG!C.......................................................................................................................................................1+1 SECURE_RAND......................................................................................................................................................1+2 S!GN.....................................................................................................................................................................1+2 ENCRYPT...............................................................................................................................................................1+2 DECRYPT...............................................................................................................................................................1+2 HASH....................................................................................................................................................................1+2 TRUNCATE............................................................................................................................................................1+3 CONPRESS............................................................................................................................................................1+3 EXPAND................................................................................................................................................................1+3 ZERO....................................................................................................................................................................1+3 ASC!!....................................................................................................................................................................1+3 B!T_LENGTH.........................................................................................................................................................1++ LENGTH................................................................................................................................................................1++ OCTET_LENGTH....................................................................................................................................................1++ CHAR....................................................................................................................................................................1++ CONCAT................................................................................................................................................................1++ CONCAT_WS.........................................................................................................................................................1+5 D!FFERENCE..........................................................................................................................................................1+5 HEXTORAW...........................................................................................................................................................1+5 RAWTOHEX...........................................................................................................................................................1+5 !NSTR...................................................................................................................................................................1+5 !NSERT Function....................................................................................................................................................1+6 LOWER..................................................................................................................................................................1+6 UPPER...................................................................................................................................................................1+6 LEFT.....................................................................................................................................................................1+6 R!GHT...................................................................................................................................................................1+6 LOCATE.................................................................................................................................................................1+7 POS!T!ON.............................................................................................................................................................1+7 LPAD.....................................................................................................................................................................1+7 RPAD....................................................................................................................................................................1+7 LTR!N...................................................................................................................................................................1+7 RTR!N...................................................................................................................................................................1+8 TR!N.....................................................................................................................................................................1+8 REGEXP_REPLACE..................................................................................................................................................1+8 REPEAT.................................................................................................................................................................1+8 REPLACE...............................................................................................................................................................1+8 SOUNDEX..............................................................................................................................................................1+9 SPACE...................................................................................................................................................................1+9 STR!NGDECODE....................................................................................................................................................1+9 STR!NGENCODE....................................................................................................................................................1+9 STR!NGTOUTF8.....................................................................................................................................................1+9 SUBSTR!NG...........................................................................................................................................................150 UTF8TOSTR!NG.....................................................................................................................................................150 XNLATTR..............................................................................................................................................................150 XNLNODE..............................................................................................................................................................150 XNLCONNENT.......................................................................................................................................................150 XNLCDATA............................................................................................................................................................151 XNLSTARTDOC......................................................................................................................................................151 XNLTEXT...............................................................................................................................................................151 TO_CHAR..............................................................................................................................................................151 ARRAY_GET...........................................................................................................................................................151 ARRAY_LENGTH....................................................................................................................................................152 ARRAY_CONTA!NS.................................................................................................................................................152 AUTOCONN!T.......................................................................................................................................................152 CANCEL_SESS!ON..................................................................................................................................................152 CASEWHEN Function..............................................................................................................................................152 CAST.....................................................................................................................................................................153 COALESCE.............................................................................................................................................................153 CONvERT..............................................................................................................................................................153 CURRvAL...............................................................................................................................................................153 CSvREAD..............................................................................................................................................................153 CSvWR!TE.............................................................................................................................................................15+ DATABASE.............................................................................................................................................................15+ DATABASE_PATH...................................................................................................................................................155 9 of 180 DECODE................................................................................................................................................................155 D!SK_SPACE_USED................................................................................................................................................155 F!LE_READ............................................................................................................................................................155 GREATEST.............................................................................................................................................................155 !DENT!TY..............................................................................................................................................................156 !FNULL..................................................................................................................................................................156 LEAST...................................................................................................................................................................156 LOCK_NODE..........................................................................................................................................................156 LOCK_T!NEOUT.....................................................................................................................................................156 L!NK_SCHENA.......................................................................................................................................................157 NENORY_FREE......................................................................................................................................................157 NENORY_USED.....................................................................................................................................................157 NEXTvAL...............................................................................................................................................................157 NULL!F..................................................................................................................................................................157 NvL2.....................................................................................................................................................................158 READONLY............................................................................................................................................................158 ROWNUN..............................................................................................................................................................158 SCHENA................................................................................................................................................................158 SCOPE_!DENT!TY..................................................................................................................................................158 SESS!ON_!D..........................................................................................................................................................159 SET.......................................................................................................................................................................159 TABLE...................................................................................................................................................................159 TRANSACT!ON_!D.................................................................................................................................................159 TRUNCATE_vALUE.................................................................................................................................................160 USER.....................................................................................................................................................................160 H2vERS!ON...........................................................................................................................................................160 CURRENT_DATE....................................................................................................................................................160 CURRENT_T!NE.....................................................................................................................................................160 CURRENT_T!NESTANP...........................................................................................................................................161 DATEADD..............................................................................................................................................................161 DATED!FF.............................................................................................................................................................161 DAYNANE..............................................................................................................................................................161 DAY_OF_NONTH...................................................................................................................................................161 DAY_OF_WEEK......................................................................................................................................................162 DAY_OF_YEAR.......................................................................................................................................................162 EXTRACT...............................................................................................................................................................162 FORNATDATET!NE................................................................................................................................................162 HOUR....................................................................................................................................................................162 N!NUTE.................................................................................................................................................................163 NONTH.................................................................................................................................................................163 NONTHNANE.........................................................................................................................................................163 PARSEDATET!NE...................................................................................................................................................163 QUARTER..............................................................................................................................................................163 SECOND................................................................................................................................................................16+ WEEK....................................................................................................................................................................16+ YEAR.....................................................................................................................................................................16+ !ndex.........................................................................................................................................................................165 !NT Type...............................................................................................................................................................165 BOOLEAN Type......................................................................................................................................................165 T!NY!NT Type........................................................................................................................................................165 SNALL!NT Type.....................................................................................................................................................166 B!G!NT Type.........................................................................................................................................................166 !DENT!TY Type......................................................................................................................................................166 DEC!NAL Type.......................................................................................................................................................166 DOUBLE Type........................................................................................................................................................167 REAL Type.............................................................................................................................................................167 T!NE Type.............................................................................................................................................................167 DATE Type............................................................................................................................................................167 T!NESTANP Type..................................................................................................................................................167 B!NARY Type.........................................................................................................................................................168 OTHER Type..........................................................................................................................................................168 vARCHAR Type......................................................................................................................................................168 vARCHAR_!GNORECASE Type................................................................................................................................168 CHAR Type............................................................................................................................................................169 BLOB Type............................................................................................................................................................169 CLOB Type............................................................................................................................................................169 UU!D Type............................................................................................................................................................170 ARRAY Type..........................................................................................................................................................170 GEONETRY Type...................................................................................................................................................170 Portability...................................................................................................................................................................171 Environment...............................................................................................................................................................171 10 of 180 Building the Software..................................................................................................................................................171 Switching the Source Code.....................................................................................................................................171 Build Targets..............................................................................................................................................................172 Using Lucene 2 f 3.................................................................................................................................................172 Using Naven 2............................................................................................................................................................172 Using a Central Repository......................................................................................................................................172 Naven Plugin to Start and Stop the TCP Server........................................................................................................172 Using Snapshot version..........................................................................................................................................172 Using Eclipse...............................................................................................................................................................173 Translating.................................................................................................................................................................173 Providing Patches........................................................................................................................................................173 Reporting Problems or Requests...................................................................................................................................17+ Automated Build..........................................................................................................................................................17+ Generating Railroad Diagrams......................................................................................................................................17+ Change Log................................................................................................................................................................175 Roadmap....................................................................................................................................................................175 History of this Database Engine....................................................................................................................................175 Why Java....................................................................................................................................................................175 Supporters..................................................................................................................................................................175 ! Have a Problem or Feature Request......................................................................................................................177 Are there Known Bugs? When is the Next Release?..................................................................................................177 !s this Database Engine Open Source?....................................................................................................................177 !s Commercial Support Available?...........................................................................................................................177 How to Create a New Database?.............................................................................................................................178 How to Connect to a Database?..............................................................................................................................178 Where are the Database Files Stored?.....................................................................................................................178 What is the Size Limit (Naximum Size) of a Database?.............................................................................................178 !s it Reliable?.........................................................................................................................................................178 Why is Opening my Database Slow?........................................................................................................................179 Ny Query is Slow...................................................................................................................................................179 H2 is very Slow......................................................................................................................................................179 Column Names are !ncorrect?.................................................................................................................................179 Float is Double?.....................................................................................................................................................179 !s the GCJ version Stable? Faster?..........................................................................................................................180 How to Translate this Project?................................................................................................................................180 How to Contribute to this Project?...........................................................................................................................180 11 of 180 Quickstart Embedding H2 in an Application The H2 Console Application Embedding H2 in an Application This database can be used in embedded mode, or in server mode. To use it in embedded mode, you need to: Add the h2*.jar to the classpath (H2 does not have any dependencies) Use the JDBC driver class: org.h2.Driver The database URL jdbc:h2:~ftest opens the database test in your user home directory A new database is automatically created The H2 Console Application The Console lets you access a SQL database using a browser interface.
!f you don't have Windows XP, or if something does not work as expected, please see the detailed description in the Tutorial. Step-by-Step nstallation !nstall the software using the Windows !nstaller (if you did not yet do that). Start the Console Click [Start|, [All Programs|, [H2|, and [H2 Console (Command Line)|: A new console window appears: 12 of 180 Also, a new browser page should open with the URL http:fflocalhost:8082. You may get a security warning from the firewall. !f you don't want other computers in the network to access the database on your machine, you can let the firewall block these connections. Only local connections are required at this time. !ogin Select [Generic H2| and click [Connect|: You are now logged in. 13 of 180 Sample Click on the [Sample SQL Script|: The SQL commands appear in the command area. 1+ of 180 E"ecute Click [Run| On the left side, a new entry TEST is added below the database icon. The operations and results of the statements are shown 15 of 180 below the script. Disconnect Click on [Disconnect|: to close the connection. End Close the console window. For more information, see the Tutorial. 16 of 180 nstallation Requirements Supported Platforms !nstalling the Software Directory Structure #e$uirements To run this database, the following software stack is known to work. Other software most likely also works, but is not tested as much. Database Engine Windows XP or vista, Nac OS X, or Linux Sun Java 6 or newer Recommended Windows file system: NTFS (FAT32 only supports files up to + GB) H2 Console Nozilla Firefox Supported %latforms As this database is written in Java, it can run on many different platforms. !t is tested with Java 6 and 7. Currently, the database is developed and tested on Windows 8 and Nac OS X using Java 6, but it also works in many other operating systems and using other Java runtime environments. All major operating systems (Windows XP, Windows vista, Windows 7, Nac OS, Ubuntu,...) are supported. nstalling the Soft&are To install the software, run the installer or unzip it to a directory of your choice. Directory Structure After installing, you should get the following directory structure: Directory Contents bin JAR and batch files docs Documentation docsfhtml HTNL pages docsfjavadoc Javadoc files ext External dependencies (downloaded when building) service Tools to run the database as a Windows Service src Source files srcfdocsrc Documentation sources srcfinstaller !nstaller, shell, and release build script srcfmain Database engine source code srcftest Test source code srcftools Tools and database adapters source code 17 of 180 Tutorial Starting and Using the H2 Console Special H2 Console Syntax Settings of the H2 Console Connecting to a Database using JDBC Creating New Databases Using the Server Using Hibernate Using TopLink and Glassfish Using EclipseLink Using Apache ActiveNQ Using H2 within NetBeans Using H2 with jOOQ Using Databases in Web Applications Android CSv (Comma Separated values) Support Upgrade, Backup, and Restore Command Line Tools The Shell Tool Using OpenOffice Base Java Web Start f JNLP Using a Connection Pool Fulltext Search User-Defined variables Date and Time Using Spring OSGi Java Nanagement Extension (JNX) Starting and 'sing the H2 Console The H2 Console application lets you access a database using a browser. This can be a H2 database, or another database that supports the JDBC AP!.
This is a clientfserver application, so both a server and a client (a browser) are required to run it. Depending on your platform and environment, there are multiple ways to start the H2 Console: OS Start Windows Click [Start|, [All Programs|, [H2|, and [H2 Console (Command Line)| An icon will be added to the system tray: !f you don't get the window and the system tray icon, then maybe Java is not installed correctly (in this case, try another way to start the application). A browser window should open and point to the login page at http:fflocalhost:8082. Windows Open a file browser, navigate to h2fbin, and double click on h2.bat. A console window appears. !f there is a problem, you will see an error message in this window. A browser window will open and point to the login page (URL: http:fflocalhost:8082). Any Double click on the h2*.jar file. This only works if the .jar suffix is associated with Java. 18 of 180 Any Open a console window, navigate to the directory h2fbin, and type: java -jar h2*.jar (ire&all !f you start the server, you may get a security warning from the firewall (if you have installed one). !f you don't want other computers in the network to access the application on your machine, you can let the firewall block those connections. The connection from the local machine will still work. Only if you want other computers to access the database on this computer, you need allow remote connections in the firewall. !t has been reported that when using Kaspersky 7.0 with firewall, the H2 Console is very slow when connecting over the !P address. A workaround is to connect using 'localhost'. A small firewall is already built into the server: other computers may not connect to the server by default. To change this, go to 'Preferences' and select 'Allow connections from other computers'. Testing )a*a To find out which version of Java is installed, open a command prompt and type: java -version !f you get an error message, you may need to add the Java binary directory to the path environment variable. Error +essage ,%ort may be in use, You can only start one instance of the H2 Console, otherwise you will get the following error message: "The Web server could not be started. Possible cause: another server is already running...". !t is possible to start multiple console applications on the same computer (using different ports), but this is usually not required as the console supports multiple concurrent connections. 'sing another %ort !f the default port of the H2 Console is already in use by another application, then a different port needs to be configured. The settings are stored in a properties file. For details, see Settings of the H2 Console. The relevant entry is webPort. !f no port is specified for the TCP and PG servers, each service will try to listen on its default port. !f the default port is already in use, a random port is used. Connecting to the Ser*er using a -ro&ser !f the server started successfully, you can connect to it using a web browser. Javascript needs to be enabled. !f you started the server on the same computer as the browser, open the URL http:fflocalhost:8082. !f you want to connect to the application from another computer, you need to provide the !P address of the server, for example: http:ff192.168.0.2:8082. !f you enabled SSL on the server side, the URL needs to start with https:ff. +ultiple Concurrent Sessions Nultiple concurrent browser sessions are supported. As that the database objects reside on the server, the amount of concurrent work is limited by the memory available to the server application. 19 of 180 !ogin At the login page, you need to provide connection information to connect to a database. Set the JDBC driver class of your database, the JDBC URL, user name, and password. !f you are done, click [Connect|. You can save and reuse previously saved settings. The settings are stored in a properties file (see Settings of the H2 Console). Error +essages Error messages in are shown in red. You can showfhide the stack trace of the exception by clicking on the message. Adding Database Dri*ers To register additional JDBC drivers (NySQL, PostgreSQL, HSQLDB,...), add the jar file names to the environment variables H2DR!vERS or CLASSPATH. Example (Windows): to add the HSQLDB JDBC driver C:Programshsqldblibhsqldb.jar, set the environment variable H2DR!vERS to C:Programshsqldblibhsqldb.jar. Nultiple drivers can be set; entries need to be separated by ; (Windows) or : (other operating systems). Spaces in the path names are supported. The settings must not be quoted. 'sing the H2 Console The H2 Console application has three main panels: the toolbar on top, the tree on the left, and the queryfresult panel on the right. The database objects (for example, tables) are listed on the left. Type a SQL command in the query panel and click [Run|. The result appears just below the command. nserting Table .ames or Column .ames To insert table and column names into the script, click on the item in the tree. !f you click on a table while the query is empty, then SELECT * FRON ... is added. While typing a query, the table that was used is expanded in the tree. For example if you type SELECT * FRON TEST T WHERE T. then the table TEST is expanded. Disconnecting and Stopping the Application To log out of the database, click [Disconnect| in the toolbar panel. However, the server is still running and ready to accept new sessions. To stop the server, right click on the system tray icon and select [Exit|. !f you don't have the system tray icon, navigate to [Preferences| and click [Shutdown|, press [Ctrl|+[C| in the console where the server was started (Windows), or close the console window. Special H2 Console Synta" The H2 Console supports a few built-in commands. Those are interpreted within the H2 Console, so they work with any database. Built-in commands need to be at the beginning of a statement (before any remarks), otherwise they are not parsed correctly. !f in doubt, add ; before the command. Command(s) Description @autocommit_true; @autocommit_false; Enable or disable autocommit. @cancel; Cancel the currently running statement. @columns null null TEST; @index_info null null TEST; @tables; @tables null null TEST; Call the corresponding DatabaseNetaData.get method. Patterns are case sensitive (usually identifiers are uppercase). For information about the parameters, see the Javadoc documentation. Nissing parameters at the end of the line are set to null. The complete list of metadata commands is: @attributes, @best_row_identifier, @catalogs, @columns, @column_privileges, @cross_references, @exported_keys, @imported_keys, @index_info, 20 of 180 @primary_keys, @procedures, @procedure_columns, @schemas, @super_tables, @super_types, @tables, @table_privileges, @table_types, @type_info, @udts, @version_columns @edit select * from test; Use an updatable result set. @generated insert into test() v alues(); Show the result of Statement.getGeneratedKeys(). @history; List the command history. @info; Display the result of various Connection and DatabaseNetaData methods. @list select * from test; Show the result set in list format (each column on its own line, with row numbers). @loop 1000 select ?, ?f*rnd*f; @loop 1000 @statement select ?; Run the statement this many times. Parameters (?) are set using a loop from 0 up to x - 1. Random values are used for each ?f*rnd*f. A Statement object is used instead of a PreparedStatement if @statement is used. Result sets are read until ResultSet.next() returns false. Timing information is printed. @maxrows 20; Set the maximum number of rows to display. @memory; Show the used and free memory. This will call System.gc(). @meta select 1; List the ResultSetNetaData after running the query. @parameter_meta select ?; Show the result of the PreparedStatement.getParameterNetaData() calls. The statement is not executed. @prof_start; call hash('SHA256', '', 1000000 ); @prof_stop; Startfstop the built-in profiling tool. The top 3 stack traces of the statement(s) between start and stop are listed (if there are 3). @prof_start; @sleep 10; @prof_stop; Sleep for a number of seconds. Used to profile a long running query or operation that is running in another session (but in the same process). @transaction_isolation; @transaction_isolation 2; Display (without parameters) or change (with parameters 1, 2, +, 8) the transaction isolation level. Settings of the H2 Console The settings of the H2 Console are stored in a configuration file called .h2.server.properties in you user home directory. For Windows installations, the user home directory is usually C:Documents and Settings[username| or C:Users[username|. The configuration file contains the settings of the application and is automatically created when the H2 Console is first started. Supported settings are: webAllowOthers: allow other computers to connect. webPort: the port of the H2 Console webSSL: use encrypted (HTTPS) connections. !n addition to those settings, the properties of the last recently used connection are listed in the form <number>=<name>{ <driver>{<url>{<user> using the escape character . Example: 1=Generic H2 (Embedded){org.h2.Driver{jdbc:h2:~ftest{sa Connecting to a Database using )D-C To connect to a database, a Java application first needs to load the database driver, and then get a connection. A simple way to do that is using the following code: import java.sql.*; public class Test { public static void main(String[| a) throws Exception { Class.forName("org.h2.Driver"); Connection conn = DriverNanager. getConnection("jdbc:h2:~ftest", "sa", ""); ff add application code here conn.close(); ) ) This code first loads the driver (Class.forName(...)) and then opens a connection (using DriverNanager.getConnection()). The driver name is "org.h2.Driver". The database URL always needs to start with jdbc:h2: to be recognized by this database. The 21 of 180 second parameter in the getConnection() call is the user name (sa for System Administrator in this example). The third parameter is the password. !n this database, user names are not case sensitive, but passwords are. Creating .e& Databases By default, if the database specified in the URL does not yet exist, a new (empty) database is created automatically. The user that created the database automatically becomes the administrator of this database. Auto-creating new database can be disabled, see Opening a Database Only if it Already Exists. 'sing the Ser*er H2 currently supports three server: a web server (for the H2 Console), a TCP server (for clientfserver connections) and an PG server (for PostgreSQL clients). Please note that only the web server supports browser connections. The servers can be started in different ways, one is using the Server tool. Starting the server doesn't open a database - databases are opened as soon as a client connects. Starting the Ser*er Tool from Command !ine To start the Server tool from the command line with the default settings, run: java -cp h2*.jar org.h2.tools.Server This will start the tool with the default options. To get the list of options and default values, run: java -cp h2*.jar org.h2.tools.Server -? There are options available to use other ports, and start or not start parts. Connecting to the TC% Ser*er To remotely connect to a database using the TCP server, use the following driver and database URL: JDBC driver class: org.h2.Driver Database URL: jdbc:h2:tcp:fflocalhostf~ftest For details about the database URL, see also in Features. Please note that you can't connection with a web browser to this URL. You can only connect using a H2 client (over JDBC). Starting the TC% Ser*er &ithin an Application Servers can also be started and stopped from within an application. Sample code: import org.h2.tools.Server; ... ff start the TCP Server Server server = Server.createTcpServer(args).start(); ... ff stop the TCP Server server.stop(); Stopping a TC% Ser*er from Another %rocess The TCP server can be stopped from another process. To stop the server from the command line, run: 22 of 180 java org.h2.tools.Server -tcpShutdown tcp:fflocalhost:9092 To stop the server from a user application, use the following code: org.h2.tools.Server.shutdownTcpServer("tcp:fflocalhost:909+"); This function will only stop the TCP server. !f other server were started in the same process, they will continue to run. To avoid recovery when the databases are opened the next time, all connections to the databases should be closed before calling this method. To stop a remote server, remote connections must be enabled on the server. Shutting down a TCP server can be protected using the option -tcpPassword (the same password must be used to start and stop the TCP server). 'sing Hibernate This database supports Hibernate version 3.1 and newer. You can use the HSQLDB Dialect, or the native H2 Dialect. Unfortunately the H2 Dialect included in some old versions of Hibernate was buggy. A patch for Hibernate has been submitted and is now applied. You can rename it to H2Dialect.java and include this as a patch in your application, or upgrade to a version of Hibernate where this is fixed. When using Hibernate, try to use the H2Dialect if possible. When using the H2Dialect, compatibility modes such as NODE=NySQL are not supported. When using such a compatibility mode, use the Hibernate dialect for the corresponding database instead of the H2Dialect; but please note H2 does not support all features of all databases. 'sing Top!ink and /lassfish To use H2 with Glassfish (or Sun AS), set the Datasource Classname to org.h2.jdbcx.JdbcDataSource. You can set this in the GU! at Application Server - Resources - JDBC - Connection Pools, or by editing the file sun-resources.xml: at element jdbc- connection-pool, set the attribute datasource-classname to org.h2.jdbcx.JdbcDataSource. The H2 database is compatible with HSQLDB and PostgreSQL. To take advantage of H2 specific features, use the H2Platform. The source code of this platform is included in H2 at srcftoolsforacleftoplinkfessentialsfplatformfdatabasefDatabasePlatform.java.txt. You will need to copy this file to your application, and rename it to .java. To enable it, change the following setting in persistence.xml: <property name="toplink.target-database" value="oracle.toplink.essentials.platform.database.H2Platform"f> !n old versions of Glassfish, the property name is toplink.platform.class.name. To use H2 within Glassfish, copy the h2*.jar to the directory glassfishfglassfishflib. 'sing Eclipse!ink To use H2 in EclipseLink, use the platform class org.eclipse.persistence.platform.database.H2Platform. !f this platform is not available in your version of EclipseLink, you can use the OraclePlatform instead in many case. See also H2Platform. 'sing Apache Acti*e+Q When using H2 as the backend database for Apache ActiveNQ, please use the TransactDatabaseLocker instead of the default locking mechanism. Otherwise the database file will grow without bounds. The problem is that the default locking mechanism uses an uncommitted UPDATE transaction, which keeps the transaction log from shrinking (causes the database file to grow). !nstead of using an UPDATE statement, the TransactDatabaseLocker uses SELECT ... FOR UPDATE which is not problematic. To use it, change the ApacheNQ configuration element <jdbcPersistenceAdapter> element, property databaseLocker="org.apache.activemq.store.jdbc.adapter.TransactDatabaseLocker". However, using the NvCC mode will again result in the same problem. Therefore, please do not use the NvCC mode in this case. Another (more dangerous) solution is to set useDatabaseLock to false. 23 of 180 'sing H2 &ithin .et-eans The project H2 Database Engine Support For NetBeans allows you to start and stop the H2 server from within the !DE. There is a known issue when using the Netbeans SQL Execution Window: before executing a query, another query in the form SELECT COUNT(*) FRON <query> is run. This is a problem for queries that modify state, such as SELECT SEQ.NEXTvAL. !n this case, two sequence values are allocated instead of just one. 'sing H2 &ith 011Q jOOQ adds a thin layer on top of JDBC, allowing for type-safe SQL construction, including advanced SQL, stored procedures and advanced data types. jOOQ takes your database schema as a base for code generation. !f this is your example schema: CREATE TABLE USER (!D !NT, NANE vARCHAR(50)); then run the jOOQ code generator on the command line using this command: java -cp jooq.jar;jooq-meta.jar;jooq-codegen.jar;h2-1.3.158.jar;. org.jooq.util.GenerationTool fcodegen.xml ...where codegen.xml is on the classpath and contains this information <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <configuration xmlns="http:ffwww.jooq.orgfxsdfjooq-codegen-2.3.0.xsd"> <jdbc> <driver>org.h2.Driver<fdriver> <url>jdbc:h2:~ftest<furl> <user>sa<fuser> <password><fpassword> <fjdbc> <generator> <name>org.jooq.util.DefaultGenerator<fname> <database> <name>org.jooq.util.h2.H2Database<fname> <includes>.*<fincludes> <excludes><fexcludes> <inputSchema>PUBL!C<finputSchema> <fdatabase> <generate><fgenerate> <target> <packageName>org.jooq.h2.generated<fpackageName> <directory>.fsrc<fdirectory> <ftarget> <fgenerator> <fconfiguration> Using the generated source, you can query the database as follows: Factory create = new H2Factory(connection); Result<UserRecord> result = create.selectFrom(USER) .where(NANE.like("Johnny")) .orderBy(!D) .fetch(); See more details on jOOQ Homepage and in the jOOQ Tutorial 'sing Databases in 2eb Applications There are multiple ways to access a database from within web applications. Here are some examples if you use Tomcat or JBoss. 2+ of 180 Embedded +ode The (currently) simplest solution is to use the database in the embedded mode, that means open a connection in your application when it starts (a good solution is using a Servlet Listener, see below), or when a session starts. A database can be accessed from multiple sessions and applications at the same time, as long as they run in the same process. Nost Servlet Containers (for example Tomcat) are just using one process, so this is not a problem (unless you run Tomcat in clustered mode). Tomcat uses multiple threads and multiple classloaders. !f multiple applications access the same database at the same time, you need to put the database jar in the sharedflib or serverflib directory. !t is a good idea to open the database when the web application starts, and close it when the web application stops. !f using multiple applications, only one (any) of them needs to do that. !n the application, an idea is to use one connection per Session, or even one connection per request (action). Those connections should be closed after use if possible (but it's not that bad if they don't get closed). Ser*er +ode The server mode is similar, but it allows you to run the server in another process. 'sing a Ser*let !istener to Start and Stop a Database Add the h2*.jar file to your web application, and add the following snippet to your web.xml file (between the context-param and the filter section): <listener> <listener-class>org.h2.server.web.DbStarter<flistener-class> <flistener> For details on how to access the database, see the file DbStarter.java. By default this tool opens an embedded connection using the database URL jdbc:h2:~ftest, user name sa, and password sa. !f you want to use this connection within your servlet, you can access as follows: Connection conn = getServletContext().getAttribute("connection"); DbStarter can also start the TCP server, however this is disabled by default. To enable it, use the parameter db.tcpServer in the file web.xml. Here is the complete list of options. These options need to be placed between the description tag and the listener f filter tags: <context-param> <param-name>db.url<fparam-name> <param-value>jdbc:h2:~ftest<fparam-value> <fcontext-param> <context-param> <param-name>db.user<fparam-name> <param-value>sa<fparam-value> <fcontext-param> <context-param> <param-name>db.password<fparam-name> <param-value>sa<fparam-value> <fcontext-param> <context-param> <param-name>db.tcpServer<fparam-name> <param-value>-tcpAllowOthers<fparam-value> <fcontext-param> When the web application is stopped, the database connection will be closed automatically. !f the TCP server is started within the DbStarter, it will also be stopped automatically. 'sing the H2 Console Ser*let The H2 Console is a standalone application and includes its own web server, but it can be used as a servlet as well. To do that, include the the h2*.jar file in your application, and add the following configuration to your web.xml: 25 of 180 <servlet> <servlet-name>H2Console<fservlet-name> <servlet-class>org.h2.server.web.WebServlet<fservlet-class> <!-- <init-param> <param-name>webAllowOthers<fparam-name> <param-value><fparam-value> <finit-param> <init-param> <param-name>trace<fparam-name> <param-value><fparam-value> <finit-param> --> <load-on-startup>1<fload-on-startup> <fservlet> <servlet-mapping> <servlet-name>H2Console<fservlet-name> <url-pattern>fconsolef*<furl-pattern> <fservlet-mapping> For details, see also srcftoolsfWEB-!NFfweb.xml. To create a web application with just the H2 Console, run the following command: build warConsole Android You can use this database on an Android device (using the Dalvik vN) instead of or in addition to SQLite. So far, only very few tests and benchmarks were run, but it seems that performance is similar to SQLite, except for opening and closing a database, which is not yet optimized in H2 (H2 takes about 0.2 seconds, and SQLite about 0.02 seconds). Read operations seem to be a bit faster than SQLite, and write operations seem to be slower. So far, only very few tests have been run, and everything seems to work as expected. Fulltext search was not yet tested, however the native fulltext search should work. Reasons to use H2 instead of SQLite are: Full Unicode support including UPPER() and LOWER(). Streaming AP! for BLOB and CLOB data. Fulltext search. Nultiple connections. User defined functions and triggers. Database file encryption. Reading and writing CSv files (this feature can be used outside the database as well). Referential integrity and check constraints. Better data type and SQL support. !n-memory databases, read-only databases, linked tables. Better compatibility with other databases which simplifies porting applications. Possibly better performance (so far for read operations). Server mode (accessing a database on a different machine over TCPf!P). Currently only the JDBC AP! is supported (it is planned to support the Android database AP! in future releases). Both the regular H2 jar file and the smaller h2small-*.jar can be used. To create the smaller jar file, run the command .fbuild.sh jarSmall (Linux f Nac OS) or build.bat jarSmall (Windows). The database files needs to be stored in a place that is accessible for the application. Example: String url = "jdbc:h2:fdatafdataf" + "com.example.hello" + "fdatafhello" + ";F!LE_LOCK=FS" + ";PAGE_S!ZE=102+" + ";CACHE_S!ZE=8192"; Class.forName("org.h2.Driver"); conn = DriverNanager.getConnection(url); 26 of 180 ... Limitations: Using a connection pool is currently not supported, because the required javax.sql. classes are not available on Android. CS3 4Comma Separated 3alues5 Support The CSv file support can be used inside the database using the functions CSvREAD and CSvWR!TE, or it can be used outside the database as a standalone tool. #eading a CS3 (ile from 2ithin a Database A CSv file can be read using the function CSvREAD. Example: SELECT * FRON CSvREAD('test.csv'); Please note for performance reason, CSvREAD should not be used inside a join. !nstead, import the data first (possibly into a temporary table), create the required indexes if necessary, and then query this table. mporting Data from a CS3 (ile A fast way to load or import data (sometimes called 'bulk load') from a CSv file is to combine table creation with import. Optionally, the column names and data types can be set when creating the table. Another option is to use !NSERT !NTO ... SELECT. CREATE TABLE TEST AS SELECT * FRON CSvREAD('test.csv'); CREATE TABLE TEST(!D !NT PR!NARY KEY, NANE vARCHAR(255)) AS SELECT * FRON CSvREAD('test.csv'); 2riting a CS3 (ile from 2ithin a Database The built-in function CSvWR!TE can be used to create a CSv file from a query. Example: CREATE TABLE TEST(!D !NT, NANE vARCHAR); !NSERT !NTO TEST vALUES(1, 'Hello'), (2, 'World'); CALL CSvWR!TE('test.csv', 'SELECT * FRON TEST'); 2riting a CS3 (ile from a )a*a Application The Csv tool can be used in a Java application even when not using a database at all. Example: import java.sql.*; import org.h2.tools.Csv; import org.h2.tools.SimpleResultSet; public class TestCsv { public static void main(String[| args) throws Exception { SimpleResultSet rs = new SimpleResultSet(); rs.addColumn("NANE", Types.vARCHAR, 255, 0); rs.addColumn("ENA!L", Types.vARCHAR, 255, 0); rs.addRow("Bob Neier", "[email protected]"); rs.addRow("John Jones", "[email protected]"); new Csv().write("dataftest.csv", rs, null); ) ) 27 of 180 #eading a CS3 (ile from a )a*a Application !t is possible to read a CSv file without opening a database. Example: import java.sql.*; import org.h2.tools.Csv; public class TestCsv { public static void main(String[| args) throws Exception { ResultSet rs = new Csv().read("dataftest.csv", null, null); ResultSetNetaData meta = rs.getNetaData(); while (rs.next()) { for (int i = 0; i < meta.getColumnCount(); i++) { System.out.println( meta.getColumnLabel(i + 1) + ": " + rs.getString(i + 1)); ) System.out.println(); ) rs.close(); ) ) 'pgrade6 -ackup6 and #estore Database 'pgrade The recommended way to upgrade from one version of the database engine to the next version is to create a backup of the database (in the form of a SQL script) using the old engine, and then execute the SQL script using the new engine. -ackup using the Script Tool The recommended way to backup a database is to create a compressed SQL script file. This will result in a small, human readable, and database version independent backup. Creating the script will also verify the checksums of the database file. The Script tool is ran as follows: java org.h2.tools.Script -url jdbc:h2:~ftest -user sa -script test.zip -options compression zip !t is also possible to use the SQL command SCR!PT to create the backup of the database. For more information about the options, see the SQL command SCR!PT. The backup can be done remotely, however the file will be created on the server side. The built in FTP server could be used to retrieve the file from the server. #estore from a Script To restore a database from a SQL script file, you can use the RunScript tool: java org.h2.tools.RunScript -url jdbc:h2:~ftest -user sa -script test.zip -options compression zip For more information about the options, see the SQL command RUNSCR!PT. The restore can be done remotely, however the file needs to be on the server side. The built in FTP server could be used to copy the file to the server. !t is also possible to use the SQL command RUNSCR!PT to execute a SQL script. SQL script files may contain references to other script files, in the form of RUNSCR!PT commands. However, when using the server mode, the references script files need to be available on the server side. 1nline -ackup The BACKUP SQL statement and the Backup tool both create a zip file with the database file. However, the contents of this file are not human readable. 28 of 180 The resulting backup is transactionally consistent, meaning the consistency and atomicity rules apply. BACKUP TO 'backup.zip' The Backup tool (org.h2.tools.Backup) can not be used to create a online backup; the database must not be in use while running this program. Creating a backup by copying the database files while the database is running is not supported, except if the file systems support creating snapshots. With other file systems, it can't be guaranteed that the data is copied in the right order. Command !ine Tools This database comes with a number of command line tools. To get more information about a tool, start it with the parameter '-?', for example: java -cp h2*.jar org.h2.tools.Backup -? The command line tools are: Backup creates a backup of a database. ChangeFileEncryption allows changing the file encryption password or algorithm of a database. Console starts the browser based H2 Console. ConvertTraceFile converts a .trace.db file to a Java application and SQL script. CreateCluster creates a cluster from a standalone database. DeleteDbFiles deletes all files belonging to a database. Recover helps recovering a corrupted database. Restore restores a backup of a database. RunScript runs a SQL script against a database. Script allows converting a database to a SQL script for backup or migration. Server is used in the server mode to start a H2 server. Shell is a command line database tool. The tools can also be called from an application by calling the main or another public method. For details, see the Javadoc documentation. The Shell Tool The Shell tool is a simple interactive command line tool. To start it, type: java -cp h2*.jar org.h2.tools.Shell You will be asked for a database URL, JDBC driver, user name, and password. The connection setting can also be set as command line parameters. After connecting, you will get the list of options. The built-in commands don't need to end with a semicolon, but SQL statements are only executed if the line ends with a semicolon ;. This allows to enter multi-line statements: sql> select * from test ...> where id = 0; By default, results are printed as a table. For results with many column, consider using the list mode: sql> list Result list mode is now on sql> select * from test; !D : 1 NANE: Hello !D : 2 NANE: World (2 rows, 0 ms) 29 of 180 'sing 1pen1ffice -ase OpenOffice.org Base supports database access over the JDBC AP!. To connect to a H2 database using OpenOffice Base, you first need to add the JDBC driver to OpenOffice. The steps to connect to a H2 database are: Start OpenOffice Writer, go to [Tools|, [Options| Nake sure you have selected a Java runtime environment in OpenOffice.org f Java Click [Class Path...|, [Add Archive...| Select your h2 jar file (location is up to you, could be wherever you choose) Click [OK| (as much as needed), stop OpenOffice (including the Quickstarter) Start OpenOffice Base Connect to an existing database; select [JDBC|; [Next| Example datasource URL: jdbc:h2:~ftest JDBC driver class: org.h2.Driver Now you can access the database stored in the current users home directory. To use H2 in NeoOffice (OpenOffice without X11): !n NeoOffice, go to [NeoOffice|, [Preferences| Look for the page under [NeoOffice|, [Java| Click [Class Path|, [Add Archive...| Select your h2 jar file (location is up to you, could be wherever you choose) Click [OK| (as much as needed), restart NeoOffice. Now, when creating a new database using the "Database Wizard" : Click [File|, [New|, [Database|. Select [Connect to existing database| and the select [JDBC|. Click next. Example datasource URL: jdbc:h2:~ftest JDBC driver class: org.h2.Driver Another solution to use H2 in NeoOffice is: Package the h2 jar within an extension package !nstall it as a Java extension in NeoOffice This can be done by create it using the NetBeans OpenOffice plugin. See also Extensions Development. )a*a 2eb Start 7 ).!% When using Java Web Start f JNLP (Java Network Launch Protocol), permissions tags must be set in the .jnlp file, and the application .jar file must be signed. Otherwise, when trying to write to the file system, the following exception will occur: java.security.AccessControlException: access denied (java.io.FilePermission ... read). Example permission tags: <security> <all-permissionsf> <fsecurity> 'sing a Connection %ool For H2, opening a connection is fast if the database is already open. Still, using a connection pool improves performance if you open and close connections a lot. A simple connection pool is included in H2. !t is based on the Nini Connection Pool Nanager from Christian d'Heureuse. There are other, more complex, open source connection pools available, for example the Apache Commons DBCP. For H2, it is about twice as faster to get a connection from the built-in connection pool than to get one using DriverNanager.getConnection().The build-in connection pool is used as follows: import java.sql.*; import org.h2.jdbcx.JdbcConnectionPool; public class Test { public static void main(String[| args) throws Exception { 30 of 180 JdbcConnectionPool cp = JdbcConnectionPool.create( "jdbc:h2:~ftest", "sa", "sa"); for (int i = 0; i < args.length; i++) { Connection conn = cp.getConnection(); conn.createStatement().execute(args[i|); conn.close(); ) cp.dispose(); ) ) (ullte"t Search H2 includes two fulltext search implementations. One is using Apache Lucene, and the other (the native implementation) stores the index data in special tables in the database. 'sing the .ati*e (ullte"t Search To initialize, call: CREATE AL!AS !F NOT EX!STS FT_!N!T FOR "org.h2.fulltext.FullText.init"; CALL FT_!N!T(); You need to initialize it in each database where you want to use it. Afterwards, you can create a fulltext index for a table using: CREATE TABLE TEST(!D !NT PR!NARY KEY, NANE vARCHAR); !NSERT !NTO TEST vALUES(1, 'Hello World'); CALL FT_CREATE_!NDEX('PUBL!C', 'TEST', NULL); PUBL!C is the schema name, TEST is the table name. The list of column names (comma separated) is optional, in this case all columns are indexed. The index is updated in realtime. To search the index, use the following query: SELECT * FRON FT_SEARCH('Hello', 0, 0); This will produce a result set that contains the query needed to retrieve the data: QUERY: "PUBL!C"."TEST" WHERE "!D"=1 To drop an index on a table: CALL FT_DROP_!NDEX('PUBL!C', 'TEST'); To get the raw data, use FT_SEARCH_DATA('Hello', 0, 0);. The result contains the columns SCHENA (the schema name), TABLE (the table name), COLUNNS (an array of column names), and KEYS (an array of objects). To join a table, use a join as in: SELECT T.* FRON FT_SEARCH_DATA('Hello', 0, 0) FT, TEST T WHERE FT.TABLE='TEST' AND T.!D=FT.KEYS[0|; You can also call the index from within a Java application: org.h2.fulltext.FullText.search(conn, text, limit, offset); org.h2.fulltext.FullText.searchData(conn, text, limit, offset); 'sing the !ucene (ullte"t Search To use the Lucene full text search, you need the Lucene library in the classpath. Currently Apache Lucene version 2.x is used by default for H2 version 1.2.x, and Lucene version 3.x is used by default for H2 version 1.3.x. How to do that depends on the application; if you use the H2 Console, you can add the Lucene jar file to the environment variables H2DR!vERS or CLASSPATH. To initialize the Lucene fulltext search in a database, call: 31 of 180 CREATE AL!AS !F NOT EX!STS FTL_!N!T FOR "org.h2.fulltext.FullTextLucene.init"; CALL FTL_!N!T(); You need to initialize it in each database where you want to use it. Afterwards, you can create a full text index for a table using: CREATE TABLE TEST(!D !NT PR!NARY KEY, NANE vARCHAR); !NSERT !NTO TEST vALUES(1, 'Hello World'); CALL FTL_CREATE_!NDEX('PUBL!C', 'TEST', NULL); PUBL!C is the schema name, TEST is the table name. The list of column names (comma separated) is optional, in this case all columns are indexed. The index is updated in realtime. To search the index, use the following query: SELECT * FRON FTL_SEARCH('Hello', 0, 0); This will produce a result set that contains the query needed to retrieve the data: QUERY: "PUBL!C"."TEST" WHERE "!D"=1 To drop an index on a table (be warned that this will re-index all of the full-text indices for the entire database): CALL FTL_DROP_!NDEX('PUBL!C', 'TEST'); To get the raw data, use FTL_SEARCH_DATA('Hello', 0, 0);. The result contains the columns SCHENA (the schema name), TABLE (the table name), COLUNNS (an array of column names), and KEYS (an array of objects). To join a table, use a join as in: SELECT T.* FRON FTL_SEARCH_DATA('Hello', 0, 0) FT, TEST T WHERE FT.TABLE='TEST' AND T.!D=FT.KEYS[0|; You can also call the index from within a Java application: org.h2.fulltext.FullTextLucene.search(conn, text, limit, offset); org.h2.fulltext.FullTextLucene.searchData(conn, text, limit, offset); The Lucene fulltext search supports searching in specific column only. Column names must be uppercase (except if the original columns are double quoted). For column names starting with an underscore (_), another underscore needs to be added. Example: CREATE AL!AS !F NOT EX!STS FTL_!N!T FOR "org.h2.fulltext.FullTextLucene.init"; CALL FTL_!N!T(); DROP TABLE !F EX!STS TEST; CREATE TABLE TEST(!D !NT PR!NARY KEY, F!RST_NANE vARCHAR, LAST_NANE vARCHAR); CALL FTL_CREATE_!NDEX('PUBL!C', 'TEST', NULL); !NSERT !NTO TEST vALUES(1, 'John', 'Wayne'); !NSERT !NTO TEST vALUES(2, 'Elton', 'John'); SELECT * FRON FTL_SEARCH_DATA('John', 0, 0); SELECT * FRON FTL_SEARCH_DATA('LAST_NANE:John', 0, 0); CALL FTL_DROP_ALL(); The Lucene fulltext search implementation is not synchronized internally. !f you update the database and query the fulltext search concurrently (directly using the Java AP! of H2 or Lucene itself), you need to ensure operations are properly synchronized. !f this is not the case, you may get exceptions such as org.apache.lucene.store.AlreadyClosedException: this !ndexReader is closed. 'ser-Defined 3ariables This database supports user-defined variables. variables start with @ and can be used wherever expressions or parameters are allowed. variables are not persisted and session scoped, that means only visible from within the session in which they are defined. A value is usually assigned using the SET command: SET @USER = 'Joe'; 32 of 180 The value can also be changed using the SET() method. This is useful in queries: SET @TOTAL = NULL; SELECT X, SET(@TOTAL, !FNULL(@TOTAL, 1.) * X) F FRON SYSTEN_RANGE(1, 50); variables that are not set evaluate to NULL. The data type of a user-defined variable is the data type of the value assigned to it, that means it is not necessary (or possible) to declare variable names before using them. There are no restrictions on the assigned values; large objects (LOBs) are supported as well. Rolling back a transaction does not affect the value of a user- defined variable. Date and Time Date, time and timestamp values support !SO 8601 formatting, including time zone: CALL T!NESTANP '2008-01-01 12:00:00+01:00'; !f the time zone is not set, the value is parsed using the current time zone setting of the system. Date and time information is stored in H2 database files without time zone information. !f the database is opened using another system time zone, the date and time will be the same. That means if you store the value '2000-01-01 12:00:00' in one time zone, then close the database and open the database again in a different time zone, you will also get '2000-01-01 12:00:00'. Please note that changing the time zone after the H2 driver is loaded is not supported. 'sing Spring 'sing the TC% Ser*er Use the following configuration to start and stop the H2 TCP server using the Spring Framework: <bean id = "org.h2.tools.Server" class="org.h2.tools.Server" factory-method="createTcpServer" init-method="start" destroy-method="stop"> <constructor-arg value="-tcp,-tcpAllowOthers,-tcpPort,80+3" f> <fbean> The destroy-method will help prevent exceptions on hot-redeployment or when restarting the server. Error Code ncompatibility There is an incompatibility with the Spring JdbcTemplate and H2 version 1.3.15+ and newer, because of a change in the error code. This will cause the JdbcTemplate to not detect a duplicate key condition, and so a Data!ntegrityviolationException is thrown instead of DuplicateKeyException. See also the issue SPR-8235. The workaround is to add the following XNL file to the root of the classpath: <beans xmlns="http:ffwww.springframework.orgfschemafbeans" xmlns:xsi="http:ffwww.w3.orgf2001fXNLSchema-instance" xsi:schemaLocation= "http:ffwww.springframework.orgfschemafbeans http:ffwww.springframework.orgfschemafbeansfspring-beans.xsd" > <import resource="classpath:orgfspringframeworkfjdbcfsupportfsql-error-codes.xml"f> <bean id = "H2" class="org.springframework.jdbc.support.SQLErrorCodes"> <property name="badSqlGrammarCodes"> <value> +2000,+2001,+2101,+2102,+2111,+2112,+2121,+2122,+2132 <fvalue> <fproperty> 33 of 180 <property name="duplicateKeyCodes"> <value>23001,23505<fvalue> <fproperty> <property name="data!ntegrityviolationCodes"> <value>22003,22012,22025,23000<fvalue> <fproperty> <property name="dataAccessResourceFailureCodes"> <value>900+6,90100,90117,90121,90126<fvalue> <fproperty> <property name="cannotAcquireLockCodes"> <value>50200<fvalue> <fproperty> <fbean> <fbeans> 1S/i The standard H2 jar can be dropped in as a bundle in an OSGi container. H2 implements the JDBC Service defined in OSGi Service Platform Release + version +.2 Enterprise Specification. The H2 Data Source Factory service is registered with the following properties: OSG!_JDBC_DR!vER_CLASS=org.h2.Driver and OSG!_JDBC_DR!vER_NANE=H2. The OSG!_JDBC_DR!vER_vERS!ON property reflects the version of the driver as is. The following standard configuration properties are supported: JDBC_USER, JDBC_PASSWORD, JDBC_DESCR!PT!ON, JDBC_DATASOURCE_NANE, JDBC_NETWORK_PROTOCOL, JDBC_URL, JDBC_SERvER_NANE, JDBC_PORT_NUNBER. Any other standard property will be rejected. Non-standard properties will be passed on to H2 in the connection URL. )a*a +anagement E"tension 4)+85 Nanagement over JNX is supported, but not enabled by default. To enable JNX, append ;JNX=TRUE to the database URL when opening the database. various tools support JNX, one such tool is the jconsole. When opening the jconsole, connect to the process where the database is open (when using the server mode, you need to connect to the server process). Then go to the NBeans section. Under org.h2 you will find one entry per database. The object name of the entry is the database short name, plus the path (each colon is replaced with an underscore character). The following attributes and operations are supported: CacheSize: the cache size currently in use in KB. CacheSizeNax (readfwrite): the maximum cache size in KB. Exclusive: whether this database is open in exclusive mode or not. FileReadCount: the number of file read operations since the database was opened. FileSize: the file size in KB. FileWriteCount: the number of file write operations since the database was opened. FileWriteCountTotal: the number of file write operations since the database was created. LogNode (readfwrite): the current transaction log mode. See SET LOG for details. Node: the compatibility mode (REGULAR if no compatibility mode is used). NultiThreaded: true if multi-threaded is enabled. Nvcc: true if NvCC is enabled. ReadOnly: true if the database is read-only. TraceLevel (readfwrite): the file trace level. version: the database version in use. listSettings: list the database settings. listSessions: list the open sessions, including currently executing statement (if any) and locked tables (if any). To enable JNX, you may need to set the system properties com.sun.management.jmxremote and com.sun.management.jmxremote.port as required by the JvN. 3+ of 180 (eatures Feature List Comparison to Other Database Engines H2 in Use Connection Nodes Database URL Overview Connecting to an Embedded (Local) Database !n-Nemory Databases Database Files Encryption Database File Locking Opening a Database Only if it Already Exists Closing a Database !gnore Unknown Settings Changing Other Settings when Opening a Connection Custom File Access Node Nultiple Connections Database File Layout Logging and Recovery Compatibility Auto-Reconnect Automatic Nixed Node Page Size Using the Trace Options Using Other Logging AP!s Read Only Databases Read Only Databases in Zip or Jar File Computed Columns f Function Based !ndex Nulti-Dimensional !ndexes User-Defined Functions and Stored Procedures Pluggable or User-Defined Tables Triggers Compacting a Database Cache Settings (eature !ist +ain (eatures very fast database engine Open source Written in Java Supports standard SQL, JDBC AP! Embedded and Server mode, Clustering support Strong security features The PostgreSQL ODBC driver can be used Nulti version concurrency Additional (eatures Disk based or in-memory databases and tables, read-only database support, temporary tables Transaction support (read committed and serializable transaction isolation), 2-phase-commit Nultiple connections, table level locking Cost based optimizer, using a genetic algorithm for complex queries, zero-administration Scrollable and updatable result set support, large result set, external result sorting, functions can return a result set Encrypted database (AES), SHA-256 password encryption, encryption functions, SSL SQ! Support Support for multiple schemas, information schema Referential integrity f foreign key constraints with cascade, check constraints 35 of 180 !nner and outer joins, subqueries, read only views and inline views Triggers and Java functions f stored procedures Nany built-in functions, including XNL and lossless data compression Wide range of data types including large objects (BLOBfCLOB) and arrays Sequence and autoincrement columns, computed columns (can be used for function based indexes) ORDER BY, GROUP BY, HAv!NG, UN!ON, L!N!T, TOP Collation support, including support for the !CU+J library Support for users and roles Compatibility modes for !BN DB2, Apache Derby, HSQLDB, NS SQL Server, NySQL, Oracle, and PostgreSQL. Security (eatures !ncludes a solution for the SQL injection problem User password authentication uses SHA-256 and salt For server mode connections, user passwords are never transmitted in plain text over the network (even when using insecure connections; this only applies to the TCP server and not to the H2 Console however; it also doesn't apply if you set the password in the database URL) All database files (including script files that can be used to backup data) can be encrypted using the AES-128 encryption algorithm The remote JDBC driver supports TCPf!P connections over SSLfTLS The built-in web server supports connections over SSLfTLS Passwords can be sent to the database using char arrays instead of Strings 1ther (eatures and Tools Small footprint (smaller than 1.5 NB), low memory requirements Nultiple index types (b-tree, tree, hash) Support for multi-dimensional indexes CSv (comma separated values) file support Support for linked tables, and a built-in virtual 'range' table Supports the EXPLA!N PLAN statement; sophisticated trace options Database closing can be delayed or disabled to improve the performance Web-based Console application (translated to many languages) with autocomplete The database can generate SQL script files Contains a recovery tool that can dump the contents of the database Support for variables (for example to calculate running totals) Automatic re-compilation of prepared statements Uses a small number of database files Uses a checksum for each record and log entry for data integrity Well tested (high code coverage, randomized stress tests) Comparison to 1ther Database Engines This comparison is based on H2 1.3, Apache Derby version 10.8, HSQLDB 2.2, NySQL 5.5, PostgreSQL 9.0. Feature H2 Derby HSQLDB NySQL PostgreSQL Pure Java Yes Yes Yes No No Embedded Node (Java) Yes Yes Yes No No !n-Nemory Node Yes Yes Yes No No Explain Plan Yes Yes *12 Yes Yes Yes Built-in Clustering f Replication Yes Yes No Yes Yes Encrypted Database Yes Yes *10 Yes *10 No No Linked Tables Yes No Partially *1 Partially *2 No ODBC Driver Yes No No Yes Yes Fulltext Search Yes No No Yes Yes Domains (User-Defined Types) Yes No Yes Yes Yes Files per Database Few Nany Few Nany Nany Row Level Locking Yes *9 Yes Yes *9 Yes Yes Nulti version Concurrency Yes No Yes Yes Yes Nulti-Threaded Statement Processing No *11 Yes Yes Yes Yes 36 of 180 Role Based Security Yes Yes *3 Yes Yes Yes Updatable Result Sets Yes Yes *7 Yes Yes Yes Sequences Yes Yes Yes No Yes Limit and Offset Yes Yes *13 Yes Yes Yes Window Functions No *15 No *15 No No Yes Temporary Tables Yes Yes *+ Yes Yes Yes !nformation Schema Yes No *8 Yes Yes Yes Computed Columns Yes Yes Yes No Yes *6 Case !nsensitive Columns Yes Yes *1+ Yes Yes Yes *6 Custom Aggregate Functions Yes No Yes Yes Yes CLOBfBLOB Compression Yes No No No Yes Footprint (jarfdll size) ~1.5 NB *5 ~3 NB ~1.5 NB ~+ NB ~6 NB *1 HSQLDB supports text tables. *2 NySQL supports linked NySQL tables under the name 'federated tables'. *3 Derby support for roles based security and password checking as an option. *+ Derby only supports global temporary tables. *5 The default H2 jar file contains debug information, jar files for other databases do not. *6 PostgreSQL supports functional indexes. *7 Derby only supports updatable result sets if the query is not sorted. *8 Derby doesn't support standard compliant information schema tables. *9 When using NvCC (multi version concurrency). *10 Derby and HSQLDB don't hide data patterns well. *11 The NULT!_THREADED option is not enabled by default, and not yet supported when using NvCC. *12 Derby doesn't support the EXPLA!N statement, but it supports runtime statistics and retrieving statement execution plans. *13 Derby doesn't support the syntax L!N!T .. [OFFSET ..|, however it supports FETCH F!RST .. ROW[S| ONLY. *1+ Using collations. *15 Derby and H2 support ROW_NUNBER() OvER(). DaffodilDb and 1ne9Db !t looks like the development of this database has stopped. The last release was February 2006. +c:oi !t looks like the development of this database has stopped. The last release was August 200+. H2 in 'se For a list of applications that work with or use H2, see: Links. Connection +odes The following connection modes are supported: Embedded mode (local connections using JDBC) Server mode (remote connections using JDBC or ODBC over TCPf!P) Nixed mode (local and remote connections at the same time) Embedded +ode !n embedded mode, an application opens a database from within the same JvN using JDBC. This is the fastest and easiest connection mode. The disadvantage is that a database may only be open in one virtual machine (and class loader) at any time. As in all modes, both persistent and in-memory databases are supported. There is no limit on the number of database open concurrently, or on the number of open connections. 37 of 180
Ser*er +ode When using the server mode (sometimes called remote mode or clientfserver mode), an application opens a database remotely using the JDBC or ODBC AP!. A server needs to be started within the same or another virtual machine, or on another computer. Nany applications can connect to the same database at the same time, by connecting to this server. !nternally, the server process opens the database(s) in embedded mode. The server mode is slower than the embedded mode, because all data is transferred over TCPf!P. As in all modes, both persistent and in-memory databases are supported. There is no limit on the number of database open concurrently per server, or on the number of open connections.
+i"ed +ode The mixed mode is a combination of the embedded and the server mode. The first application that connects to a database does that in embedded mode, but also starts a server so that other applications (running in different processes or virtual machines) can concurrently access the same data. The local connections are as fast as if the database is used in just the embedded mode, while the remote connections are a bit slower. The server can be started and stopped from within the application (using the server AP!), or automatically (automatic mixed mode). When using the automatic mixed mode, all clients that want to connect to the database (no matter if it's an local or remote connection) can do so using the exact same database URL. 38 of 180
Database '#! 1*er*ie& This database supports multiple connection modes and connection settings. This is achieved using different database URLs. Settings in the URLs are not case sensitive. Topic URL Format and Examples Embedded (local) connection jdbc:h2:[file:|[<path>|<databaseName> jdbc:h2:~ftest jdbc:h2:file:fdatafsample jdbc:h2:file:C:fdatafsample (Windows only) !n-memory (private) jdbc:h2:mem: !n-memory (named) jdbc:h2:mem:<databaseName> jdbc:h2:mem:test_mem Server mode (remote connections) using TCPf!P jdbc:h2:tcp:ff<server>[:<port>|f[<path>|<databaseName> jdbc:h2:tcp:fflocalhostf~ftest jdbc:h2:tcp:ffdbserv:808+f~fsample jdbc:h2:tcp:fflocalhostfmem:test Server mode (remote connections) using SSLfTLS jdbc:h2:ssl:ff<server>[:<port>|f<databaseName> jdbc:h2:ssl:fflocalhost:8085f~fsample; Using encrypted files jdbc:h2:<url>;C!PHER=AES jdbc:h2:ssl:fflocalhostf~ftest;C!PHER=AES jdbc:h2:file:~fsecure;C!PHER=AES File locking methods jdbc:h2:<url>;F!LE_LOCK={F!LE{SOCKET{NO) jdbc:h2:file:~fprivate;C!PHER=AES;F!LE_LOCK=SOCKET Only open if it already exists jdbc:h2:<url>;!FEX!STS=TRUE jdbc:h2:file:~fsample;!FEX!STS=TRUE Don't close the database when the vN exits jdbc:h2:<url>;DB_CLOSE_ON_EX!T=FALSE Execute SQL on connection jdbc:h2:<url>;!N!T=RUNSCR!PT FRON '~fcreate.sql' jdbc:h2:file:~fsample;!N!T=RUNSCR!PT FRON '~fcreate.sql';RUNSCR!PT FRON '~fpopulate.sql' User name andfor password jdbc:h2:<url>[;USER=<username>|[;PASSWORD=<value>| jdbc:h2:file:~fsample;USER=sa;PASSWORD=123 Debug trace settings jdbc:h2:<url>;TRACE_LEvEL_F!LE=<level 0..3> jdbc:h2:file:~fsample;TRACE_LEvEL_F!LE=3 !gnore unknown settings jdbc:h2:<url>;!GNORE_UNKNOWN_SETT!NGS=TRUE Custom file access mode jdbc:h2:<url>;ACCESS_NODE_DATA=rws Database in a zip file jdbc:h2:zip:<zipFileName>!f<databaseName> jdbc:h2:zip:~fdb.zip!ftest Compatibility mode jdbc:h2:<url>;NODE=<databaseType> jdbc:h2:~ftest;NODE=NYSQL Auto-reconnect jdbc:h2:<url>;AUTO_RECONNECT=TRUE jdbc:h2:tcp:fflocalhostf~ftest;AUTO_RECONNECT=TRUE Automatic mixed mode jdbc:h2:<url>;AUTO_SERvER=TRUE jdbc:h2:~ftest;AUTO_SERvER=TRUE 39 of 180 Page size jdbc:h2:<url>;PAGE_S!ZE=512 Changing other settings jdbc:h2:<url>;<setting>=<value>[;<setting>=<value>...| jdbc:h2:file:~fsample;TRACE_LEvEL_SYSTEN_OUT=3 Connecting to an Embedded 4!ocal5 Database The database URL for connecting to a local database is jdbc:h2:[file:|[<path>|<databaseName>. The prefix file: is optional. !f no or only a relative path is used, then the current working directory is used as a starting point. The case sensitivity of the path and database name depend on the operating system, however it is recommended to use lowercase letters only. The database name must be at least three characters long (a limitation of File.createTempFile). The database name must not contain a semicolon. To point to the user home directory, use ~f, as in: jdbc:h2:~ftest. n-+emory Databases For certain use cases (for example: rapid prototyping, testing, high performance operations, read-only databases), it may not be required to persist data, or persist changes to the data. This database supports the in-memory mode, where the data is not persisted. !n some cases, only one connection to a in-memory database is required. This means the database to be opened is private. !n this case, the database URL is jdbc:h2:mem: Opening two connections within the same virtual machine means opening two different (private) databases. Sometimes multiple connections to the same in-memory database are required. !n this case, the database URL must include a name. Example: jdbc:h2:mem:db1. Accessing the same database using this URL only works within the same virtual machine and class loader environment. To access an in-memory database from another process or from another computer, you need to start a TCP server in the same process as the in-memory database was created. The other processes then need to access the database over TCPf!P or SSLfTLS, using a database URL such as: jdbc:h2:tcp:fflocalhostfmem:db1. By default, closing the last connection to a database closes the database. For an in-memory database, this means the content is lost. To keep the database open, add ;DB_CLOSE_DELAY=-1 to the database URL. To keep the content of an in-memory database as long as the virtual machine is alive, use jdbc:h2:mem:test;DB_CLOSE_DELAY=-1. Database (iles Encryption The database files can be encrypted. Two encryption algorithm AES is supported. To use file encryption, you need to specify the encryption algorithm (the 'cipher') and the file password (in addition to the user password) when connecting to the database. Creating a .e& Database &ith (ile Encryption By default, a new database is automatically created if it does not exist yet. To create an encrypted database, connect to it as it would already exist. Connecting to an Encrypted Database The encryption algorithm is set in the database URL, and the file password is specified in the password field, before the user password. A single space separates the file password and the user password; the file password itself may not contain spaces. File passwords and user passwords are case sensitive. Here is an example to connect to a password-encrypted database: Class.forName("org.h2.Driver"); String url = "jdbc:h2:~ftest;C!PHER=AES"; String user = "sa"; String pwds = "filepwd userpwd"; conn = DriverNanager. getConnection(url, user, pwds); +0 of 180 Encrypting or Decrypting a Database To encrypt an existing database, use the ChangeFileEncryption tool. This tool can also decrypt an encrypted database, or change the file encryption key. The tool is available from within the H2 Console in the tools section, or you can run it from the command line. The following command line will encrypt the database test in the user home directory with the file password filepwd and the encryption algorithm AES: java -cp h2*.jar org.h2.tools.ChangeFileEncryption -dir ~ -db test -cipher AES -encrypt filepwd Database (ile !ocking Whenever a database is opened, a lock file is created to signal other processes that the database is in use. !f database is closed, or if the process that opened the database terminates, this lock file is deleted. The following file locking methods are implemented: The default method is F!LE and uses a watchdog thread to protect the database file. The watchdog reads the lock file each second. The second method is SOCKET and opens a server socket. The socket method does not require reading the lock file every second. The socket method should only be used if the database files are only accessed by one (and always the same) computer. The third method is FS. This will use native file locking using FileChannel.lock. !t is also possible to open the database without file locking; in this case it is up to the application to protect the database files. Failing to do so will result in a corrupted database. Using the method NO forces the database to not create a lock file at all. Please note that this is unsafe as another process is able to open the same database, possibly leading to data corruption. To open the database with a different file locking method, use the parameter F!LE_LOCK. The following code opens the database with the 'socket' locking method: String url = "jdbc:h2:~ftest;F!LE_LOCK=SOCKET"; For more information about the algorithms, see Advanced f File Locking Protocols. 1pening a Database 1nly if it Already E"ists By default, when an application calls DriverNanager.getConnection(url, ...) and the database specified in the URL does not yet exist, a new (empty) database is created. !n some situations, it is better to restrict creating new databases, and only allow to open existing databases. To do this, add ;!FEX!STS=TRUE to the database URL. !n this case, if the database does not already exist, an exception is thrown when trying to connect. The connection only succeeds when the database already exists. The complete URL may look like this: String url = "jdbc:h2:fdatafsample;!FEX!STS=TRUE"; Closing a Database Delayed Database Closing Usually, a database is closed when the last connection to it is closed. !n some situations this slows down the application, for example when it is not possible to keep at least one connection open. The automatic closing of a database can be delayed or disabled with the SQL statement SET DB_CLOSE_DELAY <seconds>. The parameter <seconds> specifies the number of seconds to keep a database open after the last connection to it was closed. The following statement will keep a database open for 10 seconds after the last connection was closed: SET DB_CLOSE_DELAY 10 +1 of 180 The value -1 means the database is not closed automatically. The value 0 is the default and means the database is closed when the last connection is closed. This setting is persistent and can be set by an administrator only. !t is possible to set the value in the database URL: jdbc:h2:~ftest;DB_CLOSE_DELAY=10. Don,t Close a Database &hen the 3+ E"its By default, a database is closed when the last connection is closed. However, if it is never closed, the database is closed when the virtual machine exits normally, using a shutdown hook. !n some situations, the database should not be closed in this case, for example because the database is still used at virtual machine shutdown (to store the shutdown process in the database for example). For those cases, the automatic closing of the database can be disabled in the database URL. The first connection (the one that is opening the database) needs to set the option in the database URL (it is not possible to change the setting afterwards). The database URL to disable database closing on exit is: String url = "jdbc:h2:~ftest;DB_CLOSE_ON_EX!T=FALSE"; E"ecute SQ! on Connection Sometimes, particularly for in-memory databases, it is useful to be able to execute DDL or DNL commands automatically when a client connects to a database. This functionality is enabled via the !N!T property. Note that multiple commands may be passed to !N!T, but the semicolon delimiter must be escaped, as in the example below. String url = "jdbc:h2:mem:test;!N!T=runscript from '~fcreate.sql';runscript from '~fpopulate.sql'"; Please note the double backslash is only required in a Java or properties file. !n a GU!, or in an XNL file, only one backslash is required: <property name="url" value= "jdbc:h2:mem:test;!N!T=create schema if not exists test;runscript from '~fsqlfpopulate.sql';DB_CLOSE_DELAY=-1" f> Backslashes within the init script (for example within a runscript statement, to specify the folder names in Windows) need to be escaped as well (using a second backslash). !t might be simpler to avoid backslashes in folder names for this reason; use forward slashes instead. gnore 'nkno&n Settings Some applications (for example OpenOffice.org Base) pass some additional parameters when connecting to the database. Why those parameters are passed is unknown. The parameters PREFERDOSL!KEL!NEENDS and !GNOREDR!vERPR!v!LEGES are such examples; they are simply ignored to improve the compatibility with OpenOffice.org. !f an application passes other parameters when connecting to the database, usually the database throws an exception saying the parameter is not supported. !t is possible to ignored such parameters by adding ;!GNORE_UNKNOWN_SETT!NGS=TRUE to the database URL. Changing 1ther Settings &hen 1pening a Connection !n addition to the settings already described, other database settings can be passed in the database URL. Adding ;setting=value at the end of a database URL is the same as executing the statement SET setting value just after connecting. For a list of supported settings, see SQL Grammar or the DbSettings javadoc. Custom (ile Access +ode Usually, the database opens the database file with the access mode rw, meaning read-write (except for read only databases, where the mode r is used). To open a database in read-only mode if the database file is not read-only, use ACCESS_NODE_DATA=r. Also supported are rws and rwd. This setting must be specified in the database URL: String url = "jdbc:h2:~ftest;ACCESS_NODE_DATA=rws"; +2 of 180 For more information see Durability Problems. On many operating systems the access mode rws does not guarantee that the data is written to the disk. +ultiple Connections 1pening +ultiple Databases at the Same Time An application can open multiple databases at the same time, including multiple connections to the same database. The number of open database is only limited by the memory available. +ultiple Connections to the Same Database; Client7Ser*er !f you want to access the same database at the same time from different processes or computers, you need to use the client f server mode. !n this case, one process acts as the server, and the other processes (that could reside on other computers as well) connect to the server via TCPf!P (or SSLfTLS over TCPf!P for improved security). +ultithreading Support This database is multithreading-safe. That means, if an application is multi-threaded, it does not need to worry about synchronizing access to the database. !nternally, most requests to the same database are synchronized. That means an application can use multiple threads that access the same database at the same time, however if one thread executes a long running query, the other threads need to wait. An application should normally use one connection per thread. This database synchronizes access to the same connection, but other databases may not do this. !ocking6 !ock-Timeout6 Deadlocks Unless multi-version concurrency is used, the database uses table level locks to give each connection a consistent state of the data. There are two kinds of locks: read locks (shared locks) and write locks (exclusive locks). All locks are released when the transaction commits or rolls back. When using the default transaction isolation level 'read committed', read locks are already released after each statement. !f a connection wants to reads from a table, and there is no write lock on the table, then a read lock is added to the table. !f there is a write lock, then this connection waits for the other connection to release the lock. !f a connection cannot get a lock for a specified time, then a lock timeout exception is thrown. Usually, SELECT statements will generate read locks. This includes subqueries. Statements that modify data use write locks. !t is also possible to lock a table exclusively without modifying data, using the statement SELECT ... FOR UPDATE. The statements CONN!T and ROLLBACK releases all open locks. The commands SAvEPO!NT and ROLLBACK TO SAvEPO!NT don't affect locks. The locks are also released when the autocommit mode changes, and for connections with autocommit set to true (this is the default), locks are released after each statement. The following statements generate locks: Type of Lock SQL Statement Read SELECT * FRON TEST; CALL SELECT NAX(!D) FRON TEST; SCR!PT; Write SELECT * FRON TEST WHERE 1=0 FOR UPDATE; Write !NSERT !NTO TEST vALUES(1, 'Hello'); !NSERT !NTO TEST SELECT * FRON TEST; UPDATE TEST SET NANE='Hi'; DELETE FRON TEST; Write ALTER TABLE TEST ...; CREATE !NDEX ... ON TEST ...; DROP !NDEX ...; The number of seconds until a lock timeout exception is thrown can be set separately for each connection using the SQL command SET LOCK_T!NEOUT <milliseconds>. The initial lock timeout (that is the timeout used for new connections) can be set using the SQL command SET DEFAULT_LOCK_T!NEOUT <milliseconds>. The default lock timeout is persistent. +3 of 180 A*oiding Deadlocks To avoid deadlocks, ensure that all transactions lock the tables in the same order (for example in alphabetical order), and avoid upgrading read locks to write locks. Both can be achieved using explicitly locking tables using SELECT ... FOR UPDATE. Database (ile !ayout The following files are created for persistent databases: File Name Description Number of Files test.h2.db Database file. Contains the transaction log, indexes, and data for all tables. Format: <database>.h2.db 1 per database test.lock.db Database lock file. Automatically (re-)created while the database is in use. Format: <database>.lock.db 1 per database (only if in use) test.trace.db Trace file (if the trace option is enabled). Contains trace information. Format: <database>.trace.db Renamed to <database>.trace.db.old is too big. 0 or 1 per database test.lobs.dbf* Directory containing one file for each BLOB or CLOB value larger than a certain size. Format: <id>.t<table!d>.lob.db 1 per large object test.123.temp.db Temporary file. Contains a temporary blob or a large result set. Format: <database>.<id>.temp.db 1 per object +o*ing and #enaming Database (iles Database name and location are not stored inside the database files. While a database is closed, the files can be moved to another directory, and they can be renamed as well (as long as all files of the same database start with the same name and the respective extensions are unchanged). As there is no platform specific data in the files, they can be moved to other operating systems without problems. -ackup When the database is closed, it is possible to backup the database files. To backup data while the database is running, the SQL commands SCR!PT and BACKUP can be used. !ogging and #eco*ery Whenever data is modified in the database and those changes are committed, the changes are written to the transaction log (except for in-memory objects). The changes to the main data area itself are usually written later on, to optimize disk access. !f there is a power failure, the main data area is not up-to-date, but because the changes are in the transaction log, the next time the database is opened, the changes are re-applied automatically. Compatibility All database engines behave a little bit different. Where possible, H2 supports the ANS! SQL standard, and tries to be compatible to other databases. There are still a few differences however: !n NySQL text columns are case insensitive by default, while in H2 they are case sensitive. However H2 supports case insensitive columns as well. To create the tables with case insensitive texts, append !GNORECASE=TRUE to the database URL (example: jdbc:h2:~ftest;!GNORECASE=TRUE). ++ of 180 Compatibility +odes For certain features, this database can emulate the behavior of specific databases. However, only a small subset of the differences between databases are implemented in this way. Here is the list of currently supported modes and the differences to the regular mode: D-2 Compatibility +ode To use the !BN DB2 mode, use the database URL jdbc:h2:~ftest;NODE=DB2 or the SQL statement SET NODE DB2. For aliased columns, ResultSetNetaData.getColumnName() returns the alias name and getTableName() returns null. Support for the syntax [OFFSET .. ROW| [FETCH ... ONLY| as an alternative for L!N!T .. OFFSET. Concatenating NULL with another value results in the other value. Support the pseudo-table SYS!BN.SYSDUNNY1. Derby Compatibility +ode To use the Apache Derby mode, use the database URL jdbc:h2:~ftest;NODE=Derby or the SQL statement SET NODE Derby. For aliased columns, ResultSetNetaData.getColumnName() returns the alias name and getTableName() returns null. For unique indexes, NULL is distinct. That means only one row with NULL in one of the columns is allowed. Concatenating NULL with another value results in the other value. Support the pseudo-table SYS!BN.SYSDUNNY1. HSQ!D- Compatibility +ode To use the HSQLDB mode, use the database URL jdbc:h2:~ftest;NODE=HSQLDB or the SQL statement SET NODE HSQLDB. For aliased columns, ResultSetNetaData.getColumnName() returns the alias name and getTableName() returns null. When converting the scale of decimal data, the number is only converted if the new scale is smaller than the current scale. Usually, the scale is converted and 0s are added if required. For unique indexes, NULL is distinct. That means only one row with NULL in one of the columns is allowed. Text can be concatenated using '+'. +S SQ! Ser*er Compatibility +ode To use the NS SQL Server mode, use the database URL jdbc:h2:~ftest;NODE=NSSQLServer or the SQL statement SET NODE NSSQLServer. For aliased columns, ResultSetNetaData.getColumnName() returns the alias name and getTableName() returns null. !dentifiers may be quoted using square brackets as in [Test|. For unique indexes, NULL is distinct. That means only one row with NULL in one of the columns is allowed. Concatenating NULL with another value results in the other value. Text can be concatenated using '+'. +ySQ! Compatibility +ode To use the NySQL mode, use the database URL jdbc:h2:~ftest;NODE=NySQL or the SQL statement SET NODE NySQL. When inserting data, if a column is defined to be NOT NULL and NULL is inserted, then a 0 (or empty string, or the current timestamp for timestamp columns) value is used. Usually, this operation is not allowed and an exception is thrown. Creating indexes in the CREATE TABLE statement is allowed using !NDEX(..) or KEY(..). Example: create table test(id int primary key, name varchar(255), key idx_name(name)); Neta data calls return identifiers in lower case. When converting a floating point number to an integer, the fractional digits are not truncated, but the value is rounded. Concatenating NULL with another value results in the other value. +5 of 180 Text comparison in NySQL is case insensitive by default, while in H2 it is case sensitive (as in most other databases). H2 does support case insensitive text comparison, but it needs to be set separately, using SET !GNORECASE TRUE. This affects comparison using =, L!KE, REGEXP. 1racle Compatibility +ode To use the Oracle mode, use the database URL jdbc:h2:~ftest;NODE=Oracle or the SQL statement SET NODE Oracle. For aliased columns, ResultSetNetaData.getColumnName() returns the alias name and getTableName() returns null. When using unique indexes, multiple rows with NULL in all columns are allowed, however it is not allowed to have multiple rows with the same values otherwise. Concatenating NULL with another value results in the other value. Empty strings are treated like NULL values. %ostgreSQ! Compatibility +ode To use the PostgreSQL mode, use the database URL jdbc:h2:~ftest;NODE=PostgreSQL or the SQL statement SET NODE PostgreSQL. For aliased columns, ResultSetNetaData.getColumnName() returns the alias name and getTableName() returns null. When converting a floating point number to an integer, the fractional digits are not be truncated, but the value is rounded. The system columns CT!D and O!D are supported. LOG(x) is base 10 in this mode. Auto-#econnect The auto-reconnect feature causes the JDBC driver to reconnect to the database if the connection is lost. The automatic re- connect only occurs when auto-commit is enabled; if auto-commit is disabled, an exception is thrown. To enable this mode, append ;AUTO_RECONNECT=TRUE to the database URL. Re-connecting will open a new session. After an automatic re-connect, variables and local temporary tables definitions (excluding data) are re-created. The contents of the system table !NFORNAT!ON_SCHENA.SESS!ON_STATE contains all client side state that is re-created. !f another connection uses the database in exclusive mode (enabled using SET EXCLUS!vE 1 or SET EXCLUS!vE 2), then this connection will try to re-connect until the exclusive mode ends. Automatic +i"ed +ode Nultiple processes can access the same database without having to start the server manually. To do that, append ;AUTO_SERvER=TRUE to the database URL. You can use the same database URL independent of whether the database is already open or not. This feature doesn't work with in-memory databases. Example database URL: jdbc:h2:fdataftest;AUTO_SERvER=TRUE Use the same URL for all connections to this database. !nternally, when using this mode, the first connection to the database is made in embedded mode, and additionally a server is started internally (as a daemon thread). !f the database is already open in another process, the server mode is used automatically. The !P address and port of the server are stored in the file .lock.db, that's why in-memory databases can't be supported. The application that opens the first connection to the database uses the embedded mode, which is faster than the server mode. Therefore the main application should open the database first if possible. The first connection automatically starts a server on a random port. This server allows remote connections, however only to this database (to ensure that, the client reads .lock.db file and sends the the random key that is stored there to the server). When the first connection is closed, the server stops. !f other (remote) connections are still open, one of them will then start a server (auto-reconnect is enabled automatically). All processes need to have access to the database files. !f the first connection is closed (the connection that started the server), open transactions of other connections will be rolled back (this may not be a problem if you don't disable autocommit). Explicit +6 of 180 clientfserver connections (using jdbc:h2:tcp:ff or ssl:ff) are not supported. This mode is not supported for in-memory databases. Here is an example how to use this mode. Application 1 and 2 are not necessarily started on the same computer, but they need to have access to the database files. Application 1 and 2 are typically two different processes (however they could run within the same process). ff Application 1: DriverNanager.getConnection("jdbc:h2:fdataftest;AUTO_SERvER=TRUE"); ff Application 2: DriverNanager.getConnection("jdbc:h2:fdataftest;AUTO_SERvER=TRUE"); When using this feature, by default the server uses any free TCP port. The port can be set manually using AUTO_SERvER_PORT=9090. %age Si<e The page size for new databases is 2 KB (20+8), unless the page size is set explicitly in the database URL using PAGE_S!ZE= when the database is created. The page size of existing databases can not be changed, so this property needs to be set when the database is created. 'sing the Trace 1ptions To find problems in an application, it is sometimes good to see what database operations where executed. This database offers the following trace features: Trace to System.out andfor to a file Support for trace levels OFF, ERROR, !NFO, DEBUG The maximum size of the trace file can be set !t is possible to generate Java source code from the trace file Trace can be enabled at runtime by manually creating a file Trace 1ptions The simplest way to enable the trace option is setting it in the database URL. There are two settings, one for System.out (TRACE_LEvEL_SYSTEN_OUT) tracing, and one for file tracing (TRACE_LEvEL_F!LE). The trace levels are 0 for OFF, 1 for ERROR (the default), 2 for !NFO, and 3 for DEBUG. A database URL with both levels set to DEBUG is: jdbc:h2:~ftest;TRACE_LEvEL_F!LE=3;TRACE_LEvEL_SYSTEN_OUT=3 The trace level can be changed at runtime by executing the SQL command SET TRACE_LEvEL_SYSTEN_OUT level (for System.out tracing) or SET TRACE_LEvEL_F!LE level (for file tracing). Example: SET TRACE_LEvEL_SYSTEN_OUT 3 Setting the +a"imum Si<e of the Trace (ile When using a high trace level, the trace file can get very big quickly. The default size limit is 16 NB, if the trace file exceeds this limit, it is renamed to .old and a new file is created. !f another such file exists, it is deleted. To limit the size to a certain number of megabytes, use SET TRACE_NAX_F!LE_S!ZE mb. Example: SET TRACE_NAX_F!LE_S!ZE 1 +7 of 180 )a*a Code /eneration When setting the trace level to !NFO or DEBUG, Java source code is generated as well. This simplifies reproducing problems. The trace file looks like this: ... 12-20 20:58:09 jdbc[0|: f**fdbNeta3.getURL(); 12-20 20:58:09 jdbc[0|: f**fdbNeta3.getTables(null, "", null, new String[|{"TABLE", "v!EW")); ... To filter the Java source code, use the ConvertTraceFile tool as follows: java -cp h2*.jar org.h2.tools.ConvertTraceFile -traceFile "~ftest.trace.db" -javaClass "Test" The generated file Test.java will contain the Java source code. The generated source code may be too large to compile (the size of a Java method is limited). !f this is the case, the source code needs to be split in multiple methods. The password is not listed in the trace file and therefore not included in the source code. 'sing 1ther !ogging A%s By default, this database uses its own native 'trace' facility. This facility is called 'trace' and not 'log' within this database to avoid confusion with the transaction log. Trace messages can be written to both file and System.out. !n most cases, this is sufficient, however sometimes it is better to use the same facility as the application, for example Log+j. To do that, this database support SLF+J. SLF+J is a simple facade for various logging AP!s and allows to plug in the desired implementation at deployment time. SLF+J supports implementations such as Logback, Log+j, Jakarta Commons Logging (JCL), Java logging, x+juli, and Simple Log. To enable SLF+J, set the file trace level to + in the database URL: jdbc:h2:~ftest;TRACE_LEvEL_F!LE=+ Changing the log mechanism is not possible after the database is open, that means executing the SQL statement SET TRACE_LEvEL_F!LE + when the database is already open will not have the desired effect. To use SLF+J, all required jar files need to be in the classpath. The logger name is h2database. !f it does not work, check the file <database>.trace.db for error messages. #ead 1nly Databases !f the database files are read-only, then the database is read-only as well. !t is not possible to create new tables, add or modify data in this database. Only SELECT and CALL statements are allowed. To create a read-only database, close the database. Then, make the database file read-only. When you open the database now, it is read-only. There are two ways an application can find out whether database is read-only: by calling Connection.isReadOnly() or by executing the SQL statement CALL READONLY(). Using the Custom Access Node r the database can also be opened in read-only mode, even if the database file is not read only. #ead 1nly Databases in =ip or )ar (ile To create a read-only database in a zip file, first create a regular persistent database, and then create a backup. The database must not have pending changes, that means you need to close all connections to the database first. To speed up opening the read-only database and running queries, the database should be closed using SHUTDOWN DEFRAG. !f you are using a database named test, an easy way to create a zip file is using the Backup tool. You can start the tool from the command line, or from within the H2 Console (Tools - Backup). Please note that the database must be closed when the backup is created. Therefore, the SQL statement BACKUP TO can not be used. +8 of 180 When the zip file is created, you can open the database in the zip file using the following database URL: jdbc:h2:zip:~fdata.zip!ftest Databases in zip files are read-only. The performance for some queries will be slower than when using a regular database, because random access in zip files is not supported (only streaming). How much this affects the performance depends on the queries and the data. The database is not read in memory; therefore large databases are supported as well. The same indexes are used as when using a regular database. !f the database is larger than a few megabytes, performance is much better if the database file is split into multiple smaller files, because random access in compressed files is not possible. See also the sample application ReadOnlyDatabase!nZip. 1pening a Corrupted Database !f a database cannot be opened because the boot info (the SQL script that is run at startup) is corrupted, then the database can be opened by specifying a database event listener. The exceptions are logged, but opening the database will continue. Computed Columns 7 (unction -ased nde" A computed column is a column whose value is calculated before storing. The formula is evaluated when the row is inserted, and re-evaluated every time the row is updated. One use case is to automatically update the last-modification time: CREATE TABLE TEST(!D !NT, NANE vARCHAR, LAST_NOD T!NESTANP AS NOW()); Function indexes are not directly supported by this database, but they can be emulated by using computed columns. For example, if an index on the upper-case version of a column is required, create a computed column with the upper-case version of the original column, and create an index for this column: CREATE TABLE ADDRESS( !D !NT PR!NARY KEY, NANE vARCHAR, UPPER_NANE vARCHAR AS UPPER(NANE) ); CREATE !NDEX !DX_U_NANE ON ADDRESS(UPPER_NANE); When inserting data, it is not required (and not allowed) to specify a value for the upper-case version of the column, because the value is generated. But you can use the column when querying the table: !NSERT !NTO ADDRESS(!D, NANE) vALUES(1, 'Niller'); SELECT * FRON ADDRESS WHERE UPPER_NANE='N!LLER'; +ulti-Dimensional nde"es A tool is provided to execute efficient multi-dimension (spatial) range queries. This database does not support a specialized spatial index (R-Tree or similar). !nstead, the B-Tree index is used. For each record, the multi-dimensional key is converted (mapped) to a single dimensional (scalar) value. This value specifies the location on a space-filling curve. Currently, Z-order (also called N-order or Norton-order) is used; Hilbert curve could also be used, but the implementation is more complex. The algorithm to convert the multi-dimensional value is called bit-interleaving. The scalar value is indexed using a B-Tree index (usually using a computed column). The method can result in a drastic performance improvement over just using an index on the first column. Depending on the data and number of dimensions, the improvement is usually higher than factor 5. The tool generates a SQL query from a specified multi-dimensional range. The method used is not database dependent, and the tool can easily be ported to other databases. For an example how to use the tool, please have a look at the sample code provided in TestNultiDimension.java. +9 of 180 'ser-Defined (unctions and Stored %rocedures !n addition to the built-in functions, this database supports user-defined Java functions. !n this database, Java functions can be used as stored procedures as well. A function must be declared (registered) before it can be used. A function can be defined using source code, or as a reference to a compiled class that is available in the classpath. By default, the function aliases are stored in the current schema. #eferencing a Compiled +ethod When referencing a method, the class must already be compiled and included in the classpath where the database is running. Only static Java methods are supported; both the class and the method must be public. Example Java class: package acme; import java.math.*; public class Function { public static boolean isPrime(int value) { return new Big!nteger(String.valueOf(value)).isProbablePrime(100); ) ) The Java function must be registered in the database by calling CREATE AL!AS ... FOR: CREATE AL!AS !S_PR!NE FOR "acme.Function.isPrime"; For a complete sample application, see srcftestforgfh2fsamplesfFunction.java. Declaring (unctions as Source Code When defining a function alias with source code, the database tries to compile the source code using the Sun Java compiler (the class com.sun.tools.javac.Nain) if the tools.jar is in the classpath. !f not, javac is run as a separate process. Only the source code is stored in the database; the class is compiled each time the database is re-opened. Source code is usually passed as dollar quoted text to avoid escaping problems, however single quotes can be used as well. Example: CREATE AL!AS NEXT_PR!NE AS $$ String nextPrime(String value) { return new Big!nteger(value).nextProbablePrime().toString(); ) $$; By default, the three packages java.util, java.math, java.sql are imported. The method name (nextPrime in the example above) is ignored. Nethod overloading is not supported when declaring functions as source code, that means only one method may be declared for an alias. !f different import statements are required, they must be declared at the beginning and separated with the tag @CODE: CREATE AL!AS !P_ADDRESS AS $$ import java.net.*; @CODE String ipAddress(String host) throws Exception { return !netAddress.getByName(host).getHostAddress(); ) $$; The following template is used to create a complete Java class: package org.h2.dynamic; < import statements before the tag @CODE; if not set: import java.util.*; import java.math.*; import java.sql.*; > public class <aliasName> { 50 of 180 public static <sourceCode> ) +ethod 1*erloading Nultiple methods may be bound to a SQL function if the class is already compiled and included in the classpath. Each Java method must have a different number of arguments. Nethod overloading is not supported when declaring functions as source code. (unction Data Type +apping Functions that accept non-nullable parameters such as int will not be called if one of those parameters is NULL. !nstead, the result of the function is NULL. !f the function should be called if a parameter is NULL, you need to use java.lang.!nteger instead. SQL types are mapped to Java classes and vice-versa as in the JDBC AP!. For details, see Data Types. There are a few special cases: java.lang.Object is mapped to OTHER (a serialized object). Therefore, java.lang.Object can not be used to match all SQL types (matching all SQL types is not supported). The second special case is Object[|: arrays of any class are mapped to ARRAY. Objects of type org.h2.value.value (the internal value class) are passed through without conversion. (unctions That #e$uire a Connection !f the first parameter of a Java function is a java.sql.Connection, then the connection to database is provided. This connection does not need to be closed before returning. When calling the method from within the SQL statement, this connection parameter does not need to be (can not be) specified. (unctions Thro&ing an E"ception !f a function throws an exception, then the current statement is rolled back and the exception is thrown to the application. SQLException are directly re-thrown to the calling application; all other exceptions are first converted to a SQLException. (unctions #eturning a #esult Set Functions may returns a result set. Such a function can be called with the CALL statement: public static ResultSet query(Connection conn, String sql) throws SQLException { return conn.createStatement().executeQuery(sql); ) CREATE AL!AS QUERY FOR "org.h2.samples.Function.query"; CALL QUERY('SELECT * FRON TEST'); 'sing Simple#esultSet A function can create a result set using the SimpleResultSet tool: import org.h2.tools.SimpleResultSet; ... public static ResultSet simpleResultSet() throws SQLException { SimpleResultSet rs = new SimpleResultSet(); rs.addColumn("!D", Types.!NTEGER, 10, 0); rs.addColumn("NANE", Types.vARCHAR, 255, 0); rs.addRow(0, "Hello"); rs.addRow(1, "World"); return rs; ) 51 of 180 CREATE AL!AS S!NPLE FOR "org.h2.samples.Function.simpleResultSet"; CALL S!NPLE(); 'sing a (unction as a Table A function that returns a result set can be used like a table. However, in this case the function is called at least twice: first while parsing the statement to collect the column names (with parameters set to null where not known at compile time). And then, while executing the statement to get the data (maybe multiple times if this is a join). !f the function is called just to get the column list, the URL of the connection passed to the function is jdbc:columnlist:connection. Otherwise, the URL of the connection is jdbc:default:connection. public static ResultSet getNatrix(Connection conn, !nteger size) throws SQLException { SimpleResultSet rs = new SimpleResultSet(); rs.addColumn("X", Types.!NTEGER, 10, 0); rs.addColumn("Y", Types.!NTEGER, 10, 0); String url = conn.getNetaData().getURL(); if (url.equals("jdbc:columnlist:connection")) { return rs; ) for (int s = size.intvalue(), x = 0; x < s; x++) { for (int y = 0; y < s; y++) { rs.addRow(x, y); ) ) return rs; ) CREATE AL!AS NATR!X FOR "org.h2.samples.Function.getNatrix"; SELECT * FRON NATR!X(+) ORDER BY X, Y; %luggable or 'ser-Defined Tables For situations where you need to expose other data-sources to the SQL engine as a table, there are "pluggable tables". For some examples, have a look at the code in org.h2.test.db.TestTableEngines. !n order to create your own TableEngine, you need to implement the org.h2.api.TableEngine interface e.g. something like this: package acme; public static class NyTableEngine implements org.h2.api.TableEngine { private static class NyTable extends org.h2.table.TableBase { .. rather a lot of code here... ) public EndlessTable createTable(CreateTableData data) { return new EndlessTable(data); ) ) and then create the table from SQL like this: CREATE TABLE TEST(!D !NT, NANE vARCHAR) ENG!NE "acme.NyTableEngine"; !t is also possible to pass in parameters to the table engine, like so: CREATE TABLE TEST(!D !NT, NANE vARCHAR) ENG!NE "acme.NyTableEngine" W!TH "param1", "param2"; !n which case the parameters are passed down in the tableEngineParams field of the CreateTableData object. 52 of 180 Triggers This database supports Java triggers that are called before or after a row is updated, inserted or deleted. Triggers can be used for complex consistency checks, or to update related data in the database. !t is also possible to use triggers to simulate materialized views. For a complete sample application, see srcftestforgfh2fsamplesfTriggerSample.java. A Java trigger must implement the interface org.h2.api.Trigger. The trigger class must be available in the classpath of the database engine (when using the server mode, it must be in the classpath of the server). import org.h2.api.Trigger; ... public class TriggerSample implements Trigger { public void init(Connection conn, String schemaName, String triggerName, String tableName, boolean before, int type) { ff initialize the trigger object is necessary ) public void fire(Connection conn, Object[| oldRow, Object[| newRow) throws SQLException { ff the trigger is fired ) public void close() { ff the database is closed ) public void remove() { ff the trigger was dropped ) ) The connection can be used to query or update data in other tables. The trigger then needs to be defined in the database: CREATE TR!GGER !Nv_!NS AFTER !NSERT ON !NvO!CE FOR EACH ROW CALL "org.h2.samples.TriggerSample" The trigger can be used to veto a change by throwing a SQLException. As an alternative to implementing the Trigger interface, an application can extend the abstract class org.h2.tools.TriggerAdapter. This will allows to use the ResultSet interface within trigger implementations. !n this case, only the fire method needs to be implemented: import org.h2.tools.TriggerAdapter; ... public class TriggerSample implements TriggerAdapter { public void fire(Connection conn, ResultSet oldRow, ResultSet newRow) throws SQLException { ff the trigger is fired ) ) Compacting a Database Empty space in the database file re-used automatically. When closing the database, the database is automatically compacted for up to 200 milliseconds by default. To compact more, use the SQL statement SHUTDOWN CONPACT. However re-creating the database may further reduce the database size because this will re-build the indexes. Here is a sample function to do this: public static void compact(String dir, String dbName, String user, String password) throws Exception { 53 of 180 String url = "jdbc:h2:" + dir + "f" + dbName; String file = "dataftest.sql"; Script.execute(url, user, password, file); DeleteDbFiles.execute(dir, dbName, true); RunScript.execute(url, user, password, file, null, false); ) See also the sample application org.h2.samples.Compact. The commands SCR!PT f RUNSCR!PT can be used as well to create a backup of a database and re-build the database from the script. Cache Settings The database keeps most frequently used data in the main memory. The amount of memory used for caching can be changed using the setting CACHE_S!ZE. This setting can be set in the database connection URL (jdbc:h2:~ftest;CACHE_S!ZE=131072), or it can be changed at runtime using SET CACHE_S!ZE size. The size of the cache, as represented by CACHE_S!ZE is measured in KB, with each KB being 102+ bytes. This setting has no effect for in-memory databases. For persistent databases, the setting is stored in the database and re-used when the database is opened the next time. However, when opening an existing database, the cache size is set to at most half the amount of memory available for the virtual machine (Runtime.getRuntime().maxNemory()), even if the cache size setting stored in the database is larger; however the setting stored in the database is kept. Setting the cache size in the database URL or explicitly using SET CACHE_S!ZE overrides this value (even if larger than the physical memory). To get the current used maximum cache size, use the query SELECT * FRON !NFORNAT!ON_SCHENA.SETT!NGS WHERE NANE = 'info.CACHE_NAX_S!ZE' An experimental scan-resistant cache algorithm "Two Queue" (2Q) is available. To enable it, append ;CACHE_TYPE=TQ to the database URL. The cache might not actually improve performance. !f you plan to use it, please run your own test cases first. Also included is an experimental second level soft reference cache. Rows in this cache are only garbage collected on low memory. By default the second level cache is disabled. To enable it, use the prefix SOFT_. Example: jdbc:h2:~ftest;CACHE_TYPE=SOFT_LRU. The cache might not actually improve performance. !f you plan to use it, please run your own test cases first. To get information about page reads and writes, and the current caching algorithm in use, call SELECT * FRON !NFORNAT!ON_SCHENA.SETT!NGS. The number of pages read f written is listed. 5+ of 180 %erformance Performance Comparison PolePosition Benchmark Database Performance Tuning Using the Built-!n Profiler Application Profiling Database Profiling Statement Execution Plans How Data is Stored and How !ndexes Work Fast Database !mport %erformance Comparison !n many cases H2 is faster than other (open source and not open source) database engines. Please note this is mostly a single connection benchmark run on one computer, with many very simple operations running against the database. This benchmark does not include very complex queries. The embedded mode of H2 is faster than the client-server mode because the per- statement overhead is greatly reduced. Embedded Test Case Unit H2 HSQLDB Derby Simple: !nit ms 2+1 +31 1027 Simple: Query (random) ms 193 267 7+8 Simple: Query (sequential) ms 89 179 658 Simple: Update (random) ms +06 772 12175 Simple: Delete (sequential) ms 155 266 6281 Simple: Nemory Usage NB 7 13 16 BenchA: !nit ms 200 251 1075 BenchA: Transactions ms 1071 1+58 81+2 BenchA: Nemory Usage NB 8 1+ 12 BenchB: !nit ms 787 158+ +163 BenchB: Transactions ms +65 875 27++ BenchB: Nemory Usage NB 17 13 10 BenchC: !nit ms 3+8 225 922 BenchC: Transactions ms 1382 865 3527 BenchC: Nemory Usage NB 12 20 11 Executed statements # 322929 322929 322929 Total time ms 5337 7173 +1+62 Statements per second # 60507 +5020 7788 Client-Ser*er Test Case Unit H2 HSQLDB Derby PostgreSQL NySQL Simple: !nit ms 1715 2096 3008 3093 308+ Simple: Query (random) ms 2615 2119 ++50 3201 3313 Simple: Query (sequential) ms 2531 19++ +019 3163 3295 Simple: Update (random) ms 1862 2+86 13929 ++0+ +391 Simple: Delete (sequential) ms 778 1118 7032 1682 1882 Simple: Nemory Usage NB 8 1+ 18 1 2 BenchA: !nit ms 126+ 1686 273+ 2867 3225 BenchA: Transactions ms 5998 6829 1+323 11+91 10571 BenchA: Nemory Usage NB 9 18 1+ 1 2 BenchB: !nit ms 5571 7553 11636 12226 12553 BenchB: Transactions ms 1931 3+17 3+35 2+07 21+9 BenchB: Nemory Usage NB 18 16 13 2 2 55 of 180 BenchC: !nit ms 1333 968 1769 1693 26+5 BenchC: Transactions ms 6508 +330 7910 756+ 6108 BenchC: Nemory Usage NB 12 21 1+ 2 2 Executed statements # 322929 322929 322929 322929 322929 Total time ms 32106 3+5+6 7+2+5 53791 53216 Statements per second # 10058 93+7 +3+9 6003 6068 -enchmark #esults and Comments H2 version 1.2.137 (2010-06-06) was used for the test. For most operations, the performance of H2 is about the same as for HSQLDB. One situation where H2 is slow is large result sets, because they are buffered to disk if more than a certain number of records are returned. The advantage of buffering is: there is no limit on the result set size. HSQ!D- version 2.0.0 was used for the test. Cached tables are used in this test (hsqldb.default_table_type=cached), and the write delay is 1 second (SET WR!TE_DELAY 1). Derby version 10.6.1.0 was used for the test. Derby is clearly the slowest embedded database in this test. This seems to be a structural problem, because all operations are really slow. !t will be hard for the developers of Derby to improve the performance to a reasonable level. A few problems have been identified: leaving autocommit on is a problem for Derby. !f it is switched off during the whole test, the results are about 20 better for Derby. Derby calls FileChannel.force(false), but only twice per log file (not on each commit). Disabling this call improves performance for Derby by about 2. Unlike H2, Derby does not call FileDescriptor.sync() on each checkpoint. Derby supports a testing mode (system property derby.system.durability=test) where durability is disabled. According to the documentation, this setting should be used for testing only, as the database may not recover after a crash. Enabling this setting improves performance by a factor of 2.6 (embedded mode) or 1.+ (server mode). Even if enabled, Derby is still less than half as fast as H2 in default mode. %ostgreSQ! version 8.+.+ was used for the test. The following options where changed in postgresql.conf: fsync = off, commit_delay = 1000. PostgreSQL is run in server mode. The memory usage number is incorrect, because only the memory usage of the JDBC driver is measured. +ySQ! version 5.1.+7-community was used for the test. NySQL was run with the !nnoDB backend. The setting innodb_flush_log_at_trx_commit (found in the my.ini f my.cnf file) was set to 0. Otherwise (and by default), NySQL is slow (around 1+0 statements per second in this test) because it tries to flush the data to disk for each commit. For small transactions (when autocommit is on) this is really slow. But many use cases use small or relatively small transactions. Too bad this setting is not listed in the configuration wizard, and it always overwritten when using the wizard. You need to change this setting manually in the file my.ini f my.cnf, and then restart the service. The memory usage number is incorrect, because only the memory usage of the JDBC driver is measured. (irebird Firebird 1.5 (default installation) was tested, but the results are not published currently. !t is possible to run the performance test with the Firebird database, and any information on how to configure Firebird for higher performance are welcome. 56 of 180 2hy 1racle 7 +S SQ! Ser*er 7 D-2 are .ot !isted The license of these databases does not allow to publish benchmark results. This doesn't mean that they are fast. They are in fact quite slow, and need a lot of memory. But you will need to test this yourself. SQLite was not tested because the JDBC driver doesn't support transactions. About this -enchmark Ho& to #un This test was as follows: build benchmark Separate %rocess per Database For each database, a new process is started, to ensure the previous test does not impact the current test. .umber of Connections This is mostly a single-connection benchmark. BenchB uses multiple connections; the other tests use one connection. #eal-2orld Tests Good benchmarks emulate real-world use cases. This benchmark includes + test cases: BenchSimple uses one table and many small updates f deletes. BenchA is similar to the TPC-A test, but single connection f single threaded (see also: www.tpc.org). BenchB is similar to the TPC-B test, using multiple connections (one thread per connection). BenchC is similar to the TPC-C test, but single connection f single threaded. Comparing Embedded &ith Ser*er Databases This is mainly a benchmark for embedded databases (where the application runs in the same virtual machine as the database engine). However NySQL and PostgreSQL are not Java databases and cannot be embedded into a Java application. For the Java databases, both embedded and server modes are tested. Test %latform This test is run on Nac OS X 10.6. No virus scanner was used, and disk indexing was disabled. The JvN used is Sun JDK 1.6. +ultiple #uns When a Java benchmark is run first, the code is not fully compiled and therefore runs slower than when running multiple times. A benchmark should always run the same test multiple times and ignore the first run(s). This benchmark runs three times, but only the last run is measured. +emory 'sage !t is not enough to measure the time taken, the memory usage is important as well. Performance can be improved by using a bigger cache, but the amount of memory is limited. HSQLDB tables are kept fully in memory by default; this benchmark uses 'disk based' tables for all databases. Unfortunately, it is not so easy to calculate the memory usage of PostgreSQL and NySQL, because they run in a different process than the test. This benchmark currently does not print memory usage of those databases. 57 of 180 Delayed 1perations Some databases delay some operations (for example flushing the buffers) until after the benchmark is run. This benchmark waits between each database tested, and each database runs in a different process (sequentially). Transaction Commit 7 Durability Durability means transaction committed to the database will not be lost. Some databases (for example NySQL) try to enforce this by default by calling fsync() to flush the buffers, but most hard drives don't actually flush all data. Calling the method slows down transaction commit a lot, but doesn't always make data durable. When comparing the results, it is important to think about the effect. Nany database suggest to 'batch' operations when possible. This benchmark switches off autocommit when loading the data, and calls commit after each 1000 inserts. However many applications need 'short' transactions at runtime (a commit after each update). This benchmark commits after each update f delete in the simple benchmark, and after each business transaction in the other benchmarks. For databases that support delayed commits, a delay of one second is used. 'sing %repared Statements Wherever possible, the test cases use prepared statements. Currently .ot Tested; Startup Time The startup time of a database engine is important as well for embedded use. This time is not measured currently. Also, not tested is the time used to create a database and open an existing database. Here, one (wrapper) connection is opened at the start, and for each step a new connection is opened and then closed. %ole%osition -enchmark The PolePosition is an open source benchmark. The algorithms are all quite simple. !t was developed f sponsored by db+o. This test was not run for a longer time, so please be aware that the results below are for older database versions (H2 version 1.1, HSQLDB 1.8, Java 1.+). Test Case Unit H2 HSQLDB NySQL Nelbourne write ms 369 2+9 2022 Nelbourne read ms +7 +9 93 Nelbourne read_hot ms 2+ +3 95 Nelbourne delete ms 1+7 133 176 Sepang write ms 965 1201 3213 Sepang read ms 765 9+8 3+55 Sepang read_hot ms 789 859 3563 Sepang delete ms 138+ 1596 621+ Bahrain write ms 1186 1387 690+ Bahrain query_indexed_string ms 336 170 693 Bahrain query_string ms 1806+ 39703 +12+3 Bahrain query_indexed_int ms 10+ 13+ 678 Bahrain update ms 191 87 159 Bahrain delete ms 1215 729 6812 !mola retrieve ms 198 19+ +036 Barcelona write ms +13 832 3191 Barcelona read ms 119 160 1177 Barcelona query ms 20 5169 101 Barcelona delete ms 388 319 3287 Total ms 2672+ 53962 87112 There are a few problems with the PolePosition test: HSQLDB uses in-memory tables by default while H2 uses persistent tables. The HSQLDB version included in PolePosition does not support changing this, so you need to replace poleposition-0.20flibfhsqldb.jar with a newer version (for example hsqldb-1.8.0.7.jar), and then use the setting 58 of 180 hsqldb.connecturl=jdbc:hsqldb:file:datafhsqldbfdbbench2;hsqldb.default_table_type=cached;sql.enforce_size=true in the file Jdbc.properties. HSQLDB keeps the database open between tests, while H2 closes the database (losing all the cache). To change that, use the database URL jdbc:h2:file:datafh2fdbbench;DB_CLOSE_DELAY=-1 The amount of cache memory is quite important, specially for the PolePosition test. Unfortunately, the PolePosition test does not take this into account. Database %erformance Tuning :eep Connections 1pen or 'se a Connection %ool !f your application opens and closes connections a lot (for example, for each request), you should consider using a connection pool. Opening a connection using DriverNanager.getConnection is specially slow if the database is closed. By default the database is closed if the last connection is closed. !f you open and close connections a lot but don't want to use a connection pool, consider keeping a 'sentinel' connection open for as long as the application runs, or use delayed database closing. See also Closing a database. 'se a +odern )3+ Newer JvNs are faster. Upgrading to the latest version of your JvN can provide a "free" boost to performance. Switching from the default Client JvN to the Server JvN using the -server command-line option improves performance at the cost of a slight increase in start-up time. 3irus Scanners Some virus scanners scan files every time they are accessed. !t is very important for performance that database files are not scanned for viruses. The database engine never interprets the data stored in the files as programs, that means even if somebody would store a virus in a database file, this would be harmless (when the virus does not run, it cannot spread). Some virus scanners allow to exclude files by suffix. Ensure files ending with .db are not scanned. 'sing the Trace 1ptions !f the performance hot spots are in the database engine, in many cases the performance can be optimized by creating additional indexes, or changing the schema. Sometimes the application does not directly generate the SQL statements, for example if an OfR mapping tool is used. To view the SQL statements and JDBC AP! calls, you can use the trace options. For more information, see Using the Trace Options. nde" 'sage This database uses indexes to improve the performance of SELECT, UPDATE, DELETE. !f a column is used in the WHERE clause of a query, and if an index exists on this column, then the index can be used. Nulti-column indexes are used if all or the first columns of the index are used. Both equality lookup and range scans are supported. !ndexes are used to order result sets, but only if the condition uses the same index or no index at all. The results are sorted in memory if required. !ndexes are created automatically for primary key and unique constraints. !ndexes are also created for foreign key constraints, if required. For other columns, indexes need to be created manually using the CREATE !NDEX statement. Ho& Data is Stored nternally For persistent databases, if a table is created with a single column primary key of type B!G!NT, !NT, SNALL!NT, T!NY!NT, then the data of the table is organized in this way. This is sometimes also called a "clustered index" or "index organized table". H2 internally stores table data and indexes in the form of b-trees. Each b-tree stores entries as a list of unique keys (one or more columns) and data (zero or more columns). The table data is always organized in the form of a "data b-tree" with a single column key of type long. !f a single column primary key of type B!G!NT, !NT, SNALL!NT, T!NY!NT is specified when creating the table (or just after creating the table, but before inserting any rows), then this column is used as the key of the data b-tree. !f no primary key has been specified, if the primary key column is of another data type, or if the primary key contains more 59 of 180 than one column, then a hidden auto-increment column of type B!G!NT is added to the table, which is used as the key for the data b-tree. All other columns of the table are stored within the data area of this data b-tree (except for large BLOB, CLOB columns, which are stored externally). For each additional index, one new "index b-tree" is created. The key of this b-tree consists of the indexed columns, plus the key of the data b-tree. !f a primary key is created after the table has been created, or if the primary key contains multiple column, or if the primary key is not of the data types listed above, then the primary key is stored in a new index b-tree. 1ptimi<er This database uses a cost based optimizer. For simple and queries and queries with medium complexity (less than 7 tables in the join), the expected cost (running time) of all possible plans is calculated, and the plan with the lowest cost is used. For more complex queries, the algorithm first tries all possible combinations for the first few tables, and the remaining tables added using a greedy algorithm (this works well for most joins). Afterwards a genetic algorithm is used to test at most 2000 distinct plans. Only left-deep plans are evaluated. E"pression 1ptimi<ation After the statement is parsed, all expressions are simplified automatically if possible. Operations are evaluated only once if all parameters are constant. Functions are also optimized, but only if the function is constant (always returns the same result for the same parameter values). !f the WHERE clause is always false, then the table is not accessed at all. C1'.T4>5 1ptimi<ation !f the query only counts all rows of a table, then the data is not accessed. However, this is only possible if no WHERE clause is used, that means it only works for queries of the form SELECT COUNT(*) FRON table. 'pdating 1ptimi<er Statistics 7 Column Selecti*ity When executing a query, at most one index per join can be used. !f the same table is joined multiple times, for each join only one index is used (the same index could be used for both joins, or each join could use a different index). Example: for the query SELECT * FRON TEST T1, TEST T2 WHERE T1.NANE='A' AND T2.!D=T1.!D, two index can be used, in this case the index on NANE for T1 and the index on !D for T2. !f a table has multiple indexes, sometimes more than one index could be used. Example: if there is a table TEST(!D, NANE, F!RSTNANE) and an index on each column, then two indexes could be used for the query SELECT * FRON TEST WHERE NANE='A' AND F!RSTNANE='B', the index on NANE or the index on F!RSTNANE. !t is not possible to use both indexes at the same time. Which index is used depends on the selectivity of the column. The selectivity describes the 'uniqueness' of values in a column. A selectivity of 100 means each value appears only once, and a selectivity of 1 means the same value appears in many or most rows. For the query above, the index on NANE should be used if the table contains more distinct names than first names. The SQL statement ANALYZE can be used to automatically estimate the selectivity of the columns in the tables. This command should be run from time to time to improve the query plans generated by the optimizer. n-+emory 4Hash5 nde"es Using in-memory indexes, specially in-memory hash indexes, can speed up queries and data manipulation. !n-memory indexes are automatically used for in-memory databases, but can also be created for persistent databases using CREATE NENORY TABLE. !n many cases, the rows itself will also be kept in-memory. Please note this may cause memory problems for large tables. !n-memory hash indexes are backed by a hash table and are usually faster than regular indexes. However, hash indexes only supports direct lookup (WHERE !D = ?) but not range scan (WHERE !D < ?). To use hash indexes, use HASH as in: CREATE UN!QUE HASH !NDEX and CREATE TABLE ...(!D !NT PR!NARY KEY HASH,...). 60 of 180 'se %repared Statements !f possible, use prepared statements with parameters. %repared Statements and .4???5 Avoid generating SQL statements with a variable size !N(...) list. !nstead, use a prepared statement with arrays as in the following example: PreparedStatement prep = conn.prepareStatement( "SELECT * FRON TABLE(X !NT=?) T !NNER JO!N TEST ON T.X=TEST.!D"); prep.setObject(1, new Object[| { "1", "2" )); ResultSet rs = prep.executeQuery(); 1ptimi<ation E"amples See srcftestforgfh2fsamplesfoptimizations.sql for a few examples of queries that benefit from special optimizations built into the database. Cache Si<e and Type By default the cache size of H2 is quite small. Consider using a larger cache size, or enable the second level soft reference cache. See also Cache Settings. Data Types Each data type has different storage and performance characteristics: The DEC!NALfNUNER!C type is slower and requires more storage than the REAL and DOUBLE types. Text types are slower to read, write, and compare than numeric types and generally require more storage. See Large Objects for information on B!NARY vs. BLOB and vARCHAR vs. CLOB performance. Parsing and formatting takes longer for the T!NE, DATE, and T!NESTANP types than the numeric types. SNALL!NTfT!NY!NTfBOOLEAN are not significantly smaller or faster to work with than !NTEGER in most modes. Sorted nsert 1ptimi<ation To reduce disk space usage and speed up table creation, an optimization for sorted inserts is available. When used, b-tree pages are split at the insertion point. To use this optimization, add SORTED before the SELECT statement: CREATE TABLE TEST(!D !NT PR!NARY KEY, NANE vARCHAR) AS SORTED SELECT X, SPACE(100) FRON SYSTEN_RANGE(1, 100); !NSERT !NTO TEST SORTED SELECT X, SPACE(100) FRON SYSTEN_RANGE(101, 200); 'sing the -uilt-n %rofiler A very simple Java profiler is built-in. To use it, use the following template: import org.h2.util.Profiler; Profiler prof = new Profiler(); prof.startCollecting(); ff .... some long running process, at least a few seconds prof.stopCollecting(); System.out.println(prof.getTop(3)); 61 of 180 Application %rofiling Analy<e (irst Before trying to optimize performance, it is important to understand where the problem is (what part of the application is slow). Blind optimization or optimization based on guesses should be avoided, because usually it is not an efficient strategy. There are various ways to analyze an application. Sometimes two implementations can be compared using System.currentTimeNillis(). But this does not work for complex applications with many modules, and for memory problems. A simple way to profile an application is to use the built-in profiling tool of java. Example: java -Xrunhprof:cpu=samples,depth=16 com.acme.Test Unfortunately, it is only possible to profile the application from start to end. Another solution is to create a number of full thread dumps. To do that, first run jps -l to get the process id, and then run jstack <pid> or kill -QU!T <pid> (Linux) or press Ctrl+C (Windows). A simple profiling tool is included in H2. To use it, the application needs to be changed slightly. Example: import org.h2.util; ... Profiler profiler = new Profiler(); profiler.startCollecting(); ff application code System.out.println(profiler.getTop(3)); The profiler is built into the H2 Console tool, to analyze databases that open slowly. To use it, run the H2 Console, and then click on 'Test Connection'. Afterwards, click on "Test successful" and you get the most common stack traces, which helps to find out why it took so long to connect. You will only get the stack traces if opening the database took more than a few seconds. Database %rofiling The ConvertTraceFile tool generates SQL statement statistics at the end of the SQL script file. The format used is similar to the profiling data generated when using java -Xrunhprof. For this to work, the trace level needs to be 2 or higher (TRACE_LEvEL_F!LE=2). The easiest way to set the trace level is to append the setting to the database URL, for example: jdbc:h2:~ftest;TRACE_LEvEL_F!LE=2 or jdbc:h2:tcp:fflocalhostf~ftest;TRACE_LEvEL_F!LE=2. As an example, execute the the following script using the H2 Console: SET TRACE_LEvEL_F!LE 2; DROP TABLE !F EX!STS TEST; CREATE TABLE TEST(!D !NT PR!NARY KEY, NANE vARCHAR(255)); @LOOP 1000 !NSERT !NTO TEST vALUES(?, ?); SET TRACE_LEvEL_F!LE 0; After running the test case, convert the .trace.db file using the ConvertTraceFile tool. The trace file is located in the same directory as the database file. java -cp h2*.jar org.h2.tools.ConvertTraceFile -traceFile "~ftest.trace.db" -script "~ftest.sql" The generated file test.sql will contain the SQL statements as well as the following profiling data (results vary): ----------------------------------------- -- SQL Statement Statistics -- time: total time in milliseconds (accumulated) -- count: how many times the statement ran -- result: total update count or row count ----------------------------------------- -- self accu time count result sql -- 62 62 158 1000 1000 !NSERT !NTO TEST vALUES(?, ?); 62 of 180 -- 37 100 93 1 0 CREATE TABLE TEST(!D !NT PR!NARY KEY, NANE vARCHAR(255)); -- 0 100 0 1 0 DROP TABLE !F EX!STS TEST; -- 0 100 0 1 0 SET TRACE_LEvEL_F!LE 3; Statement E"ecution %lans The SQL statement EXPLA!N displays the indexes and optimizations the database uses for a statement. The following statements support EXPLA!N: SELECT, UPDATE, DELETE, NERGE, !NSERT. The following query shows that the database uses the primary key index to search for rows: EXPLA!N SELECT * FRON TEST WHERE !D=1; SELECT TEST.!D, TEST.NANE FRON PUBL!C.TEST f* PUBL!C.PR!NARY_KEY_2: !D = 1 *f WHERE !D = 1 For joins, the tables in the execution plan are sorted in the order they are processed. The following query shows the database first processes the table !NvO!CE (using the primary key). For each row, it will additionally check that the value of the column ANOUNT is larger than zero, and for those rows the database will search in the table CUSTONER (using the primary key). The query plan contains some redundancy so it is a valid statement. CREATE TABLE CUSTONER(!D !DENT!TY, NANE vARCHAR); CREATE TABLE !NvO!CE(!D !DENT!TY, CUSTONER_!D !NT REFERENCES CUSTONER(!D), ANOUNT NUNBER); EXPLA!N SELECT !.!D, C.NANE FRON CUSTONER C, !NvO!CE ! WHERE !.!D=10 AND ANOUNT>0 AND C.!D=!.CUSTONER_!D; SELECT !.!D, C.NANE FRON PUBL!C.!NvO!CE ! f* PUBL!C.PR!NARY_KEY_9: !D = 10 *f f* WHERE (!.!D = 10) AND (ANOUNT > 0) *f !NNER JO!N PUBL!C.CUSTONER C f* PUBL!C.PR!NARY_KEY_5: !D = !.CUSTONER_!D *f ON 1=1 WHERE (C.!D = !.CUSTONER_!D) AND ((!.!D = 10) AND (ANOUNT > 0)) Displaying the Scan Count EXPLA!N ANALYZE additionally shows the scanned rows per table and pages read from disk per table or index. This will actually execute the query, unlike EXPLA!N which only prepares it. The following query scanned 1000 rows, and to do that had to read 85 pages from the data area of the table. Running the query twice will not list the pages read from disk, because they are now in the cache. The tableScan means this query doesn't use an index. EXPLA!N ANALYZE SELECT * FRON TEST; SELECT TEST.!D, TEST.NANE FRON PUBL!C.TEST f* PUBL!C.TEST.tableScan *f f* scanCount: 1000 *f f* total: 85 TEST.TEST_DATA read: 85 (100) 63 of 180 *f The cache will prevent the pages are read twice. H2 reads all columns of the row unless only the columns in the index are read. Except for large CLOB and BLOB, which are not store in the table. Special 1ptimi<ations For certain queries, the database doesn't need to read all rows, or doesn't need to sort the result even if ORDER BY is used. For queries of the form SELECT COUNT(*), N!N(!D), NAX(!D) FRON TEST, the query plan includes the line f* direct lookup *f if the data can be read from an index. For queries of the form SELECT D!ST!NCT CUSTONER_!D FRON !NvO!CE, the query plan includes the line f* distinct *f if there is an non-unique or multi-column index on this column, and if this column has a low selectivity. For queries of the form SELECT * FRON TEST ORDER BY !D, the query plan includes the line f* index sorted *f to indicate there is no separate sorting required. For queries of the form SELECT * FRON TEST GROUP BY !D ORDER BY !D, the query plan includes the line f* group sorted *f to indicate there is no separate sorting required. Ho& Data is Stored and Ho& nde"es 2ork !nternally, each row in a table is identified by a unique number, the row id. The rows of a table are stored with the row id as the key. The row id is a number of type long. !f a table has a single column primary key of type !NT or B!G!NT, then the value of this column is the row id, otherwise the database generates the row id automatically. There is a (non-standard) way to access the row id: using the _ROW!D_ pseudo-column: CREATE TABLE ADDRESS(F!RST_NANE vARCHAR, NANE vARCHAR, C!TY vARCHAR, PHONE vARCHAR); !NSERT !NTO ADDRESS vALUES('John', 'Niller', 'Berne', '123 +56 789'); !NSERT !NTO ADDRESS vALUES('Philip', 'Jones', 'Berne', '123 012 3+5'); SELECT _ROW!D_, * FRON ADDRESS; The data is stored in the database as follows: _ROW!D_ F!RST_NANE NANE C!TY PHONE 1 John Niller Berne 123 +56 789 2 Philip Jones Berne 123 012 3+5 Access by row id is fast because the data is sorted by this key. Please note the row id is not available until after the row was added (that means, it can not be used in computed columns or constraints). !f the query condition does not contain the row id (and if no other index can be used), then all rows of the table are scanned. A table scan iterates over all rows in the table, in the order of the row id. To find out what strategy the database uses to retrieve the data, use EXPLA!N SELECT: SELECT * FRON ADDRESS WHERE NANE = 'Niller'; EXPLA!N SELECT PHONE FRON ADDRESS WHERE NANE = 'Niller'; SELECT PHONE FRON PUBL!C.ADDRESS f* PUBL!C.ADDRESS.tableScan *f WHERE NANE = 'Niller'; nde"es An index internally is basically just a table that contains the indexed column(s), plus the row id: CREATE !NDEX !NDEX_PLACE ON ADDRESS(C!TY, NANE, F!RST_NANE); 6+ of 180 !n the index, the data is sorted by the indexed columns. So this index contains the following data: C!TY NANE F!RST_NANE _ROW!D_ Berne Jones Philip 2 Berne Niller John 1 When the database uses an index to query the data, it searches the index for the given data, and (if required) reads the remaining columns in the main data table (retrieved using the row id). An index on city, name, and first name (multi-column index) allows to quickly search for rows when the city, name, and first name are known. !f only the city and name, or only the city is known, then this index is also used (so creating an additional index on just the city is not needed). This index is also used when reading all rows, sorted by the indexed columns. However, if only the first name is known, then this index is not used: EXPLA!N SELECT PHONE FRON ADDRESS WHERE C!TY = 'Berne' AND NANE = 'Niller' AND F!RST_NANE = 'John'; SELECT PHONE FRON PUBL!C.ADDRESS f* PUBL!C.!NDEX_PLACE: F!RST_NANE = 'John' AND C!TY = 'Berne' AND NANE = 'Niller' *f WHERE (F!RST_NANE = 'John') AND ((C!TY = 'Berne') AND (NANE = 'Niller')); EXPLA!N SELECT PHONE FRON ADDRESS WHERE C!TY = 'Berne'; SELECT PHONE FRON PUBL!C.ADDRESS f* PUBL!C.!NDEX_PLACE: C!TY = 'Berne' *f WHERE C!TY = 'Berne'; EXPLA!N SELECT * FRON ADDRESS ORDER BY C!TY, NANE, F!RST_NANE; SELECT ADDRESS.F!RST_NANE, ADDRESS.NANE, ADDRESS.C!TY, ADDRESS.PHONE FRON PUBL!C.ADDRESS f* PUBL!C.!NDEX_PLACE *f ORDER BY 3, 2, 1 f* index sorted *f; EXPLA!N SELECT PHONE FRON ADDRESS WHERE F!RST_NANE = 'John'; SELECT PHONE FRON PUBL!C.ADDRESS f* PUBL!C.ADDRESS.tableScan *f WHERE F!RST_NANE = 'John'; !f your application often queries the table for a phone number, then it makes sense to create an additional index on it: CREATE !NDEX !DX_PHONE ON ADDRESS(PHONE); This index contains the phone number, and the row id: PHONE _ROW!D_ 123 012 3+5 2 123 +56 789 1 'sing +ultiple nde"es Within a query, only one index per logical table is used. Using the condition PHONE = '123 567 789' OR C!TY = 'Berne' would use a table scan instead of first using the index on the phone number and then the index on the city. !t makes sense to write two queries and combine then using UN!ON. !n this case, each individual query uses a different index: EXPLA!N SELECT NANE FRON ADDRESS WHERE PHONE = '123 567 789' 65 of 180 UN!ON SELECT NANE FRON ADDRESS WHERE C!TY = 'Berne'; (SELECT NANE FRON PUBL!C.ADDRESS f* PUBL!C.!DX_PHONE: PHONE = '123 567 789' *f WHERE PHONE = '123 567 789') UN!ON (SELECT NANE FRON PUBL!C.ADDRESS f* PUBL!C.!NDEX_PLACE: C!TY = 'Berne' *f WHERE C!TY = 'Berne') (ast Database mport To speed up large imports, consider using the following options temporarily: SET LOG 0 (disabling the transaction log) SET CACHE_S!ZE (a large cache is faster) SET LOCK_NODE 0 (disable locking) SET UNDO_LOG 0 (disable the session undo log) These options can be set in the database URL: jdbc:h2:~ftest;LOG=0;CACHE_S!ZE=65536;LOCK_NODE=0;UNDO_LOG=0. Nost of those options are not recommended for regular use, that means you need to reset them after use. !f you have to import a lot of rows, use a PreparedStatement or use CSv import. Please note that CREATE TABLE(...) ... AS SELECT ... is faster than CREATE TABLE(...); !NSERT !NTO ... SELECT .... 66 of 180 Ad*anced Result Sets Large Objects Linked Tables Recursive Queries Updatable views Transaction !solation Nulti-version Concurrency Control (NvCC) Clustering f High Availability Two Phase Commit Compatibility Standards Compliance Run as Windows Service ODBC Driver Using H2 in Nicrosoft .NET AC!D Durability Problems Using the Recover Tool File Locking Protocols Using Passwords Password Hash Protection against SQL !njection Protection against Remote Access Restricting Class Loading and Usage Security Protocols SSLfTLS Connections Universally Unique !dentifiers (UU!D) Settings Read from System Properties Setting the Server Bind Address Pluggable File System Split File System Database Upgrade Java Objects Serialization Limits and Limitations Glossary and Links #esult Sets Statements that #eturn a #esult Set The following statements return a result set: SELECT, EXPLA!N, CALL, SCR!PT, SHOW, HELP. All other statements return an update count. !imiting the .umber of #o&s Before the result is returned to the application, all rows are read by the database. Server side cursors are not supported currently. !f only the first few rows are interesting for the application, then the result set size should be limited to improve the performance. This can be done using L!N!T in a query (example: SELECT * FRON TEST L!N!T 100), or by using Statement.setNaxRows(max). !arge #esult Sets and E"ternal Sorting For large result set, the result is buffered to disk. The threshold can be defined using the statement SET NAX_NENORY_ROWS. !f ORDER BY is used, the sorting is done using an external sort algorithm. !n this case, each block of rows is sorted using quick sort, then written to disk; when reading the data, the blocks are merged together. 67 of 180 !arge 1b0ects Storing and #eading !arge 1b0ects !f it is possible that the objects don't fit into memory, then the data type CLOB (for textual data) or BLOB (for binary data) should be used. For these data types, the objects are not fully read into memory, by using streams. To store a BLOB, use PreparedStatement.setBinaryStream. To store a CLOB, use PreparedStatement.setCharacterStream. To read a BLOB, use ResultSet.getBinaryStream, and to read a CLOB, use ResultSet.getCharacterStream. When using the clientfserver mode, large BLOB and CLOB data is stored in a temporary file on the client side. 2hen to use C!1-7-!1- By default, this database stores large LOB (CLOB and BLOB) objects separate from the main table data. Small LOB objects are stored in-place, the threshold can be set using NAX_LENGTH_!NPLACE_LOB, but there is still an overhead to use CLOBfBLOB. Because of this, BLOB and CLOB should never be used for columns with a maximum size below about 200 bytes. The best threshold depends on the use case; reading in-place objects is faster than reading from separate files, but slows down the performance of operations that don't involve this column. !arge 1b0ect Compression CLOB and BLOB values can be compressed by using SET CONPRESS_LOB. The LZF algorithm is faster but needs more disk space. By default compression is disabled, which usually speeds up write operations. !f you store many large compressible values such as XNL, HTNL, text, and uncompressed binary files, then compressing can save a lot of disk space (sometimes more than 50), and read operations may even be faster. !inked Tables This database supports linked tables, which means tables that don't exist in the current database but are just links to another database. To create such a link, use the CREATE L!NKED TABLE statement: CREATE L!NKED TABLE L!NK('org.postgresql.Driver', 'jdbc:postgresql:test', 'sa', 'sa', 'TEST'); You can then access the table in the usual way. Whenever the linked table is accessed, the database issues specific queries over JDBC. Using the example above, if you issue the query SELECT * FRON L!NK WHERE !D=1, then the following query is run against the PostgreSQL database: SELECT * FRON TEST WHERE !D=?. The same happens for insert and update statements. Only simple statements are executed against the target database, that means no joins. Prepared statements are used where possible. To view the statements that are executed against the target table, set the trace level to 3. !f multiple linked tables point to the same database (using the same database URL), the connection is shared. To disable this, set the system property h2.shareLinkedConnections=false. The statement CREATE L!NKED TABLE supports an optional schema name parameter. The following are not supported because they may result in a deadlock: creating a linked table to the same database, and creating a linked table to another database using the server mode if the other database is open in the same server (use the embedded mode instead). Data types that are not supported in H2 are also not supported for linked tables, for example unsigned data types if the value is outside the range of the signed type. !n such cases, the columns needs to be cast to a supported type. 'pdatable 3ie&s By default, views are not updatable. To make a view updatable, use an "instead of" trigger as follows: CREATE TR!GGER TR!GGER_NANE 68 of 180 !NSTEAD OF !NSERT, UPDATE, DELETE ON v!EW_NANE FOR EACH ROW CALL "com.acme.TriggerClassName"; Update the base table(s) within the trigger as required. For details, see the sample application org.h2.samples.Updatableview. Transaction solation Transaction isolation is provided for all data manipulation language (DNL) statements. Nost data definition language (DDL) statements commit the current transaction. See the Grammar for details. This database supports the following transaction isolation levels: Read Committed This is the default level. Read locks are released immediately after executing the statement, but write locks are kept until the transaction commits. Higher concurrency is possible when using this level. To enable, execute the SQL statement SET LOCK_NODE 3 or append ;LOCK_NODE=3 to the database URL: jdbc:h2:~ftest;LOCK_NODE=3 Serializable Both read locks and write locks are kept until the transaction commits. To enable, execute the SQL statement SET LOCK_NODE 1 or append ;LOCK_NODE=1 to the database URL: jdbc:h2:~ftest;LOCK_NODE=1 Read Uncommitted This level means that transaction isolation is disabled. To enable, execute the SQL statement SET LOCK_NODE 0 or append ;LOCK_NODE=0 to the database URL: jdbc:h2:~ftest;LOCK_NODE=0 When using the isolation level 'serializable', dirty reads, non-repeatable reads, and phantom reads are prohibited. Dirty Reads Neans a connection can read uncommitted changes made by another connection. Possible with: read uncommitted Non-Repeatable Reads A connection reads a row, another connection changes a row and commits, and the first connection re-reads the same row and gets the new result. Possible with: read uncommitted, read committed Phantom Reads A connection reads a set of rows using a condition, another connection inserts a row that falls in this condition and commits, then the first connection re-reads using the same condition and gets the new row. Possible with: read uncommitted, read committed Table !e*el !ocking The database allows multiple concurrent connections to the same database. To make sure all connections only see consistent data, table level locking is used by default. This mechanism does not allow high concurrency, but is very fast. Shared locks and exclusive locks are supported. Before reading from a table, the database tries to add a shared lock to the table (this is only possible if there is no exclusive lock on the object by another connection). !f the shared lock is added successfully, the table can be read. !t is allowed that other connections also have a shared lock on the same object. !f a connection wants to write to a table (update or delete a row), an exclusive lock is required. To get the exclusive lock, other connection must not have any locks on the object. After the connection commits, all locks are released. This database keeps all locks in memory. When a lock is released, and multiple connections are waiting for it, one of them is picked at random. !ock Timeout !f a connection cannot get a lock on an object, the connection waits for some amount of time (the lock timeout). During this time, hopefully the connection holding the lock commits and it is then possible to get the lock. !f this is not possible because the other connection does not release the lock for some time, the unsuccessful connection will get a lock timeout exception. The lock timeout can be set individually for each connection. 69 of 180 +ulti-3ersion Concurrency Control 4+3CC5 The NvCC feature allows higher concurrency than using (table level or row level) locks. When using NvCC in this database, delete, insert and update operations will only issue a shared lock on the table. An exclusive lock is still used when adding or removing columns, when dropping the table, and when using SELECT ... FOR UPDATE. Connections only 'see' committed data, and own changes. That means, if connection A updates a row but doesn't commit this change yet, connection B will see the old value. Only when the change is committed, the new value is visible by other connections (read committed). !f multiple connections concurrently try to update the same row, the database waits until it can apply the change, but at most until the lock timeout expires. To use the NvCC feature, append ;NvCC=TRUE to the database URL: jdbc:h2:~ftest;NvCC=TRUE NvCC is disabled by default. The NvCC feature is not fully tested yet. The limitations of the NvCC mode are: it can not be used at the same time as NULT!_THREADED=TRUE; the complete undo log (the list of uncommitted changes) must fit in memory when using multi-version concurrency. The setting NAX_NENORY_UNDO has no effect. !t is not possible to enable or disable this setting while the database is already open. The setting must be specified in the first connection (the one that opens the database). !f NvCC is enabled, changing the lock mode (LOCK_NODE) has no effect. Clustering 7 High A*ailability This database supports a simple clustering f high availability mechanism. The architecture is: two database servers run on two different computers, and on both computers is a copy of the same database. !f both servers run, each database operation is executed on both computers. !f one server fails (power, hardware or network failure), the other server can still continue to work. From this point on, the operations will be executed only on one server until the other server is back up. Clustering can only be used in the server mode (the embedded mode does not support clustering). The cluster can be re- created using the CreateCluster tool without stopping the remaining server. Applications that are still connected are automatically disconnected, however when appending ;AUTO_RECONNECT=TRUE, they will recover from that. To initialize the cluster, use the following steps: Create a database Use the CreateCluster tool to copy the database to another location and initialize the clustering. Afterwards, you have two databases containing the same data. Start two servers (one for each copy of the database) You are now ready to connect to the databases with the client application(s) 'sing the CreateCluster Tool To understand how clustering works, please try out the following example. !n this example, the two databases reside on the same computer, but usually, the databases will be on different servers. Create two directories: server1, server2. Each directory will simulate a directory on a computer. Start a TCP server pointing to the first directory. You can do this using the command line: java org.h2.tools.Server -tcp -tcpPort 9101 -baseDir server1 Start a second TCP server pointing to the second directory. This will simulate a server running on a second (redundant) computer. You can do this using the command line: java org.h2.tools.Server -tcp -tcpPort 9102 -baseDir server2 70 of 180 Use the CreateCluster tool to initialize clustering. This will automatically create a new, empty database if it does not exist. Run the tool on the command line: java org.h2.tools.CreateCluster -urlSource jdbc:h2:tcp:fflocalhost:9101f~ftest -urlTarget jdbc:h2:tcp:fflocalhost:9102f~ftest -user sa -serverList localhost:9101,localhost:9102 You can now connect to the databases using an application or the H2 Console using the JDBC URL jdbc:h2:tcp:fflocalhost:9101,localhost:9102f~ftest !f you stop a server (by killing the process), you will notice that the other machine continues to work, and therefore the database is still accessible. To restore the cluster, you first need to delete the database that failed, then restart the server that was stopped, and re-run the CreateCluster tool. Detect 2hich Cluster nstances are #unning To find out which cluster nodes are currently running, execute the following SQL statement: SELECT vALUE FRON !NFORNAT!ON_SCHENA.SETT!NGS WHERE NANE='CLUSTER' !f the result is '' (two single quotes), then the cluster mode is disabled. Otherwise, the list of servers is returned, enclosed in single quote. Example: 'server1:9191,server2:9191'. Clustering Algorithm and !imitations Read-only queries are only executed against the first cluster node, but all other statements are executed against all nodes. There is currently no load balancing made to avoid problems with transactions. The following functions may yield different results on different cluster nodes and must be executed with care: RANDON_UU!D(), SECURE_RAND(), SESS!ON_!D(), NENORY_FREE(), NENORY_USED(), CSvREAD(), CSvWR!TE(), RAND() [when not using a seed|. Those functions should not be used directly in modifying statements (for example !NSERT, UPDATE, NERGE). However, they can be used in read-only statements and the result can then be used for modifying statements. Using auto-increment and identity columns is currently not supported. !nstead, sequence values need to be manually requested and then used to insert data (using two statements). When using the cluster modes, result sets are read fully in memory by the client, so that there is no problem if the server dies that executed the query. Result sets must fit in memory on the client side. The SQL statement SET AUTOCONN!T FALSE is not supported in the cluster mode. To disable autocommit, the method Connection.setAutoCommit(false) needs to be called. !t is possible that a transaction from one connection overtakes a transaction from a different connection. Depending on the operations, this might result in different results, for example when conditionally incrementing a value in a row. T&o %hase Commit The two phase commit protocol is supported. 2-phase-commit works as follows: Autocommit needs to be switched off A transaction is started, for example by inserting a row The transaction is marked 'prepared' by executing the SQL statement PREPARE CONN!T transactionName The transaction can now be committed or rolled back !f a problem occurs before the transaction was successfully committed or rolled back (for example because a network problem occurred), the transaction is in the state 'in-doubt' When re-connecting to the database, the in-doubt transactions can be listed with SELECT * FRON !NFORNAT!ON_SCHENA.!N_DOUBT Each transaction in this list must now be committed or rolled back by executing CONN!T TRANSACT!ON transactionName or ROLLBACK TRANSACT!ON transactionName The database needs to be closed and re-opened to apply the changes 71 of 180 Compatibility This database is (up to a certain point) compatible to other databases such as HSQLDB, NySQL and PostgreSQL. There are certain areas where H2 is incompatible. Transaction Commit &hen Autocommit is 1n At this time, this database engine commits a transaction (if autocommit is switched on) just before returning the result. For a query, this means the transaction is committed even before the application scans through the result set, and before the result set is closed. Other database engines may commit the transaction in this case when the result set is closed. :ey&ords 7 #eser*ed 2ords There is a list of keywords that can't be used as identifiers (table names, column names and so on), unless they are quoted (surrounded with double quotes). The list is currently: CROSS, CURRENT_DATE, CURRENT_T!NE, CURRENT_T!NESTANP, D!ST!NCT, EXCEPT, EX!STS, FALSE, FOR, FRON, FULL, GROUP, HAv!NG, !NNER, !NTERSECT, !S, JO!N, L!KE, L!N!T, N!NUS, NATURAL, NOT, NULL, ON, ORDER, PR!NARY, ROWNUN, SELECT, SYSDATE, SYST!NE, SYST!NESTANP, TODAY, TRUE, UN!ON, UN!QUE, WHERE Certain words of this list are keywords because they are functions that can be used without '()' for compatibility, for example CURRENT_T!NESTANP. Standards Compliance This database tries to be as much standard compliant as possible. For the SQL language, ANS!f!SO is the main standard. There are several versions that refer to the release date: SQL-92, SQL:1999, and SQL:2003. Unfortunately, the standard documentation is not freely available. Another problem is that important features are not standardized. Whenever this is the case, this database tries to be compatible to other databases. Supported Character Sets6 Character Encoding6 and 'nicode H2 internally uses Unicode, and supports all character encoding systems and character sets supported by the virtual machine you use. #un as 2indo&s Ser*ice Using a native wrapper f adapter, Java applications can be run as a Windows Service. There are various tools available to do that. The Java Service Wrapper from Tanuki Software, !nc. is included in the installation. Batch files are provided to install, start, stop and uninstall the H2 Database Engine Service. This service contains the TCP Server and the H2 Console web application. The batch files are located in the directory h2fservice. The service wrapper bundled with H2 is a 32-bit version. To use a 6+-bit version of Windows (x6+), you need to use a 6+-bit version of the wrapper, for example the one from Simon Krenger. When running the database as a service, absolute path should be used. Using ~ in the database URL is problematic in this case, because it means to use the home directory of the current user. The service might run without or with the wrong user, so that the database files might end up in an unexpected place. nstall the Ser*ice The service needs to be registered as a Windows Service first. To do that, double click on 1_install_service.bat. !f successful, a command prompt window will pop up and disappear immediately. !f not, a message will appear. 72 of 180 Start the Ser*ice You can start the H2 Database Engine Service using the service manager of Windows, or by double clicking on 2_start_service.bat. Please note that the batch file does not print an error message if the service is not installed. Connect to the H2 Console After installing and starting the service, you can connect to the H2 Console application using a browser. Double clicking on 3_start_browser.bat to do that. The default port (8082) is hard coded in the batch file. Stop the Ser*ice To stop the service, double click on +_stop_service.bat. Please note that the batch file does not print an error message if the service is not installed or started. 'ninstall the Ser*ice To uninstall the service, double click on 5_uninstall_service.bat. !f successful, a command prompt window will pop up and disappear immediately. !f not, a message will appear. Additional )D-C dri*ers To use other databases (for example NySQL), the location of the JDBC drivers of those databases need to be added to the environment variables H2DR!vERS or CLASSPATH before installing the service. Nultiple drivers can be set; each entry needs to be separated with a ; (Windows) or : (other operating systems). Spaces in the path names are supported. The settings must not be quoted. 1D-C Dri*er This database does not come with its own ODBC driver at this time, but it supports the PostgreSQL network protocol. Therefore, the PostgreSQL ODBC driver can be used. Support for the PostgreSQL network protocol is quite new and should be viewed as experimental. !t should not be used for production applications. To use the PostgreSQL ODBC driver on 6+ bit versions of Windows, first run c:fwindowsfsyswow6+fodbcad32.exe. At this point you set up your DSN just like you would on any other system. See also: Re: ODBC Driver on Windows 6+ bit 1D-C nstallation First, the ODBC driver must be installed. Any recent PostgreSQL ODBC driver should work, however version 8.2 (psqlodbc- 08_02*) or newer is recommended. The Windows version of the PostgreSQL ODBC driver is available at http:ffwww.postgresql.orgfftpfodbcfversionsfmsi. Starting the Ser*er After installing the ODBC driver, start the H2 Server using the command line: java -cp h2*.jar org.h2.tools.Server The PG Server (PG for PostgreSQL protocol) is started as well. By default, databases are stored in the current working directory where the server is started. Use -baseDir to save databases in another directory, for example the user home directory: java -cp h2*.jar org.h2.tools.Server -baseDir ~ The PG server can be started and stopped from within a Java application as follows: 73 of 180 Server server = Server.createPgServer("-baseDir", "~"); server.start(); ... server.stop(); By default, only connections from localhost are allowed. To allow remote connections, use -pgAllowOthers when starting the server. To map an ODBC database name to a different JDBC database name, use the option -key when starting the server. Please note only one mapping is allowed. The following will map the ODBC database named TEST to the database URL jdbc:h2:~fdataftest;cipher=aes: java org.h2.tools.Server -pg -key TEST "~fdataftest;cipher=aes" 1D-C Configuration After installing the driver, a new Data Source must be added. !n Windows, run odbcad32.exe to open the Data Source Administrator. Then click on 'Add...' and select the PostgreSQL Unicode driver. Then click 'Finish'. You will be able to change the connection properties. The property column represents the property key in the odbc.ini file (which may be different from the GU!). Property Example Remarks Data Source H2 Test The name of the ODBC Data Source Database ~ftest;ifexist s=true The database name. This can include connections settings. By default, the database is stored in the current working directory where the Server is started except when the -baseDir setting is used. The name must be at least 3 characters. Servername localhost The server name or !P address. By default, only remote connections are allowed Username sa The database user name. SSL false (disabled) At this time, SSL is not supported. Port 5+35 The port where the PG Server is listening. Password sa The database password. To improve performance, please enable 'server side prepare' under Options f Datasource f Page 2 f Server side prepare. Afterwards, you may use this data source. %/ %rotocol Support !imitations At this time, only a subset of the PostgreSQL network protocol is implemented. Also, there may be compatibility problems on the SQL level, with the catalog, or with text encoding. Problems are fixed as they are found. Currently, statements can not be canceled when using the PG protocol. Also, H2 does not provide index meta over ODBC. PostgreSQL ODBC Driver Setup requires a database password; that means it is not possible to connect to H2 databases without password. This is a limitation of the ODBC driver. Security Considerations Currently, the PG Server does not support challenge response or encrypt passwords. This may be a problem if an attacker can listen to the data transferred between the ODBC driver and the server, because the password is readable to the attacker. Also, it is currently not possible to use encrypted SSL connections. Therefore the ODBC driver should not be used where security is important. The first connection that opens a database using the PostgreSQL server needs to be an administrator user. Subsequent connections don't need to be opened by an administrator. 7+ of 180 'sing +icrosoft Access When using Nicrosoft Access to edit data in a linked H2 table, you may need to enable the following option: Tools - Options - EditfFind - ODBC fields. 'sing H2 in +icrosoft ?.ET The database can be used from Nicrosoft .NET even without using Java, by using !KvN.NET. You can access a H2 database on .NET using the JDBC AP!, or using the ADO.NET interface. 'sing the AD1?.ET A% on ?.ET An implementation of the ADO.NET interface is available in the open source project H2Sharp. 'sing the )D-C A% on ?.ET !nstall the .NET Framework from Nicrosoft. Nono has not yet been tested. !nstall !KvN.NET. Copy the h2*.jar file to ikvmfbin Run the H2 Console using: ikvm -jar h2*.jar Convert the H2 Console to an .exe file using: ikvmc -target:winexe h2*.jar. You may ignore the warnings. Create a .dll file using (change the version accordingly): ikvmc.exe -target:library -version:1.0.69.0 h2*.jar !f you want your C# application use H2, you need to add the h2.dll and the !KvN.OpenJDK.ClassLibrary.dll to your C# solution. Here some sample code: using System; using java.sql; class Test { static public void Nain() { org.h2.Driver.load(); Connection conn = DriverNanager.getConnection("jdbc:h2:~ftest", "sa", "sa"); Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("SELECT 'Hello World'"); while (rs.next()) { Console.WriteLine(rs.getString(1)); ) ) ) ACD !n the database world, AC!D stands for: Atomicity: transactions must be atomic, meaning either all tasks are performed or none. Consistency: all operations must comply with the defined constraints. !solation: transactions must be isolated from each other. Durability: committed transaction will not be lost. Atomicity Transactions in this database are always atomic. 75 of 180 Consistency By default, this database is always in a consistent state. Referential integrity rules are enforced except when explicitly disabled. solation For H2, as with most other database systems, the default isolation level is 'read committed'. This provides better performance, but also means that transactions are not completely isolated. H2 supports the transaction isolation levels 'serializable', 'read committed', and 'read uncommitted'. Durability This database does not guarantee that all committed transactions survive a power failure. Tests show that all databases sometimes lose transactions on power failure (for details, see below). Where losing transactions is not acceptable, a laptop or UPS (uninterruptible power supply) should be used. !f durability is required for all possible cases of hardware failure, clustering should be used, such as the H2 clustering mode. Durability %roblems Complete durability means all committed transaction survive a power failure. Some databases claim they can guarantee durability, but such claims are wrong. A durability test was run against H2, HSQLDB, PostgreSQL, and Derby. All of those databases sometimes lose committed transactions. The test is included in the H2 download, see org.h2.test.poweroff.Test. 2ays to 4.ot5 Achie*e Durability Naking sure that committed transactions are not lost is more complicated than it seems first. To guarantee complete durability, a database must ensure that the log record is on the hard drive before the commit call returns. To do that, databases use different methods. One is to use the 'synchronous write' file access mode. !n Java, RandomAccessFile supports the modes rws and rwd: rwd: every update to the file's content is written synchronously to the underlying storage device. rws: in addition to rwd, every update to the metadata is written synchronously. A test (org.h2.test.poweroff.TestWrite) with one of those modes achieves around 50 thousand write operations per second. Even when the operating system write buffer is disabled, the write rate is around 50 thousand operations per second. This feature does not force changes to disk because it does not flush all buffers. The test updates the same byte in the file again and again. !f the hard drive was able to write at this rate, then the disk would need to make at least 50 thousand revolutions per second, or 3 million RPN (revolutions per minute). There are no such hard drives. The hard drive used for the test is about 7200 RPN, or about 120 revolutions per second. There is an overhead, so the maximum write rate must be lower than that. Calling fsync flushes the buffers. There are two ways to do that in Java: FileDescriptor.sync(). The documentation says that this forces all system buffers to synchronize with the underlying device. This method is supposed to return after all in-memory modified copies of buffers associated with this file descriptor have been written to the physical medium. FileChannel.force(). This method is supposed to force any updates to this channel's file to be written to the storage device that contains it. By default, NySQL calls fsync for each commit. When using one of those methods, only around 60 write operations per second can be achieved, which is consistent with the RPN rate of the hard drive used. Unfortunately, even when calling FileDescriptor.sync() or FileChannel.force(), data is not always persisted to the hard drive, because most hard drives do not obey fsync(): see Your Hard Drive Lies to You. !n Nac OS X, fsync does not flush hard drive buffers. See Bad fsync?. So the situation is confusing, and tests prove there is a problem. Trying to flush hard drive buffers is hard, and if you do the performance is very bad. First you need to make sure that the hard drive actually flushes all buffers. Tests show that this can not be done in a reliable way. Then the maximum number of transactions is around 60 per second. Because of those reasons, the default behavior of H2 is to delay writing committed transactions. 76 of 180 !n H2, after a power failure, a bit more than one second of committed transactions may be lost. To change the behavior, use SET WR!TE_DELAY and CHECKPO!NT SYNC. Nost other databases support commit delay as well. !n the performance comparison, commit delay was used for all databases that support it. #unning the Durability Test To test the durability f non-durability of this and other databases, you can use the test application in the package org.h2.test.poweroff. Two computers with network connection are required to run this test. One computer just listens, while the test application is run (and power is cut) on the other computer. The computer with the listener application opens a TCPf!P port and listens for an incoming connection. The second computer first connects to the listener, and then created the databases and starts inserting records. The connection is set to 'autocommit', which means after each inserted record a commit is performed automatically. Afterwards, the test computer notifies the listener that this record was inserted successfully. The listener computer displays the last inserted record number every 10 seconds. Now, switch off the power manually, then restart the computer, and run the application again. You will find out that in most cases, none of the databases contains all the records that the listener computer knows about. For details, please consult the source code of the listener and test application. 'sing the #eco*er Tool The Recover tool can be used to extract the contents of a database file, even if the database is corrupted. !t also extracts the content of the transaction log and large objects (CLOB or BLOB). To run the tool, type on the command line: java -cp h2*.jar org.h2.tools.Recover For each database in the current directory, a text file will be created. This file contains raw insert statements (for the data) and data definition (DDL) statements to recreate the schema of the database. This file can be executed using the RunScript tool or a RUNSCR!PT FRON SQL statement. The script includes at least one CREATE USER statement. !f you run the script against a database that was created with the same user, or if there are conflicting users, running the script will fail. Consider running the script against a database that was created with a user name that is not in the script. The Recover tool creates a SQL script from database file. !t also processes the transaction log. To verify the database can recover at any time, append ;RECOvER_TEST=6+ to the database URL in your test environment. This will simulate an application crash after each 6+ writes to the database file. A log file named databaseName.h2.db.log is created that lists the operations. The recovery is tested using an in-memory file system, that means it may require a larger heap setting. (ile !ocking %rotocols Nultiple concurrent connections to the same database are supported, however a database file can only be open for reading and writing (in embedded mode) by one process at the same time. Otherwise, the processes would overwrite each others data and corrupt the database file. To protect against this problem, whenever a database is opened, a lock file is created to signal other processes that the database is in use. !f the database is closed, or if the process that opened the database stops normally, this lock file is deleted. !n special cases (if the process did not terminate normally, for example because there was a power failure), the lock file is not deleted by the process that created it. That means the existence of the lock file is not a safe protocol for file locking. However, this software uses a challenge-response protocol to protect the database files. There are two methods (algorithms) implemented to provide both security (that is, the same database files cannot be opened by two processes at the same time) and simplicity (that is, the lock file does not need to be deleted manually by the user). The two methods are 'file method' and 'socket methods'. The file locking protocols (except the file locking method 'FS') have the following limitation: if a shared file system is used, and the machine with the lock owner is sent to sleep (standby or hibernate), another machine may take over. !f the machine that originally held the lock wakes up, the database may become corrupt. !f this situation can occur, the application must ensure the database is closed when the application is put to sleep. (ile !ocking +ethod ,(ile, The default method for database file locking for version 1.3 and older is the 'File Nethod'. The algorithm is: 77 of 180 !f the lock file does not exist, it is created (using the atomic operation File.createNewFile). Then, the process waits a little bit (20 ms) and checks the file again. !f the file was changed during this time, the operation is aborted. This protects against a race condition when one process deletes the lock file just after another one create it, and a third process creates the file again. !t does not occur if there are only two writers. !f the file can be created, a random number is inserted together with the locking method ('file'). Afterwards, a watchdog thread is started that checks regularly (every second once by default) if the file was deleted or modified by another (challenger) thread f process. Whenever that occurs, the file is overwritten with the old data. The watchdog thread runs with high priority so that a change to the lock file does not get through undetected even if the system is very busy. However, the watchdog thread does use very little resources (CPU time), because it waits most of the time. Also, the watchdog only reads from the hard disk and does not write to it. !f the lock file exists and was recently modified, the process waits for some time (up to two seconds). !f it was still changed, an exception is thrown (database is locked). This is done to eliminate race conditions with many concurrent writers. Afterwards, the file is overwritten with a new version (challenge). After that, the thread waits for 2 seconds. !f there is a watchdog thread protecting the file, he will overwrite the change and this process will fail to lock the database. However, if there is no watchdog thread, the lock file will still be as written by this thread. !n this case, the file is deleted and atomically created again. The watchdog thread is started in this case and the file is locked. This algorithm is tested with over 100 concurrent threads. !n some cases, when there are many concurrent threads trying to lock the database, they block each other (meaning the file cannot be locked by any of them) for some time. However, the file never gets locked by two threads at the same time. However using that many concurrent threads f processes is not the common use case. Generally, an application should throw an error to the user if it cannot open a database, and not try again in a (fast) loop. (ile !ocking +ethod ,Socket, There is a second locking mechanism implemented, but disabled by default. To use it, append ;F!LE_LOCK=SOCKET to the database URL. The algorithm is: !f the lock file does not exist, it is created. Then a server socket is opened on a defined port, and kept open. The port and !P address of the process that opened the database is written into the lock file. !f the lock file exists, and the lock method is 'file', then the software switches to the 'file' method. !f the lock file exists, and the lock method is 'socket', then the process checks if the port is in use. !f the original process is still running, the port is in use and this process throws an exception (database is in use). !f the original process died (for example due to a power failure, or abnormal termination of the virtual machine), then the port was released. The new process deletes the lock file and starts again. This method does not require a watchdog thread actively polling (reading) the same file every second. The problem with this method is, if the file is stored on a network share, two processes (running on different computers) could still open the same database files, if they do not have a direct TCPf!P connection. (ile !ocking +ethod ,(S, This is the default mode for version 1.+ and newer. This database file locking mechanism uses native file system lock on the database file. No *.lock.db file is created in this case, and no background thread is started. This mechanism may not work on all systems as expected. Some systems allow to lock the same file multiple times within the same virtual machine, and on some system native file locking is not supported or files are not unlocked after a power failure. To enable this feature, append ;F!LE_LOCK=FS to the database URL. This feature is relatively new. When using it for production, please ensure your system does in fact lock files as expected. 'sing %ass&ords 'sing Secure %ass&ords Remember that weak passwords can be broken regardless of the encryption and security protocols. Don't use passwords that can be found in a dictionary. Appending numbers does not make passwords secure. A way to create good passwords that can be remembered is: take the first letters of a sentence, use upper and lower case characters, and creatively include special characters (but it's more important to use a long password than to use special characters). Example: i'sE2rtPiUKtT from the sentence it's easy to remember this password if you know the trick. 78 of 180 %ass&ords; 'sing Char Arrays instead of Strings Java strings are immutable objects and cannot be safely 'destroyed' by the application. After creating a string, it will remain in the main memory of the computer at least until it is garbage collected. The garbage collection cannot be controlled by the application, and even if it is garbage collected the data may still remain in memory. !t might also be possible that the part of memory containing the password is swapped to disk (if not enough main memory is available), which is a problem if the attacker has access to the swap file of the operating system. !t is a good idea to use char arrays instead of strings for passwords. Char arrays can be cleared (filled with zeros) after use, and therefore the password will not be stored in the swap file. This database supports using char arrays instead of string to pass user and file passwords. The following code can be used to do that: import java.sql.*; import java.util.*; public class Test { public static void main(String[| args) throws Exception { Class.forName("org.h2.Driver"); String url = "jdbc:h2:~ftest"; Properties prop = new Properties(); prop.setProperty("user", "sa"); System.out.print("Password?"); char[| password = System.console().readPassword(); prop.put("password", password); Connection conn = null; try { conn = DriverNanager.getConnection(url, prop); ) finally { Arrays.fill(password, (char) 0); ) conn.close(); ) ) This example requires Java 1.6. When using Swing, use javax.swing.JPasswordField. %assing the 'ser .ame and7or %ass&ord in the '#! !nstead of passing the user name as a separate parameter as in Connection conn = DriverNanager. getConnection("jdbc:h2:~ftest", "sa", "123"); the user name (andfor password) can be supplied in the URL itself: Connection conn = DriverNanager. getConnection("jdbc:h2:~ftest;USER=sa;PASSWORD=123"); The settings in the URL override the settings passed as a separate parameter. %ass&ord Hash Sometimes the database password needs to be stored in a configuration file (for example in the web.xml file). !n addition to connecting with the plain text password, this database supports connecting with the password hash. This means that only the hash of the password (and not the plain text password) needs to be stored in the configuration file. This will only protect others from reading or re-constructing the plain text password (even if they have access to the configuration file); it does not protect others from accessing the database using the password hash. To connect using the password hash instead of plain text password, append ;PASSWORD_HASH=TRUE to the database URL, and replace the password with the password hash. To calculate the password hash from a plain text password, run the following command within the H2 Console tool: @password_hash <upperCaseUserName> <password>. As an example, if the user name is sa and the password is test, run the command @password_hash SA test. Then use the resulting password hash as you would use the plain text password. When using an encrypted database, then the user password and file password need to be hashed separately. To calculate the hash of the file password, run: @password_hash file <filePassword>. 79 of 180 %rotection against SQ! n0ection 2hat is SQ! n0ection This database engine provides a solution for the security vulnerability known as 'SQL !njection'. Here is a short description of what SQL injection means. Some applications build SQL statements with embedded user input such as: String sql = "SELECT * FRON USERS WHERE PASSWORD='"+pwd+"'"; ResultSet rs = conn.createStatement().executeQuery(sql); !f this mechanism is used anywhere in the application, and user input is not correctly filtered or encoded, it is possible for a user to inject SQL functionality or statements by using specially built input such as (in this example) this password: ' OR ''='. !n this case the statement becomes: SELECT * FRON USERS WHERE PASSWORD='' OR ''=''; Which is always true no matter what the password stored in the database is. For more information about SQL !njection, see Glossary and Links. Disabling !iterals SQL !njection is not possible if user input is not directly embedded in SQL statements. A simple solution for the problem above is to use a prepared statement: String sql = "SELECT * FRON USERS WHERE PASSWORD=?"; PreparedStatement prep = conn.prepareStatement(sql); prep.setString(1, pwd); ResultSet rs = prep.executeQuery(); This database provides a way to enforce usage of parameters when passing user input to the database. This is done by disabling embedded literals in SQL statements. To do this, execute the statement: SET ALLOW_L!TERALS NONE; Afterwards, SQL statements with text and number literals are not allowed any more. That means, SQL statement of the form WHERE NANE='abc' or WHERE Customer!d=10 will fail. !t is still possible to use prepared statements and parameters as described above. Also, it is still possible to generate SQL statements dynamically, and use the Statement AP!, as long as the SQL statements do not include literals. There is also a second mode where number literals are allowed: SET ALLOW_L!TERALS NUNBERS. To allow all literals, execute SET ALLOW_L!TERALS ALL (this is the default setting). Literals can only be enabled or disabled by an administrator. 'sing Constants Disabling literals also means disabling hard-coded 'constant' literals. This database supports defining constants using the CREATE CONSTANT command. Constants can be defined only when literals are enabled, but used even when literals are disabled. To avoid name clashes with column names, constants can be defined in other schemas: CREATE SCHENA CONST AUTHOR!ZAT!ON SA; CREATE CONSTANT CONST.ACT!vE vALUE 'Active'; CREATE CONSTANT CONST.!NACT!vE vALUE '!nactive'; SELECT * FRON USERS WHERE TYPE=CONST.ACT!vE; Even when literals are enabled, it is better to use constants instead of hard-coded number or text literals in queries or views. With constants, typos are found at compile time, the source code is easier to understand and change. 80 of 180 'sing the =E#145 (unction !t is not required to create a constant for the number 0 as there is already a built-in function ZERO(): SELECT * FRON USERS WHERE LENGTH(PASSWORD)=ZERO(); %rotection against #emote Access By default this database does not allow connections from other machines when starting the H2 Console, the TCP server, or the PG server. Remote access can be enabled using the command line options -webAllowOthers, -tcpAllowOthers, -pgAllowOthers. !f you enable remote access, please also consider using the options -baseDir, -ifExists, so that remote users can not create new databases or access existing databases with weak passwords. When using the option -baseDir, only databases within that directory may be accessed. Ensure the existing accessible databases are protected using strong passwords. #estricting Class !oading and 'sage By default there is no restriction on loading classes and executing Java code for admins. That means an admin may call system functions such as System.setProperty by executing: CREATE AL!AS SET_PROPERTY FOR "java.lang.System.setProperty"; CALL SET_PROPERTY('abc', '1'); CREATE AL!AS GET_PROPERTY FOR "java.lang.System.getProperty"; CALL GET_PROPERTY('abc'); To restrict users (including admins) from loading classes and executing code, the list of allowed classes can be set in the system property h2.allowedClasses in the form of a comma separated list of classes or patterns (items ending with *). By default all classes are allowed. Example: java -Dh2.allowedClasses=java.lang.Nath,com.acme.* This mechanism is used for all user classes, including database event listeners, trigger classes, user-defined functions, user- defined aggregate functions, and JDBC driver classes (with the exception of the H2 driver) when using the H2 Console. Security %rotocols The following paragraphs document the security protocols used in this database. These descriptions are very technical and only intended for security experts that already know the underlying security primitives. 'ser %ass&ord Encryption When a user tries to connect to a database, the combination of user name, @, and password are hashed using SHA-256, and this hash value is transmitted to the database. This step does not protect against an attacker that re-uses the value if he is able to listen to the (unencrypted) transmission between the client and the server. But, the passwords are never transmitted as plain text, even when using an unencrypted connection between client and server. That means if a user reuses the same password for different things, this password is still protected up to some point. See also 'RFC 2617 - HTTP Authentication: Basic and Digest Access Authentication' for more information. When a new database or user is created, a new random salt value is generated. The size of the salt is 6+ bits. Using the random salt reduces the risk of an attacker pre-calculating hash values for many different (commonly used) passwords. The combination of user-password hash value (see above) and salt is hashed using SHA-256. The resulting value is stored in the database. When a user tries to connect to the database, the database combines user-password hash value with the stored salt value and calculates the hash value. Other products use multiple iterations (hash the hash value again and again), but this is not done in this product to reduce the risk of denial of service attacks (where the attacker tries to connect with bogus passwords, and the server spends a lot of time calculating the hash value for each password). The reasoning is: if the attacker has access to the hashed passwords, he also has access to the data in plain text, and therefore does not need the password any more. !f the data is protected by storing it on another computer and only accessible remotely, then the iteration count is not required at all. 81 of 180 (ile Encryption The database files can be encrypted using the AES-128 algorithm. When a user tries to connect to an encrypted database, the combination of file@ and the file password is hashed using SHA- 256. This hash value is transmitted to the server. When a new database file is created, a new cryptographically secure random salt value is generated. The size of the salt is 6+ bits. The combination of the file password hash and the salt value is hashed 102+ times using SHA-256. The reason for the iteration is to make it harder for an attacker to calculate hash values for common passwords. The resulting hash value is used as the key for the block cipher algorithm. Then, an initialization vector (!v) key is calculated by hashing the key again using SHA-256. This is to make sure the !v is unknown to the attacker. The reason for using a secret !v is to protect against watermark attacks. Before saving a block of data (each block is 8 bytes long), the following operations are executed: first, the !v is calculated by encrypting the block number with the !v key (using the same block cipher algorithm). This !v is combined with the plain text using XOR. The resulting data is encrypted using the AES-128 algorithm. When decrypting, the operation is done in reverse. First, the block is decrypted using the key, and then the !v is calculated combined with the decrypted text using XOR. Therefore, the block cipher mode of operation is CBC (cipher-block chaining), but each chain is only one block long. The advantage over the ECB (electronic codebook) mode is that patterns in the data are not revealed, and the advantage over multi block CBC is that flipped cipher text bits are not propagated to flipped plaintext bits in the next block. Database encryption is meant for securing the database while it is not in use (stolen laptop and so on). !t is not meant for cases where the attacker has access to files while the database is in use. When he has write access, he can for example replace pieces of files with pieces of older versions and manipulate data like this. File encryption slows down the performance of the database engine. Compared to unencrypted mode, database operations take about 2.5 times longer using AES (embedded mode). 2rong %ass&ord 7 'ser .ame Delay To protect against remote brute force password attacks, the delay after each unsuccessful login gets double as long. Use the system properties h2.delayWrongPasswordNin and h2.delayWrongPasswordNax to change the minimum (the default is 250 milliseconds) or maximum delay (the default is +000 milliseconds, or + seconds). The delay only applies for those using the wrong password. Normally there is no delay for a user that knows the correct password, with one exception: after using the wrong password, there is a delay of up to (randomly distributed) the same delay as for a wrong password. This is to protect against parallel brute force attacks, so that an attacker needs to wait for the whole delay. Delays are synchronized. This is also required to protect against parallel attacks. There is only one exception message for both wrong user and for wrong password, to make it harder to get the list of user names. !t is not possible from the stack trace to see if the user name was wrong or the password. HTT%S Connections The web server supports HTTP and HTTPS connections using SSLServerSocket. There is a default self-certified certificate to support an easy starting point, but custom certificates are supported as well. SS!7T!S Connections Remote SSLfTLS connections are supported using the Java Secure Socket Extension (SSLServerSocket, SSLSocket). By default, anonymous SSL is enabled. The default cipher suite is SSL_DH_anon_W!TH_RC+_128_ND5. To use your own keystore, set the system properties javax.net.ssl.keyStore and javax.net.ssl.keyStorePassword before starting the H2 server and client. See also Customizing the Default Key and Trust Stores, Store Types, and Store Passwords for more information. To disable anonymous SSL, set the system property h2.enableAnonymousSSL to false. 82 of 180 'ni*ersally 'ni$ue dentifiers 4''D5 This database supports UU!Ds. Also supported is a function to create new UU!Ds using a cryptographically strong pseudo random number generator. With random UU!Ds, the chance of two having the same value can be calculated using the probability theory. See also 'Birthday Paradox'. Standardized randomly generated UU!Ds have 122 random bits. + bits are used for the version (Randomly generated UU!D), and 2 bits for the variant (Leach-Salz). This database supports generating such UU!Ds using the built-in function RANDON_UU!D(). Here is a small program to estimate the probability of having two identical UU!Ds after generating a number of values: public class Test { public static void main(String[| args) throws Exception { double x = Nath.pow(2, 122); for (int i = 35; i < 62; i++) { double n = Nath.pow(2, i); double p = 1 - Nath.exp(-(n * n) f 2 f x); System.out.println("2'" + i + "=" + (1L << i) + " probability: 0" + String.valueOf(1 + p).substring(1)); ) ) ) Some values are: Number of UU!s Probability of Duplicates 2'36=68'719'+76'736 0.000'000'000'000'000'+ 2'+1=2'199'023'255'552 0.000'000'000'000'+ 2'+6=70'368'7++'177'66+ 0.000'000'000'+ To help non-mathematicians understand what those numbers mean, here a comparison: one's annual risk of being hit by a meteorite is estimated to be one chance in 17 billion, that means the probability is about 0.000'000'000'06. #ecursi*e Queries H2 has experimental support for recursive queries using so called "common table expressions" (CTE). Examples: W!TH RECURS!vE T(N) AS ( SELECT 1 UN!ON ALL SELECT N+1 FRON T WHERE N<10 ) SELECT * FRON T; -- returns the values 1 .. 10 W!TH RECURS!vE T(N) AS ( SELECT 1 UN!ON ALL SELECT N*2 FRON T WHERE N<10 ) SELECT * FRON T; -- returns the values 1, 2, +, 8, 16 CREATE TABLE FOLDER(!D !NT PR!NARY KEY, NANE vARCHAR(255), PARENT !NT); !NSERT !NTO FOLDER vALUES(1, null, null), (2, 'src', 1), (3, 'main', 2), (+, 'org', 3), (5, 'test', 2); W!TH L!NK(!D, NANE, LEvEL) AS ( SELECT !D, NANE, 0 FRON FOLDER WHERE PARENT !S NULL UN!ON ALL SELECT FOLDER.!D, !FNULL(L!NK.NANE {{ 'f', '') {{ FOLDER.NANE, LEvEL + 1 FRON L!NK !NNER JO!N FOLDER ON L!NK.!D = FOLDER.PARENT ) SELECT NANE FRON L!NK WHERE NANE !S NOT NULL ORDER BY !D; -- src 83 of 180 -- srcfmain -- srcfmainforg -- srcftest Limitations: Recursive queries need to be of the type UN!ON ALL, and the recursion needs to be on the second part of the query. No tables or views with the name of the table expression may exist. Different table expression names need to be used when using multiple distinct table expressions within the same transaction and for the same session. All columns of the table expression are of type vARCHAR, and may need to be cast to the required data type. views with recursive queries are not supported. Subqueries and !NSERT !NTO ... FRON with recursive queries are not supported. Parameters are only supported within the last SELECT statement (a workaround is to use session variables like @start within the table expression). The syntax is: W!TH RECURS!vE recursiveQueryName(columnName, ...) AS ( nonRecursiveSelect UN!ON ALL recursiveSelect ) select Settings #ead from System %roperties Some settings of the database can be set on the command line using -DpropertyName=value. !t is usually not required to change those settings manually. The settings are case sensitive. Example: java -Dh2.serverCachedObjects=256 org.h2.tools.Server The current value of the settings can be read in the table !NFORNAT!ON_SCHENA.SETT!NGS. For a complete list of settings, see SysProperties. Setting the Ser*er -ind Address Usually server sockets accept connections on anyfall local addresses. This may be a problem on multi-homed hosts. To bind only to one address, use the system property h2.bindAddress. This setting is used for both regular server sockets and for SSL server sockets. !Pv+ and !Pv6 address formats are supported. %luggable (ile System This database supports a pluggable file system AP!. The file system implementation is selected using a file name prefix. !nternally, the interfaces are very similar to the Java 7 N!O2 AP!, but do not (yet) use or require Java 7. The following file systems are included: zip: read-only zip-file based file system. Format: zip:fzipFileName!ffileName. split: file system that splits files in 1 GB files (stackable with other file systems). nio: file system that uses FileChannel instead of RandomAccessFile (faster in some operating systems). nioNapped: file system that uses memory mapped files (faster in some operating systems). Please note that there currently is a file size limitation of 2 GB when using this file system when using a 32-bit JvN. To work around this limitation, combine it with the split file system: split:nioNapped:test. memFS: in-memory file system (slower than mem; experimental; mainly used for testing the database engine itself). memLZF: compressing in-memory file system (slower than memFS but uses less memory; experimental; mainly used for testing the database engine itself). As an example, to use the the nio file system, use the following database URL: jdbc:h2:nio:~ftest. To register a new file system, extend the classes org.h2.store.fs.FilePath, FileBase, and call the method FilePath.register before using it. For input streams (but not for random access files), URLs may be used in addition to the registered file systems. Example: jar:file:fffc:ftempfexample.zip!forgfexamplefnested.csv. To read a stream from the classpath, use the prefix classpath:, as in classpath:forgfh2fsamplesfnewsfeed.sql. 8+ of 180 Split (ile System The file system prefix split: is used to split logical files into multiple physical files, for example so that a database can get larger than the maximum file system size of the operating system. !f the logical file is larger than the maximum file size, then the file is split as follows: <fileName> (first block, is always created) <fileName>.1.part (second block) Nore physical files (*.2.part, *.3.part) are automatically created f deleted if needed. The maximum physical file size of a block is 2'30 bytes, which is also called 1 GiB or 1 GB. However this can be changed if required, by specifying the block size in the file name. The file name format is: split:<x>:<fileName> where the file size per block is 2'x. For 1 NiB block sizes, use x = 20 (because 2'20 is 1 NiB). The following file name means the logical file is split into 1 NiB blocks: split:20:test.h2.db. An example database URL for this case is jdbc:h2:split:20:~ftest. Database 'pgrade !n version 1.2, H2 introduced a new file store implementation which is incompatible to the one used in versions < 1.2. To automatically convert databases to the new file store, it is necessary to include an additional jar file. The file can be found at http:ffh2database.comfh2mig_pagestore_addon.jar . !f this file is in the classpath, every connect to an older database will result in a conversion process. The conversion itself is done internally via 'script to' and 'runscript from'. After the conversion process, the files will be renamed from dbName.data.db to dbName.data.db.backup dbName.index.db to dbName.index.db.backup by default. Also, the temporary script will be written to the database directory instead of a temporary directory. Both defaults can be customized via org.h2.upgrade.DbUpgrade.setDeleteOldDb(boolean) org.h2.upgrade.DbUpgrade.setScript!nTmpDir(boolean) prior opening a database connection. Since version 1.2.1+0 it is possible to let the old h2 classes (v 1.2.128) connect to the database. The automatic upgrade .jar file must be present, and the URL must start with jdbc:h2v1_1: (the JDBC driver class is org.h2.upgrade.v1_1.Driver). !f the database should automatically connect using the old version if a database with the old format exists (without upgrade), and use the new version otherwise, then append ;NO_UPGRADE=TRUE to the database URL. Please note the old driver did not process the system property "h2.baseDir" correctly, so that using this setting is not supported when upgrading. )a*a 1b0ects Seriali<ation Java objects serialization is enabled by default for columns of type OTHER, using standard Java serializationfdeserialization semantics. To disable this feature set the system property h2.serializeJavaObject=false (default: true). Serialization and deserialization of java objects is customizable both at system level and at database level providing a JavaObjectSerializer implementation: At system level set the system property h2.javaObjectSerializer with the Fully Qualified Name of the JavaObjectSerializer interface implementation. !t will be used over the entire JvN session to (de)serialize java objects being stored in column of type OTHER. Example h2.javaObjectSerializer=com.acme.SerializerClassName. At database level execute the SQL statement SET JAvA_OBJECT_SER!AL!ZER 'com.acme.SerializerClassName' or append ;JAvA_OBJECT_SER!AL!ZER='com.acme.SerializerClassName' to the database URL: jdbc:h2:~ftest;JAvA_OBJECT_SER!AL!ZER='com.acme.SerializerClassName'. Please note that this SQL statement can only be executed before any tables are defined. 85 of 180 !imits and !imitations This database has the following known limitations: Database file size limit: + TB (using the default page size of 2 KB) or higher (when using a larger page size). This limit is including CLOB and BLOB data. The maximum file size for FAT or FAT32 file systems is + GB. That means when using FAT or FAT32, the limit is + GB for the data. This is the limitation of the file system. The database does provide a workaround for this problem, it is to use the file name prefix split:. !n that case files are split into files of 1 GB by default. An example database URL is: jdbc:h2:split:~ftest. The maximum number of rows per table is 2'6+. Nain memory requirements: The larger the database, the more main memory is required. With the current storage mechanism (the page store), the minimum main memory required is around 1 NB for each 8 GB database file size. Limit on the complexity of SQL statements. Statements of the following form will result in a stack overflow exception: SELECT * FRON DUAL WHERE X = 1 OR X = 2 OR X = 2 OR X = 2 OR X = 2 OR X = 2 -- repeat previous line 500 times -- There is no limit for the following entities, except the memory and storage capacity: maximum identifier length (table name, column name, and so on); maximum number of tables, columns, indexes, triggers, and other database objects; maximum statement length, number of parameters per statement, tables per statement, expressions in order by, group by, having, and so on; maximum rows per query; maximum columns per table, columns per index, indexes per table, lob columns per table, and so on; maximum row length, index row length, select row length; maximum length of a varchar column, decimal column, literal in a statement. Querying from the metadata tables is slow if there are many tables (thousands). For limitations on data types, see the documentation of the respective Java data type or the data type documentation of this database. /lossary and !inks Term Description AES-128 A block encryption algorithm. See also: Wikipedia: AES Birthday Paradox Describes the higher than expected probability that two persons in a room have the same birthday. Also valid for randomly generated UU!Ds. See also: Wikipedia: Birthday Paradox Digest Protocol to protect a password (but not to protect data). See also: RFC 2617: HTTP Digest Access Authentication GCJ Compiler for Java. GNU Compiler for the Java and NativeJ (commercial) HTTPS A protocol to provide security to HTTP connections. See also: RFC 2818: HTTP Over TLS Nodes of Operation Wikipedia: Block cipher modes of operation Salt Random number to increase the security of passwords. See also: Wikipedia: Key derivation function SHA-256 A cryptographic one-way hash function. See also: Wikipedia: SHA hash functions SQL !njection A security vulnerability where an application embeds SQL statements or expressions in user input. See also: Wikipedia: SQL !njection Watermark Attack Security problem of certain encryption programs where the existence of certain data can be proven without decrypting. For more information, search in the internet for 'watermark attack cryptoloop' SSLfTLS Secure Sockets Layer f Transport Layer Security. See also: Java Secure Socket Extension (JSSE) 86 of 180 SQ! /rammar nde" Commands 4Data +anipulation5 SELECT !NSERT UPDATE DELETE BACKUP CALL EXPLA!N NERGE RUNSCR!PT SCR!PT SHOW Commands 4Data Definition5 ALTER !NDEX RENANE ALTER SCHENA RENANE ALTER SEQUENCE ALTER TABLE ADD ALTER TABLE ADD CONSTRA!NT ALTER TABLE ALTER COLUNN ALTER TABLE DROP COLUNN ALTER TABLE DROP CONSTRA!NT ALTER TABLE SET ALTER TABLE RENANE ALTER USER ADN!N ALTER USER RENANE ALTER USER SET PASSWORD ALTER v!EW ANALYZE CONNENT CREATE AGGREGATE CREATE AL!AS CREATE CONSTANT CREATE DONA!N CREATE !NDEX CREATE L!NKED TABLE CREATE ROLE CREATE SCHENA CREATE SEQUENCE CREATE TABLE CREATE TR!GGER CREATE USER CREATE v!EW DROP AGGREGATE DROP AL!AS DROP ALL OBJECTS DROP CONSTANT DROP DONA!N DROP !NDEX DROP ROLE DROP SCHENA DROP SEQUENCE DROP TABLE DROP TR!GGER DROP USER DROP v!EW TRUNCATE TABLE 87 of 180 Commands 41ther5 CHECKPO!NT CHECKPO!NT SYNC CONN!T CONN!T TRANSACT!ON GRANT R!GHT GRANT ALTER ANY SCHENA GRANT ROLE HELP PREPARE CONN!T REvOKE R!GHT REvOKE ROLE ROLLBACK ROLLBACK TRANSACT!ON SAvEPO!NT SET @ SET ALLOW_L!TERALS SET AUTOCONN!T SET CACHE_S!ZE SET CLUSTER SET B!NARY_COLLAT!ON SET COLLAT!ON SET CONPRESS_LOB SET DATABASE_EvENT_L!STENER SET DB_CLOSE_DELAY SET DEFAULT_LOCK_T!NEOUT SET DEFAULT_TABLE_TYPE SET EXCLUS!vE SET !GNORECASE SET JAvA_OBJECT_SER!AL!ZER SET LOG SET LOCK_NODE SET LOCK_T!NEOUT SET NAX_LENGTH_!NPLACE_LOB SET NAX_LOG_S!ZE SET NAX_NENORY_ROWS SET NAX_NENORY_UNDO SET NAX_OPERAT!ON_NENORY SET NODE SET NULT!_THREADED SET OPT!N!ZE_REUSE_RESULTS SET PASSWORD SET QUERY_STAT!ST!CS SET QUERY_T!NEOUT SET REFERENT!AL_!NTEGR!TY SET RETENT!ON_T!NE SET SALT HASH SET SCHENA SET SCHENA_SEARCH_PATH SET THROTTLE SET TRACE_LEvEL SET TRACE_NAX_F!LE_S!ZE SET UNDO_LOG SET WR!TE_DELAY SHUTDOWN 1ther /rammar Alias And Condition Array Boolean Bytes Case Case When Cipher Column Definition 88 of 180 Comments Compare Condition Condition Right Hand Side Constraint Constraint Name Definition Csv Options Data Type Date Decimal Digit Dollar Quoted String Expression Factor Hex Hex Number !ndex Column !nt Long Name Null Number Numeric Operand Order Quoted Name Referential Constraint Referential Action Script Compression Encryption Select Expression String Summand Table Expression values Expression Term Time Timestamp value System Tables !nformation Schema Range Table SE!ECT SELECT [ TOP term | [ D!ST!NCT { ALL | selectExpression [,...| FRON tableExpression [,...| [ WHERE expression | [ GROUP BY expression [,...| | [ HAv!NG expression | [ { UN!ON [ ALL | { N!NUS { EXCEPT { !NTERSECT ) select | [ ORDER BY order [,...| | [ L!N!T expression [ OFFSET expression | [ SANPLE_S!ZE rowCount!nt | | [ FOR UPDATE | Selects data from a table or multiple tables. GROUP BY groups the the result by the given expression(s). HAv!NG filter rows after grouping. ORDER BY sorts the result by the given column(s) or expression(s). UN!ON combines the result of this query with the results of another query. L!N!T limits the number of rows returned by the query (no limit if null or smaller than zero). OFFSET specified how many rows to skip. SANPLE_S!ZE limits the number of rows read for aggregate queries. Nultiple set operators (UN!ON, !NTERSECT, N!NUS, EXPECT) are evaluated from left to right. For compatibility with other databases and future versions of H2 please use parentheses. !f FOR UPDATE is specified, the tables are locked for writing. When using NvCC, only the selected rows are locked as in an UPDATE statement. !n this case, aggregate, GROUP BY, D!ST!NCT queries or joins are not allowed in this case. 89 of 180 Example: SELECT * FRON TEST; SELECT * FRON TEST ORDER BY NANE; SELECT !D, COUNT(*) FRON TEST GROUP BY !D; SELECT NANE, COUNT(*) FRON TEST GROUP BY NANE HAv!NG COUNT(*) > 2; SELECT '!D' COL, NAX(!D) AS NAX FRON TEST UN!ON SELECT 'NANE', NAX(NANE) FRON TEST; SELECT * FRON TEST L!N!T 1000; SELECT * FRON (SELECT !D, COUNT(*) FRON TEST GROUP BY !D UN!ON SELECT NULL, COUNT(*) FRON TEST) ORDER BY 1 NULLS LAST; .SE#T !NSERT !NTO tableName { [ ( columnName [,...| ) | { vALUES { ( { DEFAULT { expression ) [,...| ) ) [,...| { [ D!RECT | [ SORTED | select ) ) { { SET { columnName = { DEFAULT { expression ) ) [,...| ) !nserts a new row f new rows into a table. When using D!RECT, then the results from the query are directly applied in the target table without any intermediate step. When using SORTED, b-tree pages are split at the insertion point. This can improve performance and reduce disk usage. Example: !NSERT !NTO TEST vALUES(1, 'Hello') '%DATE UPDATE tableName [ [ AS | newTableAlias | SET { { columnName = { DEFAULT { expression ) ) [,...| ) { { ( columnName [,...| ) = ( select ) ) [ WHERE expression | [ L!N!T expression | Updates data in a table. Example: UPDATE TEST SET NANE='Hi' WHERE !D=1; UPDATE PERSON P SET NANE=(SELECT A.NANE FRON ADDRESS A WHERE A.!D=P.!D); DE!ETE DELETE [ TOP term | FRON tableName [ WHERE expression | [ L!N!T term | Deletes rows form a table. !f TOP or L!N!T is specified, at most the specified number of rows are deleted (no limit if null or smaller than zero). Example: DELETE FRON TEST WHERE !D=2 -AC:'% BACKUP TO fileNameString 90 of 180 Backs up the database files to a .zip file. Objects are not locked, but the backup is transactionally consistent because the transaction log is also copied. Admin rights are required to execute this command. Example: BACKUP TO 'backup.zip' CA!! CALL expression Calculates a simple expression. This statement returns a result set with one row, except if the called function returns a result set itself. !f the called function returns an array, then each element in this array is returned as a column. Example: CALL 15*25 E8%!A. EXPLA!N { [ PLAN FOR | { ANALYZE ) { select { insert { update { delete { merge ) Shows the execution plan for a statement. When using EXPLA!N ANALYZE, the statement is actually executed, and the query plan will include the actual row scan count for each table. Example: EXPLA!N SELECT * FRON TEST WHERE !D=1 +E#/E NERGE !NTO tableName [ ( columnName [,...| ) | [ KEY ( columnName [,...| ) | { vALUES { ( { DEFAULT { expression ) [,...| ) ) [,...| { select ) Updates existing rows, and insert rows that don't exist. !f no key column is specified, the primary key columns are used to find the row. !f more than one row per new row is affected, an exception is thrown. !f the table contains an auto-incremented key or identity column, and the row was updated, the generated key is set to 0; otherwise it is set to the new key. Example: NERGE !NTO TEST KEY(!D) vALUES(2, 'World') #'.SC#%T RUNSCR!PT FRON fileNameString scriptCompressionEncryption [ CHARSET charsetString | Runs a SQL script from a file. The script is a text file containing SQL statements; each statement must end with ';'. This command can be used to restore a database from a backup. The password must be in single quotes; it is case sensitive and can contain spaces. !nstead of a file name, an URL may be used. To read a stream from the classpath, use the prefix 'classpath:'. See the Pluggable File System section on the Advanced page. The compression algorithm must match the one used when creating the script. !nstead of a file, an URL may be used. 91 of 180 Admin rights are required to execute this command. Example: RUNSCR!PT FRON 'backup.sql' RUNSCR!PT FRON 'classpath:fcomfacmeftest.sql' SC#%T SCR!PT [ S!NPLE | [ NODATA | [ NOPASSWORDS | [ NOSETT!NGS | [ DROP | [ BLOCKS!ZE blockSize!nt | [ TO fileNameString scriptCompressionEncryption [ CHARSET charsetString | | [ TABLE tableName [, ...| | [ SCHENA schemaName [, ...| | Creates a SQL script from the database. S!NPLE does not use multi-row insert statements. NODATA will not emit !NSERT statements. !f the DROP option is specified, drop statements are created for tables, views, and sequences. !f the block size is set, CLOB and BLOB values larger than this size are split into separate blocks. BLOCKS!ZE is used when writing out LOB data, and specifies the point at the values transition from being inserted as inline values, to be inserted using out-of-line commands. NOSETT!NGS turns off dumping the database settings (the SET XXX commands) !f no file name is specified, the script is returned as a result set. This command can be used to create a backup of the database. For long term storage, it is more portable than copying the database files. !f a file name is specified, then the whole script (including insert statements) is written to this file, and a result set without the insert statements is returned. The password must be in single quotes; it is case sensitive and can contain spaces. This command locks objects while it is running. Admin rights are required to execute this command. When using the TABLE or SCHENA option, only the selected table(s) f schema(s) are included. Example: SCR!PT NODATA SH12 SHOW { SCHENAS { TABLES [ FRON schemaName | { COLUNNS FRON tableName [ FRON schemaName | ) Lists the schemas, tables, or the columns of a table. Example: SHOW TABLES A!TE# .DE8 #E.A+E ALTER !NDEX indexName RENANE TO new!ndexName Renames an index. This command commits an open transaction. Example: 92 of 180 ALTER !NDEX !DXNANE RENANE TO !DX_TEST_NANE A!TE# SCHE+A #E.A+E ALTER SCHENA schema RENANE TO newSchemaName Renames a schema. This command commits an open transaction. Example: ALTER SCHENA TEST RENANE TO PRODUCT!ON A!TE# SEQ'E.CE ALTER SEQUENCE sequenceName [ RESTART W!TH long | [ !NCRENENT BY long | [ N!NvALUE long { NON!NvALUE { NO N!NvALUE | [ NAXvALUE long { NONAXvALUE { NO NAXvALUE | [ CYCLE long { NOCYCLE { NO CYCLE | [ CACHE long { NOCACHE { NO CACHE | Changes the parameters of a sequence. This command does not commit the current transaction; however the new value is used by other transactions immediately, and rolling back this command has no effect. Example: ALTER SEQUENCE SEQ_!D RESTART W!TH 1000 A!TE# TA-!E ADD ALTER TABLE tableName ADD [ COLUNN | { [ !F NOT EX!STS | columnDefinition [ { BEFORE { AFTER ) columnName | { ( { columnDefinition ) [,...| ) ) Adds a new column to a table. This command commits an open transaction. Example: ALTER TABLE TEST ADD CREATEDATE T!NESTANP A!TE# TA-!E ADD C1.ST#A.T ALTER TABLE tableName ADD constraint [ CHECK { NOCHECK | Adds a constraint to a table. !f NOCHECK is specified, existing rows are not checked for consistency (the default is to check consistency for existing rows). The required indexes are automatically created if they don't exist yet. !t is not possible to disable checking for unique constraints. This command commits an open transaction. Example: ALTER TABLE TEST ADD CONSTRA!NT NANE_UN!QUE UN!QUE(NANE) A!TE# TA-!E A!TE# C1!'+. ALTER TABLE tableName ALTER COLUNN columnName { { dataType [ DEFAULT expression | [ [ NOT | NULL | [ AUTO_!NCRENENT { !DENT!TY | ) 93 of 180 { { RENANE TO name ) { { RESTART W!TH long ) { { SELECT!v!TY int ) { { SET DEFAULT expression ) { { SET NULL ) { { SET NOT NULL ) ) Changes the data type of a column, rename a column, change the identity value, or change the selectivity. Changing the data type fails if the data can not be converted. RESTART changes the next value of an auto increment column. The column must already be an auto increment column. For RESTART, the same transactional rules as for ALTER SEQUENCE apply. SELECT!v!TY sets the selectivity (1-100) for a column. Setting the selectivity to 0 means the default value. Selectivity is used by the cost based optimizer to calculate the estimated cost of an index. Selectivity 100 means values are unique, 10 means every distinct value appears 10 times on average. SET DEFAULT changes the default value of a column. SET NULL sets a column to allow NULL. The row may not be part of a primary key. Single column indexes on this column are dropped. SET NOT NULL sets a column to not allow NULL. Rows may not contains NULL in this column. This command commits an open transaction. Example: ALTER TABLE TEST ALTER COLUNN NANE CLOB; ALTER TABLE TEST ALTER COLUNN NANE RENANE TO TEXT; ALTER TABLE TEST ALTER COLUNN !D RESTART W!TH 10000; ALTER TABLE TEST ALTER COLUNN NANE SELECT!v!TY 100; ALTER TABLE TEST ALTER COLUNN NANE SET DEFAULT ''; ALTER TABLE TEST ALTER COLUNN NANE SET NOT NULL; ALTER TABLE TEST ALTER COLUNN NANE SET NULL; A!TE# TA-!E D#1% C1!'+. ALTER TABLE tableName DROP COLUNN [ !F EX!STS | columnName Removes a column from a table. This command commits an open transaction. Example: ALTER TABLE TEST DROP COLUNN NANE A!TE# TA-!E D#1% C1.ST#A.T ALTER TABLE tableName DROP { CONSTRA!NT [ !F EX!STS | constraintName { PR!NARY KEY ) Removes a constraint or a primary key from a table. This command commits an open transaction. Example: ALTER TABLE TEST DROP CONSTRA!NT UN!QUE_NANE 9+ of 180 A!TE# TA-!E SET ALTER TABLE tableName SET REFERENT!AL_!NTEGR!TY { FALSE { TRUE [ CHECK { NOCHECK | ) Disables or enables referential integrity checking for a table. This command can be used inside a transaction. Enabling referential integrity does not check existing data, except if CHECK is specified. Use SET REFERENT!AL_!NTEGR!TY to disable it for all tables; the global flag and the flag for each table are independent. This command commits an open transaction. Example: ALTER TABLE TEST SET REFERENT!AL_!NTEGR!TY FALSE A!TE# TA-!E #E.A+E ALTER TABLE tableName RENANE TO newName Renames a table. This command commits an open transaction. Example: ALTER TABLE TEST RENANE TO NY_DATA A!TE# 'SE# AD+. ALTER USER userName ADN!N { TRUE { FALSE ) Switches the admin flag of a user on or off. Only unquoted or uppercase user names are allowed. Admin rights are required to execute this command. This command commits an open transaction. Example: ALTER USER TON ADN!N TRUE A!TE# 'SE# #E.A+E ALTER USER userName RENANE TO newUserName Renames a user. After renaming a user, the password becomes invalid and needs to be changed as well. Only unquoted or uppercase user names are allowed. Admin rights are required to execute this command. This command commits an open transaction. Example: ALTER USER TON RENANE TO THONAS A!TE# 'SE# SET %ASS21#D ALTER USER userName SET { PASSWORD string { SALT bytes HASH bytes ) 95 of 180 Changes the password of a user. Only unquoted or uppercase user names are allowed. The password must be enclosed in single quotes. !t is case sensitive and can contain spaces. The salt and hash values are hex strings. Admin rights are required to execute this command. This command commits an open transaction. Example: ALTER USER SA SET PASSWORD 'rioyxlgt' A!TE# 3E2 ALTER v!EW viewName RECONP!LE Recompiles a view after the underlying tables have been changed or created. This command is used for views created using CREATE FORCE v!EW. This command commits an open transaction. Example: ALTER v!EW ADDRESS_v!EW RECONP!LE A.A!@=E ANALYZE [ SANPLE_S!ZE rowCount!nt | Updates the selectivity statistics of all tables. The selectivity is used by the cost based optimizer to select the best index for a given query. !f no sample size is set, up to 10000 rows per table are read. The value 0 means all rows are read. The selectivity can be set manually using ALTER TABLE ALTER COLUNN SELECT!v!TY. Nanual values are overwritten by this statement. The selectivity is available in the !NFORNAT!ON_SCHENA.COLUNNS table. This command commits an open transaction. Example: ANALYZE SANPLE_S!ZE 1000 C1++E.T CONNENT ON { { COLUNN [ schemaName. | tableName.columnName ) { { { TABLE { v!EW { CONSTANT { CONSTRA!NT { AL!AS { !NDEX { ROLE { SCHENA { SEQUENCE { TR!GGER { USER { DONA!N ) [ schemaName. | objectName ) ) !S expression Sets the comment of a database object. Use NULL to remove the comment. Admin rights are required to execute this command. This command commits an open transaction. Example: CONNENT ON TABLE TEST !S 'Table used for testing' C#EATE A//#E/ATE CREATE AGGREGATE [ !F NOT EX!STS | newAggregateName FOR className 96 of 180 Creates a new user-defined aggregate function. The method name must be the full qualified class name. The class must implement the interface org.h2.api.AggregateFunction. Admin rights are required to execute this command. This command commits an open transaction. Example: CREATE AGGREGATE NED!AN FOR "com.acme.db.Nedian" C#EATE A!AS CREATE AL!AS [ !F NOT EX!STS | newFunctionAliasName [ DETERN!N!ST!C | [ NOBUFFER | { FOR classAndNethodName { AS sourceCodeString ) Creates a new function alias. !f this is a ResultSet returning function, by default the return value is cached in a local temporary file. NOBUFFER - disables caching of ResultSet return value to temporary file. DETERN!N!ST!C - Deterministic functions must always return the same value for the same parameters. The method name must be the full qualified class and method name, and may optionally include the parameter classes as in java.lang.!nteger.parse!nt(java.lang.String, int). The class and the method must both be public, and the method must be static. The class must be available in the classpath of the database engine (when using the server mode, it must be in the classpath of the server). When defining a function alias with source code, the Sun javac is compiler is used if the file tools.jar is in the classpath. !f not, javac is run as a separate process. Only the source code is stored in the database; the class is compiled each time the database is re-opened. Source code is usually passed as dollar quoted text to avoid escaping problems. !f import statements are used, then the tag @CODE must be added before the method. !f the method throws an SQLException, it is directly re-thrown to the calling application; all other exceptions are first converted to a SQLException. !f the first parameter of the Java function is a java.sql.Connection, then a connection to the database is provided. This connection must not be closed. !f the class contains multiple methods with the given name but different parameter count, all methods are mapped. Admin rights are required to execute this command. This command commits an open transaction. !f you have the Groovy jar in your classpath, it is also possible to write methods using Groovy. Example: CREATE AL!AS NY_SQRT FOR "java.lang.Nath.sqrt"; CREATE AL!AS GET_SYSTEN_PROPERTY FOR "java.lang.System.getProperty"; CALL GET_SYSTEN_PROPERTY('java.class.path'); CALL GET_SYSTEN_PROPERTY('com.acme.test', 'true'); CREATE AL!AS REvERSE AS $$ String reverse(String s) { return new StringBuilder(s).reverse().toString(); ) $$; CALL REvERSE('Test'); CREATE AL!AS tr AS [email protected] static String tr(String str, String sourceSet, String replacementSet){ return str.tr(sourceSet, replacementSet); ) $$ C#EATE C1.STA.T CREATE CONSTANT [ !F NOT EX!STS | newConstantName vALUE expression Creates a new constant. This command commits an open transaction. 97 of 180 Example: CREATE CONSTANT ONE vALUE 1 C#EATE D1+A. CREATE DONA!N [ !F NOT EX!STS | newDomainName AS dataType [ DEFAULT expression | [ [ NOT | NULL | [ SELECT!v!TY selectivity | [ CHECK condition | Creates a new data type (domain). The check condition must evaluate to true or to NULL (to prevent NULL, use NOT NULL). !n the condition, the term vALUE refers to the value being tested. Domains are usable within the whole database. They can not be created in a specific schema. This command commits an open transaction. Example: CREATE DONA!N ENA!L AS vARCHAR(255) CHECK (POS!T!ON('@', vALUE) > 1) C#EATE .DE8 CREATE { [ UN!QUE | [ HASH | [ SPAT!AL| !NDEX [ [ !F NOT EX!STS | new!ndexName | { PR!NARY KEY [ HASH | ) ON tableName ( indexColumn [,...| ) Creates a new index. This command commits an open transaction. Hash indexes are meant for in-memory databases and memory tables (CREATE NENORY TABLE). For other tables, or if the index contains multiple columns, the HASH keyword is ignored. Hash indexes can only test for equality, and do not support range queries (similar to a hash table). Non-unique keys are supported. Spatial indexes are supported only on Geometry columns. Example: CREATE !NDEX !DXNANE ON TEST(NANE) C#EATE !.:ED TA-!E CREATE [ FORCE | [ [ GLOBAL { LOCAL | TENPORARY | L!NKED TABLE [ !F NOT EX!STS | name ( driverString, urlString, userString, passwordString, [ originalSchemaString, | originalTableString ) [ EN!T UPDATES { READONLY | Creates a table link to an external table. The driver name may be empty if the driver is already loaded. !f the schema name is not set, only one table with that name may exist in the target database. FORCE - Create the L!NKED TABLE even if the remote databaseftable does not exist. EN!T UPDATES - Usually, for update statements, the old rows are deleted first and then the new rows are inserted. !t is possible to emit update statements (except on rollback), however in this case multi-row unique key updates may not always work. Linked tables to the same database share one connection. READONLY - is set, the remote table may not be updated. This is enforced by H2. !f the connection to the source database is lost, the connection is re-opened (this is a workaround for NySQL that disconnects after 8 hours of inactivity by default). 98 of 180 !f a query is used instead of the original table name, the table is read only. Queries must be enclosed in parenthesis: (SELECT * FRON ORDERS). To use JND! to get the connection, the driver class must be a javax.naming.Context (for example javax.naming.!nitialContext), and the URL must be the resource name (for example java:compfenvfjdbcfTest). Admin rights are required to execute this command. This command commits an open transaction. Example: CREATE L!NKED TABLE L!NK('org.h2.Driver', 'jdbc:h2:test2', 'sa', 'sa', 'TEST'); CREATE L!NKED TABLE L!NK('', 'jdbc:h2:test2', 'sa', 'sa', '(SELECT * FRON TEST WHERE !D>0)'); CREATE L!NKED TABLE L!NK('javax.naming.!nitialContext', 'java:compfenvfjdbcfTest', NULL, NULL, '(SELECT * FRON TEST WHERE !D>0)'); C#EATE #1!E CREATE ROLE [ !F NOT EX!STS | newRoleName Creates a new role. This command commits an open transaction. Example: CREATE ROLE READONLY C#EATE SCHE+A CREATE SCHENA [ !F NOT EX!STS | name [ AUTHOR!ZAT!ON ownerUserName | Creates a new schema. !f no owner is specified, the current user is used. The user that executes the command must have admin rights, as well as the owner. Specifying the owner currently has no effect. This command commits an open transaction. Example: CREATE SCHENA TEST_SCHENA AUTHOR!ZAT!ON SA C#EATE SEQ'E.CE CREATE SEQUENCE [ !F NOT EX!STS | newSequenceName [ START W!TH long | [ !NCRENENT BY long | [ N!NvALUE long { NON!NvALUE { NO N!NvALUE | [ NAXvALUE long { NONAXvALUE { NO NAXvALUE | [ CYCLE long { NOCYCLE { NO CYCLE | [ CACHE long { NOCACHE { NO CACHE | Creates a new sequence. The data type of a sequence is B!G!NT. Used values are never re-used, even when the transaction is rolled back. The cache is the number of pre-allocated numbers. !f the system crashes without closing the database, at most this many numbers are lost. The default cache size is 32. To disable caching, use the cache size 1 or lower. This command commits an open transaction. Example: 99 of 180 CREATE SEQUENCE SEQ_!D C#EATE TA-!E CREATE [ CACHED { NENORY | [ TENP { [ GLOBAL { LOCAL | TENPORARY | TABLE [ !F NOT EX!STS | name [ ( { columnDefinition { constraint ) [,...| ) | [ ENG!NE tableEngineName [ W!TH tableEngineParamName [,...| | | [ NOT PERS!STENT | [ TRANSACT!ONAL | [ AS select | Creates a new table. Cached tables (the default for regular tables) are persistent, and the number of rows is not limited by the main memory. Nemory tables (the default for temporary tables) are persistent, but the index data is kept in main memory, that means memory tables should not get too large. Temporary tables are deleted when closing or opening a database. Temporary tables can be global (accessible by all connections) or local (only accessible by the current connection). The default for temporary tables is global. !ndexes of temporary tables are kept fully in main memory, unless the temporary table is created using CREATE CACHED TABLE. The ENG!NE option is only required when custom table implementations are used. The table engine class must implement the interface org.h2.api.TableEngine. Any table engine parameters are passed down in the tableEngineParams field of the CreateTableData object. Tables with the NOT PERS!STENT modifier are kept fully in memory, and all rows are lost when the database is closed. The column definition is optional if a query is specified. !n that case the column list of the query is used. This command commits an open transaction, except when using TRANSACT!ONAL (only supported for temporary tables). Example: CREATE TABLE TEST(!D !NT PR!NARY KEY, NANE vARCHAR(255)) C#EATE T#//E# CREATE TR!GGER [ !F NOT EX!STS | newTriggerName { BEFORE { AFTER { !NSTEAD OF ) { !NSERT { UPDATE { DELETE { SELECT { ROLLBACK ) [,...| ON tableName [ FOR EACH ROW | [ QUEUE int | [ NOWA!T | CALL triggeredClassName Creates a new trigger. The trigger class must be public and implement org.h2.api.Trigger. !nner classes are not supported. The class must be available in the classpath of the database engine (when using the server mode, it must be in the classpath of the server). BEFORE triggers are called after data conversion is made, default values are set, null and length constraint checks have been made; but before other constraints have been checked. !f there are multiple triggers, the order in which they are called is undefined. ROLLBACK can be specified in combination with !NSERT, UPDATE, and DELETE. Only row based AFTER trigger can be called on ROLLBACK. Exceptions that occur within such triggers are ignored. As the operations that occur within a trigger are part of the transaction, ROLLBACK triggers are only required if an operation communicates outside of the database. !NSTEAD OF triggers are implicitly row based and behave like BEFORE triggers. Only the first such trigger is called. Such triggers on views are supported. They can be used to make views updatable. A BEFORE SELECT trigger is fired just before the database engine tries to read from the table. The trigger can be used to update a table on demand. The trigger is called with both 'old' and 'new' set to null. The NERGE statement will call both !NSERT and UPDATE triggers. Not supported are SELECT triggers with the option FOR EACH ROW, and AFTER SELECT triggers. 100 of 180 Committing or rolling back a transaction within a trigger is not allowed, except for SELECT triggers. By default a trigger is called once for each statement, without the old and new rows. FOR EACH ROW triggers are called once for each inserted, updated, or deleted row. QUEUE is implemented for syntax compatibility with HSQL and has no effect. The trigger need to be created in the same schema as the table. The schema name does not need to be specified when creating the trigger. This command commits an open transaction. Example: CREATE TR!GGER TR!G_!NS BEFORE !NSERT ON TEST FOR EACH ROW CALL "NyTrigger" C#EATE 'SE# CREATE USER [ !F NOT EX!STS | newUserName { PASSWORD string { SALT bytes HASH bytes ) [ ADN!N | Creates a new user. For compatibility, only unquoted or uppercase user names are allowed. The password must be in single quotes. !t is case sensitive and can contain spaces. The salt and hash values are hex strings. Admin rights are required to execute this command. This command commits an open transaction. Example: CREATE USER GUEST PASSWORD 'abc' C#EATE 3E2 CREATE [ OR REPLACE | [ FORCE | v!EW [ !F NOT EX!STS | newviewName [ ( columnName [,...| ) | AS select Creates a new view. !f the force option is used, then the view is created even if the underlying table(s) don't exist. !f the OR REPLACE clause is used an existing view will be replaced, and any dependent views will not need to be recreated. !f dependent views will become invalid as a result of the change an error will be generated, but this error can be ignored if the FORCE clause is also used. views are not updatable except when using 'instead of' triggers. Admin rights are required to execute this command. This command commits an open transaction. Example: CREATE v!EW TEST_v!EW AS SELECT * FRON TEST WHERE !D < 100 D#1% A//#E/ATE DROP AGGREGATE [ !F EX!STS | aggregateName Drops an existing user-defined aggregate function. Admin rights are required to execute this command. This command commits an open transaction. 101 of 180 Example: DROP AGGREGATE NED!AN D#1% A!AS DROP AL!AS [ !F EX!STS | existingFunctionAliasName Drops an existing function alias. Admin rights are required to execute this command. This command commits an open transaction. Example: DROP AL!AS NY_SQRT D#1% A!! 1-)ECTS DROP ALL OBJECTS [ DELETE F!LES | Drops all existing views, tables, sequences, schemas, function aliases, roles, user-defined aggregate functions, domains, and users (except the current user). !f DELETE F!LES is specified, the database files will be removed when the last user disconnects from the database. Warning: this command can not be rolled back. Admin rights are required to execute this command. Example: DROP ALL OBJECTS D#1% C1.STA.T DROP CONSTANT [ !F EX!STS | constantName Drops a constant. This command commits an open transaction. Example: DROP CONSTANT ONE D#1% D1+A. DROP DONA!N [ !F EX!STS | domainName Drops a data type (domain). This command commits an open transaction. Example: DROP DONA!N ENA!L D#1% .DE8 DROP !NDEX [ !F EX!STS | indexName 102 of 180 Drops an index. This command commits an open transaction. Example: DROP !NDEX !F EX!STS !DXNANE D#1% #1!E DROP ROLE [ !F EX!STS | roleName Drops a role. This command commits an open transaction. Example: DROP ROLE READONLY D#1% SCHE+A DROP SCHENA [ !F EX!STS | schemaName Drops a schema. This command commits an open transaction. Example: DROP SCHENA TEST_SCHENA D#1% SEQ'E.CE DROP SEQUENCE [ !F EX!STS | sequenceName Drops a sequence. This command commits an open transaction. Example: DROP SEQUENCE SEQ_!D D#1% TA-!E DROP TABLE [ !F EX!STS | tableName [,...| [ RESTR!CT { CASCADE | Drops an existing table, or a list of tables. The command will fail if dependent views exist and the RESTR!CT clause is used (the default). All dependent views are dropped as well if the CASCADE clause is used. This command commits an open transaction. Example: DROP TABLE TEST D#1% T#//E# DROP TR!GGER [ !F EX!STS | triggerName Drops an existing trigger. This command commits an open transaction. 103 of 180 Example: DROP TR!GGER TR!G_!NS D#1% 'SE# DROP USER [ !F EX!STS | userName Drops a user. The current user cannot be dropped. For compatibility, only unquoted or uppercase user names are allowed. Admin rights are required to execute this command. This command commits an open transaction. Example: DROP USER TON D#1% 3E2 DROP v!EW [ !F EX!STS | viewName [ RESTR!CT { CASCADE | Drops an existing view. All dependent views are dropped as well if the CASCADE clause is used (the default). The command will fail if dependent views exist and the RESTR!CT clause is used. This command commits an open transaction. Example: DROP v!EW TEST_v!EW T#'.CATE TA-!E TRUNCATE TABLE tableName Removes all rows from a table. Unlike DELETE FRON without where clause, this command can not be rolled back. This command is faster than DELETE without where clause. Only regular data tables without foreign key constraints can be truncated (except if referential integrity is disabled for this database or for this table). Linked tables can't be truncated. This command commits an open transaction. Example: TRUNCATE TABLE TEST CHEC:%1.T CHECKPO!NT Flushes the data to disk. Admin rights are required to execute this command. Example: CHECKPO!NT 10+ of 180 CHEC:%1.T [email protected] CHECKPO!NT SYNC Flushes the data to disk and and forces all system buffers be written to the underlying device. Admin rights are required to execute this command. Example: CHECKPO!NT SYNC C1++T CONN!T [ WORK | Commits a transaction. Example: CONN!T C1++T T#A.SACT1. CONN!T TRANSACT!ON transactionName Sets the resolution of an in-doubt transaction to 'commit'. Admin rights are required to execute this command. This command is part of the 2-phase-commit protocol. Example: CONN!T TRANSACT!ON X!D_TEST /#A.T #/HT GRANT { SELECT { !NSERT { UPDATE { DELETE { ALL ) [,...| ON tableName [,...| TO { PUBL!C { userName { roleName ) Grants rights for a table to a user or role. Admin rights are required to execute this command. This command commits an open transaction. Example: GRANT SELECT ON TEST TO READONLY /#A.T A!TE# A.@ SCHE+A GRANT ALTER ANY SCHENA TO userName Grant schema altering rights to a user. Admin rights are required to execute this command. This command commits an open transaction. 105 of 180 Example: GRANT ALTER ANY SCHENA TO Bob /#A.T #1!E GRANT roleName TO { PUBL!C { userName { roleName ) Grants a role to a user or role. Admin rights are required to execute this command. This command commits an open transaction. Example: GRANT READONLY TO PUBL!C HE!% HELP [ anything [...| | Displays the help pages of SQL commands or keywords. Example: HELP SELECT %#E%A#E C1++T PREPARE CONN!T newTransactionName Prepares committing a transaction. This command is part of the 2-phase-commit protocol. Example: PREPARE CONN!T X!D_TEST #E31:E #/HT REvOKE { SELECT { !NSERT { UPDATE { DELETE { ALL ) [,...| ON tableName [,...| FRON { PUBL!C { userName { roleName ) Removes rights for a table from a user or role. Admin rights are required to execute this command. This command commits an open transaction. Example: REvOKE SELECT ON TEST FRON READONLY #E31:E #1!E REvOKE roleName FRON { PUBL!C { userName { roleName ) 106 of 180 Removes a role from a user or role. Admin rights are required to execute this command. This command commits an open transaction. Example: REvOKE READONLY FRON TON #1!!-AC: ROLLBACK [ TO SAvEPO!NT savepointName | Rolls back a transaction. !f a savepoint name is used, the transaction is only rolled back to the specified savepoint. Example: ROLLBACK #1!!-AC: T#A.SACT1. ROLLBACK TRANSACT!ON transactionName Sets the resolution of an in-doubt transaction to 'rollback'. Admin rights are required to execute this command. This command is part of the 2-phase-commit protocol. Example: ROLLBACK TRANSACT!ON X!D_TEST SA3E%1.T SAvEPO!NT savepointName Create a new savepoint. See also ROLLBACK. Savepoints are only valid until the transaction is committed or rolled back. Example: SAvEPO!NT HALF_DONE SET A SET @variableName [ = | expression Updates a user-defined variable. variables are not persisted and session scoped, that means only visible from within the session in which they are defined. This command does not commit a transaction, and rollback does not affect it. Example: SET @TOTAL=0 107 of 180 SET A!!12B!TE#A!S SET ALLOW_L!TERALS { NONE { ALL { NUNBERS ) This setting can help solve the SQL injection problem. By default, text and number literals are allowed in SQL statements. However, this enables SQL injection if the application dynamically builds SQL statements. SQL injection is not possible if user data is set using parameters ('?'). NONE means literals of any kind are not allowed, only parameters and constants are allowed. NUNBERS mean only numerical and boolean literals are allowed. ALL means all literals are allowed (default). See also CREATE CONSTANT. Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting is persistent. This setting can be appended to the database URL: jdbc:h2:test;ALLOW_L!TERALS=NONE Example: SET ALLOW_L!TERALS NONE SET A'T1C1++T SET AUTOCONN!T { TRUE { ON { FALSE { OFF ) Switches auto commit on or off. This setting can be appended to the database URL: jdbc:h2:test;AUTOCONN!T=OFF - however this will not work as expected when using a connection pool (the connection pool manager will re-enable autocommit when returning the connection to the pool, so autocommit will only be disabled the first time the connection is used. Example: SET AUTOCONN!T OFF SET CACHEBS=E SET CACHE_S!ZE int Sets the size of the cache in KB (each KB being 102+ bytes) for the current database. The default value is 1638+ (16 NB). The value is rounded to the next higher power of two. Depending on the virtual machine, the actual memory required may be higher. This setting is persistent and affects all connections as there is only one cache per database. Using a very small value (specially 0) will reduce performance a lot. This setting only affects the database engine (the server in a clientfserver environment). !t has no effect for in-memory databases. Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting is persistent. This setting can be appended to the database URL: jdbc:h2:test;CACHE_S!ZE=8192 Example: SET CACHE_S!ZE 8192 SET C!'STE# SET CLUSTER serverListString This command should not be used directly by an application, the statement is executed automatically by the system. The behavior may change in future releases. Sets the cluster server list. An empty string switches off the cluster mode. Switching on 108 of 180 the cluster mode requires admin rights, but any user can switch it off (this is automatically done when the client detects the other server is not responding). This command is effective immediately, but does not commit an open transaction. Example: SET CLUSTER '' SET -.A#@BC1!!AT1. SET B!NARY_COLLAT!ON { UNS!GNED { S!GNED ) | ) Sets the collation used for comparing B!NARY columns, the default is S!GNED for version 1.3 and older, and UNS!GNED for version 1.+ and newer. This command can only be executed if there are no tables defined. Admin rights are required to execute this command. This command commits an open transaction. This setting is persistent. Example: SET B!NARY_COLLAT!ON S!GNED SET C1!!AT1. SET [ DATABASE | COLLAT!ON { OFF { collationName [ STRENGTH { PR!NARY { SECONDARY { TERT!ARY { !DENT!CAL ) | ) Sets the collation used for comparing strings. This command can only be executed if there are no tables defined. See java.text.Collator for details about the supported collations and the STRENGTH (PR!NARY is usually case- and umlaut- insensitive; SECONDARY is case-insensitive but umlaut-sensitive; TERT!ARY is both case- and umlaut-sensitive; !DENT!CAL is sensitive to all differences and only affects ordering). The !CU+J collator is used if it is in the classpath. !t is also used if the collation name starts with !CU+J_ (in that case, the !CU+J must be in the classpath, otherwise an exception is thrown). The default collator is used if the collation name starts with DEFAULT_ (even if !CU+J is in the classpath). Admin rights are required to execute this command. This command commits an open transaction. This setting is persistent. Example: SET COLLAT!ON ENGL!SH SET C1+%#ESSB!1- SET CONPRESS_LOB { NO { LZF { DEFLATE ) Sets the compression algorithm for BLOB and CLOB data. Compression is usually slower, but needs less disk space. LZF is faster but uses more space. Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting is persistent. Example: SET CONPRESS_LOB LZF 109 of 180 SET DATA-ASEBE3E.TB!STE.E# SET DATABASE_EvENT_L!STENER classNameString Sets the event listener class. An empty string ('') means no listener should be used. This setting is not persistent. Admin rights are required to execute this command, except if it is set when opening the database (in this case it is reset just after opening the database). This setting can be appended to the database URL: jdbc:h2:test;DATABASE_EvENT_L!STENER='sample.NyListener' Example: SET DATABASE_EvENT_L!STENER 'sample.NyListener' SET D-BC!1SEBDE!A@ SET DB_CLOSE_DELAY int Sets the delay for closing a database if all connections are closed. The value -1 means the database is never closed until the close delay is set to some other value or SHUTDOWN is called. The value 0 means no delay (default; the database is closed if the last connection to it is closed). values 1 and larger mean the number of seconds the database is left open after closing the last connection. !f the application exits normally or System.exit is called, the database is closed immediately, even if a delay is set. Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting is persistent. This setting can be appended to the database URL: jdbc:h2:test;DB_CLOSE_DELAY=-1 Example: SET DB_CLOSE_DELAY -1 SET DE(A'!TB!1C:BT+E1'T SET DEFAULT LOCK_T!NEOUT int Sets the default lock timeout (in milliseconds) in this database that is used for the new sessions. The default value for this setting is 1000 (one second). Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting is persistent. Example: SET DEFAULT_LOCK_T!NEOUT 5000 SET DE(A'!TBTA-!EBT@%E SET DEFAULT_TABLE_TYPE { NENORY { CACHED ) Sets the default table storage type that is used when creating new tables. Nemory tables are kept fully in the main memory (including indexes), however the data is still stored in the database file. The size of memory tables is limited by the memory. The default is CACHED. Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting is persistent. !t has no effect for in-memory databases. 110 of 180 Example: SET DEFAULT_TABLE_TYPE NENORY SET E8C!'S3E SET EXCLUS!vE { 0 { 1 { 2 ) Switched the database to exclusive mode (1, 2) and back to normal mode (0). !n exclusive mode, new connections are rejected, and operations by other connections are paused until the exclusive mode is disabled. When using the value 1, existing connections stay open. When using the value 2, all existing connections are closed (and current transactions are rolled back) except the connection that executes SET EXCLUS!vE. Only the connection that set the exclusive mode can disable it. When the connection is closed, it is automatically disabled. Admin rights are required to execute this command. This command commits an open transaction. Example: SET EXCLUS!vE 1 SET /.1#ECASE SET !GNORECASE { TRUE { FALSE ) !f !GNORECASE is enabled, text columns in newly created tables will be case-insensitive. Already existing tables are not affected. The effect of case-insensitive columns is similar to using a collation with strength PR!NARY. Case-insensitive columns are compared faster than when using a collation. String literals and parameters are however still considered case sensitive even if this option is set. Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting is persistent. This setting can be appended to the database URL: jdbc:h2:test;!GNORECASE=TRUE Example: SET !GNORECASE TRUE SET )A3AB1-)ECTBSE#A!=E# SET JAvA_OBJECT_SER!AL!ZER { null { className ) Sets the object used to serialize and deserialize java objects being stored in column of type OTHER. The serializer class must be public and implement org.h2.api.JavaObjectSerializer. !nner classes are not supported. The class must be available in the classpath of the database engine (when using the server mode, it must be both in the classpath of the server and the client). This command can only be executed if there are no tables defined. Admin rights are required to execute this command. This command commits an open transaction. This setting is persistent. This setting can be appended to the database URL: jdbc:h2:test;JAvA_OBJECT_SER!AL!ZER='com.acme.SerializerClassName' Example: SET JAvA_OBJECT_SER!AL!ZER 'com.acme.SerializerClassName' SET !1/ SET LOG int 111 of 180 Sets the transaction log mode. The values 0, 1, and 2 are supported, the default is 2. This setting affects all connections. LOG 0 means the transaction log is disabled completely. !t is the fastest mode, but also the most dangerous: if the process is killed while the database is open in this mode, the data might be lost. !t must only be used if this is not a problem, for example when initially loading a database, or when running tests. LOG 1 means the transaction log is enabled, but FileDescriptor.sync is disabled. This setting is about half as fast as with LOG 0. This setting is useful if no protection against power failure is required, but the data must be protected against killing the process. LOG 2 (the default) means the transaction log is enabled, and FileDescriptor.sync is called for each checkpoint. This setting is about half as fast as LOG 1. Depending on the file system, this will also protect against power failure in the majority if cases. Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting is not persistent. This setting can be appended to the database URL: jdbc:h2:test;LOG=0 Example: SET LOG 1 SET !1C:B+1DE SET LOCK_NODE int Sets the lock mode. The values 0, 1, 2, and 3 are supported. The default is 3 (READ_CONN!TTED). This setting affects all connections. The value 0 means no locking (should only be used for testing; also known as READ_UNCONN!TTED). Please note that using SET LOCK_NODE 0 while at the same time using multiple connections may result in inconsistent transactions. The value 1 means table level locking (also known as SER!AL!ZABLE). The value 2 means table level locking with garbage collection (if the application does not close all connections). The value 3 means table level locking, but read locks are released immediately (default; also known as READ_CONN!TTED). Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting is persistent. This setting can be appended to the database URL: jdbc:h2:test;LOCK_NODE=3 Example: SET LOCK_NODE 1 SET !1C:BT+E1'T SET LOCK_T!NEOUT int Sets the lock timeout (in milliseconds) for the current session. The default value for this setting is 1000 (one second). This command does not commit a transaction, and rollback does not affect it. This setting can be appended to the database URL: jdbc:h2:test;LOCK_T!NEOUT=10000 Example: SET LOCK_T!NEOUT 1000 112 of 180 SET +A8B!E./THB.%!ACEB!1- SET NAX_LENGTH_!NPLACE_LOB int Sets the maximum size of an in-place LOB object. This is the maximum length of an LOB that is stored with the record itself, and the default value is 128. This setting has no effect for in-memory databases. Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting is persistent. Example: SET NAX_LENGTH_!NPLACE_LOB 128 SET +A8B!1/BS=E SET NAX_LOG_S!ZE int Sets the maximum size of the transaction log, in megabytes. !f the log is larger, and if there is no open transaction, the transaction log is truncated. !f there is an open transaction, the transaction log will continue to grow however. The default max size is 16 NB. This setting has no effect for in-memory databases. Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting is persistent. Example: SET NAX_LOG_S!ZE 2 SET +A8B+E+1#@B#12S SET NAX_NENORY_ROWS int The maximum number of rows in a result set that are kept in-memory. !f more rows are read, then the rows are buffered to disk. The default value is 10000. Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting is persistent. !t has no effect for in-memory databases. Example: SET NAX_NENORY_ROWS 1000 SET +A8B+E+1#@B'.D1 SET NAX_NENORY_UNDO int The maximum number of undo records per a session that are kept in-memory. !f a transaction is larger, the records are buffered to disk. The default value is 50000. Changes to tables without a primary key can not be buffered to disk. This setting is not supported when using multi-version concurrency. Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting is persistent. !t has no effect for in-memory databases. 113 of 180 Example: SET NAX_NENORY_UNDO 1000 SET +A8B1%E#AT1.B+E+1#@ SET NAX_OPERAT!ON_NENORY int Sets the maximum memory used for large operations (delete and insert), in bytes. Operations that use more memory are buffered to disk, slowing down the operation. The default max size is 100000. 0 means no limit. This setting is not persistent. Admin rights are required to execute this command, as it affects all connections. !t has no effect for in-memory databases. This setting can be appended to the database URL: jdbc:h2:test;NAX_OPERAT!ON_NENORY=10000 Example: SET NAX_OPERAT!ON_NENORY 0 SET +1DE SET NODE { REGULAR { DB2 { DERBY { HSQLDB { NSSQLSERvER { NYSQL { ORACLE { POSTGRESQL ) Changes to another database compatibility mode. For details, see Compatibility Nodes in the feature section. This setting is not persistent. Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting can be appended to the database URL: jdbc:h2:test;NODE=NYSQL Example: SET NODE HSQLDB SET +'!TBTH#EADED SET NULT!_THREADED { 0 { 1 ) Enabled (1) or disabled (0) multi-threading inside the database engine. By default, this setting is disabled. Currently, enabling this is experimental only. This is a global setting, which means it is not possible to open multiple databases with different modes at the same time in the same virtual machine. This setting is not persistent, however the value is kept until the virtual machine exits or it is changed. Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting can be appended to the database URL: jdbc:h2:test;NULT!_THREADED=1 Example: SET NULT!_THREADED 1 SET 1%T+=EB#E'SEB#ES'!TS SET OPT!N!ZE_REUSE_RESULTS { 0 { 1 ) Enabled (1) or disabled (0) the result reuse optimization. !f enabled, subqueries and views used as subqueries are only re-run if the data in one of the tables was changed. This option is enabled by default. 11+ of 180 Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting can be appended to the database URL: jdbc:h2:test;OPT!N!ZE_REUSE_RESULTS=0 Example: SET OPT!N!ZE_REUSE_RESULTS 0 SET %ASS21#D SET PASSWORD string Changes the password of the current user. The password must be in single quotes. !t is case sensitive and can contain spaces. This command commits an open transaction. Example: SET PASSWORD 'abcstzri!.5' SET Q'E#@BSTATSTCS SET QUERY_STAT!ST!CS { TRUE { FALSE ) Disabled or enables query statistics gathering for the whole database. The statistics are reflected in the !NFORNAT!ON_SCHENA.QUERY_STAT!ST!CS meta-table. This setting is not persistent. This command commits an open transaction. Admin rights are required to execute this command, as it affects all connections. Example: SET QUERY_STAT!ST!CS FALSE SET Q'E#@BT+E1'T SET QUERY_T!NEOUT int Set the query timeout of the current session to the given value. The timeout is in milliseconds. All kinds of statements will throw an exception if they take longer than the given value. The default timeout is 0, meaning no timeout. This command does not commit a transaction, and rollback does not affect it. Example: SET QUERY_T!NEOUT 10000 SET #E(E#E.TA!B.TE/#T@ SET REFERENT!AL_!NTEGR!TY { TRUE { FALSE ) Disabled or enables referential integrity checking for the whole database. Enabling it does not check existing data. Use ALTER TABLE SET to disable it only for one table. This setting is not persistent. This command commits an open transaction. Admin rights are required to execute this command, as it affects all connections. 115 of 180 Example: SET REFERENT!AL_!NTEGR!TY FALSE SET #ETE.T1.BT+E SET RETENT!ON_T!NE int This property is only used when using the NvStore storage engine. How long to retain old, persisted data, in milliseconds. The default is +5000 (+5 seconds), 0 means overwrite data as early as possible. !t is assumed that a file system and hard disk will flush all write buffers within this time. Using a lower value might be dangerous, unless the file system and hard disk flush the buffers earlier. To manually flush the buffers, use CHECKPO!NT SYNC, however please note that according to various tests this does not always work as expected depending on the operating system and hardware. Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting is persistent. This setting can be appended to the database URL: jdbc:h2:test;RETENT!ON_T!NE=0 Example: SET RETENT!ON_T!NE 0 SET SA!T HASH SET SALT bytes HASH bytes Sets the password salt and hash for the current user. The password must be in single quotes. !t is case sensitive and can contain spaces. This command commits an open transaction. Example: SET SALT '00' HASH '1122' SET SCHE+A SET SCHENA schemaName Changes the default schema of the current connection. The default schema is used in statements where no schema is set explicitly. The default schema for new connections is PUBL!C. This command does not commit a transaction, and rollback does not affect it. This setting can be appended to the database URL: jdbc:h2:test;SCHENA=ABC Example: SET SCHENA !NFORNAT!ON_SCHENA SET SCHE+ABSEA#CHB%ATH SET SCHENA_SEARCH_PATH schemaName [,...| Changes the schema search path of the current connection. The default schema is used in statements where no schema is set explicitly. The default schema for new connections is PUBL!C. 116 of 180 This command does not commit a transaction, and rollback does not affect it. This setting can be appended to the database URL: jdbc:h2:test;SCHENA_SEARCH_PATH=ABC,DEF Example: SET SCHENA_SEARCH_PATH !NFORNAT!ON_SCHENA, PUBL!C SET TH#1TT!E SET THROTTLE int Sets the throttle for the current connection. The value is the number of milliseconds delay after each 50 ms. The default value is 0 (throttling disabled). This command does not commit a transaction, and rollback does not affect it. This setting can be appended to the database URL: jdbc:h2:test;THROTTLE=50 Example: SET THROTTLE 200 SET T#ACEB!E3E! SET { TRACE_LEvEL_F!LE { TRACE_LEvEL_SYSTEN_OUT ) int Sets the trace level for file the file or system out stream. Levels are: 0=off, 1=error, 2=info, 3=debug. The default level is 1 for file and 0 for system out. To use SLF+J, append ;TRACE_LEvEL_F!LE=+ to the database URL when opening the database. This setting is not persistent. Admin rights are required to execute this command, as it affects all connections. This command does not commit a transaction, and rollback does not affect it. This setting can be appended to the database URL: jdbc:h2:test;TRACE_LEvEL_SYSTEN_OUT=3 Example: SET TRACE_LEvEL_SYSTEN_OUT 3 SET T#ACEB+A8B(!EBS=E SET TRACE_NAX_F!LE_S!ZE int Sets the maximum trace file size. !f the file exceeds the limit, the file is renamed to .old and a new file is created. !f another .old file exists, it is deleted. The default max size is 16 NB. This setting is persistent. Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting can be appended to the database URL: jdbc:h2:test;TRACE_NAX_F!LE_S!ZE=3 Example: SET TRACE_NAX_F!LE_S!ZE 10 SET '.D1B!1/ SET UNDO_LOG int Enables (1) or disables (0) the per session undo log. The undo log is enabled by default. When disabled, transactions can not be rolled back. This setting should only be used for bulk operations that don't need to be atomic. 117 of 180 This command commits an open transaction. Example: SET UNDO_LOG 0 SET 2#TEBDE!A@ SET WR!TE_DELAY int Set the maximum delay between a commit and flushing the log, in milliseconds. This setting is persistent. The default is 500 ms. Admin rights are required to execute this command, as it affects all connections. This command commits an open transaction. This setting can be appended to the database URL: jdbc:h2:test;WR!TE_DELAY=0 Example: SET WR!TE_DELAY 2000 SH'TD12. SHUTDOWN [ !NNED!ATELY { CONPACT { DEFRAG | This statement closes all open connections to the database and closes the database. This command is usually not required, as the database is closed automatically when the last connection to it is closed. !f no option is used, then the database is closed normally. All connections are closed, open transactions are rolled back. SHUTDOWN CONPACT fully compacts the database (re-creating the database may further reduce the database size). !f the database is closed normally (using SHUTDOWN or by closing all connections), then the database is also compacted, but only for at most the time defined by the database setting h2.maxCompactTime in milliseconds (see there). SHUTDOWN !NNED!ATELY closes the database files without any cleanup and without compacting. SHUTDOWN DEFRAG re-orders the pages when closing the database so that table scans are faster. Admin rights are required to execute this command. Example: SHUTDOWN CONPACT Alias name An alias is a name that is only valid in the context of the statement. Example: A And Condition condition [ { AND condition ) [...| | 118 of 180 value or condition. Example: !D=1 AND NANE='Hi' Array ( [ expression, [ expression [,...| | | ) An array of values. An empty array is '()'. Trailing commas are ignored. An array with one element must contain a comma to be parsed as an array. Example: (1, 2) (1, ) () -oolean TRUE { FALSE A boolean value. Example: TRUE -ytes X8apos;hex8apos; A binary value. The hex value is not case sensitive. Example: X'01FF' Case CASE expression { WHEN expression THEN expression ) [...| [ ELSE expression | END Returns the first expression where the value is equal to the test expression. !f no else part is specified, return NULL. Example: CASE CNT WHEN 0 THEN 'No' WHEN 1 THEN 'One' ELSE 'Some' END Case 2hen CASE { WHEN expression THEN expression) [...| [ ELSE expression | END 119 of 180 Returns the first expression where the condition is true. !f no else part is specified, return NULL. Example: CASE WHEN CNT<10 THEN 'Low' ELSE 'High' END Cipher AES Only the algorithm AES (AES-128) is supported currently. Example: AES Column Definition columnName dataType [ { DEFAULT expression { AS computedColumnExpression ) | [ [ NOT | NULL | [ { AUTO_!NCRENENT { !DENT!TY ) [ ( start!nt [, increment!nt | ) | | [ SELECT!v!TY selectivity | [ CONNENT expression | [ PR!NARY KEY [ HASH | { UN!QUE | [ CHECK condition | Default expressions are used if no explicit value was used when adding a row. The computed column expression is evaluated and assigned whenever the row changes. !dentity and auto-increment columns are columns with a sequence as the default. The column declared as the identity columns is implicitly the primary key column of this table (unlike auto-increment columns). The options PR!NARY KEY, UN!QUE, and CHECK are not supported for ALTER statements. Check constraints can reference columns of the table, and they can reference objects that exist while the statement is executed. Conditions are only checked when a row is added or modified in the table where the constraint exists. Example: CREATE TABLE TEST(!D !NT PR!NARY KEY, NANE vARCHAR(255) DEFAULT ''); CREATE TABLE TEST(!D B!G!NT !DENT!TY); CREATE TABLE TEST(QUANT!TY !NT, PR!CE DEC!NAL, ANOUNT DEC!NAL AS QUANT!TY*PR!CE); Comments -- anything { ff anything { f* anything *f Comments can be used anywhere in a command and are ignored by the database. Line comments end with a newline. Block comments cannot be nested, but can be multiple lines long. Example: ff This is a comment Compare <> { <= { >= { = { < { > { != { 88 120 of 180 Comparison operator. The operator != is the same as <>. The operator 88 means overlapping; it can only be used with geometry types. Example: <> Condition operand [ conditionRightHandSide | { NOT condition { EX!STS ( select ) Boolean value or condition. Example: !D<>2 Condition #ight Hand Side compare { { { ALL { ANY { SONE ) ( select ) ) { operand ) { !S [ NOT | NULL { !S [ NOT | [ D!ST!NCT FRON | operand { BETWEEN operand AND operand { !N ( { select { expression [,...| ) ) { [ NOT | L!KE operand [ ESCAPE string | { [ NOT | REGEXP operand The right hand side of a condition. The conditions !S [ NOT | and !S [ NOT | D!ST!NCT FRON are null-safe, meaning NULL is considered the same as NULL, and the condition never evaluates to NULL. When comparing with L!KE, the wildcards characters are _ (any one character) and (any characters). The database uses an index when comparing with L!KE except if the operand starts with a wildcard. To search for the characters and _, the characters need to be escaped. The default escape character is (backslash). To select no escape character, use ESCAPE '' (empty string). At most one escape character is allowed. Each character that follows the escape character in the pattern needs to match exactly. Patterns that end with an escape character are invalid and the expression returns NULL. When comparing with REGEXP, regular expression matching is used. See Java Natcher.find for details. Example: L!KE 'Jo' Constraint [ constraintNameDefinition | { CHECK expression { UN!QUE ( columnName [,...| ) { referentialConstraint { PR!NARY KEY [ HASH | ( columnName [,...| ) ) Defines a constraint. The check condition must evaluate to TRUE, FALSE or NULL. TRUE and NULL mean the operation is to be permitted, and FALSE means the operation is to be rejected. To prevent NULL in a column, use NOT NULL instead of a check constraint. Example: PR!NARY KEY(!D, NANE) 121 of 180 Constraint .ame Definition CONSTRA!NT [ !F NOT EX!STS | newConstraintName Defines a constraint name. Example: CONSTRA!NT CONST_!D Cs* 1ptions charsetString [, fieldSepString [, fieldDelimString [, escString [, nullString||||| { optionString Optional parameters for CSvREAD and CSvWR!TE. !nstead of setting the options one by one, all options can be combined into a space separated key-value pairs, as follows: STR!NGDECODE('charset=UTF-8 escape=" fieldDelimiter=" fieldSeparator=, ' {{ 'lineComment=# lineSeparator=n null= rowSeparator='). The following options are supported: caseSensitiveColumnNames (true or false; disabled by default), charset, escape, fieldDelimiter, fieldSeparator, lineComment (disabled by default), lineSeparator, null, Note that an empty value is always treated as null. This feature for compatibility, it is only here to support reading existing CSv files that contain explicit null delimiters. rowSeparator (not set by default), preserveWhitespace (true or false; disabled by default), writeColumnHeader (true or false; enabled by default). For a newline or other special character, use STR!NGDECODE as in the example above. A space needs to be escaped with a backslash (' '), and a backslash needs to be escaped with another backslash (''). All other characters are not to be escaped, that means newline and tab characters are written as such. Example: CALL CSvWR!TE('test2.csv', 'SELECT * FRON TEST', 'charset=UTF-8 fieldSeparator={'); Data Type intType { booleanType { tinyintType { smallintType { bigintType { identityType { decimalType { doubleType { realType { dateType { timeType { timestampType { binaryType { otherType { varcharType { varchar!gnorecaseType { charType { blobType { clobType { uuidType { arrayType A data type definition. 122 of 180 Example: !NT Date DATE 8apos;yyyy-NN-dd8apos; A date literal. The limitations are the same as for the Java data type java.sql.Date, but for compatibility with other databases the suggested minimum and maximum years are 0001 and 9999. Example: DATE '200+-12-31' Decimal [ + { - | { { number [ . number | ) { { . number ) ) [ E [ + { - | expNumber [...| | | A decimal number with fixed precision and scale. !nternally, java.lang.BigDecimal is used. To ensure the floating point representation is used, use CAST(X AS DOUBLE). There are some special decimal values: to represent positive infinity, use POWER(0, -1); for negative infinity, use (-POWER(0, -1)); for -0.0, use (-CAST(0 AS DOUBLE)); for NaN (not a number), use SQRT(-1). Example: SELECT -1600.05 SELECT CAST(0 AS DOUBLE) SELECT -1.+e-10 Digit 0-9 A digit. Example: 0 Dollar Quoted String $$anything$$ A string starts and ends with two dollar signs. Two dollar signs are not allowed within the text. A whitespace is required before the first set of dollar signs. No escaping is required within the text. Example: $$John's car$$ E"pression andCondition [ { OR andCondition ) [...| | 123 of 180 value or condition. Example: !D=1 OR NANE='Hi' (actor term [ { { * { f { ) term ) [...| | A value or a numeric factor. Example: !D * 10 He" { { digit { a-f { A-F ) { digit { a-f { A-F ) ) [...| The hexadecimal representation of a number or of bytes. Two characters are one byte. Example: cafe He" .umber [ + { - | 0x hex A number written in hexadecimal notation. Example: 0xff nde" Column columnName [ ASC { DESC | [ NULLS { F!RST { LAST ) | !ndexes this column in ascending or descending order. Usually it is not required to specify the order; however doing so will speed up large queries that order the column in the same way. Example: NANE nt [ + { - | number The maximum integer number is 21+7+836+7, the minimum is -21+7+836+8. 12+ of 180 Example: 10 !ong [ + { - | number Long numbers are between -922337203685+775808 and 922337203685+775807. Example: 100000 .ame { { A-Z{_ ) [ { A-Z{_{0-9 ) [...| | ) { quotedName Names are not case sensitive. There is no maximum name length. Example: TEST .ull NULL NULL is a value without data type and means 'unknown value'. Example: NULL .umber digit [...| The maximum length of the number depends on the data type used. Example: 100 .umeric decimal { int { long { hexNumber The data type of a numeric value is always the lowest possible for the given value. !f the number contains a dot this is decimal; otherwise it is int, long, or decimal (depending on the value). Example: 125 of 180 SELECT -1600.05 SELECT CAST(0 AS DOUBLE) SELECT -1.+e-10 1perand summand [ { {{ summand ) [...| | A value or a concatenation of values. !n the default mode, the result is NULL if either parameter is NULL. Example: 'Hi' {{ ' Eva' 1rder { int { expression ) [ ASC { DESC | [ NULLS { F!RST { LAST ) | Sorts the result by the given column number, or by an expression. !f the expression is a single parameter, then the value is interpreted as a column number. Negative column numbers reverse the sort order. Example: NANE DESC NULLS LAST Quoted .ame "anything" Quoted names are case sensitive, and can contain spaces. There is no maximum name length. Two double quotes can be used to create a single double quote inside an identifier. Example: "FirstName" #eferential Constraint FORE!GN KEY ( columnName [,...| ) REFERENCES [ refTableName | [ ( refColumnName [,...| ) | [ ON DELETE referentialAction | [ ON UPDATE referentialAction | Defines a referential constraint. !f the table name is not specified, then the same table is referenced. RESTR!CT is the default action. !f the referenced columns are not specified, then the primary key columns are used. The required indexes are automatically created if required. Some tables may not be referenced, such as metadata tables. Example: FORE!GN KEY(!D) REFERENCES TEST(!D) #eferential Action CASCADE { RESTR!CT { NO ACT!ON { SET { DEFAULT { NULL ) 126 of 180 The action CASCADE will cause conflicting rows in the referencing (child) table to be deleted or updated. RESTR!CT is the default action. As this database does not support deferred checking, RESTR!CT and NO ACT!ON will both throw an exception if the constraint is violated. The action SET DEFAULT will set the column in the referencing (child) table to the default value, while SET NULL will set it to NULL. Example: FORE!GN KEY(!D) REFERENCES TEST(!D) ON UPDATE CASCADE Script Compression Encryption [ CONPRESS!ON { DEFLATE { LZF { Z!P { GZ!P ) | [ C!PHER cipher PASSWORD string | The compression and encryption algorithm to use for script files. When using encryption, only DEFLATE and LZF are supported. LZF is faster but uses more space. Example: CONPRESS!ON LZF Select E"pression * { expression [ [ AS | columnAlias | { tableAlias.* An expression in a SELECT statement. Example: !D AS vALUE String 8apos;anything8apos; A string starts and ends with a single quote. Two single quotes can be used to create a single quote inside a string. Example: 'John''s car' Summand factor [ { { + { - ) factor ) [...| | A value or a numeric sum. Please note the text concatenation operator is {{. Example: !D + 20 127 of 180 Table E"pression { [ schemaName. | tableName { ( select ) { valuesExpression ) [ [ AS | newTableAlias | [ { { LEFT { R!GHT ) [ OUTER | { [ !NNER | { CROSS { NATURAL ) JO!N tableExpression [ ON expression | | Joins a table. The join expression is not supported for cross and natural joins. A natural join is an inner join, where the condition is automatically on the columns with the same name. Example: TEST AS T LEFT JO!N TEST AS T1 ON T.!D = T1.!D 3alues E"pression vALUES { ( expression [,...| ) ) [,...| A list of rows that can be used like a table. The column list of the resulting table is C1, C2, and so on. Example: SELECT * FRON (vALUES(1, 'Hello'), (2, 'World')) AS v; Term value { columnName { ?[ int | { NEXT vALUE FOR sequenceName { function { { - { + ) term { ( expression ) { select { case { caseWhen { tableAlias.columnName A value. Parameters can be indexed, for example ?1 meaning the first parameter. Each table has a pseudo-column named _ROW!D_ that contains the unique row identifier. Example: 'Hello' Time T!NE 8apos;hh:mm:ss8apos; A time literal. A value is between plus and minus 2 million hours and has nanosecond resolution. Example: T!NE '23:59:59' 128 of 180 Timestamp T!NESTANP 8apos;yyyy-NN-dd hh:mm:ss[.nnnnnnnnn|8apos; A timestamp literal. The limitations are the same as for the Java data type java.sql.Timestamp, but for compatibility with other databases the suggested minimum and maximum years are 0001 and 9999. Example: T!NESTANP '2005-12-31 23:59:59' 3alue string { dollarQuotedString { numeric { date { time { timestamp { boolean { bytes { array { null A literal value of any data type, or null. Example: 10 nformation Schema The system tables in the schema !NFORNAT!ON_SCHENA contain the meta data of all tables in the database as well as the current settings. Table Columns CATALOGS CATALOG_NANE COLLAT!ONS NANE, KEY COLUNNS TABLE_CATALOG, TABLE_SCHENA, TABLE_NANE, COLUNN_NANE, ORD!NAL_POS!T!ON, COLUNN_DEFAULT, !S_NULLABLE, DATA_TYPE, CHARACTER_NAX!NUN_LENGTH, CHARACTER_OCTET_LENGTH, NUNER!C_PREC!S!ON, NUNER!C_PREC!S!ON_RAD!X, NUNER!C_SCALE, CHARACTER_SET_NANE, COLLAT!ON_NANE, TYPE_NANE, NULLABLE, !S_CONPUTED, SELECT!v!TY, CHECK_CONSTRA!NT, SEQUENCE_NANE, RENARKS, SOURCE_DATA_TYPE COLUNN_PR!v!L EGES GRANTOR, GRANTEE, TABLE_CATALOG, TABLE_SCHENA, TABLE_NANE, COLUNN_NANE, PR!v!LEGE_TYPE, !S_GRANTABLE CONSTANTS CONSTANT_CATALOG, CONSTANT_SCHENA, CONSTANT_NANE, DATA_TYPE, RENARKS, SQL, !D CONSTRA!NTS CONSTRA!NT_CATALOG, CONSTRA!NT_SCHENA, CONSTRA!NT_NANE, CONSTRA!NT_TYPE, TABLE_CATALOG, TABLE_SCHENA, TABLE_NANE, UN!QUE_!NDEX_NANE, CHECK_EXPRESS!ON, COLUNN_L!ST, RENARKS, SQL, !D CROSS_REFEREN CES PKTABLE_CATALOG, PKTABLE_SCHENA, PKTABLE_NANE, PKCOLUNN_NANE, FKTABLE_CATALOG, FKTABLE_SCHENA, FKTABLE_NANE, FKCOLUNN_NANE, ORD!NAL_POS!T!ON, UPDATE_RULE, DELETE_RULE, FK_NANE, PK_NANE, DEFERRAB!L!TY DONA!NS DONA!N_CATALOG, DONA!N_SCHENA, DONA!N_NANE, COLUNN_DEFAULT, !S_NULLABLE, DATA_TYPE, PREC!S!ON, SCALE, TYPE_NANE, SELECT!v!TY, CHECK_CONSTRA!NT, RENARKS, SQL, !D FUNCT!ON_AL!A SES AL!AS_CATALOG, AL!AS_SCHENA, AL!AS_NANE, JAvA_CLASS, JAvA_NETHOD, DATA_TYPE, TYPE_NANE, COLUNN_COUNT, RETURNS_RESULT, RENARKS, !D, SOURCE FUNCT!ON_COL UNNS AL!AS_CATALOG, AL!AS_SCHENA, AL!AS_NANE, JAvA_CLASS, JAvA_NETHOD, COLUNN_COUNT, POS, COLUNN_NANE, DATA_TYPE, TYPE_NANE, PREC!S!ON, SCALE, RAD!X, NULLABLE, COLUNN_TYPE, RENARKS, COLUNN_DEFAULT HELP !D, SECT!ON, TOP!C, SYNTAX, TEXT !NDEXES TABLE_CATALOG, TABLE_SCHENA, TABLE_NANE, NON_UN!QUE, !NDEX_NANE, ORD!NAL_POS!T!ON, COLUNN_NANE, CARD!NAL!TY, PR!NARY_KEY, !NDEX_TYPE_NANE, !S_GENERATED, !NDEX_TYPE, ASC_OR_DESC, PAGES, F!LTER_COND!T!ON, RENARKS, SQL, !D, SORT_TYPE, CONSTRA!NT_NANE, !NDEX_CLASS !N_DOUBT TRANSACT!ON, STATE LOCKS TABLE_SCHENA, TABLE_NANE, SESS!ON_!D, LOCK_TYPE QUERY_STAT!ST !CS SQL_STATENENT, EXECUT!ON_COUNT, N!N_EXECUT!ON_T!NE, NAX_EXECUT!ON_T!NE, CUNULAT!vE_EXECUT!ON_T!NE, AvERAGE_EXECUT!ON_T!NE, STD_DEv_EXECUT!ON_T!NE, 129 of 180 N!N_ROW_COUNT, NAX_ROW_COUNT, CUNULAT!vE_ROW_COUNT, AvERAGE_ROW_COUNT, STD_DEv_ROW_COUNT R!GHTS GRANTEE, GRANTEETYPE, GRANTEDROLE, R!GHTS, TABLE_SCHENA, TABLE_NANE, !D ROLES NANE, RENARKS, !D SCHENATA CATALOG_NANE, SCHENA_NANE, SCHENA_OWNER, DEFAULT_CHARACTER_SET_NANE, DEFAULT_COLLAT!ON_NANE, !S_DEFAULT, RENARKS, !D SEQUENCES SEQUENCE_CATALOG, SEQUENCE_SCHENA, SEQUENCE_NANE, CURRENT_vALUE, !NCRENENT, !S_GENERATED, RENARKS, CACHE, N!N_vALUE, NAX_vALUE, !S_CYCLE, !D SESS!ONS !D, USER_NANE, SESS!ON_START, STATENENT, STATENENT_START, CONTA!NS_UNCONN!TTED SESS!ON_STATE KEY, SQL SETT!NGS NANE, vALUE TABLES TABLE_CATALOG, TABLE_SCHENA, TABLE_NANE, TABLE_TYPE, STORAGE_TYPE, SQL, RENARKS, LAST_NOD!F!CAT!ON, !D, TYPE_NANE, TABLE_CLASS, ROW_COUNT_EST!NATE TABLE_PR!v!LEG ES GRANTOR, GRANTEE, TABLE_CATALOG, TABLE_SCHENA, TABLE_NANE, PR!v!LEGE_TYPE, !S_GRANTABLE TABLE_TYPES TYPE TR!GGERS TR!GGER_CATALOG, TR!GGER_SCHENA, TR!GGER_NANE, TR!GGER_TYPE, TABLE_CATALOG, TABLE_SCHENA, TABLE_NANE, BEFORE, JAvA_CLASS, QUEUE_S!ZE, NO_WA!T, RENARKS, SQL, !D TYPE_!NFO TYPE_NANE, DATA_TYPE, PREC!S!ON, PREF!X, SUFF!X, PARANS, AUTO_!NCRENENT, N!N!NUN_SCALE, NAX!NUN_SCALE, RAD!X, POS, CASE_SENS!T!vE, NULLABLE, SEARCHABLE USERS NANE, ADN!N, RENARKS, !D v!EWS TABLE_CATALOG, TABLE_SCHENA, TABLE_NANE, v!EW_DEF!N!T!ON, CHECK_OPT!ON, !S_UPDATABLE, STATUS, RENARKS, !D #ange Table The range table is a dynamic system table that contains all values from a start to an end value. The table contains one column called X. Both the start and end values are included in the result. The table is used as follows: Example: SELECT X FRON SYSTEN_RANGE(1, 10); 130 of 180 (unctions nde" Aggregate (unctions AvG BOOL_AND BOOL_OR COUNT GROUP_CONCAT NAX N!N SUN SELECT!v!TY STDDEv_POP STDDEv_SANP vAR_POP vAR_SANP .umeric (unctions ABS ACOS AS!N ATAN COS COSH COT S!N S!NH TAN TANH ATAN2 B!TAND B!TOR B!TXOR NOD CE!L!NG DEGREES EXP FLOOR LOG LOG10 RAD!ANS SQRT P! POWER RAND RANDON_UU!D ROUND ROUNDNAG!C SECURE_RAND S!GN ENCRYPT DECRYPT HASH TRUNCATE CONPRESS EXPAND ZERO 131 of 180 String (unctions ASC!! B!T_LENGTH LENGTH OCTET_LENGTH CHAR CONCAT CONCAT_WS D!FFERENCE HEXTORAW RAWTOHEX !NSTR !NSERT Function LOWER UPPER LEFT R!GHT LOCATE POS!T!ON LPAD RPAD LTR!N RTR!N TR!N REGEXP_REPLACE REPEAT REPLACE SOUNDEX SPACE STR!NGDECODE STR!NGENCODE STR!NGTOUTF8 SUBSTR!NG UTF8TOSTR!NG XNLATTR XNLNODE XNLCONNENT XNLCDATA XNLSTARTDOC XNLTEXT TO_CHAR Time and Date (unctions CURRENT_DATE CURRENT_T!NE CURRENT_T!NESTANP DATEADD DATED!FF DAYNANE DAY_OF_NONTH DAY_OF_WEEK DAY_OF_YEAR EXTRACT FORNATDATET!NE HOUR N!NUTE NONTH NONTHNANE PARSEDATET!NE QUARTER SECOND WEEK YEAR 132 of 180 System (unctions ARRAY_GET ARRAY_LENGTH ARRAY_CONTA!NS AUTOCONN!T CANCEL_SESS!ON CASEWHEN Function CAST COALESCE CONvERT CURRvAL CSvREAD CSvWR!TE DATABASE DATABASE_PATH DECODE D!SK_SPACE_USED F!LE_READ GREATEST !DENT!TY !FNULL LEAST LOCK_NODE LOCK_T!NEOUT L!NK_SCHENA NENORY_FREE NENORY_USED NEXTvAL NULL!F NvL2 READONLY ROWNUN SCHENA SCOPE_!DENT!TY SESS!ON_!D SET TABLE TRANSACT!ON_!D TRUNCATE_vALUE USER H2vERS!ON A3/ AvG ( [ D!ST!NCT | { numeric ) ) The average (mean) value. !f no rows are selected, the result is NULL. Aggregates are only allowed in select statements. The returned value is of the same data type as the parameter. Example: AvG(X) -11!BA.D BOOL_AND(boolean) Returns true if all expressions are true. !f no rows are selected, the result is NULL. Aggregates are only allowed in select statements. Example: 133 of 180 BOOL_AND(!D>10) -11!B1# BOOL_OR(boolean) Returns true if any expression is true. !f no rows are selected, the result is NULL. Aggregates are only allowed in select statements. Example: BOOL_OR(NANE L!KE 'W') C1'.T COUNT( { * { { [ D!ST!NCT | expression ) ) ) The count of all row, or of the non-null values. This method returns a long. !f no rows are selected, the result is 0. Aggregates are only allowed in select statements. Example: COUNT(*) /#1'%BC1.CAT GROUP_CONCAT ( [ D!ST!NCT | string [ ORDER BY { expression [ ASC { DESC | ) [,...| | [ SEPARATOR expression | ) Concatenates strings with a separator. The default separator is a ',' (without space). This method returns a string. !f no rows are selected, the result is NULL. Aggregates are only allowed in select statements. Example: GROUP_CONCAT(NANE ORDER BY !D SEPARATOR ', ') +A8 NAX(value) The highest value. !f no rows are selected, the result is NULL. Aggregates are only allowed in select statements. The returned value is of the same data type as the parameter. Example: NAX(NANE) +. N!N(value) The lowest value. !f no rows are selected, the result is NULL. Aggregates are only allowed in select statements. The returned value is of the same data type as the parameter. 13+ of 180 Example: N!N(NANE) S'+ SUN( [ D!ST!NCT | { numeric ) ) The sum of all values. !f no rows are selected, the result is NULL. Aggregates are only allowed in select statements. The data type of the returned value depends on the parameter data type like this: BOOLEAN, T!NY!NT, SNALL!NT, !NT -> B!G!NT, B!G!NT -> DEC!NAL, REAL -> DOUBLE Example: SUN(X) SE!ECT3T@ SELECT!v!TY(value) Estimates the selectivity (0-100) of a value. The value is defined as (100 * distinctCount f rowCount). The selectivity of 0 rows is 0 (unknown). Up to 10000 values are kept in memory. Aggregates are only allowed in select statements. Example: SELECT SELECT!v!TY(F!RSTNANE), SELECT!v!TY(NANE) FRON TEST WHERE ROWNUN()<20000 STDDE3B%1% STDDEv_POP( [ D!ST!NCT | numeric ) The population standard deviation. This method returns a double. !f no rows are selected, the result is NULL. Aggregates are only allowed in select statements. Example: STDDEv_POP(X) STDDE3BSA+% STDDEv_SANP( [ D!ST!NCT | numeric ) The sample standard deviation. This method returns a double. !f no rows are selected, the result is NULL. Aggregates are only allowed in select statements. Example: STDDEv(X) 3A#B%1% vAR_POP( [ D!ST!NCT | numeric ) 135 of 180 The population variance (square of the population standard deviation). This method returns a double. !f no rows are selected, the result is NULL. Aggregates are only allowed in select statements. Example: vAR_POP(X) 3A#BSA+% vAR_SANP( [ D!ST!NCT | numeric ) The sample variance (square of the sample standard deviation). This method returns a double. !f no rows are selected, the result is NULL. Aggregates are only allowed in select statements. Example: vAR_SANP(X) A-S ABS ( { numeric ) ) See also Java Nath.abs. Please note that Nath.abs(!nteger.N!N_vALUE) == !nteger.N!N_vALUE and Nath.abs(Long.N!N_vALUE) == Long.N!N_vALUE. The returned value is of the same data type as the parameter. Example: ABS(!D) AC1S ACOS(numeric) Calculate the arc cosine. See also Java Nath.acos. This method returns a double. Example: ACOS(D) AS. AS!N(numeric) Calculate the arc sine. See also Java Nath.asin. This method returns a double. Example: AS!N(D) ATA. ATAN(numeric) Calculate the arc tangent. See also Java Nath.atan. This method returns a double. 136 of 180 Example: ATAN(D) C1S COS(numeric) Calculate the trigonometric cosine. See also Java Nath.cos. This method returns a double. Example: COS(ANGLE) C1SH COSH(numeric) Calculate the hyperbolic cosine. See also Java Nath.cosh. This method returns a double. Example: COSH(X) C1T COT(numeric) Calculate the trigonometric cotangent (1fTAN(ANGLE)). See also Java Nath.* functions. This method returns a double. Example: COT(ANGLE) S. S!N(numeric) Calculate the trigonometric sine. See also Java Nath.sin. This method returns a double. Example: S!N(ANGLE) S.H S!NH(numeric) Calculate the hyperbolic sine. See also Java Nath.sinh. This method returns a double. Example: S!NH(ANGLE) 137 of 180 TA. TAN(numeric) Calculate the trigonometric tangent. See also Java Nath.tan. This method returns a double. Example: TAN(ANGLE) TA.H TANH(numeric) Calculate the hyperbolic tangent. See also Java Nath.tanh. This method returns a double. Example: TANH(X) ATA.2 ATAN2(numeric, numeric) Calculate the angle when converting the rectangular coordinates to polar coordinates. See also Java Nath.atan2. This method returns a double. Example: ATAN2(X, Y) -TA.D B!TAND(long, long) The bitwise AND operation. This method returns a long. See also Java operator 8. Example: B!TAND(A, B) -T1# B!TOR(long, long) The bitwise OR operation. This method returns a long. See also Java operator {. Example: B!TOR(A, B) 138 of 180 -T81# B!TXOR(long, long) The bitwise XOR operation. This method returns a long. See also Java operator '. Example: B!TXOR(A, B) +1D NOD(long, long) The modulo operation. This method returns a long. See also Java operator . Example: NOD(A, B) CE!./ { CE!L!NG { CE!L ) (numeric) See also Java Nath.ceil. This method returns a double. Example: CE!L(A) DE/#EES DEGREES(numeric) See also Java Nath.toDegrees. This method returns a double. Example: DEGREES(A) E8% EXP(numeric) See also Java Nath.exp. This method returns a double. Example: EXP(A) (!11# FLOOR(numeric) 139 of 180 See also Java Nath.floor. This method returns a double. Example: FLOOR(A) !1/ { LOG { LN ) (numeric) See also Java Nath.log. !n the PostgreSQL mode, LOG(x) is base 10. This method returns a double. Example: LOG(A) !1/CD LOG10(numeric) See also Java Nath.log10 (in Java 5). This method returns a double. Example: LOG10(A) #ADA.S RAD!ANS(numeric) See also Java Nath.toRadians. This method returns a double. Example: RAD!ANS(A) SQ#T SQRT(numeric) See also Java Nath.sqrt. This method returns a double. Example: SQRT(A) % P!() See also Java Nath.P!. This method returns a double. Example: 1+0 of 180 P!() %12E# POWER(numeric, numeric) See also Java Nath.pow. This method returns a double. Example: POWER(A, B) #A.D { RAND { RANDON ) ( [ int | ) Calling the function without parameter returns the next a pseudo random number. Calling it with an parameter seeds the session's random number generator. This method returns a double between 0 (including) and 1 (excluding). Example: RAND() #A.D1+B''D RANDON_UU!D() Returns a new UU!D with 122 pseudo random bits. Please note that using an index on randomly generated data will result on poor performance once there are millions of rows in a table. The reason is that the cache behavior is very bad with randomly distributed data. This is a problem for any database system. Example: RANDON_UU!D() #1'.D ROUND(numeric [, digits!nt|) Rounds to a number of digits, or to the nearest long if the number of digits if not set. This method returns a double. Example: ROUND(vALUE, 2) #1'.D+A/C ROUNDNAG!C(numeric) This function rounds numbers in a good way, but it is slow. !t has a special handling for numbers around 0. Only numbers smaller or equal +f-1000000000000 are supported. The value is converted to a String internally, and then the last last + 1+1 of 180 characters are checked. '000x' becomes '0000' and '999x' becomes '999999', which is rounded automatically. This method returns a double. Example: ROUNDNAG!C(vALUEf3*3) SEC'#EB#A.D SECURE_RAND(int) Generates a number of cryptographically secure random numbers. This method returns bytes. Example: CALL SECURE_RAND(16) S/. S!GN ( { numeric ) ) Returns -1 if the value is smaller 0, 0 if zero, and otherwise 1. Example: S!GN(vALUE) E.C#@%T ENCRYPT(algorithmString, keyBytes, dataBytes) Encrypts data using a key. The supported algorithm is AES. The block size is 16 bytes. This method returns bytes. Example: CALL ENCRYPT('AES', '00', STR!NGTOUTF8('Test')) DEC#@%T DECRYPT(algorithmString, keyBytes, dataBytes) Decrypts data using a key. The supported algorithm is AES. The block size is 16 bytes. This method returns bytes. Example: CALL TR!N(CHAR(0) FRON UTF8TOSTR!NG( DECRYPT('AES', '00', '3fabb+de8f1ee2e97d7793bab2db1116'))) HASH HASH(algorithmString, dataBytes, iteration!nt) Calculate the hash value using an algorithm, and repeat this process for a number of iterations. Currently, the only algorithm supported is SHA256. This method returns bytes. 1+2 of 180 Example: CALL HASH('SHA256', STR!NGTOUTF8('Password'), 1000) T#'.CATE { TRUNC { TRUNCATE ) ( { {numeric, digits!nt) { timestamp ) ) Truncates to a number of digits (to the next value closer to 0). This method returns a double. When used with a timestamp, truncates a timestamp to a date (day) value. Example: TRUNCATE(vALUE, 2) C1+%#ESS CONPRESS(dataBytes [, algorithmString|) Compresses the data using the specified compression algorithm. Supported algorithms are: LZF (faster but lower compression; default), and DEFLATE (higher compression). Compression does not always reduce size. very small objects and objects with little redundancy may get larger. This method returns bytes. Example: CONPRESS(STR!NGTOUTF8('Test')) E8%A.D EXPAND(bytes) Expands data that was compressed using the CONPRESS function. This method returns bytes. Example: UTF8TOSTR!NG(EXPAND(CONPRESS(STR!NGTOUTF8('Test')))) =E#1 ZERO() Returns the value 0. This function can be used even if numeric literals are disabled. Example: ZERO() ASC ASC!!(string) Returns the ASC!! value of the first character in the string. This method returns an int. Example: 1+3 of 180 ASC!!('Hi') -TB!E./TH B!T_LENGTH(string) Returns the number of bits in a string. This method returns a long. For BLOB, CLOB, BYTES and JAvA_OBJECT, the precision is used. Each character needs 16 bits. Example: B!T_LENGTH(NANE) !E./TH { LENGTH { CHAR_LENGTH { CHARACTER_LENGTH ) ( string ) Returns the number of characters in a string. This method returns a long. For BLOB, CLOB, BYTES and JAvA_OBJECT, the precision is used. Example: LENGTH(NANE) 1CTETB!E./TH OCTET_LENGTH(string) Returns the number of bytes in a string. This method returns a long. For BLOB, CLOB, BYTES and JAvA_OBJECT, the precision is used. Each character needs 2 bytes. Example: OCTET_LENGTH(NANE) CHA# { CHAR { CHR ) ( int ) Returns the character that represents the ASC!! value. This method returns a string. Example: CHAR(65) C1.CAT CONCAT(string, string [,...|) Combines strings. Unlike with the operator {{, NULL parameters are ignored, and do not cause the result to become NULL. This method returns a string. Example: 1++ of 180 CONCAT(NANE, '!') C1.CATB2S CONCAT_WS(separatorString, string, string [,...|) Combines strings with separator. Unlike with the operator {{, NULL parameters are ignored, and do not cause the result to become NULL. This method returns a string. Example: CONCAT_WS(',', NANE, '!') D((E#E.CE D!FFERENCE(string, string) Returns the difference between the sounds of two strings. This method returns an int. Example: D!FFERENCE(T1.NANE, T2.NANE) HE8T1#A2 HEXTORAW(string) Converts a hex representation of a string to a string. + hex characters per string character are used. Example: HEXTORAW(DATA) #A2T1HE8 RAWTOHEX(string) Converts a string to the hex representation. + hex characters per string character are used. This method returns a string. Example: RAWTOHEX(DATA) .ST# !NSTR(string, searchString, [, start!nt|) Returns the location of a search string in a string. !f a start position is used, the characters before it are ignored. !f position is negative, the rightmost location is returned. 0 is returned if the search string is not found. Example: !NSTR(ENA!L,'@') 1+5 of 180 .SE#T (unction !NSERT(originalString, start!nt, length!nt, addString) !nserts a additional string into the original string at a specified start position. The length specifies the number of characters that are removed at the start position in the original string. This method returns a string. Example: !NSERT(NANE, 1, 1, ' ') !12E# { LOWER { LCASE ) ( string ) Converts a string to lowercase. Example: LOWER(NANE) '%%E# { UPPER { UCASE ) ( string ) Converts a string to uppercase. Example: UPPER(NANE) !E(T LEFT(string, int) Returns the leftmost number of characters. Example: LEFT(NANE, 3) #/HT R!GHT(string, int) Returns the rightmost number of characters. Example: R!GHT(NANE, 3) 1+6 of 180 !1CATE LOCATE(searchString, string [, start!nt|) Returns the location of a search string in a string. !f a start position is used, the characters before it are ignored. !f position is negative, the rightmost location is returned. 0 is returned if the search string is not found. Example: LOCATE('.', NANE) %1ST1. POS!T!ON(searchString, string) Returns the location of a search string in a string. See also LOCATE. Example: POS!T!ON('.', NANE) !%AD LPAD(string, int[, paddingString|) Left pad the string to the specified length. !f the length is shorter than the string, it will be truncated at the end. !f the padding string is not set, spaces will be used. Example: LPAD(ANOUNT, 10, '*') #%AD RPAD(string, int[, paddingString|) Right pad the string to the specified length. !f the length is shorter than the string, it will be truncated. !f the padding string is not set, spaces will be used. Example: RPAD(TEXT, 10, '-') !T#+ LTR!N(string) Removes all leading spaces from a string. Example: LTR!N(NANE) 1+7 of 180 #T#+ RTR!N(string) Removes all trailing spaces from a string. Example: RTR!N(NANE) T#+ TR!N ( [ { LEAD!NG { TRA!L!NG { BOTH ) [ string | FRON | string ) Removes all leading spaces, trailing spaces, or spaces at both ends, from a string. Other characters can be removed as well. Example: TR!N(BOTH '_' FRON NANE) #E/E8%B#E%!ACE REGEXP_REPLACE(inputString, regexString, replacementString) Replaces each substring that matches a regular expression. For details, see the Java String.replaceAll() method. !f any parameter is null, the result is null. Example: REGEXP_REPLACE('Hello World', ' +', ' ') #E%EAT REPEAT(string, int) Returns a string repeated some number of times. Example: REPEAT(NANE {{ ' ', 10) #E%!ACE REPLACE(string, searchString [, replacementString|) Replaces all occurrences of a search string in a text with another string. !f no replacement is specified, the search string is removed from the original string. !f any parameter is null, the result is null. Example: REPLACE(NANE, ' ') 1+8 of 180 S1'.DE8 SOUNDEX(string) Returns a four character code representing the sound of a string. See also http:ffwww.archives.govfgenealogyfcensusfsoundex.html . This method returns a string. Example: SOUNDEX(NANE) S%ACE SPACE(int) Returns a string consisting of a number of spaces. Example: SPACE(80) ST#./DEC1DE STR!NGDECODE(string) Converts a encoded string using the Java string literal encoding format. Special characters are b, t, n, f, r, ", , <octal>, u<unicode>. This method returns a string. Example: CALL STR!NGENCODE(STR!NGDECODE('Lines 1nLine 2')) ST#./E.C1DE STR!NGENCODE(string) Encodes special characters in a string using the Java string literal encoding format. Special characters are b, t, n, f, r, ", , <octal>, u<unicode>. This method returns a string. Example: CALL STR!NGENCODE(STR!NGDECODE('Lines 1nLine 2')) ST#./T1'T(E STR!NGTOUTF8(string) Encodes a string to a byte array using the UTF8 encoding format. This method returns bytes. Example: CALL UTF8TOSTR!NG(STR!NGTOUTF8('This is a test')) 1+9 of 180 S'-ST#./ { SUBSTR!NG { SUBSTR ) ( string, start!nt [, length!nt | ) Returns a substring of a string starting at a position. !f the start index is negative, then the start index is relative to the end of the string. The length is optional. Also supported is: SUBSTR!NG(string [FRON start| [FOR length|). Example: CALL SUBSTR('[Hello|', 2, 5); CALL SUBSTR('Hello World', -5); 'T(ET1ST#./ UTF8TOSTR!NG(bytes) Decodes a byte array in the UTF8 format to a string. Example: CALL UTF8TOSTR!NG(STR!NGTOUTF8('This is a test')) 8+!ATT# XNLATTR(nameString, valueString) Creates an XNL attribute element of the form name=value. The value is encoded as XNL text. This method returns a string. Example: CALL XNLNODE('a', XNLATTR('href', 'http:ffh2database.com')) 8+!.1DE XNLNODE(elementString [, attributesString [, contentString [, indentBoolean|||) Create an XNL node element. An empty or null attribute string means no attributes are set. An empty or null content string means the node is empty. The content is indented by default if it contains a newline. This method returns a string. Example: CALL XNLNODE('a', XNLATTR('href', 'http:ffh2database.com'), 'H2') 8+!C1++E.T XNLCONNENT(commentString) Creates an XNL comment. Two dashes (--) are converted to - -. This method returns a string. Example: CALL XNLCONNENT('Test') 150 of 180 8+!CDATA XNLCDATA(valueString) Creates an XNL CDATA element. !f the value contains ||>, an XNL text element is created instead. This method returns a string. Example: CALL XNLCDATA('data') 8+!STA#TD1C XNLSTARTDOC() Returns the XNL declaration. The result is always <?xml version=1.0?>. Example: CALL XNLSTARTDOC() 8+!TE8T XNLTEXT(valueString [, escapeNewlineBoolean|) Creates an XNL text element. !f enabled, newline and linefeed is converted to an XNL entity (8#). This method returns a string. Example: CALL XNLTEXT('test') T1BCHA# TO_CHAR(value [, formatString[, nlsParamString||) Oracle-compatible TO_CHAR function that can format a timestamp, a number, or text. Example: CALL TO_CHAR(T!NESTANP '2010-01-01 00:00:00', 'DD NON, YYYY') A##A@B/ET ARRAY_GET(arrayExpression, indexExpression) Returns one element of an array. This method returns a string. Example: CALL ARRAY_GET(('Hello', 'World'), 2) 151 of 180 A##A@B!E./TH ARRAY_LENGTH(arrayExpression) Returns the length of an array. Example: CALL ARRAY_LENGTH(('Hello', 'World')) A##[email protected] ARRAY_CONTA!NS(arrayExpression, value) Returns a boolean true if the array contains the value. Example: CALL ARRAY_CONTA!NS(('Hello', 'World'), 'Hello') A'T1C1++T AUTOCONN!T() Returns true if auto commit is switched on for this session. Example: AUTOCONN!T() CA.CE!BSESS1. CANCEL_SESS!ON(session!nt) Cancels the currently executing statement of another session. The method only works if the multithreaded kernel is enabled (see SET NULT!_THREADED). Returns true if the statement was canceled, false if the session is closed or no statement is currently executing. Admin rights are required to execute this command. Example: CANCEL_SESS!ON(3) CASE2HE. (unction CASEWHEN(boolean, avalue, bvalue) Returns 'a' if the boolean expression is true, otherwise 'b'. Returns the same data type as the parameter. Example: CASEWHEN(!D=1, 'A', 'B') 152 of 180 CAST CAST(value AS dataType) Converts a value to another data type. The following conversion rules are used: When converting a number to a boolean, 0 is false and every other value is true. When converting a boolean to a number, false is 0 and true is 1. When converting a number to a number of another type, the value is checked for overflow. When converting a number to binary, the number of bytes matches the precision. When converting a string to binary, it is hex encoded (every byte two characters); a hex string can be converted to a number by first converting it to binary. !f a direct conversion is not possible, the value is first converted to a string. Example: CAST(NANE AS !NT); CAST(65535 AS B!NARY); CAST(CAST('FFFF' AS B!NARY) AS !NT); C1A!ESCE { COALESCE { NvL ) (avalue, bvalue [,...|) Returns the first value that is not null. Example: COALESCE(A, B, C) C1.3E#T CONvERT(value, dataType) Converts a value to another data type. Example: CONvERT(NANE, !NT) C'##3A! CURRvAL( [ schemaName, | sequenceString ) Returns the current (last) value of the sequence, independent of the session. !f the sequence was just created, the method returns (start - interval). !f the schema name is not set, the current schema is used. !f the schema name is not set, the sequence name is converted to uppercase (for compatibility). This method returns a long. Example: CURRvAL('TEST_SEQ') CS3#EAD CSvREAD(fileNameString [, columnsString [, csvOptions | | ) Returns the result set of reading the CSv (comma separated values) file. For each parameter, NULL means the default value should be used. 153 of 180 !f the column names are specified (a list of column names separated with the fieldSeparator), those are used, otherwise (or if they are set to NULL) the first line of the file is interpreted as the column names. !n that case, column names that contain no special characters (only letters, '_', and digits; similar to the rule for Java identifiers) are considered case insensitive. Other column names are case sensitive, that means you need to use quoted identifiers (see below). The default charset is the default value for this system, and the default field separator is a comma. Nissing unquoted values as well as data that matches nullString is parsed as NULL. All columns of type vARCHAR. The BON (the byte-order-mark) character 0xfeff at the beginning of the file is ignored. This function can be used like a table: SELECT * FRON CSvREAD(...). !nstead of a file, an URL may be used, for example jar:file:fffc:ftempfexample.zip!forgfexamplefnested.csv. To read a stream from the classpath, use the prefix classpath:. To read from HTTP, use the prefix http: (as in a browser). For performance reason, CSvREAD should not be used inside a join. !nstead, import the data first (possibly into a temporary table) and then use the table. Admin rights are required to execute this command. Example: CALL CSvREAD('test.csv'); -- Read a file containing the columns !D, NANE with CALL CSvREAD('test2.csv', '!D{NANE', 'charset=UTF-8 fieldSeparator={'); SELECT * FRON CSvREAD('dataftest.csv', null, 'rowSeparator=;'); -- Read a tab-separated file SELECT * FRON CSvREAD('dataftest.tsv', null, 'rowSeparator=' {{ CHAR(9)); SELECT "Last Name" FRON CSvREAD('address.csv'); SELECT "Last Name" FRON CSvREAD('classpath:forgfacmefdatafaddress.csv'); CS32#TE CSvWR!TE ( fileNameString, queryString [, csvOptions [, lineSepString| | ) Writes a CSv (comma separated values). The file is overwritten if it exists. !f only a file name is specified, it will be written to the current working directory. For each parameter, NULL means the default value should be used. The default charset is the default value for this system, and the default field separator is a comma. The values are converted to text using the default string representation; if another conversion is required you need to change the select statement accordingly. The parameter nullString is used when writing NULL (by default nothing is written when NULL appears). The default line separator is the default value for this system (system property line.separator). The returned value is the number or rows written. Admin rights are required to execute this command. Example: CALL CSvWR!TE('dataftest.csv', 'SELECT * FRON TEST'); CALL CSvWR!TE('dataftest2.csv', 'SELECT * FRON TEST', 'charset=UTF-8 fieldSeparator={'); -- Write a tab-separated file CALL CSvWR!TE('dataftest.tsv', 'SELECT * FRON TEST', 'charset=UTF-8 fieldSeparator=' {{ CHAR(9)); DATA-ASE DATABASE() Returns the name of the database. Example: CALL DATABASE(); 15+ of 180 DATA-ASEB%ATH DATABASE_PATH() Returns the directory of the database files and the database name, if it is file based. Returns NULL otherwise. Example: CALL DATABASE_PATH(); DEC1DE DECODE(value, whenvalue, thenvalue [,...|) Returns the first matching value. NULL is considered to match NULL. !f no match was found, then NULL or the last parameter (if the parameter count is even) is returned. This function is provided for Oracle compatibility (see there for details). Example: CALL DECODE(RAND()>0.5, 0, 'Red', 1, 'Black'); DS:BS%ACEB'SED D!SK_SPACE_USED(tableNameString) Returns the approximate amount of space used by the table specified. Does not currently take into account indexes or LOB's. This function may be expensive since it has to load every page in the table. Example: CALL D!SK_SPACE_USED('my_table'); (!EB#EAD F!LE_READ(fileNameString [,encodingString|) Returns the contents of a file. !f only one parameter is supplied, the data are returned as a BLOB. !f two parameters are used, the data is returned as a CLOB (text). The second parameter is the character set to use, NULL meaning the default character set for this system. File names and URLs are supported. To read a stream from the classpath, use the prefix classpath:. Admin rights are required to execute this command. Example: SELECT LENGTH(F!LE_READ('~f.h2.server.properties')) LEN; SELECT F!LE_READ('http:fflocalhost:8182fstylesheet.css', NULL) CSS; /#EATEST GREATEST(avalue, bvalue [,...|) Returns the largest value that is not NULL, or NULL if all values are NULL. 155 of 180 Example: CALL GREATEST(1, 2, 3); DE.TT@ !DENT!TY() Returns the last inserted identity value for this session. This value changes whenever a new sequence number was generated, even within a trigger or Java function. See also SCOPE_!DENT!TY. This method returns a long. Example: CALL !DENT!TY(); (.'!! !FNULL(avalue, bvalue) Returns the value of 'a' if it is not null, otherwise 'b'. Example: CALL !FNULL(NULL, ''); !EAST LEAST(avalue, bvalue [,...|) Returns the smallest value that is not NULL, or NULL if all values are NULL. Example: CALL LEAST(1, 2, 3); !1C:B+1DE LOCK_NODE() Returns the current lock mode. See SET LOCK_NODE. This method returns an int. Example: CALL LOCK_NODE(); !1C:BT+E1'T LOCK_T!NEOUT() Returns the lock timeout of the current session (in milliseconds). Example: 156 of 180 LOCK_T!NEOUT() !.:BSCHE+A L!NK_SCHENA(targetSchemaString, driverString, urlString, userString, passwordString, sourceSchemaString) Creates table links for all tables in a schema. !f tables with the same name already exist, they are dropped first. The target schema is created automatically if it does not yet exist. The driver name may be empty if the driver is already loaded. The list of tables linked is returned in the form of a result set. Admin rights are required to execute this command. Example: CALL L!NK_SCHENA('TEST2', '', 'jdbc:h2:test2', 'sa', 'sa', 'PUBL!C'); +E+1#@B(#EE NENORY_FREE() Returns the free memory in KB (where 102+ bytes is a KB). This method returns an int. The garbage is run before returning the value. Admin rights are required to execute this command. Example: NENORY_FREE() +E+1#@B'SED NENORY_USED() Returns the used memory in KB (where 102+ bytes is a KB). This method returns an int. The garbage is run before returning the value. Admin rights are required to execute this command. Example: NENORY_USED() .E8T3A! NEXTvAL ( [ schemaName, | sequenceString ) Returns the next value of the sequence. Used values are never re-used, even when the transaction is rolled back. !f the schema name is not set, the current schema is used, and the sequence name is converted to uppercase (for compatibility). This method returns a long. Example: NEXTvAL('TEST_SEQ') .'!!( NULL!F(avalue, bvalue) Returns NULL if 'a' is equals to 'b', otherwise 'a'. 157 of 180 Example: NULL!F(A, B) .3!2 NvL2(testvalue, avalue, bvalue) !f the test value is null, then 'b' is returned. Otherwise, 'a' is returned. The data type of the returned value is the data type of 'a' if this is a text type. Example: NvL2(X, 'not null', 'null') #EAD1.!@ READONLY() Returns true if the database is read-only. Example: READONLY() #12.'+ { ROWNUN() ) { { ROW_NUNBER() OvER() ) Returns the number of the current row. This method returns a long. !t is supported for SELECT statements, as well as for DELETE and UPDATE. The first row has the row number 1, and is calculated before ordering and grouping the result set, but after evaluating index conditions (even when the index conditions are specified in an outer query). To get the row number after ordering and grouping, use a subquery. Example: SELECT ROWNUN(), * FRON TEST; SELECT ROWNUN(), * FRON (SELECT * FRON TEST ORDER BY NANE); SELECT !D FRON (SELECT T.*, ROWNUN AS R FRON TEST T) WHERE R BETWEEN 2 AND 3; SCHE+A SCHENA() Returns the name of the default schema for this session. Example: CALL SCHENA() SC1%EBDE.TT@ SCOPE_!DENT!TY() 158 of 180 Returns the last inserted identity value for this session for the current scope. Changes within triggers and Java functions are ignored. See also !DENT!TY(). This method returns a long. Example: CALL SCOPE_!DENT!TY(); SESS1.BD SESS!ON_!D() Returns the unique session id number for the current database connection. This id stays the same while the connection is open. This method returns an int. The database engine may re-use a session id after the connection is closed. Example: CALL SESS!ON_!D() SET SET(@variableName, value) Updates a variable with the given value. The new value is returned. When used in a query, the value is updated in the order the rows are read. When used in a subquery, not all rows might be read depending on the query plan. This can be used to implement running totals f cumulative sums. Example: SELECT X, SET(@!, !FNULL(@!, 0)+X) RUNN!NG_TOTAL FRON SYSTEN_RANGE(1, 10) TA-!E { TABLE { TABLE_D!ST!NCT ) ( { name dataType = expression ) [,...| ) Returns the result set. TABLE_D!ST!NCT removes duplicate rows. Example: SELECT * FRON TABLE(!D !NT=(1, 2), NANE vARCHAR=('Hello', 'World')) T#A.SACT1.BD TRANSACT!ON_!D() Returns the current transaction id for this session. This method returns NULL if there is no uncommitted change, or if the the database is not persisted. Otherwise a value of the following form is returned: logFile!d-position-session!d. This method returns a string. The value is unique across database restarts (values are not re-used). Example: CALL TRANSACT!ON_!D() 159 of 180 T#'.CATEB3A!'E TRUNCATE_vALUE(value, precision!nt, forceBoolean) Truncate a value to the required precision. The precision of the returned value may be a bit larger than requested, because fixed precision values are not truncated (unlike the numeric TRUNCATE method). Unlike CAST, the truncating a decimal value may lose precision if the force flag is set to true. The method returns a value with the same data type as the first parameter. Example: CALL TRUNCATE_vALUE(X, 10, TRUE); 'SE# { USER { CURRENT_USER ) () Returns the name of the current user of this session. Example: CURRENT_USER() H23E#S1. H2vERS!ON() Returns the H2 version as a String. Example: H2vERS!ON() C'##E.TBDATE { CURRENT_DATE [ () | { CURDATE() { SYSDATE { TODAY ) Returns the current date. This method always returns the same value within a transaction. Example: CURRENT_DATE() C'##E.TBT+E { CURRENT_T!NE [ () | { CURT!NE() ) Returns the current time. This method always returns the same value within a transaction. Example: CURRENT_T!NE() 160 of 180 C'##E.TBT+ESTA+% { CURRENT_T!NESTANP [ ( [ int | ) | { NOW( [ int | ) ) Returns the current timestamp. The precision parameter for nanoseconds precision is optional. This method always returns the same value within a transaction. Example: CURRENT_T!NESTANP() DATEADD { DATEADD{ T!NESTANPADD ) (unitString, add!nt, timestamp) Adds units to a timestamp. The string indicates the unit. Use negative values to subtract units. The same units as in the EXTRACT function are supported. This method returns a timestamp. Example: DATEADD('NONTH', 1, DATE '2001-01-31') DATED(( { DATED!FF { T!NESTANPD!FF ) (unitString, aTimestamp, bTimestamp) Returns the the number of crossed unit boundaries between two timestamps. This method returns a long. The string indicates the unit. The same units as in the EXTRACT function are supported. Example: DATED!FF('YEAR', T1.CREATED, T2.CREATED) [email protected]+E DAYNANE(date) Returns the name of the day (in English). Example: DAYNANE(CREATED) DA@B1(B+1.TH DAY_OF_NONTH(date) Returns the day of the month (1-31). Example: DAY_OF_NONTH(CREATED) 161 of 180 DA@B1(B2EE: DAY_OF_WEEK(date) Returns the day of the week (1 means Sunday). Example: DAY_OF_WEEK(CREATED) DA@B1(B@EA# DAY_OF_YEAR(date) Returns the day of the year (1-366). Example: DAY_OF_YEAR(CREATED) E8T#ACT EXTRACT ( { YEAR { YY { NONTH { NN { WEEK { DAY { DD { DAY_OF_YEAR { DOY { HOUR { HH { N!NUTE { N! { SECOND { SS { N!LL!SECOND { NS ) FRON timestamp ) Returns a specific value from a timestamps. This method returns an int. Example: EXTRACT(SECOND FRON CURRENT_T!NESTANP) (1#+ATDATET+E FORNATDATET!NE ( timestamp, formatString [ , localeString [ , timeZoneString | | ) Formats a date, time or timestamp as a string. The most important format characters are: y year, N month, d day, H hour, m minute, s second. For details of the format, see java.text.SimpleDateFormat. This method returns a string. Example: CALL FORNATDATET!NE(T!NESTANP '2001-02-03 0+:05:06', 'EEE, d NNN yyyy HH:mm:ss z', 'en', 'GNT') H1'# HOUR(timestamp) Returns the hour (0-23) from a timestamp. Example: HOUR(CREATED) 162 of 180 +.'TE N!NUTE(timestamp) Returns the minute (0-59) from a timestamp. Example: N!NUTE(CREATED) +1.TH NONTH(timestamp) Returns the month (1-12) from a timestamp. Example: NONTH(CREATED) +1.TH.A+E NONTHNANE(date) Returns the name of the month (in English). Example: NONTHNANE(CREATED) %A#SEDATET+E PARSEDATET!NE(string, formatString [, localeString [, timeZoneString||) Parses a string and returns a timestamp. The most important format characters are: y year, N month, d day, H hour, m minute, s second. For details of the format, see java.text.SimpleDateFormat. Example: CALL PARSEDATET!NE('Sat, 3 Feb 2001 03:05:06 GNT', 'EEE, d NNN yyyy HH:mm:ss z', 'en', 'GNT') Q'A#TE# QUARTER(timestamp) Returns the quarter (1-+) from a timestamp. Example: QUARTER(CREATED) 163 of 180 SEC1.D SECOND(timestamp) Returns the second (0-59) from a timestamp. Example: SECOND(CREATED) 2EE: WEEK(timestamp) Returns the week (1-53) from a timestamp. This method uses the current system locale. Example: WEEK(CREATED) @EA# YEAR(timestamp) Returns the year from a timestamp. Example: YEAR(CREATED) 16+ of 180 Data Types nde" !NT Type BOOLEAN Type T!NY!NT Type SNALL!NT Type B!G!NT Type !DENT!TY Type DEC!NAL Type DOUBLE Type REAL Type T!NE Type DATE Type T!NESTANP Type B!NARY Type OTHER Type vARCHAR Type vARCHAR_!GNORECASE Type CHAR Type BLOB Type CLOB Type UU!D Type ARRAY Type GEONETRY Type .T Type !NT { !NTEGER { NED!UN!NT { !NT+ { S!GNED Possible values: -21+7+836+8 to 21+7+836+7. Napped to java.lang.!nteger. Example: !NT -11!EA. Type BOOLEAN { B!T { BOOL Possible values: TRUE and FALSE. Napped to java.lang.Boolean. Example: BOOLEAN [email protected] Type T!NY!NT Possible values are: -128 to 127. 165 of 180 Napped to java.lang.Byte. Example: T!NY!NT S+A!!.T Type SNALL!NT { !NT2 { YEAR Possible values: -32768 to 32767. Napped to java.lang.Short. Example: SNALL!NT -/.T Type B!G!NT { !NT8 Possible values: -922337203685+775808 to 922337203685+775807. Napped to java.lang.Long. Example: B!G!NT DE.TT@ Type !DENT!TY Auto-!ncrement value. Possible values: -922337203685+775808 to 922337203685+775807. Used values are never re-used, even when the transaction is rolled back. Napped to java.lang.Long. Example: !DENT!TY DEC+A! Type { DEC!NAL { NUNBER { DEC { NUNER!C ) ( precision!nt [ , scale!nt | ) Data type with fixed precision and scale. This data type is recommended for storing currency values. Napped to java.math.BigDecimal. Example: DEC!NAL(20, 2) 166 of 180 D1'-!E Type { DOUBLE [ PREC!S!ON | { FLOAT { FLOAT8 ) A floating point number. Should not be used to represent currency values, because of rounding problems. Napped to java.lang.Double. Example: DOUBLE #EA! Type { REAL { FLOAT+ ) A single precision floating point number. Should not be used to represent currency values, because of rounding problems. Napped to java.lang.Float. Example: REAL T+E Type T!NE The time data type. The format is hh:mm:ss. Napped to java.sql.Time. When converted to a java.sql.Date, the date is set to 1970-01-01. Example: T!NE DATE Type DATE The date data type. The format is yyyy-NN-dd. Napped to java.sql.Date, with the time set to 00:00:00 (or to the next possible time if midnight doesn't exist for the given date and timezone due to a daylight saving change). Example: DATE T+ESTA+% Type { T!NESTANP { DATET!NE { SNALLDATET!NE ) The timestamp data type. The format is yyyy-NN-dd hh:mm:ss[.nnnnnnnnn|. 167 of 180 Napped to java.sql.Timestamp (java.util.Date is also supported). Example: T!NESTANP -.A#@ Type { B!NARY { vARB!NARY { LONGvARB!NARY { RAW { BYTEA ) [ ( precision!nt ) | Represents a byte array. For very long arrays, use BLOB. The maximum size is 2 GB, but the whole object is kept in memory when using this data type. The precision is a size constraint; only the actual data is persisted. For large text data BLOB or CLOB should be used. Napped to byte[|. Example: B!NARY(1000) 1THE# Type OTHER This type allows storing serialized Java objects. !nternally, a byte array is used. Serialization and deserialization is done on the client side only. Deserialization is only done when getObject is called. Java operations cannot be executed inside the database engine for security reasons. Use PreparedStatement.setObject to store values. Napped to java.lang.Object (or any subclass). Example: OTHER 3A#CHA# Type { vARCHAR { LONGvARCHAR { vARCHAR2 { NvARCHAR { NvARCHAR2 { vARCHAR_CASESENS!T!vE) [ ( precision!nt ) | A Unicode String. Use two single quotes ('') to create a quote. The maximum precision is !nteger.NAX_vALUE. The precision is a size constraint; only the actual data is persisted. The whole text is loaded into memory when using this data type. For large text data CLOB should be used; see there for details. Napped to java.lang.String. Example: vARCHAR(255) 3A#CHA#B/.1#ECASE Type vARCHAR_!GNORECASE [ ( precision!nt ) | Same as vARCHAR, but not case sensitive when comparing. Stored in mixed case. 168 of 180 The maximum precision is !nteger.NAX_vALUE. The precision is a size constraint; only the actual data is persisted. The whole text is loaded into memory when using this data type. For large text data CLOB should be used; see there for details. Napped to java.lang.String. Example: vARCHAR_!GNORECASE CHA# Type { CHAR { CHARACTER { NCHAR ) [ ( precision!nt ) | A Unicode String. This type is supported for compatibility with other databases and older applications. The difference to vARCHAR is that trailing spaces are ignored and not persisted. The maximum precision is !nteger.NAX_vALUE. The precision is a size constraint; only the actual data is persisted. The whole text is kept in memory when using this data type. For large text data CLOB should be used; see there for details. Napped to java.lang.String. Example: CHAR(10) -!1- Type { BLOB { T!NYBLOB { NED!UNBLOB { LONGBLOB { !NAGE { O!D ) [ ( precision!nt ) | Like B!NARY, but intended for very large values such as files or images. Unlike when using B!NARY, large objects are not kept fully in-memory. Use PreparedStatement.setBinaryStream to store values. See also CLOB and Advanced f Large Objects. Napped to java.sql.Blob (java.io.!nputStream is also supported). Example: BLOB C!1- Type { CLOB { T!NYTEXT { TEXT { NED!UNTEXT { LONGTEXT { NTEXT { NCLOB ) [ ( precision!nt ) | CLOB is like vARCHAR, but intended for very large values. Unlike when using vARCHAR, large CLOB objects are not kept fully in-memory; instead, they are streamed. CLOB should be used for documents and texts with arbitrary size such as XNL or HTNL documents, text files, or memo fields of unlimited size. Use PreparedStatement.setCharacterStream to store values. See also Advanced f Large Objects. vARCHAR should be used for text with relatively short average size (for example shorter than 200 characters). Short CLOB values are stored inline, but there is an overhead compared to vARCHAR. Napped to java.sql.Clob (java.io.Reader is also supported). Example: CLOB 169 of 180 ''D Type UU!D Universally unique identifier. This is a 128 bit value. To store values, use PreparedStatement.setBytes, setString, or setObject(uuid) (where uuid is a java.util.UU!D). ResultSet.getObject will return a java.util.UU!D. Please note that using an index on randomly generated data will result on poor performance once there are millions of rows in a table. The reason is that the cache behavior is very bad with randomly distributed data. This is a problem for any database system. For details, see the documentation of java.util.UU!D. Example: UU!D A##A@ Type ARRAY An array of values. Napped to java.lang.Object[| (arrays of any non-primitive type are also supported). Use a value list (1, 2) or PreparedStatement.setObject(.., new Object[| {..)) to store values, and ResultSet.getObject(..) or ResultSet.getArray(..) to retrieve the values. Example: ARRAY /E1+ET#@ Type GEONETRY A spatial geometry type, based on the com.vividsolutions.jts library. Normally represented in textual format using the WKT (well known text) format. Use a quoted string containing a WKT formatted string or PreparedStatement.setObject() to store values, and ResultSet.getObject(..) or ResultSet.getString(..) to retrieve the values. Example: GEONETRY 170 of 180 -uild Portability Environment Building the Software Build Targets Using Naven 2 Using Eclipse Translating Providing Patches Reporting Problems or Requests Automated Build Generating Railroad Diagrams %ortability This database is written in Java and therefore works on many platforms. !t can also be compiled to a native executable using GCJ. En*ironment To run this database, a Java Runtime Environment (JRE) version 1.6 or higher is required. To create the database executables, the following software stack was used. To use this database, it is not required to install this software however. Nac OS X and Windows Sun JDK version 1.6 and 1.7 Eclipse Eclipse Plugins: Subclipse, Eclipse Checkstyle Plug-in, EclEmma Java Code Coverage Emma Java Code Coverage Nozilla Firefox OpenOffice NS!S (Nullsoft Scriptable !nstall System) Naven -uilding the Soft&are You need to install a JDK, for example the Sun JDK version 1.6 or 1.7. Ensure that Java binary directory is included in the PATH environment variable, and that the environment variable JAvA_HONE points to your Java installation. On the command line, go to the directory h2 and execute the following command: build -? For Linux and OS X, use .fbuild.sh instead of build. You will get a list of targets. !f you want to build the jar file, execute (Windows): build jar To run the build tool in shell mode, use the command line option - as in .fbuild.sh -. S&itching the Source Code The source code uses Java 1.6 features. To switch the source code to the installed version of Java, run: 171 of 180 build switchSource -uild Targets The build system can generate smaller jar files as well. The following targets are currently supported: jarClient creates the file h2client.jar. This only contains the JDBC client. jarSmall creates the file h2small.jar. This only contains the embedded database. Debug information is disabled. jarJaqu creates the file h2jaqu.jar. This only contains the JaQu (Java Query) implementation. All other jar files do not include JaQu. javadoc!mpl creates the Javadocs of the implementation. To create the file h2client.jar, go to the directory h2 and execute the following command: build jarClient 'sing !ucene 2 7 F Both Apache Lucene 2 and Lucene 3 are supported. Currently Apache Lucene version 2.x is used by default for H2 version 1.2.x, and Lucene version 3.x is used by default for H2 version 1.3.x. To use a different version of Lucene when compiling, it needs to be specified as follows: build -Dlucene=2 clean compile 'sing +a*en 2 'sing a Central #epository You can include the database in your Naven 2 project as a dependency. Example: <dependency> <group!d>com.h2database<fgroup!d> <artifact!d>h2<fartifact!d> <version>1.3.176<fversion> <fdependency> New versions of this database are first uploaded to http:ffhsql.sourceforge.netfm2-repof and then automatically synchronized with the main Naven repository; however after a new release it may take a few hours before they are available there. +a*en %lugin to Start and Stop the TC% Ser*er A Naven plugin to start and stop the H2 TCP server is available from Laird Nelson at GitHub. To start the H2 server, use: mvn com.edugility.h2-maven-plugin:1.0-SNAPSHOT:spawn To stop the H2 server, use: mvn com.edugility.h2-maven-plugin:1.0-SNAPSHOT:stop 'sing Snapshot 3ersion To build a h2-*-SNAPSHOT.jar file and upload it the to the local Naven 2 repository, execute the following command: 172 of 180 build maven!nstallLocal Afterwards, you can include the database in your Naven 2 project as a dependency: <dependency> <group!d>com.h2database<fgroup!d> <artifact!d>h2<fartifact!d> <version>1.0-SNAPSHOT<fversion> <fdependency> 'sing Eclipse To create an Eclipse project for H2, use the following steps: !nstall Subversion and Eclipse. Get the H2 source code from the Subversion repository: svn checkout http:ffh2database.googlecode.comfsvnftrunk h2database-read-only Download all dependencies (Windows): build.bat download !n Eclipse, create a new Java project from existing source code: File, New, Project, Java Project, Create project from existing source. Select the h2 folder, click Next and Finish. To resolve com.sun.javadoc import statements, you may need to manually add the file <java.home>f..flibftools.jar to the build path. Translating The translation of this software is split into the following parts: H2 Console: srcfmainforgfh2fserverfwebfresf_text_*.prop Error messages: srcfmainforgfh2fresf_messages_*.prop To translate the H2 Console, start it and select Preferences f Translate. After you are done, send the translated *.prop file to the Google Group. The web site is currently translated using Google. %ro*iding %atches !f you like to provide patches, please consider the following guidelines to simplify merging them: Only use Java 6 features (do not use Java 7) (see Environment). Follow the coding style used in the project, and use Checkstyle (see above) to verify. For example, do not use tabs (use spaces instead). The checkstyle configuration is in srcfinstallerfcheckstyle.xml. A template of the Eclipse settings are in srcfinstallerfeclipse.settingsf*. !f you want to use them, you need to copy them to the .settings directory. The formatting options (eclipseCodeStyle) are also included. Please provide test cases and integrate them into the test suite. For Java level tests, see srcftestforgfh2ftestfTestAll.java. For SQL level tests, see srcftestforgfh2ftestftest.in.txt or testSimple.in.txt. The test cases should cover at least 90 of the changed and new code; use a code coverage tool to verify that (see above). or use the build target coverage. verify that you did not break other features: run the test cases by executing build test. Provide end user documentation if required (srcfdocsrcfhtmlf*). Document grammar changes in srcfdocsrcfhelpfhelp.csv Provide a change log entry (srcfdocsrcfhtmlfchangelog.html). verify the spelling using build spellcheck. !f required add the new words to srcftoolsforgfh2fbuildfdocfdictionary.txt. Run srcfinstallerfbuildRelease to find and fix formatting errors. verify the formatting using build docs and build javadoc. Submit patches as .patch files (compressed if big). To create a patch using Eclipse, use Team f Create Patch. For legal reasons, patches need to be public in the form of an email to the group, or in the form of an issue report or attachment. Significant contributions need to include the following statement: 173 of 180 "! wrote the code, it's mine, and !'m contributing it to H2 for distribution multiple-licensed under the H2 License, version 1.0, and under the Eclipse Public License, version 1.0 (http:ffh2database.comfhtmlflicense.html)." #eporting %roblems or #e$uests Please consider the following checklist if you have a question, want to report a problem, or if you have a feature request: For bug reports, please provide a short, self contained, correct (compilable), example of the problem. Feature requests are always welcome, even if the feature is already on the roadmap. Your mail will help prioritize feature requests. !f you urgently need a feature, consider providing a patch. Before posting problems, check the FAQ and do a Google search. When got an unexpected exception, please try the Error Analyzer tool. !f this doesn't help, please report the problem, including the complete error message and stack trace, and the root cause stack trace(s). When sending source code, please use a public web clipboard such as Pastebin, Cl1p, or Nystic Paste to avoid formatting problems. Please keep test cases as simple and short as possible, but so that the problem can still be reproduced. As a template, use: HelloWorld.java. Nethod that simply call other methods should be avoided, as well as unnecessary exception handling. Please use the JDBC AP! and no external tools or libraries. The test should include all required initialization code, and should be started with the main method. For large attachments, use a public temporary storage such as Rapidshare. Google Group versus issue tracking: Use the Google Group for questions or if you are not sure it's a bug. !f you are sure it's a bug, you can create an issue, but you don't need to (sending an email to the group is enough). Please note that only few people monitor the issue tracking system. For out-of-memory problems, please analyze the problem yourself first, for example using the command line option -XX:+HeapDumpOnOutOfNemoryError (to create a heap dump file on out of memory) and a memory analysis tool such as the Eclipse Nemory Analyzer (NAT). !t may take a few days to get an answers. Please do not double post. Automated -uild This build process is automated and runs regularly. The build process includes running the tests and code coverage, using the command line .fbuild.sh clean jar coverage -Dh2.ftpPassword=... uploadBuild. The last results are available here: Test Output Code Coverage Summary Code Coverage Details (download, 1.3 NB) Build Newsfeed Latest Jar File (download, 1 NB) /enerating #ailroad Diagrams The railroad diagrams of the SQL grammar are HTNL, formatted as nested tables. The diagrams are generated as follows: The BNF parser (org.h2.bnf.Bnf) reads and parses the BNF from the file help.csv. The page parser (org.h2.server.web.PageParser) reads the template HTNL file and fills in the diagrams. The rail images (one straight, four junctions, two turns) are generated using a simple Java application. To generate railroad diagrams for other grammars, see the package org.h2.jcr. This package is used to generate the SQL-2 railroad diagrams for the JCR 2.0 specification. 17+ of 180 History and #oadmap Change Log Roadmap History of this Database Engine Why Java Supporters Change !og The up-to-date change log is available at http:ffwww.h2database.comfhtmlfchangelog.html #oadmap The current roadmap is available at http:ffwww.h2database.comfhtmlfroadmap.html History of this Database Engine The development of H2 was started in Nay 200+, but it was first published on December 1+th 2005. The main author of H2, Thomas Nueller, is also the original developer of Hypersonic SQL. !n 2001, he joined PointBase !nc. where he wrote PointBase Nicro, a commercial Java SQL database. At that point, he had to discontinue Hypersonic SQL. The HSQLDB Group was formed to continued to work on the Hypersonic SQL codebase. The name H2 stands for Hypersonic 2, however H2 does not share code with Hypersonic SQL or HSQLDB. H2 is built from scratch. 2hy )a*a The main reasons to use a Java database are: very simple to integrate in Java applications Support for many different platforms Nore secure than native applications (no buffer overflows) User defined functions (or triggers) run very fast Unicode support Some think Java is too slow for low level operations, but this is no longer true. Garbage collection for example is now faster than manual memory management. Developing Java code is faster than developing C or C++ code. When using Java, most time can be spent on improving the algorithms instead of porting the code to different platforms or doing memory management. Features such as Unicode and network libraries are already built-in. !n Java, writing secure code is easier because buffer overflows can not occur. Features such as reflection can be used for randomized testing. Java is future proof: a lot of companies support Java. Java is now open source. To increase the portability and ease of use, this software depends on very few libraries. Features that are not available in open source Java implementations (such as Swing) are not used, or only used for optional features. Supporters Nany thanks for those who reported bugs, gave valuable feedback, spread the word, and translated this project. Also many thanks to the donors: Code +2 Software, !nc., Ninneapolis Nartin Wildam, Austria Code Lutin, France NetSuxxess GmbH, Germany 175 of 180 Poker Copilot, Steve NcLeod, Germany SkyCash, Poland Lumber-mill, !nc., Japan StockNarketEye, USA Eckenfelder GmbH 8 Co.KG, Germany Anthony Goubard, Netherlands Richard Hickey, USA Alessio Jacopo D'Adamo, !taly Ashwin Jayaprakash, USA Donald Bleyl, USA Frank Berger, Germany Florent Ramiere, France Jun !yama, Japan Antonio Casqueiro, Portugal Oliver Computing LLC, USA Harpal Grover Consulting !nc., USA Elisabetta Berlini, !taly William Gilbert, USA Antonio Dieguez Rojas, Chile Ontology Works, USA Pete Haidinyak, USA William Osmond, USA Joachim Ansorg, Germany Oliver Soerensen, Germany Christos vasilakis, Greece Fyodor Kupolov, Denmark Jakob Jenkov, Denmark Stphane Chartrand, Switzerland Glenn Kidd, USA Gustav Trede, Sweden Joonas Pulakka, Finland Bjorn Darri Sigurdsson, !celand !yama Jun, Japan Gray Watson, USA Erik Dick, Germany Pengxiang Shao, China Bilingual Narketing Group, USA Philippe Narschall, Switzerland Knut Staring, Norway Theis Borg, Denmark Nark De Nendonca Duske, USA Joel A. Garringer, USA Olivier Chafik, France Rene Schwietzke, Germany Jalpesh Patadia, USA Takanori Kawashima, Japan Terrence JC Huang, China JiaDong Huang, Australia Laurent van Roy, Belgium Qian Chen, China Clinton Hyde, USA Kritchai Phromros, Thailand 176 of 180 (re$uently Asked Questions ! Have a Problem or Feature Request Are there Known Bugs? When is the Next Release? !s this Database Engine Open Source? !s Commercial Support Available? How to Create a New Database? How to Connect to a Database? Where are the Database Files Stored? What is the Size Limit (Naximum Size) of a Database? !s it Reliable? Why is Opening my Database Slow? Ny Query is Slow H2 is very Slow Column Names are !ncorrect? Float is Double? !s the GCJ version Stable? Faster? How to Translate this Project? How to Contribute to this Project? Ha*e a %roblem or (eature #e$uest Please read the support checklist. Are there :no&n -ugsG 2hen is the .e"t #eleaseG Usually, bugs get fixes as they are found. There is a release every few weeks. Here is the list of known and confirmed issues: When opening a database file in a timezone that has different daylight saving rules: the time part of dates where the daylight saving doesn't match will differ. This is not a problem within regions that use the same rules (such as, within USA, or within Europe), even if the timezone itself is different. As a workaround, export the database to a SQL script using the old timezone, and create a new database in the new timezone. This problem does not occur when using the system property "h2.storeLocalTime" (however such database files are not compatible with older versions of H2). Apache Harmony: there seems to be a bug in Harmony that affects H2. See HARNONY-6505. Tomcat and Glassfish 3 set most static fields (final or non-final) to null when unloading a web application. This can cause a NullPointerException in H2 versions 1.1.107 and older, and may still not work in newer versions. Please report it if you run into this issue. !n Tomcat >= 6.0 this behavior can be disabled by setting the system property org.apache.catalina.loader.WebappClassLoader.ENABLE_CLEAR_REFERENCES=false, however Tomcat may then run out of memory. A known workaround is to put the h2*.jar file in a shared lib directory (commonflib). Some problems have been found with right outer join. !nternally, it is converted to left outer join, which does not always produce the same results as other databases when used in combination with other joins. This problem is fixed in H2 version 1.3. When using !nstall+j before +.1.+ on Linux and enabling pack200, the h2*.jar becomes corrupted by the install process, causing application failure. A workaround is to add an empty file h2*.jar.nopack next to the h2*.jar file. This problem is solved in !nstall+j +.1.+. For a complete list, see Open !ssues. s this Database Engine 1pen SourceG Yes. !t is free to use and distribute, and the source code is included. See also under license. s Commercial Support A*ailableG Yes, commercial support is available, see Commercial Support. 177 of 180 Ho& to Create a .e& DatabaseG By default, a new database is automatically created if it does not yet exist. See Creating New Databases. Ho& to Connect to a DatabaseG The database driver is org.h2.Driver, and the database URL starts with jdbc:h2:. To connect to a database using JDBC, use the following code: Class.forName("org.h2.Driver"); Connection conn = DriverNanager.getConnection("jdbc:h2:~ftest", "sa", ""); 2here are the Database (iles StoredG When using database URLs like jdbc:h2:~ftest, the database is stored in the user directory. For Windows, this is usually C:Documents and Settings<userName> or C:Users<userName>. !f the base directory is not set (as in jdbc:h2:test), the database files are stored in the directory where the application is started (the current working directory). When using the H2 Console application from the start menu, this is <!nstallation Directory>fbin. The base directory can be set in the database URL. A fixed or relative path can be used. When using the URL jdbc:h2:file:datafsample, the database is stored in the directory data (relative to the current working directory). The directory is created automatically if it does not yet exist. !t is also possible to use the fully qualified directory name (and for Windows, drive name). Example: jdbc:h2:file:C:fdataftest 2hat is the Si<e !imit 4+a"imum Si<e5 of a DatabaseG See Limits and Limitations. s it #eliableG That is not easy to say. !t is still a quite new product. A lot of tests have been written, and the code coverage of these tests is higher than 80 for each package. Randomized stress tests are run regularly. But there are probably still bugs that have not yet been found (as with most software). Some features are known to be dangerous, they are only supported for situations where performance is more important than reliability. Those dangerous features are: Disabling the transaction log or FileDescriptor.sync() using LOG=0 or LOG=1. Using the transaction isolation level READ_UNCONN!TTED (LOCK_NODE 0) while at the same time using multiple connections. Disabling database file protection using (setting F!LE_LOCK to NO in the database URL). Disabling referential integrity using SET REFERENT!AL_!NTEGR!TY FALSE. !n addition to that, running out of memory should be avoided. !n older versions, OutOfNemory errors while using the database could corrupt a databases. This database is well tested using automated test cases. The tests run every night and run for more than one hour. But not all areas of this database are equally well tested. When using one of the following features for production, please ensure your use case is well tested (if possible with automated test cases). The areas that are not well tested are: Platforms other than Windows XP, Linux, Nac OS X, or JvNs other than Sun 1.6 or 1.7 The features AUTO_SERvER and AUTO_RECONNECT. Cluster mode, 2-phase commit, savepoints. 2+f7 operation. Fulltext search. Operations on LOBs over 2 GB. The optimizer may not always select the best plan. Using the !CU+J collator. Areas considered experimental are: The PostgreSQL server Clustering (there are cases were transaction isolation can be broken due to timing issues, for example one session overtaking another session). 178 of 180 Nulti-threading within the engine using SET NULT!_THREADED=1. Compatibility modes for other databases (only some features are implemented). The soft reference cache (CACHE_TYPE=SOFT_LRU). !t might not improve performance, and out of memory issues have been reported. Some users have reported that after a power failure, the database cannot be opened sometimes. !n this case, use a backup of the database or the Recover tool. Please report such problems. The plan is that the database automatically recovers in all situations. 2hy is 1pening my Database Slo&G To find out what the problem is, use the H2 Console and click on "Test Connection" instead of "Login". After the "Login Successful" appears, click on it (it's a link). This will list the top stack traces. Then either analyze this yourself, or post those stack traces in the Google Group. Other possible reasons are: the database is very big (many GB), or contains linked tables that are slow to open. +y Query is Slo& Slow SELECT (or DELETE, UPDATE, NERGE) statement can have multiple reasons. Follow this checklist: Run ANALYZE (see documentation for details). Run the query with EXPLA!N and check if indexes are used (see documentation for details). !f required, create additional indexes and try again using ANALYZE and EXPLA!N. !f it doesn't help please report the problem. H2 is 3ery Slo& By default, H2 closes the database when the last connection is closed. !f your application closes the only connection after each operation, the database is opened and closed a lot, which is quite slow. There are multiple ways to solve this problem, see Database Performance Tuning. Column .ames are ncorrectG For the query SELECT !D AS X FRON TEST the method ResultSetNetaData.getColumnName() returns !D, ! expect it to return X. What's wrong? This is not a bug. According the the JDBC specification, the method ResultSetNetaData.getColumnName() should return the name of the column and not the alias name. !f you need the alias name, use ResultSetNetaData.getColumnLabel(). Some other database don't work like this yet (they don't follow the JDBC specification). !f you need compatibility with those databases, use the Compatibility Node, or append ;AL!AS_COLUNN_NANE=TRUE to the database URL. This also applies to DatabaseNetaData calls that return a result set. The columns in the JDBC AP! are column labels, not column names. (loat is DoubleG For a table defined as CREATE TABLE TEST(X FLOAT) the method ResultSet.getObject() returns a java.lang.Double, ! expect it to return a java.lang.Float. What's wrong? This is not a bug. According the the JDBC specification, the JDBC data type FLOAT is equivalent to DOUBLE, and both are mapped to java.lang.Double. See also Napping SQL and Java Types - 8.3.10 FLOAT. 179 of 180 s the /C) 3ersion StableG (asterG The GCJ version is not as stable as the Java version. When running the regression test with the GCJ version, sometimes the application just stops at what seems to be a random point without error message. Currently, the GCJ version is also slower than when using the Sun vN. However, the startup of the GCJ version is faster than when using a vN. Ho& to Translate this %ro0ectG For more information, see BuildfTranslating. Ho& to Contribute to this %ro0ectG There are various way to help develop an open source project like H2. The first step could be to translate the error messages and the GU! to your native language. Then, you could provide patches. Please start with small patches. That could be adding a test case to improve the code coverage (the target code coverage for this project is 90, higher is better). You will have to develop, build and run the tests. Once you are familiar with the code, you could implement missing features from the feature request list. ! suggest to start with very small features that are easy to implement. Keep in mind to provide test cases as well. 180 of 180