1 / CUBRID Technical Training
Confidential
CUBRID Developer's Course
Author: Bomyung Oh
Team / Department: DBMS Development Lab
Author(2): Kyungsik Seo
Team / Department: DBMS Development Lab
2 / CUBRID Technical Training
ConfidentialComparison of the feature development speed with MySQL
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
3.23
4.0
5.05.1
R3.0R3.1
R2.0
R1.0
•Views•Triggers•Stored Procedure•AUTO_INCREMENT•Query Plan Cache•Query Result Cache•Replication•Partitioning•Click Counter
• Views• Triggers• Stored Procedures• AUTO_INCREMENT• Query Cache• Replication• Full Text Indexing
• Partitioning• Event scheduler• MySQL Cluster• XML Functions
4.1
• HA Feature• Hierarchical Query
5.4 5.5
• SQL Compatibility• CUBRID FBO
• CUBRID Cluster ClusterCUBRID
MySQL
R3.2
3 / CUBRID Technical Training
Confidential
Who are using CUBRID
Over 100,000 Downloads
4 / CUBRID Technical Training
Confidential
1. Introduction to CUBRID
Overview and Architecture of CUBRIDUsing CUBRID
Introduction to CUBRID HA
5 / CUBRID Technical Training
Confidential
1.1 Overview and Architec-ture of CUBRID
6 / CUBRID Technical Training
Confidential
What is CUBRID?
IntroductionCUBRID is a comprehensive open source relational database management system that is highly optimized for Web Applications, particularly those with Read-intensive transactions.
Koreahttp://dev.naver.com/projects/cubrid/http://www.cubrid.com/online_manual/cubrid_830/index.htmhttp://www.cubrid.comhttp://devcafe.nhncorp.com/g_cubrid
Globalhttp://www.cubrid.org/http://wiki.cubrid.org/index.php/CUBRID_Manuals/cubrid_2008_R3.0_manual
You Tubehttp://www.youtube.com/user/cubrid
7 / CUBRID Technical Training
Confidential
Middleware
DB Server
Application Client
DB Interface
CUBRID Architecture (Simplified)
A 3-tier structure that separates DB Servers from Brokers
Broker : DB Server = 1 : N is possible
DB Server 1
DataVolume1
Broker 1
WAS
JDBC
WAS
JDBC
Broker 2
DB Server 2
DataVolume2
JDBC driver
Java Apps
cub_cas
cub_master
cub_broker
cub_server
volume filevolume file
log filelog file
Broker port: 30000
Server port: 1523
connect
send_fd
connect
send_fd
cub_job
Manager port: 8001,8002
Query Edi-tor
CUBRID Manager
cub_job
cub_autoconnectServer port: 1523
cub_auto
8 / CUBRID Technical Training
Confidential
CUBRID Architecture (Detailed)
AdminUtility
Server
Broker
Interface
Parser ObjectManager
SchemaManager
TransactionManager
QueryTransform
QueryOptimizer
PlanGeneration
Workspace Manager
Memory Manager
Native C API
Communication Module
ConnectionPooling
Monitoring Logging
JDBC
JobQueuing
ODBCCCI PHP OLE DB PythonRuby
Client Library
Communication Module
TransactionManager
LogManager
LockManager
QueryManager
AccessMethod
B+TreeModule
File ManagerSystemCatalog Module
Buffer Manager
Disk Manager
DataVolume
IndexVolume
TempVolume
ActiveLog
ArchiveLog
Backup /Restore
CUBRIDManager
CUBRIDManager
GUI
CM Server
Create, Delete, Copy,
Rename
Load /Unload
Compact /Optimize
Add Volume
Check /Diag
File Based
Objects
9 / CUBRID Technical Training
Confidential
CUBRID Process (Detailed)
cub_cas
cubridcs.so
cub_cas
cubridcs.socsql
cubridcs.so
volume filevolume file
log filelog file
cub_master cub_server
cub_broker
JDBC driver
CCI library
mount(read/write)
descriptor pass
UDS
TCPrequest &response
register
databases.txt
read
cubrid.conf
port listening job queuemulti-thread
connect
parse
parse
port listeningquery &result
query &result
shared memory
descriptor pass
cubrid_broker.conf
parse
connect
fork
cub_admin
cubridsa.so
File
API
Process
Dynamic shared library
cubrid.so
10 / CUBRID Technical Training
Confidential
1.2 Using CUBRID
11 / CUBRID Technical Training
Confidential
Prerequisites for Installation
Check supported platforms(Linux/Windows)
Install JRE version 1.5 or higher and set up the environment variables
(CUBRID Manager)
Visual C++ 2008 distribution pack installation
Create DB users(multiple instances)
For Linux For Windows
uname –r rpm –qa | grep glibc
http://java.sun.com/javase/downloads/index.jsp
http://www.microsoft.com/downloads/details.aspx?displaylang=ko&FamilyID=9b2da534-3e03-4391-8a4d-074b9f2bc1bf
Download CUBRIDhttp://sourceforge.net/projects/cubrid
Install and launch CUBRID
12 / CUBRID Technical Training
Confidential
CUBRID Installation and Starting CUBRID Service
How to install CUBRID and start CUBRID Service in the Windows environment For detailed information, see the manual provided at the following link:. Run the
exe file to start the installation wizard.http://www.cubrid.org/manual/gs/gs_install_windows.htm
Starting CUBRID Service in the CUBRID tray
How to install CUBRID and start CUBRID Service in the Linux environment For detailed information, see the manual provided at the following link:
http://www.cubrid.org/manual/gs/gs_install_linux.htm
Starting CUBRID Service (CUBRID-related processes must be started)For detailed information, see the manual provided at the following link: http://www.cubrid.org/manual/gs/gs_must_svcstart.htm
Start the CUBRID service by using the following command:
% sh CUBRID-8.3.0.0312-linux.x86_64.sh% . /home1/cub_user/.cubrid.sh
% cubrid service start
13 / CUBRID Technical Training
Confidential
DB Creation and DB Start
How to create a new DB and start itFor detailed information, see the manual provided at the following link:http://www.cubrid.org/manual/admin/admin_db_create_create.htm
– Creating testdb and starting it with a command
Starting an existing DB (demodb is included in the installation of CUBRID, by default)For detailed information, see the manual provided at the following link: http://www.cubrid.org/manual/gs/gs_must_svcstart.htm
– Creating demodb and starting it with a command
% cubrid createdb testdb
% cubrid server start testdb
% cubrid server start demodb
14 / CUBRID Technical Training
Confidential
CUBRID Manager - Configuration
Java-based GUI tools JRE/JDK version 1.6 or higher is required CUBRID Manager is a tool used to control the functions of servers and brokers, and to monitor and analyze logs CUBIRD Manager consists of the search pane to the left, the query edit pane to the right, the top menu, and the
toolbar
15 / CUBRID Technical Training
Confidential
CUBRID Manager – start
Start CUBRID Manager
insert host connection information(Default manager account
ID: admin / PW: admin)
Start CUBRID Server
insert DB connection information
(Default DB accountID: dba / PW: No password)
Start DB Server
Execute queries
16 / CUBRID Technical Training
Confidential
Disconnect from the host
Stop DB Server
Stop CUBRID Manager
CUBRID Manager - stop
17 / CUBRID Technical Training
Confidential
1.3 Introduction to CUBRID HA
18 / CUBRID Technical Training
Confidential
Introduction to CUBRID HA
Replication
No-Automatic Fail-over No-Automatic Sync
HA
Automatic Fail-over Automatic Sync
19 / CUBRID Technical Training
Confidential
HA Configuration and Usage – DB Server Redundancy
Replication
ActiveServer
StandbyServer
Broker #2Broker #1
APWeb Server
APWeb Server
Fail-over Fail-back
Automatic failover
Automatic failover
Node Fail
20 / CUBRID Technical Training
Confidential
HA Configuration and Usage – Broker Redundancy
Replication
ActiveServer
StandbyServer
Broker #2Broker #1
APWeb Server
APWeb Server
Automatic failover
JDBC DriverCCI Library
Fail-over Fail-back
Node Fail
21 / CUBRID Technical Training
Confidential
Diagram of HA Architecture (Detailed)
active logarchive logs
A-NodeActive Server Node
A-node’sactive & archive logs
ServerActive
ReplicaStandby
active logarchive logs
S1-NodeStandby Server Node
coyplogdb
S1-node’sactive & archive logs
Update Select
applylogdb coyplogdbapplylogdb
#Configurations#
A-node & S1-node’s <cubrid.conf>ha_mode=yesha_node_list=hagrpname@A-node:S1-node
A-node & S1-node’s <cubrid-ha>CUBRID_USER=usernameDB_LIST=‘dbname‘
broker node’s <databases.txt>dbname vol_path A-node:S1-node log_path
#Configurations#
#A-Node’s log pathS1-Node’s active & archive logs = $CUBRID_DATABASES/database-name_S1-Node-hostname(ex. /home1/cubrid1/DB/tdb01_Snode1)copylogdb & applylogdb error logs = $CUBRID/log
#S1-Node’s log pathA-Node’s active & archive logs = $CUBRID_DATABASES/database-name_A-Node-hostname(ex. /home1/cubrid1/DB/tdb01_Anode1)copylogdb & applylogdb error logs = $CUBRID/log
Sync
Semi-Sync
Async
Replication Log is includedReplication Log is not included
22 / CUBRID Technical Training
Confidential
2. CUBRID Architecture
CUBRID Volume StructureCUBRID Parameters
Broker ParametersError Log File
System Catalog
23 / CUBRID Technical Training
Confidential
2.1 CUBRID Volume Structure
24 / CUBRID Technical Training
Confidential
CUBRID Volume Structure
OS CUBRID
Disk (Volume) X
File Volume
Pages File(*)
Page Page
* : The table is mapped to a CUBRID file. **: A CUBRID file can be separated to multiple CUBRID volumes.
File_1 File_2 File_3 Free_Pages
Volumes
25 / CUBRID Technical Training
Confidential
DB Volume Structure
26 / CUBRID Technical Training
Confidential
DB Volume – Information Volume
Information Volumes Data volume
Saves the data of an application, such as tables or records A record storage file, called heap, is created in a data volume
Index volume A volume in which B+Tree indexes are saved for faster data access or
queries Temp volume
A volume in which intermediate results are saved to fetch result sets that exceed the size of the memory buffer, or to execute join queries
A temporary volume with an appropriate size must be created when creating a DB volume.
This is a permanent volume that is used for temporary purposes, and is dif-ferent from temporary volumes that are used only temporarily.
Generic volume The initial volume during DB creation, which can be used as the data, index,
or temp volume. If the usage of the volume (data, index, or temporary) is not specified, it can
be used for general purposes.
27 / CUBRID Technical Training
Confidential
DB Volume – Log Volume
Log Volumes The active log volume includes the most recent updates that have been applied to a
database. Records the status of a committed, aborted, or active transaction. It is used to recover a DB from a storage media failure. When the space allocated to an active log is completely used up, the content of the
active log will be copied to and stored in a new log (archive log).
• Example: demodb_lgat(active log), demodb_lgar*(arcive log)
28 / CUBRID Technical Training
Confidential
DB Volume – Control Volume
Control Information Volumes Volume Information
Includes the location information on DB volumes to be created or added This file cannot be manually modified, deleted, or moved. The name of the file is in {dbname}_vinf format.
Log Information Records the information of the current logs and archive logs Records the information on a new archive log file and unnecessary archive log
file. The name of the file is in {dbname}_lginf format
-5 C:\CUBRID\databases\demodb\demodb_vinf
-4 C:\CUBRID\databases\demodb\demodb_lginf
-3 C:\CUBRID\databases\demodb\demodb_bkvinf
-2 C:\CUBRID\databases\demodb\demodb_lgat
0 C:\CUBRID\databases\demodb\demodb
1 C:\CUBRID\DATABA~1\demodb\demodb_x0010
COMMENT: CUBRID/LogInfo for database /CUBRID/databases/demodb
ACTIVE: /CUBRID/databases/demodb_lgat 5000 pages
ARCHIVE: 0 /CUBRID/databases/demodb_lgar000 0 4997
COMMENT: Log archive /CUBRID/databases/demodb_lgar000 is not needed any longer unless a
database media crash occurs.
29 / CUBRID Technical Training
Confidential
DB Volume – Backup Volume
Backup Volume Information Records the location and backup information of a backup volume Located in the same path in which log files are stored. The name of the file is in {dbname}_bkvinf format.
0 0 /Backup/demodb_bk000 0 level full backup of the first file. 0 1 /Backup/demodb_bk001 0 level full backup of the second file. 1 0 /Backup/demodb_bk100 1 level incremental backup of the first file. 2 0 /Backup/demodb_bk200 2 level incremental backup of the first file.
Backup levelinformation
The path informa-tion of a backup
file
The sequence number of a
backup volume per level
30 / CUBRID Technical Training
Confidential
DB Volume – $CUBRID/conf/databases.txt
databases.txt Contains the name, path, and the name of the built host of a DB. Records the information related to the DB that is created in the databases.txt file upon
the creation of a DB. Saved to the path in which the $CUBRID_DATABASES environment variables are speci-
fied. If it does not exist in the directory specified by the environment variable, the current
directory will be used instead. Caution
If a host name has been changed or a DB deleted by an OS command, this file must be modified as well.
As the user must be able to modify the databases.txt file during DB creation or deletion, the user must have the privilege to write to this file. If a user without the appropriate privilege attempts to create a DB, the DB creation will fail. For this reason, a DBA should enable the user-write privilege for the directory, or create a databases.txt file in the directory of each user and configure the environment variables.
demodb /CUBRID/databases/demodb hostname /CUBRID/databases/demodb
DB name DB path Host name DB log path
31 / CUBRID Technical Training
Confidential
DB Volume Management
Distributes according to usage to avoid the disk bottlenecks Distributes data, index, temp, and log volume so that they are separated from each
other Avoids the disk bottlenecks and improves disk management
Distributes volumes that can be used simultaneously data & log, data & index, data & temp
Configures a volume to an appropriate size to prevent it from adding more volumes while in service Data, Index, Temp, Active Log: Page size and the number of pages must be consid-
ered Backup: Backs up with the -r option, and then deletes unnecessary archive logs
disk1 disk2 disk3
db1 db1_logdb1_temp db1_data db1_index db_backup
An example of volume configuration
32 / CUBRID Technical Training
Confidential
2.2 CUBRID Parameters
$CUBRID/conf/cubrid.conf
33 / CUBRID Technical Training
ConfidentialEnvironment Configuration File - $CUBRID/conf/cubrid.conf
cubrid.conf A file in which the value of CUBRID system parameters are saved. The file is located in a subdirectory of $CUBRID/conf . You are recommended to specify
different values from one DB to another DB in the DB.
There are two types of parameters: DB server parameters and DB client parameters. If a parameter has been changed in a process, that process must be restarted.
SQL is used to change a client parameter. Syntax for configuring parameters
Case-insensitive The name and value of a parameter must be inserted on the same line. An equals sign (=) can be used, and a blank character can be added at both sides
of the sign.. If the value of a parameter is a string, insert the string without quotation marks. If
a blank character is included in the string, encase it with quotation marks.
[commom]data_buffer_pages=250000
[demodb]data_buffer_pages=500000
34 / CUBRID Technical Training
Confidential
Higher in priority than the configuration of cubrid.conf Add CUBRID_ at the beginning of the parameter to configure it as an environment
variable
Configuring with an SQL statement Only client parameters can be configured Use “;” for multiple configurations
set CUBRID_SORT_BUFFER_PAGE=512
SET SYSTEM PARAMETERS 'parameter_name=value [{; name=value}...]‘
SET SYSTEM PARAMETERS 'csql_history_num=70’
SET SYSTEM PARAMETERS 'csql_history_num=70; index_scan_in_oid_order=1'
Environment Configuration File - $CUBRID/conf/cubrid.conf
35 / CUBRID Technical Training
Confidential
Memory Related Configurations
data_buffer_pages The number of data pages cached to the memory by a DB server Requires an amount of memory equivalent to num_data_buffers times
database page size (the page size specified when the DB is initialized; de-fault is 4KB). (The size of the required memory is 100MB if the default is 25,000)
The actual size of a DB, the size of the memory, and the number and size of other processes must be considered when determining the size
The larger the value, the more data needs to be cached to the memory, which means less disk I/O. However, a value that is too large will cause the full swapping of page buffers.
index_scan_oid_buffer_pages Configure the number of buffer pages in which the OID list is to be tempo-
rarily stored when scanning indexes The default value is 4, (0.05~16).
36 / CUBRID Technical Training
Confidential
Memory Related Configurations
sort_buffer_pages The number of pages used to process queries that require sorting. One sort buffer is allocated to each active client request. The allocated memory is released upon the completion of sorting. A value between 16 and 500 is recommended.
temp_file_memory_size_in_pages Determines the number of buffer pages that cache the temporary results of
a query The default value is 4, and the maximum value is 20.
37 / CUBRID Technical Training
Confidential
Log Related Configurations
checkpoint_interval_in_mins, checkpoint_interval_in_npages Configures the interval of a checkpoint execution in min./page The larger the value, the more time it takes to recover a DB.
media_failure_support Configures whether to keep an archive log in the event of a storage media
failure If it is configured to the default value (yes), all active logs will be copied to
and stored in an archive log when changes are made to a transaction while the active logs are full.
Please note that any archive logs which have been created while active logs that are full will be deleted if this value is no.
38 / CUBRID Technical Training
Confidential
isolation_level A parameter used to manage transaction concurrency It must be an integer from 1 to 6 or a character string (Default: 3) The larger the value of the parameter, the lower the concurrency
SERIALIZABLE: Inaccessible until transaction is complete REPEATABLE: S_LOCK is maintained until the transaction is complete at SELECT READ UNCOMMITTED: Allows incomplete transactions to be read READ COMMITTED: Allows only completed transactions to be read
On Concurrency Control and Locking
CUBRID isolation level MySQL isolation levelDirtyread
Non-re-peatableread
Phantom read
"TRAN_SERIALIZABLE" or 6 SERIALIZABLE (4) N N N
"TRAN_REP_CLASS_REP_INSTANCE" or "TRAN_REP_READ" or 5 REPEATABLE READ (3) N N Y
"TRAN_REP_CLASS_COMMIT_INSTANCE" or "TRAN_READ_COMMITTED" or "TRAN_CURSOR_STABILITY" or 4 READ COMMITTED (2) N Y Y
"TRAN_REP_CLASS_UNCOMMIT_INSTANCE" or "TRAN_READ_UNCOMMITTED" or 3 READ UNCOMMITTED (1) Y Y Y
"TRAN_COMMIT_CLASS_COMMIT_INSTANCE" or 2 N Y Y
"TRAN_COMMIT_CLASS_UNCOMMIT_INSTANCE" or 1 Y Y Y
39 / CUBRID Technical Training
Confidential
Configurations Related to Concurrency and Lock
deadlock_detection_interval_in_secs Configures the interval, in seconds, of deadlock detection for stopped trans-
actions. Resolves deadlock by rolling back one of the deadlocked transactions The default value is 1sec. Be sure not to set the interval to a large number,
as doing so will allow deadlocks remain undetected for that length of time.
lock_escalation Converts to table lock if the number of row locks belonging to a table is
greater than the specified value. The default value is 100,000. If this value is small, the table management overhead will be reduced, but
the concurrency will be decreased. If this value is large, the table management overhead is will be increased,
but the concurrency will be improved.
lock_timeout_in_secs Specifies the waiting time of a lock If the lock has not been allowed within the specified period of time, the
transaction is cancelled, and an error is returned. The default value is -1, in which case the wait time is unlimited. If it is 0,
there is no wait time.
40 / CUBRID Technical Training
Confidential
Configurations Related to Query Caches
max_plan_cache_entries Configures the maximum number of query plans to be cached to the mem-
ory (Default: 1,000) If this value is lower than 1, it will not work - it works only when the value is
at least 1.
Configures the hint so that query execution plans are created without using cache
• Use /*+ RECOMPILE +/ in queries
– select /*+ RECOMPILE */ * from record where …
41 / CUBRID Technical Training
Confidential
Configurations Related to Syntax and Type
block_ddl_statement Limits Data Definition Language (as known as DDL) The default value should not be no.
block_nowhere_statement It does not execute queries if there are no WHERE clauses in an UPDATE/
DELETE statement. The default value should not be no.
single_byte_compare When comparing strings, set it so that it will compare the strings by a single
byte.When using Unicode, set it to Yes (for UTF-8). Default: no
42 / CUBRID Technical Training
Confidential
Other Parameters
Parameters related to communication services cubrid_port_id
Master Process Port The default value is 1523 If 1523 is already in use, the parameter must be changed to another
port number.
Client/server request-related max_clients
This number represents maximum number of DB clients that can be connected to a DB server at the same time, which by extension also means the total number of concurrent transactions. (Default value: 50)
The actual number of concurrent users must be considered
DB Server restart configuration auto_restart_server
Automatically restarts a DB server that has been stopped due to a fail-ure
The default value when restarting the DB is yes. In the HA, the default value is no.
43 / CUBRID Technical Training
Confidential
Other Parameters
Parameters related to transaction processing
async_commit Enables the asynchronous commit function (Default value: must not be
set to no) Returns a commit to a client before the commit log is flushed to a disk When a failure occurs in a DB server, all commit transactions that have
not been flushed to a disk will not be able to be recovered.
group_commit_interval_in_msecs Collects commits that have occurred during the setting in a group, and
executes them (Default value: no need to configure) Improves performance by collecting commit logs and flushing them to a
disk
44 / CUBRID Technical Training
Confidential
2.3 Broker Parameters
$CUBRID/conf/cubrid_broker.conf
45 / CUBRID Technical Training
ConfidentialBroker Environment Configuration - $CUBRID/conf/cubrid_broker.conf
Modifying environment configuration Configuration file: $CUBRID/conf/cubrid_broker.conf The file can be modified in an editor. Any changes made will be applied
when the Broker restarts. To modify the configuration without a restart, use the following command:
Configurable environment variables APPL_SERVER_MAX_SIZE, SQL_LOG, TIME_TO_KILL SESSION_TIMEOUT, KEEP_CONNECTION
If an environment variable and its value are incorrect, an error will occur during the restart, which will prevent the restart.
% broker_changer <br-name> <conf-name> <conf-value>
% broker_changer broker1 sql_log on
OK
46 / CUBRID Technical Training
Confidential
Introduction to Broker Parameters
Parameter name Description Value
MASTER_SHM_IDA parameter that specifies the share memory no., which is nec-essary for the general operation of a Broker.The value should be a unique value in a system.
30001(int)
ADMIN_LOG_FILESpecifies the location and name of an admin log file (in which CUBRID CAS start/stop/restart/etc. are recorded)
log/admin.log(char)
<Broker name>(Broker name)
Specifies the unique name of a Broker.Specify the name immediately after the percentile mark ("%") . The name is case-insensitive.
BROKER1(char)
SERVICEDetermines whether to start the BROKER when starting CUBRID CAS
ON / OFF
BROKER_PORT(Broker Port)
Specifies the port no. of a Broker. The number must be unique in a system, as applications such as JDBC, ODBC, etc. communicate through it.If a firewall has been configured in the system, the port must be open.In Windows, the CAS ports of a Broker are created in the order of “Broker port+1”.
30000(int)
47 / CUBRID Technical Training
Confidential
Introduction to Broker Parameters
Parameter name Description Value
APPL_SERVER_SHM_IDThe key value of the shared memory, which is used by the Broker and the CAS of the group
30000(int)
MIN_NUM_APPL_SERVER(AS Minimum)
The initial number of CASs (the number of CASs that will be started at the initial startup)
5(int)
MAX_NUM_APPL_SERVER(AS Maximum)
Specifies the maximum number of CASs to be increased40(int)
APPL_SERVER_ MAX_SIZE Specifies the allowed process size of CAS in MB 20(int)
LOG_DIRSpecifies a directory in which an access log will be recorded
log/broker(char)
ERROR_LOG_DIRSpecifies a directory in which an error log will be recorded
log/broker/error_log(char)
SQL_LOGDetermines whether or not to leave the record of trans-actions that are processed by CAS
ON / ERROR / TIMEOUT / NO-TICE / OFF
48 / CUBRID Technical Training
Confidential
Introduction to Broker Parameters
Parameter name Description Value
TIME_TO_KILL
Automatically rolls back the CASs that have been increased beyond the initial
number when they do not receive a request for a specified amount of time (in
seconds).
60(int)
SESSION_TIMEOUT
When there is a request for transaction processing, the same CAS processes
the transaction from the beginning to the end (commit/rollback). If there are no
requests for a specific period of time, the transaction is forcibly rolled back.
If this value is set to -1, the CAS will wait for an unlimited amount of time with-
out rolling back the transaction.
300(int)
KEEP_CONNECTION
Specifies the mode of connection between CAS and a client
There are three modes available: ON - Connects to the client by connection
unit. OFF - Connects to the client by transaction unit. AUTO - Works in the same
manner as ON when the number of CASs exceeds the number of clients, or in
the same manner as OFF when the number of clients exceeds the number of
CASs.
ON/OFF/ AUTO
STATEMENT_POOLING
Determines whether or not to support CAS according to the use of statement
pooling in Apache DBCP. If this parameter is ON, all handles of CAS will be
reused upon commit.
ON / OFF
49 / CUBRID Technical Training
Confidential
2.4 Error Log File
$CUBRID/log/$CUBRID/log/server/$CUBRID/log/broker/$CUBRID/log/broker/sql_log$CUBRID/log/broker/error_logCUBRRENT_DIRECTORY, $HOME
50 / CUBRID Technical Training
ConfidentialBroker Log File – Connection Log$CUBRID/log/broker/
Checking connection log The connection log is a record of the time it takes for each CAS to process a
request by Broker. This log has the name of "<broker name>.access" and resides in a direc-
tory specified in the ACCESS_LOG of cubrid_broker.conf.
1 192.168.100.201 - - 1158198049.151 1158198049.246 2008/09/14 10:40:49 ~ 2008/09/14 10:40:49
29438 - -1
2 192.168.100.201 - - 1158198049.401 1158198049.406 2008/09/14 10:40:49 ~ 2008/09/14 10:40:49
29438 - -1
Value Description
1 The CAS ID
192.168.1.201 The IP address of a client that has sent a request
1158198049.151 1158198049.246The timestamp for the request time and the roll back time
2008/09/14 10:40:49 ~ 2008/09/14 10:40:49
The receipt and roll back time of a request
29438 The process ID of the CAS
- -1 or ERR 1025-If - -1, processes without an errorIf an error occurs, specifies the offset of the error log as "ERR."
51 / CUBRID Technical Training
ConfidentialBroker Log File – Error Log$CUBRID/log/broker/error_log
Checking error log Records the information about an error that has occurred while processing
the request from an application client into the broker_name_app_server_num.err file
Time: 02/04/09 13:45:17.687 - SYNTAX ERROR *** ERROR CODE = -493, Tran =
1, EID = 38
Syntax: Unknown class "unknown_tbl". select * from unknown_tbl
Value Description
Time: 02/04/09 13:45:17.687 The time at which the error has occurred
SYNTAX ERROR The type of the error
ERROR CODE = -493 The error code
Tran = 1 The transaction ID
EID = 38
The error IDWhen an error occurs while processing an SQL state-ment, this ID is used to search for the SQL log that is re-lated to the error log of a DB server or a DB client
Syntax:… The error message
52 / CUBRID Technical Training
ConfidentialBroker Log File – SQL Log$CUBRID/log/broker/sql_log
SQL log The SQL log file records the SQL that an application client requests, and is
saved under the name of "broker_name_app_server_num.sql.log."
02/04 13:45:17.687 (38) prepare 0 insert into unique_tbl values (1)
02/04 13:45:17.687 (38) prepare srv_h_id 1
02/04 13:45:17.687 (38) execute srv_h_id 1 insert into unique_tbl values (1)
02/04 13:45:17.687 (38) execute error:-670 tuple 0 time 0.000, EID = 39
02/04 13:45:17.687 (0) auto_rollback
02/04 13:45:17.687 (0) auto_rollback 0
*** 0.000
02/04 13:45:17.687 (39) prepare 0 select * from unique_tbl
02/04 13:45:17.687 (39) prepare srv_h_id 1 (PC)
02/04 13:45:17.687 (39) execute srv_h_id 1 select * from unique_tbl
02/04 13:45:17.687 (39) execute 0 tuple 1 time 0.000
02/04 13:45:17.687 (0) auto_commit
02/04 13:45:17.687 (0) auto_commit 0
*** 0.000
• The time at which the application sent the re-
quest
• (39) : The sequence number of the SQL state-
ment group, for prepared statement pooling
• (PC) : Uses the content stored in the plan cache
• SELECT... : The SQL statement to be executed.
- When pooling statements, the binding vari-
able of the WHERE clause is displayed as ?.
• Execute 0 tuple 1 time 0.000
- One row is executed, which takes 0.000 sec-
onds.
• auto_commit/auto_rollback
- It signifies that the target will either be com-
mitted automatically or rolled back
- The second auto_commit/auto_rollback is
an error code. 0 signifies that the transaction
has been completed without an error.
53 / CUBRID Technical Training
Confidential
2.5 System Catalog
54 / CUBRID Technical Training
Confidential
Catalog Information
Provides schema information access through SQL Table information
db_class Important fields: class_name and owner_name
Column information db_attribute
Important fields: class_name, attr_name, and attr_type Other
db_vclass db_index db_index_key db_trig db_partition db_stored_procedure db_auth
55 / CUBRID Technical Training
Confidential
Catalog Information – Checking Table Information
Searching for table information in the catalog (db_class)
Searching for table information in the catalog (db_index)
56 / CUBRID Technical Training
Confidential
3. CUBRID SQL
Types, Operators, and FunctionsComparison of Major SQLs
Query Plans and Hints
57 / CUBRID Technical Training
Confidential
3.1 Types, Operators, and Functions
58 / CUBRID Technical Training
Confidential
CUBRID Identifiers
Item CUBRID MySQL
DB nameUnique within a domainCase-sensitive X
Unique within a domainCase-sensitive O
Table nameUnique within a DBCase-sensitive X
Unique within a DBCase-sensitive O
Column nameUnique within a tableCase-sensitive X
Unique within a tableCase-sensitive X.
Index nameUnique within a tableCase-sensitive X
Unique within a tableCase-sensitive X.
Identifier creation rules
An identifier must start with a character Space (“ “) X Can include special characters that are not opera-tors, and numbers
Space (“ “) XCannot include “\”, ”/”, or “.”
When using a re-served word as a identifier
Use double quotation marks (“”), a backtick(“`“), or brackets ([ ])
Use double quotation marks (“”), or backtick (“`”)
StringsUse a single quotation mark ( ‘ )Use a double quotation mark ( “ ) (ansi_quotes=no)
Use a double quotation mark (“)
For comments --. //, /* */
BLOB/CLOB Storage Supported in CUBRID2008 R3.1 or higherThe data stored on another data page
59 / CUBRID Technical Training
Confidential
MySQL Type Name CUBRID Type Bytes Description
BIT( n) BIT(n)
BINARY(M) BIT VARYING(n)
VARBINARY(M) BIT VARYING(n)
BOOL, BOOLEAN Not supported Replace it with BIT or SMALLINT
Numeric type [UN-SIGNED]
Not supported
TINYINT Replace it with SMALL-INT
2 TINYINT 1 byte, SMALLINT 2 bytes
SMALLINT[(M)] SMALLINT 2
MEDIUMINT[(M)] Replace it with INT 4 MIDIUMINT 3 bytes, INT 4 bytes
INT, INTEGERINT(M)
INT, INTEGERReplace it with INT
4INT 4 bytes
BIGINT[(M)] BIGINT 8 BIGINT 8 bytes
FLOAT(n) FLOAT(n) 4MySQL: 1<=n<=53CUBRID: 1<=n<=38
DECIMAL(p,s)NUMERIC(p,s)
DECIMAL(p,s)NUMERIC(p,s)
16MySQL: 1<=p<=65 , 0<=s<=30CUBRID: 1<=p<=38 , 0<=s<=p
DOUBLE[(M,B)] DOUBLE 8
CUBRID Data Types
60 / CUBRID Technical Training
Confidential
MySQL Type Name CUBRID Type Format Description
DATE DATE '10/31/2008' Unit: days
DATETIME DATETIME '01:15:45.000 PM 10/31/2008'
Unit: milliseconds
TIMESTAMP[(M)] TIMESTAMP '01:15:45 PM 10/31/2008' Unit: seconds
TIME TIME '01:15:45 PM' Unit: seconds
YEAR[(2|4)] Not supportedReplace it with CHAR(4)
CHAR(M) CHAR(n)
VARCHAR(M) VARCHAR(n)
TINYBLOBBLOBMEDIUMBLOBLONGBLOB
BLOB Supported in higher versions than CUBRID 2008 R3.1
TINYTEXTTEXTMEDIUMTEXTLONGTEXT
Replace it with VARCHAR(n) oth CLOB
Supported in higher versions than CUBRID 2008 R3.1
ENUM('value1','value2',...)
Not supported
SET('value1','value2',...) Not supported
CUBRID Data Types
61 / CUBRID Technical Training
Confidential
CUBRID Operators
MySQL Type CUBRID Type Description
AND, &&OR, ||XORNOT, !
AND, &&OR, ||XORNOT, !
Same as logical operators
IS NOT NULLIS NOTIS NULLIS=<=><>, !=>>=<<=
IS NOT NULLIS NOTIS NULLIS=<=><>, !=>>=<<=
Same as comparison operators
+- */, DIV%, MOD
+- */, DIV%, MOD
Same as arithmetic operators
&|^~<<>>
&|^~<<>>
Same as bit operators
REGEXPRLIKE
Not supported
62 / CUBRID Technical Training
Confidential
CUBRID Functions(2008 R3.0 based)MySQL CUBRIDABS ABS ACOS ACOSASCII ASCIIASIN ASINATAN ATANATN2 ATN2AVG AVG BIT_LENGTH BIT_LENGTH CEILING CEIL CHAR CHR CHAR_LENGTH CHAR_LENGTH COALESCE COALESCE CONCAT CONCATCOS COSCOT COTCOUNT COUNTCURRENT_DATE CURRENT_DATE
CURRENT_TIME CURRENT_TIME
DATE_ADD DATE_ADDDATEDIFF DATEDIFFDECODE DECODE DEGREES DEGREESDIV DIVFIELD FIELD
MySQL CUBRIDFLOOR FLOOR FORMAT FORMATGREATEST GREATEST GROUP_CONCAT GROUP_CONCATIFNULL IFNULLINSTR INSTR LAST_DAY LAST_DAY LEAST LEAST LEFT LEFTLN LNLOAD_FILE LOCATELOCATE LOCATELOG LOGLOG10 LOG10LOG2 LOG2LOWER,LCASE LOWER,LCASELPAD LPAD LTRIM LTRIM MAX MAX MID MIDMIN MIN MOD MOD NOW NOWNULLIF NULLIF PI PIPOWER POWERRADIANS RADIANS
63 / CUBRID Technical Training
Confidential
CUBRID FunctionsMySQL CUBRID
RAND DRANDOM
REPLACE REPLACE
REVERSE REVERSE
RIGHT RIGHT
ROUND ROUND
RTRIM RTRIM
SIGN SIGN
SIN SIN
SQRT SQRT
STD STDDEV
SUBSTRING SUBSTRING
SUM SUM
TAN TAN
TRIM TRIM
TRUNCATE TRUNCATE
UCASE,UPPER UCASE,UPPER
VARIANCE VARIANCE
MySQL CUBRID
CONV Not supported
CRC32 Not supported
DATENAME Not supported
DAY Not supported
ELT Not supported
FIND_IN_SET Not supported
INSERT Not supported
MAKE_SET Not supported
MONTH Not supported
NCHAR Not supported
NOT REGEXP Not supported
REPEAT Not supported
REPLICATE Not supported
RLIKE Not supported
SPACE Not supported
SQUARE Not supported
UNICODE Not supported
YEAR Not supportedNot supported INCR Not supported MONTHS_BETWEEN Not supported NVL2
64 / CUBRID Technical Training
Confidential
3.2 Comparison of Major SQLs
65 / CUBRID Technical Training
Confidential
Cautions regarding CUBRID SQL Does not support implicit type conversion.
Cannot process quotation marks in numeric data.
Does not support character sets. Saves and displays the character set configured in an application as it is. Can specify a character set via the JDBC connection url.
Does not support multi-byte characters. Column sizes must be defined to allow sufficient space for multi-byte charac-ters. The length or position value in a string function is processed byte by byte.
Functions for joining DBs are not supported.
Cannot change the column size by using the ALTER TABLE statement. This will be fixed in a future version.
If the prepare statement pooling is used, only one result set can be handled per connection. It is recommended to open multiple connections for use.
66 / CUBRID Technical Training
Confidential
Join Query
SELECT select_listFROM TABLE1 T1
INNER JOIN TABLE2 T2 ON T1.COL1 = T2.COL2WHERE T1.A = 'test' AND T2.B = 1;
CUBRID
Inner Join, Outer Join (Full outer Join is not supported), Cross Join, Self JoinIt is recommended to write query statements in compliance with the ANSI-92 stan-dard, which specifies the join condition in the ON clause.If there are columns that have the same name in a join target table, you must spec-ify the table name in the select_list. If it is not specified, ERROR: Reference to id is ambiguous. will occur.
SELECT select_listFROM TABLE1 T1
LEFT OUTER JOIN TABLE2 T2 ON T1.COL1 = T2.COL2 AND T2.B=1WHERE T1.A = 'test';
[Inner] Join
Left [Outer] Join
67 / CUBRID Technical Training
Confidential
Pagination(LIMIT RESULT SET)
SELECT select_list FROM TABLE1 T1WHERE T1.A = 'test' AND ROWNUM <= 100ORDER BY ORDER_COLUMN;
CUBRID
Processes a page by using ROWNUM, ORDERBY_NUM(), and LIMIT ROWNUM<=n: Gets a number of 'n' results that satisfy the condition and then ap-plies ORDER BY or GROUP BY ORDERBY_NUM() <=n : Displays only a number of 'n' results from the ORDER BY re-sults LIMIT 1, n: Displays only a number of 'n' results from the final result
ROWNUM
SELECT select_list FROM TABLE1 T1WHERE T1.A = 'test' ORDER BY ORDER_COLUMNFOR ORDERBY_NUM() <= 100;
ORDERBY_NUM()
SELECT select_list FROM TABLE1 T1WHERE T1.A = 'test' ORDER BY ORDER_COLUMNLIMIT 1,100;
LIMIT (from R3.0)
68 / CUBRID Technical Training
Confidential
AUTO_INCREMENT and SERIAL
MySQL
Creates a sequence value by using AUTO_INCREMENT If a transaction has been rolled back, pre-created values can be reused. Only one AUTO_INCREMENT column can be used per table. An index must be configured in the AUTO_INCREMENT column.
CUBRID
Creates a SERIAL object, or creates a sequence value by using AUTO_INCREMENT Even if the transaction has been rolled back, pre-created values are not reused.(there are no duplicates, and discontinuity is allowed.) SERIAL can be used in multiple tables, as it is an object separate from a table. Sup-ports the memory cache function Multiple AUTO_INCREMENT columns can be used in a table It is not necessary to configure an index in the AUTO_INCREMENT column
CREATE SERIAL SERIAL_NAME START WITH 1 MAXVALUE 1000 NOCYCLE;CREATE TABLE TABLE1( seqnum INT,
name VARCHAR); INSERT INTO TABLE1 VALUES (SERIAL_NAME.next_value, 'test'); //seqnum=1
SERIAL
CREATE TABLE TABLE1( seqnum INT AUTO_INCREMENT(1,1000) NOT NULL,name VARCHAR);
INSERT INTO TABLE1 (name) VALUES ('test'); //seqnum=1
AUTO_INCREMENT
69 / CUBRID Technical Training
Confidential
INDEX
MySQLThe performance of indexes is low because the Key Filter function is not provided (for InnoDB)
CUBRID
The performance of indexes is high because the Key Filter function is provided. No un-necessary scans will occur. -> When processing the WHERE clause, excludes records that will not be scanned at the index level by using filtering.Supports the multiple column sorting index (col1 ASC, col2 DESC)
CREATE INDEX on TABLE1(zipcode,lastname,address);SELECT * FROM TABLE1 WHERE zipcode=1000 AND name LIKE '%test%' AND address LIKE '%seoul‘;
CUBRID internal process: Step 1: Searches for a target in which zipcode=1000 at the index level Step 2: Extracts targets that satisfy the name and address conditions by accessing them at the data level.(In contrast, MySQL accesses all the data in which zipcode=1000 at the data level, and then extracts the data that satisfy the other conditions.)
INDEX usage tips: The smaller the size of an index key, the better the performance. Configure an index for columns with a good distribution (narrow range), basic keys, and columns which are the connection point for a join. When configuring indexes, use columns that are infrequently updated.
70 / CUBRID Technical Training
Confidential
SELECT/UPDATE/DELETE...USING INDEX {NONE | index_name[(+)],…};
Index Definition and Using USING INDEX
CREATE [ UNIQUE ] INDEX [ index_name ]
ON table_name ( column_name[(prefix_length)] [ASC | DESC] [ {, column_name[(prefix_length)] [ASC | DESC]} ...] ) [ ; ]
The UNIQUE index creates an index that is used for uniqueness constraints. If no index name has been specified, it will be automatically created. You can define an index only for the front part of a character string (Prefix Index)
Index names are distinguished by table and are used as table_name.index_name. Scans indexes only when the cost of index scan specified in the USING INDEX clause is lower than the sequential scan. USING INDEX The index scan is executed unconditionally in the case of index_name(+). For USING INDEX NONE, the sequential scan is executed unconditionally. If more than two index names are specified behind the USING INDEX clause, the appro-priate index will be selected by the optimizer. If more than two tables are joined, index names must be specified for all tables.
71 / CUBRID Technical Training
Confidential
Index Definition and Using USING INDEX - Tuning
If an index column (yymm) is processed by a function in the WHERE clause, there is no index scan.
Before After
SELECT student_idFROM recordWHERE substring(yymm, 1, 4) = ‘1997’;
SELECT student_id FROM recordWHERE yymm BETWEEN ‘199701’ AND ‘199712’;
Before After
SELECT COUNT(t.id) FROM tbl AS tWHERE IF(t.mdate != ‘0001-01-01’, t.mdate, t.cdate)BETWEEN ‘2009-02-21’ AND ‘2009-02-22’AND t.status=0AND t.id NOT IN(1,2,3);
SELECT COUNT(tmp.id) FROM(SELECT t.id, t.mdate FROM tbl AS tWHERE t.mdateBETWEEN ‘2009-02-21’ AND ‘2009-02-22’AND t.status=0 ) UNION(SELECT t.id, t.mdate FROM tbl AS tWHERE t.cdateBETWEEN ‘2009-02-21’ AND ‘2009-02-22’AND t.status=0 ) ) tmp WHERE tmp.id NOT IN(1,2,3);
72 / CUBRID Technical Training
Confidential
Index Definition and Using USING INDEX - Tuning
When defining an index, this configures Covering Index while checking the query plan.
Before After
CREATE INDEX idx1 ON userinfo(phone);SELECT COUNT(*) FROM userinfoWHERE allow_search=1 AND phone=‘02’;
CREATE INDEX idx1 ON userinfo(phone, allow_search);SELECT COUNT(*) FROM userinfoWHERE allow_search=1 AND phone=‘02’;
When comparing the value of an index column to NULL, there will be no index scan. Modifying query
Before After
SELECT name,email_addr FROM studentWHERE email_addr IS NOT NULL;
SELECT name,email_addr FROM studentWHERE email_addr >= '';
Create an index to be able to cover search conditions Create an index to be able to cover the ORDER BY sorting condition The index scan is not available if you perform the LIKE search by binding a dy-namic parameter.
SELECT * FROM tbl WERE col1 LIKE ? || '%‘ //A sequential scan occurs SELECT * FROM tbl WHERE col1 LIKE 'AAA‘ || '%‘ //insert a static value
73 / CUBRID Technical Training
Confidential
3.3 Query Plans and Hints
74 / CUBRID Technical Training
Confidential
Query Plans and Hints
Query plan
Related hint Description
sscan USING INDEX NONECreates an execution plan by executing a sequential scan
iscanUSING INDEX idx_name(+)
Creates an execution plan by executing an index scan
nl-join /*+ USE_NL */ Creates an inner loop join execution plan
idx-join /*+ USE_IDX */Creates an execution plan if there is an index in a join key
m-join /*+ USE_MERGE */ Creates a sort-merge join execution plan
/*+ ORDERED */Creates an execution plan that joins in the order of ta-bles specified in the FROM clause
Creates a query plan based on the scan methods (sscan and iscan) and the join methods (nl-join, idx-join, and m-join)
75 / CUBRID Technical Training
ConfidentialConfiguring the Display and Check of a Query Plan (CUBRID Manager)
Display Query Plan
76 / CUBRID Technical Training
Confidential
An Example of Display Query Plan (sscan)
SELECT * FROM athlete WHERE name='Yoo Nam-Kyu';
• sscan: A sequential scan•card: Number of records in an ex-pected result set• page#: Expected number of page accesses• sel(selectivity): Expected selectiv-ity that satisfies search conditions
(card, page#)
sel
(card, page#)
77 / CUBRID Technical Training
Confidential
Example of a Display Query Plan (iscan)
CREATE INDEX ON athlete(name);SELECT * FROM athlete WHERE name='Yoo Nam-Kyu';
• iscan: An index scan
78 / CUBRID Technical Training
Confidential
Example of a Display Query Plan (nl-join)
SELECT * FROM olympic, nation WHERE olympic.host_nation=nation.name;
outer table: Contains a small number of recordsinner table: Contains many records and has indexes
79 / CUBRID Technical Training
Confidential
Example of a Display Query Plan (idx-join)
SELECT * FROM game, athlete WHERE game.athlete_code=athlete.code;
80 / CUBRID Technical Training
Confidential
Example of a Display Query Plan (m-join)
SELECT /*+ USE_MERGE */ * FROM game, athlete WHERE game.athlete_code=athlete.code;
81 / CUBRID Technical Training
Confidential
4 JDBC and Other Management
JDBC ProgrammingTransaction Management
82 / CUBRID Technical Training
Confidential
4.1 JDBC Programming
83 / CUBRID Technical Training
Confidential
SQL Type Java Type
CHAR, VARCHAR java.lang.String, java.sql.Date, java.sql.Time, java.sql.Timestamp, java.lang.Byte, java.lang.Short, java.lang.Integer, java.lang.Long, java.lang.Float, java.lang.Double, java.math.BigDecimal, byte, short, int, long, float, double
NUMERIC, SHORT, INT, FLOAT, DOUBLE
java.lang.Byte, java.lang.Short, java.lang.Integer, java.lang.Long, java.lang.Float, java.lang.Double, java.math.BigDecimal, ja-va.lang.String, byte, short, int, long, float, double
DATE, TIME, TIME-STAMP
java.sql.Date, java.sql.Time, java.sql.Timestamp, java.lang.String
The SQL Type and the Java Type
84 / CUBRID Technical Training
Confidential
JDBC Main Interfaces
Supports the JDBC 2.0 standard specifications.
Standard interface Description
CallableStatement An expanded interface for preparedStatement to support the SQL stored procedure.
PreparedStatement An interface for pre-compiled SQL statements
Connection
The database session of JDBC.Provides a statement object for the session, and manages the transaction of the statement.The default is auto-commit.
DatabaseMetaDataProvides the information of a DB to which connection objects are being connectedReturns the JDBC ResultSet object
DriverWhen loading a driver, it creates an instance and registers it to the DriverManager.To connect to DB, it receives URL from the DriverManager, and connects to the corre-sponding registered driver.
DriverManagerSaves the list of registered JDBCdriversLoads all classes specified in the driver attribute during initializationSearches for a driver when there is a connection request from getConnection()
ResultSetA database result set.Processes a database query line by lineOwns the pointer for the currently processed line
ResultSetMetaData Provides the metadata of the column type and the attribute of ResultSet
StatementExpresses the embedded SQL statement an application used to execute database in-teroperationResultSet will be closed when a statement is finished
85 / CUBRID Technical Training
Confidential
How to use JDBC
Connect to DB by using JDBC1. Loading Driver
Class.forName("cubrid.jdbc.driver.CUBRIDDriver") Can connect to DB when a driver is loaded
2. Making the Connection Connection con = DriverManager.getConnection(url, “user", “passwd");
URL style example: jdbc:CUBRID:localhost:33000:demodb:::
3. Creating a statement object Statement stmt = con.createStatement();
4. Executing SQLstatement stmt.executeUpdate(“….”); ResultSet rs = stmt.executeQuery( “…..");
86 / CUBRID Technical Training
Confidential
Example of JDBC usage
Make a connection
Build SQL statement
Send SQL statement
Close SQL statement
Close a connection
import java.sql.*;class SimpleExample { public static void main(String args[]) { String url = “jdbc:CUBRID:localhost:33000:demodb::: ”; try { Class.forName(“cubrid.jdbc.driver.CUBRIDDriver”); } catch (ClassNotFoundException e) { System.out.println(e.getMessage()); } try { Connection myConnection =
DriverManager.getConnection(url, “user”,”passwd”); Statement myStatement = myConnection.createState-ment(); ResultSet rs = myStatement.executeQuery("select sysdate from db_root"); myStatement.close(); myConnection.close(); } catch (java.lang.Exception ex) { ex.printStackTrace(); } }}
87 / CUBRID Technical Training
Confidential
ResultSetMetaData
getTableName() Returns the name of a table for the corresponding column as string type
getColumnLabel() Returns a string object that is the assumed label for a column output
getPrecision() Returns the decimal number for a column as inttype
getScale()Returns the numbers below a decimal point of a decimal number for a column as int type
isSigned() Returns true if a column has a signed number
isNullable()
When null is not allowed, columnNoNulls is returned.When null is allowed, columnNullable is returned.When it is not known whether null is allowed or not, the int value of coulmnNul-lableUnknow is returned.
isWritable() Returns true if it is possible to write a value into a column
88 / CUBRID Technical Training
Confidential
ResultSet
Send SQL statement
Fetch row
Get columns
More columns
More rows
No
No
Yes
Yes
...…Connection myConnection =
DriverManager.getConnection(url,”user”,”passwd”);Statement myStatement = myConnection.createStatement();ResultSet rs = myStatement.executeQuery(“SELECT name,
title, salary FROM employee”);int I = 0;while (rs.next()) {
I++;String empName = rs.getString(“name”);String empTitle = rs.getString(“title”);long empSalary = rs.getLong(“salary”);System.out.println(“Employee ” + empName + ”
is “ + empTitle + “ and earns $” + emp-
Salary);}…...
89 / CUBRID Technical Training
Confidential
Cautions on CUBRID JDBC usage
Returning resources Make sure to return a DB object such as ResultSet or
Statement,Connection after it is used. Return occurs when the close() method is called for a corresponding ob-
ject. If AutoCommit False is used, return occurs after the transaction for a
connection(Commit/Rollback) is explicitly finished.
If you execute inner query statements, you must allocate a different connec-tion object to each of them.
When other transactions occur in a cycle statement that uses re-trieved data
When a transaction(Commit/Rollback) occurs for a connection object that is being used, the ResultSet being used is finished.
90 / CUBRID Technical Training
Confidential
4.3 Transaction Management
91 / CUBRID Technical Training
Confidential
Introduction to CUBRID locking protocol
locking Lock is managed for each transaction, for tables and records For a record, S-lock is acquired for reading, and X-lock is acquired for
writing. To get S-lock for a record, you must get IS-lock for the corresponding
table. To get S-lock for a record, you must get IX-lock for the corresponding
table.
Features Configuring SIX-lock for a table
When a transaction that has S-lock for a table requests X-lock
Valid range of lock X-lock : The time a transaction is finished (i.e., confirmation or
withdrawal time) S-lock : REP (the time when a transaction is finished), COMMIT
(the time when reading is finished), UNCOMMIT (does not re-quest lock)
92 / CUBRID Technical Training
Confidential
Features of CUBRID locking protocol
Configuring S-lock for a table When reading the schema of a corresponding table When reading the higher-tier or lower-tier table of a corresponding table When the number of records a transaction reads is greater than the
lock_escalation value
Configuring X-lock for a table When modifying a corresponding table When the number of records a transaction writes is greater than the
lock_escalation value
NULL_LOCK IS_LOCK S_LOCK IX_LOCK SIX_LOCK U_LOCK X_LOCK
NULL_LOCK TRUE TRUE TRUE TRUE TRUE TRUE TRUE
IS_LOCK TRUE TRUE TRUE TRUE TRUE N/A FALSE
S_LOCK TRUE TRUE TRUE FALSE FALSE FALSE FALSE
IX_LOCK TRUE TRUE FALSE TRUE FALSE N/A FALSE
SIX_LOCK TRUE TRUE FALSE FALSE FALSE N/A FALSE
U_LOCK TRUE N/A TRUE N/A N/A FALSE FALSE
X_LOCK TRUE FALSE FALSE FALSE FALSE FALSE FALSE
93 / CUBRID Technical Training
Confidential
Checking locking information
You can check the current locking status of the DB. Creates an object for lock object unit: table, record) Displays information for each object
Provided information Lock related configuration of a DB server Information of DB clients connected to a DB server Lock table information of an object
94 / CUBRID Technical Training
Confidential
Checking locking information – lockdb util-ity
Command: lockdb Shows a current snapshot of the locking status of the DB.
cubrid lockdb [OPTION] database-name
Options: -o
Saves output to a file
cubrid lockdb demodb
Lock-related configuration of a DB server
Lock Escalation at = 100000, Run Deadlock interval = 1
Number of locks that can be converted from a row rock to a table lock
95 / CUBRID Technical Training
Confidential
OID = 0| 1780| 7
Object type: Instance of class ( 0| 288| 6) = table_a.
Total mode of holders = X_LOCK, Total mode of waiters = X_LOCK.
Num holders= 1, Num blocked-holders= 0, Num waiters= 1
LOCK HOLDERS:
Tran_index = 2, Granted_mode = X_LOCK, Count = 2
LOCK WAITERS:
Tran_index = 1, Blocked_mode = X_LOCK
Start_waiting_at = Wed Sep 23 12:06:06 2009
Wait_for_nsecs = -1
lock target object information
No. 2 transaction has X_LOCK for this object.
No. 1 transaction is waiting to acquire X_LOCK for this object.
Checking locking information – lockdb util-ity
Lock information of an object
96 / CUBRID Technical Training
Confidential
Checking locking information – lockdb util-ity
Transaction information
Transaction (index 1, cub_cas, dba@mycom|2908)
Isolation REPEATABLE CLASSES AND READ UNCOMMITTED INSTANCES
State TRAN_ACTIVE
Timeout_period -1
Transaction (index 2, cub_cas, dba@mycom|2980)
Isolation REPEATABLE CLASSES AND READ UNCOMMITTED INSTANCES
State TRAN_ACTIVE
Timeout_period -1
No. 1 transaction, cub_cas process,logging into dba, processID:2908
No.2 transaction, cub_cas process,logging into dba, processID:2980
Waiting time to acquire lock, -1: no timeout
Lock level: Guaranteeing table read, Dirty read is allowed for the record
97 / CUBRID Technical Training
Confidential
Checking locking information – CUBRID Manager
CUBRID Manger Only visible to dba user
98 / CUBRID Technical Training
Confidential
Checking locking information – CUBRID Manager
Transaction info
99 / CUBRID Technical Training
Confidential
Checking locking information – CUBRID Manager
Checking an application that has a transaction For CAS, check its information in the CUBRID broker. Check the order of ID in a broker by using a processID.
As the process IDs in the above example are 2908 and 2980, they cor-respond to ID1 and ID2 of query_editor broker.
As 2980is occupying X_LOCK, the corresponding transaction (ID2)must be forced to stop, if necessary.
For an application, logic change, etc. may be necessary for the ap-plication.
For a query editor or CSQL, stop the transaction (commit/rollback).
100 / CUBRID Technical Training
Confidential
Transaction Management
Stopping a broker transaction Forcibly stop the corresponding transaction (rollback) by using the Killtran
command% usage: cubrid killtran [OPTION] database-name
valid options:
-i, --kill-transaction-index=INDEX kill transaction with transaction INDEX
--kill-user-name=ID kill all transactions with user ID
--kill-host-name=HOST kill all transactions with client HOST
--kill-program-name=NAME kill all transactions with client program NAME
-p, --dba-password=PASS password of the DBA user; will prompt if don't specify
-d, --display-information display information about active transactions
-f, --force kill the transaction without a prompt for verification
101 / CUBRID Technical Training
Confidential
5 Practice
102 / CUBRID Technical Training
Confidential
CUBRID Installation
• Installing CUBRID (for Windows)– Downloading and installing CUBRID.
• Creating demodb
• Checking if the CUBRID service tray has started
• Checking if the CUBRID service has started
– service, process
103 / CUBRID Technical Training
Confidential
– CUBRID manager client• Checking if DB is created
• Starting DB server– Checking if there is aJAVA related error message during start
• Using the Query Editor– Executing a simple query: select * from db_class
CUBRID Installation
104 / CUBRID Technical Training
Confidential
• Stopping DB Server
• Stopping CUBRID service– Checking process
• Starting CUBRID service
CUBRID Installation
105 / CUBRID Technical Training
Confidential
DB creation
• Creating a DB that satisfies the following conditions– Creation location and size of each volume
• Page size: 4Kb• First volume: 5,000p, C:\CUBRID\databases\<DB name>• Log volume: 100,000p, C:\CUBRID\databases\<DB name>\log• Data volume: 500,000p, C:\CUBRID\databases\<DB name>• Index volume: 250,000p, C:\CUBRID\databases\<DB name>• Temp volume: 250,000p, C:\CUBRID\databases\<DB name>
106 / CUBRID Technical Training
Confidential
DB creation
• Checking the created volume– Checking the content of databases.txt – Checking the files in each directory by referring to the volume
information file • control volumes• information volumes• log volumes
Computer name
107 / CUBRID Technical Training
Confidential
Schema management
• Creating a table that satisfies the following conditions– Company table (company)
• Company ID (integer): primary key, company name (string)
– Customer table (client)• CustomerID (integer): not duplicated• Customer name, title, email, telephone no., address: Character string
create table company (comp_id int primary key, // company IDcomp_name varchar(200) // company name
);
create table client (client_id int primary key, // customer IDcomp_id int, // company IDclient_name varchar(20), // customer nametitle varchar(10), // titleemail varchar(100), // emailphone varchar(20), // phone no.address varchar(200), // address
);
108 / CUBRID Technical Training
Confidential
Schema management
– Viewing table information in a CUBRID Manager client
109 / CUBRID Technical Training
Confidential
Schema management
• Modifying a table according to the following conditions– Re-creating after deleting a primary key – Changing type
• Title: charvarchar or varchar char
– Adding/changing an initial value• Title: Specifying an initial value to ‘new staff’ and deleting it
alter class client drop constraint pk_client_client_idalter class client add primary key(client_id)// or (possible to assign PK name), alter class client add constraint pk_id primary key (client_id)
alter class client rename attribute title as old_titlealter class client add attribute title char(20)update client set title = cast(old_title as char(20))alter class client drop attribute old_title
alter class client change title default 'new staff'alter class client change title default NULL
110 / CUBRID Technical Training
Confidential
Schema management
• Index – Client
• A customer name is unique. Add an index whose name is u_name.• Title is in reverse order. Add an index whose name is idx1 to sort cus-
tomer names in forward direction.
• Searching table information by using a catalog– Checking the information of a created table
• Table name, column information, index information
select * from db_classselect * from db_attribute where class_name = 'client'select * from db_index where class_name = 'client'
create unique index u_name on client(client_name)create index idx1 on client(title desc, client_name)
111 / CUBRID Technical Training
Confidential
Data search and manipulation
• Inserting data– Insert (10,’company10’), (20,’company20’) into the company table.
– Insert an arbitrary id,name, and the company ID whose comp_id is 20 into a client table in the insert-select format.
– Check inserted data information by selecting rows from the client table.
insert into company values (10, 'company10');insert into company values (10, 'company10'),(20, 'company20'); insert into company (comp_id, comp_name) values (20, 'company20');
insert into client (comp_id, client_id, client_name) select comp_id, 20, 'new staff20' from company where comp_id = 20
112 / CUBRID Technical Training
Confidential
Data search and manipulation
• Modifying data – insert an arbitrary id and name into a client table.
– Check the inserted data information by searching for the client table.
– Change the comp_id to 10 for the data inserted in the client table.
– Check inserted data information by searching for the client table.
insert into client (client_id, client_name) values (30, 'new staff30')
update client set comp_id = 10 where client_id = 30
113 / CUBRID Technical Training
Confidential
Data search and manipulation
• Data search– Retrieve the countries that achieved medals in the 1988 Olympics from
the participants and their medal information• Table where participants are listed: participant• Medal information table : game
- Retrieve medal information of the participants in the 1988 Olympics
select (select name from nation where code = a.nation_code), medalfrom participant a, game bwhere a.host_year = 1988 and a.nation_code = b.nation_code and a.host_year = b.host_year
select (select name from nation where code = a.nation_code), medalfrom participant a left outer join game b on a.nation_code = b.nation_code and a.host_year = b.host_yearwhere a.host_year = 1988
114 / CUBRID Technical Training
Confidential
Data search and manipulation
• Using index– Sorting the cities that have hosted the Olympics in chronological order
• Table in which the names of cities that have hosted the Olympics are listed: olympic
– Sorting the cities that have hosted the Olympics, so that the most re-cent ones appear at the front
select host_year,host_nation,host_city from olympic where host_year > '' using index pk_olympic_host_year(+)
create index r_year on olympic(host_year desc)select host_year, host_nation, host_city from olympic where host_year > '' using index r_year(+) order by host_year desc
115 / CUBRID Technical Training
Confidential
Operators and functions
• Arithmetic/Join/Type conversion operators– Checking how many months and days are left until Christmas
– Displaying how many hours, minutes, and seconds are left until a train-ing session is finished
– Finding out what year this is through more than two methods.
– Checking the date of the last day of this month
select months_between(to_date('12/25/2008'), sysdate), '12/25/2008' - sys-date from db_root
select to_char(t1/3600) + 'hour' +to_char(abs(mod(t1,3600)/60)) + 'minute' + to_char(abs(mod(t1,60))) + 'second'from (select '17:00' - systime from db_root) as t(t1)
select to_char(sysdate, 'yyyy') from db_rootselect extract(year from sysdate) from db_root
select extract(day from last_day(sysdate)) from db_root
116 / CUBRID Technical Training
Confidential
Operators and functions
• Function– Finding an arbitrary number between 1 and 100
– Rounding 3.141592653 to the nearest millionth
– Finding out the number of bus stops where you can catch the No. 10 bus
– Length of the following string (‘substring xyzxxy’), position of ‘str’, ex-tracting 6 characters from the 4th character, removing ‘xy’ from the string, replacing ‘s’ with ‘S’
select mod(rand(), 100) + 1 from db_root
select round(3.141592653, 6), trunc(3.141592653, 6) from db_root
select count(sation_id) from bus where bus_num = '10'
select length('substring xyzxxy'), instr ('substring xyzxxy', 'str'), sub-str('substring xyzxxy', 4, 6), rtrim('substring xyzxxy', 'xy'), replace(('substring xyzxxy', 's', 'S')from db_root
117 / CUBRID Technical Training
Confidential
Operators and functions
– For the Olympic medals, use 'G' for a 'gold medal,' 'S' for a 'silver medal,' and 'B' for a 'bronze medal.'
• Olympic medal table : game
– Use '1900s' for the Olympics held in the 1900s, '2000s' for 2000s, and 'Other' for other years, and calculate the number Olympics held.
• Table showing Olympics years: olympic
select decode(medal, 'G'. 'gold medal', 'S', 'silver medal', 'B', 'bronze medal') from game
select case when host_year between 1900 and 1999 then '1900s' when host_year between 2000 and 2999 then '2000s' else 'other years' end as years, count(*)from olympicgroup by case when host_year between 1900 and 1999 then '1900s' when host_year between 2000 and 2999 then '2000s' else 'other years' end
118 / CUBRID Technical Training
Confidential
Operators and functions
• rownum– Selecting hosting information of the 11th to 20th Olympics
• Olympics hosting information table: olympic
– Selecting 11th to 20th by sorting Olympics hosting information by year chronological order
– Modifying the above query using index hint
– Grouping by host_nation column
select * from olympic where rownum between 11 and 20
select * from olympic order by host_year for orderby_num() between 11 and 20; select * from olympic order by host_year limit 11, 20;
select * from olympic where host_year > 0 and rownum between 11 and 20 us-ing index pk_olympic_host_year(+)
select host_nation from olympic where rownum between 11 and 20 group by host_nation
119 / CUBRID Technical Training
Confidential
Operators and functions
• serial– Create an arbitrary serial object, get the subsequent value, and check
the current value.
create serial seq_noselect seq_no.next_value from db_rootselect seq_no.current_value from db_root
120 / CUBRID Technical Training
Confidential
Operators and functions
• Auto increment– Create a table having an auto increment column
– Insert data to the auto increment column– Insert no date to the auto increment column
– Select rows and check the auto increment column values– Delete rows and re-insert data
create table bbs (id int auto_increment,title string,cnt int default 0
)
insert into bbs(id, title) values(5, 'arbitrary inserting for auto incre-ment')insert into bbs(title) values('auto inserting for auto increment')
select * from bbsdelete from bbsinsert into bbs(title) values('auto inserting for auto increment')
Top Related