diff --git a/.circleci/config.yml b/.circleci/config.yml index 588cab5958e..d4cccd092c0 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -2,11 +2,6 @@ defaults: &defaults working_directory: /home docker: - image: cubridci/cubridci:develop - -oraclelinux: &oraclelinux - working_directory: /home - docker: - - image: cubridci/cubridci:ol7.8 test_defaults: &test_defaults steps: @@ -20,7 +15,20 @@ test_defaults: &test_defaults command: | ulimit -c 1 /entrypoint.sh checkout - circleci tests glob cubrid-testcases/$TEST_SUITE/_* | circleci tests split | tee tc.list + if [ $TEST_SUITE = "plcsql" ] + then + # Hack way to run plcsql test without modifying CUBRID CI docker + TEST_SUITE="sql" + glob_path=cubrid-testcases/sql/{_05_plcsql,_35_fig_cake/plcsql} + elif [ $TEST_SUITE = "sql" ] + then + rm -rf cubrid-testcases/$TEST_SUITE/_05_plcsql + rm -rf cubrid-testcases/$TEST_SUITE/_35_fig_cake/plcsql + glob_path="cubrid-testcases/$TEST_SUITE/_*" + else + glob_path="cubrid-testcases/$TEST_SUITE/_*" + fi + circleci tests glob $glob_path | circleci tests split | tee tc.list find cubrid-testcases/$TEST_SUITE/_* -maxdepth 0 -type d -print0 | grep -vzZ -f tc.list | xargs -0 rm -rf /entrypoint.sh test - run: @@ -84,19 +92,11 @@ jobs: parallelism: 8 <<: *test_defaults - test_medium_ol: - <<: *oraclelinux - environment: - TEST_SUITE: medium - resource_class: medium - <<: *test_defaults - - test_sql_ol: - <<: *oraclelinux + test_plcsql: + <<: *defaults environment: - TEST_SUITE: sql + TEST_SUITE: plcsql resource_class: medium - parallelism: 8 <<: *test_defaults build-windows: @@ -144,11 +144,8 @@ workflows: - test_sql: requires: - build - - - test_medium_ol: - requires: - - build - - test_sql_ol: + - test_plcsql: requires: - build + - build-windows diff --git a/.github/workflows/license_headers/apache_bat3.txt b/.github/workflows/license_headers/apache_bat3.txt new file mode 100644 index 00000000000..74760ea39a9 --- /dev/null +++ b/.github/workflows/license_headers/apache_bat3.txt @@ -0,0 +1,18 @@ +@echo off + +@rem +@rem +@rem Copyright 2016 CUBRID Corporation +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem diff --git a/.gitignore b/.gitignore index f8bc5ea0792..610245c07e4 100644 --- a/.gitignore +++ b/.gitignore @@ -67,7 +67,7 @@ cm_common/cub_jobsa cm_common/cub_sainfo .installed /java/bin/ -/java/jspserver.jar +/java/pl_server.jar /java/src-jsp/ /java/src/ /msg/*/*.cat diff --git a/CMakeLists.txt b/CMakeLists.txt index d81e300409b..be059c6ecac 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -808,6 +808,10 @@ if(WITH_JDBC AND EXISTS ${CMAKE_SOURCE_DIR}/cubrid-jdbc/src) install(DIRECTORY ${JDBC_DIR}/ DESTINATION ${CUBRID_JDBCDIR} COMPONENT JDBC FILES_MATCHING PATTERN "*.jar" + PATTERN ".github" EXCLUDE + PATTERN "cmake" EXCLUDE + PATTERN "src" EXCLUDE + PATTERN "output" EXCLUDE ) endif() @@ -827,7 +831,7 @@ add_subdirectory(demo) add_subdirectory(contrib) add_subdirectory(locales) add_subdirectory(timezones) -add_subdirectory(jsp) +add_subdirectory(pl_engine) if(AT_LEAST_ONE_UNIT_TEST) add_subdirectory(unit_tests) endif() diff --git a/cs/CMakeLists.txt b/cs/CMakeLists.txt index e184e7a028f..0bd794bfaf4 100644 --- a/cs/CMakeLists.txt +++ b/cs/CMakeLists.txt @@ -50,6 +50,7 @@ set(COMPAT_SOURCES ${COMPAT_DIR}/db_json_path.cpp ${COMPAT_DIR}/db_json_types_internal.cpp ${COMPAT_DIR}/db_macro.c + ${COMPAT_DIR}/db_method_static.cpp ${COMPAT_DIR}/db_obj.c ${COMPAT_DIR}/db_old.c ${COMPAT_DIR}/db_query.c @@ -294,6 +295,7 @@ set(JSP_SOURCES set(METHOD_SOURCES ${METHOD_DIR}/method_connection_cl.cpp + ${METHOD_DIR}/method_compile_def.cpp ${METHOD_DIR}/method_callback.cpp ${METHOD_DIR}/method_def.cpp ${METHOD_DIR}/method_error.cpp @@ -512,7 +514,7 @@ add_library(cubridcs SHARED ) set_target_properties(cubridcs PROPERTIES SOVERSION "${CUBRID_MAJOR_VERSION}.${CUBRID_MINOR_VERSION}") -target_compile_definitions(cubridcs PRIVATE CS_MODE ${COMMON_DEFS}) +target_compile_definitions(cubridcs PRIVATE CS_MODE CUBRID_EXPORTING ${COMMON_DEFS}) if(NOT USE_CUBRID_ENV) target_compile_definitions(cubridcs PRIVATE ${DIR_DEFS}) endif(NOT USE_CUBRID_ENV) diff --git a/cubrid/CMakeLists.txt b/cubrid/CMakeLists.txt index 7a043c2b418..22b0a70e0d7 100644 --- a/cubrid/CMakeLists.txt +++ b/cubrid/CMakeLists.txt @@ -272,8 +272,11 @@ set(JSP_SOURCES ) set(METHOD_SOURCES + ${METHOD_DIR}/method_connection_java.cpp ${METHOD_DIR}/method_connection_sr.cpp ${METHOD_DIR}/method_connection_pool.cpp + ${METHOD_DIR}/method_compile_def.cpp + ${METHOD_DIR}/method_compile.cpp ${METHOD_DIR}/method_def.cpp ${METHOD_DIR}/method_error.cpp ${METHOD_DIR}/method_invoke_builtin.cpp @@ -518,7 +521,7 @@ if(WIN32) set_target_properties(cubrid PROPERTIES OUTPUT_NAME libcubrid) endif(WIN32) -target_compile_definitions(cubrid PRIVATE SERVER_MODE ${COMMON_DEFS}) +target_compile_definitions(cubrid PRIVATE SERVER_MODE CUBRID_EXPORTING ${COMMON_DEFS}) if(NOT USE_CUBRID_ENV) target_compile_definitions(cubrid PRIVATE ${DIR_DEFS}) endif(NOT USE_CUBRID_ENV) diff --git a/cubridmanager b/cubridmanager index 00306607c66..8e4865a2a9a 160000 --- a/cubridmanager +++ b/cubridmanager @@ -1 +1 @@ -Subproject commit 00306607c66034429c7e39ea6ae2b37999535072 +Subproject commit 8e4865a2a9a694899283575e05017da2115121e9 diff --git a/demo/CMakeLists.txt b/demo/CMakeLists.txt index fd4cf4976c1..9dbd42e6314 100644 --- a/demo/CMakeLists.txt +++ b/demo/CMakeLists.txt @@ -19,7 +19,12 @@ install(FILES ${CMAKE_SOURCE_DIR}/demo/demodb_objects ${CMAKE_SOURCE_DIR}/demo/demodb_schema - DESTINATION ${CUBRID_DEMODIR}) + DESTINATION ${CUBRID_DEMODIR}) + +install(DIRECTORY + ${CMAKE_SOURCE_DIR}/demo/plcsql + DESTINATION ${CUBRID_DEMODIR} +) if(UNIX) set(DEMODB_SCRIPT make_cubrid_demo.sh) diff --git a/demo/plcsql/README.md b/demo/plcsql/README.md new file mode 100644 index 00000000000..f903993bdab --- /dev/null +++ b/demo/plcsql/README.md @@ -0,0 +1,478 @@ +# PLCSQL Demonstaration + +## Table of Contents + +1. [DBMS_OUTPUT](##-1.-DBMS_OUTPUT.put_line) +2. [Static SQL](##-2.-Static-SQL) +3. [TCL](##-3.-TCL-(COMMIT/ROLLBACK)) +4. [Procedure/Function](##-4.-Procedure/Function) +5. [%TYPE](##-5.-%TYPE) +6. [Pseudocolumn](##-6.-Pseudocolumn) +--- +## 1. DBMS_OUTPUT.put_line +- [demo_hello.sql](./demo_hello.sql) +``` +-- registration +csql -u public demodb -i $CUBRID/demo/plcsql/demo_hello.sql +``` + +``` +-- test +csql -u public demodb +;server-output on + call demo_hello (); +;ex +``` + +``` +-- expected +Hello CUBRID PL/CSQL! +``` +--- +## 2. Static SQL +### 2.1 Query - Single Rows +- [test_query_single_row_const.sql](./test_query_single_row_const.sql) +``` +-- registration +csql -u public demodb -i $CUBRID/demo/plcsql/test_query_single_row_const.sql +``` + +``` +-- test +csql -u public demodb +;server-output on + select test_query_single_row_const (); +;ex +``` +``` +-- expected + test_query_single_row_const() +=============================== + 10615 +``` + +- [test_query_single_row.sql](./test_query_single_row.sql) +``` +-- registration +csql -u public demodb -i $CUBRID/demo/plcsql/test_query_single_row.sql +``` + +``` +-- sample +11847 'Kim Yong-Bae' +11844 'Kim Taek Soo' +11843 'Kim Tae-Gyun' +11842 'Kim Soo-Kyung' +11836 'Kim Moon-Soo' +11833 'Kim Min-Soo' +11830 'Kim Kyung-Seok' +11829 'Kim Kyong-Hun' +11828 'Kim Ki-Tai' +11827 'Kim Jung-Chul' +11825 'Kim Jong-Shin' +11823 'Kim In-Sub' +11820 'Kim Han-Soo' +``` +``` +-- test +csql -u public demodb +;server-output on + select test_query_single_row (11828); +;ex +``` +``` +-- expected + test_query_single_row(11828) +====================== + 'Kim Ki-Tai' +``` +### 2.2 Query - Cursor +- [test_query_cursor_simple_nocond.sql](./test_query_cursor_simple_nocond.sql) +- [test_query_cursor_simple.sql](./test_query_cursor_simple.sql) +``` +-- registration +csql -u public demodb -i $CUBRID/demo/plcsql/test_query_cursor_simple_nocond.sql +csql -u public demodb -i $CUBRID/demo/plcsql/test_query_cursor_simple.sql +``` + +``` +-- test +csql -u public demodb +;server-output on + select test_query_cursor_simple_nocond (); + select test_query_cursor_simple (); +;ex +``` +``` +-- expected + test_query_cursor_simple_nocond() +=================================== + 10999 + + test_query_cursor_simple() +============================ + 10615 +``` + +- [test_query_cursor_hostvar.sql](./test_query_cursor_hostvar.sql) +``` +-- registration +csql -u public demodb -i $CUBRID/demo/plcsql/test_query_cursor_hostvar.sql +``` + +``` +-- test +csql -u public demodb +;server-output on + select test_query_cursor_hostvar (); +;ex +``` +``` +-- expected + test_query_cursor_hostvar() +====================== + 'Han Myung-Woo' +``` +### 2.3 DDL (Dynamic SQL), DML + +#### Dynmaic SQL +- [test_ddl.sql](./test_ddl.sql) +``` +-- registration +csql -u public demodb -i $CUBRID/demo/plcsql/test_ddl.sql +``` + +``` +-- test +csql -u public demodb +;server-output on + call test_ddl (); + desc a_tbl1; +;ex +``` +``` +-- expected +creating a_tbl1 table is succeed! + + Field Type Null Key Default Extra +==================================================================================================================================== + 'id' 'INTEGER' 'YES' 'UNI' NULL '' + 'name' 'VARCHAR(1073741823)' 'YES' '' NULL '' + 'phone' 'VARCHAR(1073741823)' 'YES' '' '000-0000' '' +``` + +#### INSERT +- [test_dml_insert.sql](./test_dml_insert.sql) +- [test_dml_truncate.sql](./test_dml_truncate.sql) +``` +-- preparation and registration +csql -u public demodb + drop table if exists a_tbl1; + CREATE TABLE a_tbl1(id INT UNIQUE, name VARCHAR, phone VARCHAR DEFAULT '000-0000'); +;ex + +csql -u public demodb -i $CUBRID/demo/plcsql/test_dml_insert.sql +csql -u public demodb -i $CUBRID/demo/plcsql/test_dml_truncate.sql +``` + +``` +-- test +csql -u public demodb +;server-output on + call test_dml_insert (); +;ex +``` + +``` +-- expected +/* (((((( */INSERT INTO a_tbl1 SET id=6, name='eee';/* (((((( */ +/* (((((( */INSERT INTO a_tbl1 SET id=6, name='eee';/* (((((( */ is succeed +[Test 1] ===================================================================== +Expected: +6 eee 666-6666 +Actual: +6 eee 666-6666 +[Test 1] OK +[Test 2] ===================================================================== +Expected: +7 ggg 777-7777 +Actual: +7 ggg 777-7777 +[Test 2] OK +``` + +#### TRUNCATE +``` +-- test +csql -u public demodb +;server-output on + call test_dml_truncate (); + SELECT * FROM a_tbl1; +;ex +``` + +``` +-- expected +There are no results. +``` + +#### DELETE +- [test_dml_delete.sql](./test_dml_delete.sql) +``` +-- preparation +csql -u public demodb + DROP TABLE a_tbl; + CREATE TABLE a_tbl( + id INT NOT NULL, + phone VARCHAR(10)); + INSERT INTO a_tbl VALUES(1,'111-1111'), (2,'222-2222'), (3, '333-3333'), (4, NULL), (5, NULL); +;ex +``` +``` +-- registration +csql -u public demodb -i $CUBRID/demo/plcsql/test_dml_delete.sql +``` + +``` +-- test +csql -u public demodb +;server-output on + call test_dml_delete (); +;ex +``` +``` +-- expected +111-1111 +222-2222 +333-3333 +``` + +## 3. TCL (COMMIT/ROLLBACK) + +### COMMIT +- [test_tcl_commit.sql](./test_tcl_commit.sql) +``` +-- preparation +csql -u public demodb + DROP TABLE IF EXISTS test_tcl_tbl; + CREATE TABLE test_tcl_tbl (code INT, name STRING); +;ex +``` +``` +-- registration +csql -u public demodb -i $CUBRID/demo/plcsql/test_tcl_commit.sql +``` + +``` +-- test (;set pl_transaction_control=yes) +csql -u public demodb +;set pl_transaction_control=yes +;autocommit off +;server-output on + TRUNCATE test_tcl_tbl; + COMMIT; + SELECT * FROM test_tcl_tbl; + CALL test_tcl_commit (); + ROLLBACK; -- rollback in csql session + + SELECT * FROM test_tcl_tbl; -- committed rows should be displayed + ROLLBACK; +;ex +``` +``` +-- expected + +// CALL test_tcl_commit (); +code = 3, name = ccc +code = 4, name = ddd + +// SELECT * FROM test_tcl_tbl; + code name +=================================== + 1 'aaa' + 2 'bbb' + 3 'ccc' + 4 'ddd' +``` + +``` +-- test (;set pl_transaction_control=no) +csql -u public demodb +;set pl_transaction_control=no +;autocommit off +;server-output on + TRUNCATE test_tcl_tbl; + COMMIT; -- COMMIT is required to ensure TRUNCATE is executed according to the TRUNCATE spec. + + SELECT * FROM test_tcl_tbl; + CALL test_tcl_commit (); + ROLLBACK; -- rollback in csql session + SELECT * FROM test_tcl_tbl; -- COMMIT in test_tcl_commit () must be ignored + ROLLBACK; +;ex +``` + +``` +-- expected + +// CALL test_tcl_commit (); +code = 3, name = ccc +code = 4, name = ddd + +// SELECT * FROM test_tcl_tbl; +There are no results. +``` + +### ROLLBACK +- [test_tcl_rollback.sql](./test_tcl_rollback.sql) +``` +-- preparation +csql -u public demodb + DROP TABLE IF EXISTS test_tcl_tbl2; + CREATE TABLE test_tcl_tbl2 (code INT, name STRING); +;ex +``` +``` +-- registration +csql -u public demodb -i $CUBRID/demo/plcsql/test_tcl_rollback.sql +``` + +``` +-- test (;set pl_transaction_control=yes) +csql -u public demodb +;set pl_transaction_control=yes +;set autocommit off +;server-output on + TRUNCATE test_tcl_tbl2; + COMMIT; + CALL test_tcl_rollback (); + COMMIT; + SELECT * FROM test_tcl_tbl2; +;ex +``` + +``` +-- expected + code name +=================================== + 1 'aaa' + 2 'bbb' + 3 'ccc' + 4 'ddd' +``` + +``` +-- test (;set pl_transaction_control=no) +csql -u public demodb +;set pl_transaction_control=no +;set autocommit off +;server-output on + TRUNCATE test_tcl_tbl2; + COMMIT; + CALL test_tcl_rollback (); + COMMIT; + SELECT * FROM test_tcl_tbl2; +;ex +``` + +``` +-- expected + code name +=================================== + 1 'aaa' + 2 'bbb' + 3 'ccc' + 4 'ddd' + 6 'daf' + 7 'qwe' +``` + +--- +## 4. Procedure/Function +- [demo_hello_ret.sql](./demo_hello_ret.sql) +- [demo_global_semantics_udpf.sql](./demo_global_semantics_udpf.sql) +``` +-- registration +csql -u public demodb -i $CUBRID/demo/plcsql/demo_hello_ret.sql +csql -u public demodb -i $CUBRID/demo/plcsql/demo_global_semantics_udpf.sql +``` + +``` +-- test +csql -u public demodb +;server-output on + select demo_global_semantics_udpf (); +;ex +``` + +``` +-- expected + demo_global_semantics_udpf() +====================== + 'hello cubrid' + +Hello CUBRID PL/CSQL! +``` +--- +## 5. %TYPE +- [demo_global_semantics_type.sql](./demo_global_semantics_type.sql) +-- registration +``` +csql -u public demodb -i $CUBRID/demo/plcsql/demo_global_semantics_type.sql +``` + +``` +-- test +csql -u public demodb +;server-output on + select demo_global_semantics_type (); +;ex +``` +``` +-- expected + demo_global_semantics_type() +====================== + 'Chung Min-Tae' +``` +--- +## 6. Pseudocolumn + +### 6.1 Serial +- [demo_global_semantics_serial.sql](./demo_global_semantics_serial.sql) +``` +-- preparation +csql -u public demodb + DROP SERIAL demo_pl_serial; + CREATE SERIAL demo_pl_serial; +;ex +``` + +-- registration +``` +csql -u public demodb -i $CUBRID/demo/plcsql/demo_global_semantics_serial.sql +``` + +``` +-- test +csql -u public demodb +;server-output on + select demo_global_semantics_serial (); + select demo_global_semantics_serial (); + select demo_global_semantics_serial (); +;ex +``` + +``` +-- expected + demo_global_semantics_serial() +====================== + 1 + + demo_global_semantics_serial() +====================== + 2 + + demo_global_semantics_serial() +====================== + 3 +``` diff --git a/demo/plcsql/StmtForStaticSqlLoop-test-without-condition.sql b/demo/plcsql/StmtForStaticSqlLoop-test-without-condition.sql new file mode 100644 index 00000000000..31d44c652fa --- /dev/null +++ b/demo/plcsql/StmtForStaticSqlLoop-test-without-condition.sql @@ -0,0 +1,11 @@ +create or replace function StmtForStaticSqlLoop_test_without_condition() return int as +i int; +begin + i := 0; + for r in (select code, name from athlete) loop + i := r.code; + EXIT; + end loop; + + return i; +end; diff --git a/demo/plcsql/demo_global_semantics_serial.sql b/demo/plcsql/demo_global_semantics_serial.sql new file mode 100644 index 00000000000..e9d074c592c --- /dev/null +++ b/demo/plcsql/demo_global_semantics_serial.sql @@ -0,0 +1,6 @@ +create or replace function demo_global_semantics_serial() return numeric as +i numeric; +begin + i := demo_pl_serial.NEXT_VALUE; + return i; +end; \ No newline at end of file diff --git a/demo/plcsql/demo_global_semantics_type.sql b/demo/plcsql/demo_global_semantics_type.sql new file mode 100644 index 00000000000..328cfa71687 --- /dev/null +++ b/demo/plcsql/demo_global_semantics_type.sql @@ -0,0 +1,12 @@ +create or replace function demo_global_semantics_type() return string as +v_name athlete.name%TYPE; +g char(1) := 'M'; +n char(3) := 'KOR'; + +begin + for r in (select name from athlete where gender = g and nation_code = n) loop + v_name := r.name; + EXIT; + end loop; + return v_name; +end; \ No newline at end of file diff --git a/demo/plcsql/demo_global_semantics_udpf.sql b/demo/plcsql/demo_global_semantics_udpf.sql new file mode 100644 index 00000000000..f25fecaaf1f --- /dev/null +++ b/demo/plcsql/demo_global_semantics_udpf.sql @@ -0,0 +1,7 @@ +create or replace function demo_global_semantics_udpf() return varchar as +m varchar; +begin + demo_hello (); + m := demo_hello_ret (); + return m; +end; \ No newline at end of file diff --git a/demo/plcsql/demo_hello.sql b/demo/plcsql/demo_hello.sql new file mode 100644 index 00000000000..d9db0445e52 --- /dev/null +++ b/demo/plcsql/demo_hello.sql @@ -0,0 +1,4 @@ +create or replace procedure demo_hello() as +begin + DBMS_OUTPUT.put_line('Hello CUBRID PL/CSQL!'); +end; diff --git a/demo/plcsql/demo_hello_ret.sql b/demo/plcsql/demo_hello_ret.sql new file mode 100644 index 00000000000..0581d99eeae --- /dev/null +++ b/demo/plcsql/demo_hello_ret.sql @@ -0,0 +1,4 @@ +create or replace function demo_hello_ret() return varchar as +begin + return 'hello cubrid'; +end; diff --git a/demo/plcsql/test_ddl.sql b/demo/plcsql/test_ddl.sql new file mode 100644 index 00000000000..6022a519d05 --- /dev/null +++ b/demo/plcsql/test_ddl.sql @@ -0,0 +1,11 @@ +create or replace procedure test_ddl() as + i int; + n varchar; + p varchar; + + new_table VARCHAR := 'a_tbl1'; +begin + EXECUTE IMMEDIATE 'drop table if exists ' || new_table; + EXECUTE IMMEDIATE 'CREATE TABLE ' || new_table || ' (id INT UNIQUE, name VARCHAR, phone VARCHAR DEFAULT ''000-0000'');'; + DBMS_OUTPUT.put_line ('creating ' || new_table || ' table is succeed!'); +end; diff --git a/demo/plcsql/test_dml_delete.sql b/demo/plcsql/test_dml_delete.sql new file mode 100644 index 00000000000..0a0be734afd --- /dev/null +++ b/demo/plcsql/test_dml_delete.sql @@ -0,0 +1,27 @@ +/* https://www.cubrid.org/manual/en/11.2/sql/query/update.html */ +/* +DROP TABLE a_tbl; +CREATE TABLE a_tbl( + id INT NOT NULL, + phone VARCHAR(10)); +INSERT INTO a_tbl VALUES(1,'111-1111'), (2,'222-2222'), (3, '333-3333'), (4, NULL), (5, NULL); +*/ +create or replace procedure test_dml_delete() as + p varchar; +begin + DELETE FROM a_tbl WHERE phone IS NULL; + +/* + id phone +=================================== + 1 '111-1111' + 2 '222-2222' + 3 '333-3333' + 5 NULL +*/ + + for r in (SELECT phone FROM a_tbl) loop + p := r.phone; + DBMS_OUTPUT.PUT_LINE(p); + end loop; +end; diff --git a/demo/plcsql/test_dml_insert.sql b/demo/plcsql/test_dml_insert.sql new file mode 100644 index 00000000000..cc94cefaf17 --- /dev/null +++ b/demo/plcsql/test_dml_insert.sql @@ -0,0 +1,77 @@ +/* https://www.cubrid.org/manual/en/11.2/sql/query/insert.html */ +/* + drop table if exists a_tbl1; + CREATE TABLE a_tbl1(id INT UNIQUE, name VARCHAR, phone VARCHAR DEFAULT '000-0000'); +*/ +create or replace procedure test_dml_insert() as + i int; + n varchar; + p varchar; + + new_table VARCHAR := 'a_tbl1'; + temp VARCHAR := ''; +begin +-- 0) +--insert default values with DEFAULT keyword before VALUES + INSERT INTO a_tbl1 DEFAULT VALUES; + +--insert multiple rows + INSERT INTO a_tbl1 VALUES (1,'aaa', DEFAULT),(2,'bbb', DEFAULT); + +--insert a single row specifying column values for all + INSERT INTO a_tbl1 VALUES (3,'ccc', '333-3333'); + +--insert two rows specifying column values for only + INSERT INTO a_tbl1(id) VALUES (4), (5); + +--insert a single row with SET clauses + + temp := temp || '/* (('; + temp := temp || '(((( */'; + + temp := temp || 'INSERT INTO a_tbl1 SET id=6, name=''eee'';'; + + temp := temp || '/* (('; + temp := temp || '(((( */'; + + DBMS_OUTPUT.put_line (temp); + + EXECUTE IMMEDIATE temp; + DBMS_OUTPUT.put_line(temp || ' is succeed'); + + INSERT INTO a_tbl1 SET id=7, phone='777-7777'; + +-- 1) + DBMS_OUTPUT.PUT_LINE('[Test 1] ====================================================================='); + INSERT INTO a_tbl1 SET id=6, phone='000-0000' ON DUPLICATE KEY UPDATE phone='666-6666'; + +-- 2) + DBMS_OUTPUT.PUT_LINE('Expected: '); + DBMS_OUTPUT.PUT_LINE(6 || ' ' || 'eee' || ' ' || '666-6666'); + + DBMS_OUTPUT.PUT_LINE('Actual: '); + for r in (SELECT id, name, phone FROM a_tbl1 WHERE id=6) loop + i := r.id; + n := r.name; + p := r.phone; + DBMS_OUTPUT.PUT_LINE(i || ' ' || n || ' ' || p); + end loop; + DBMS_OUTPUT.PUT_LINE('[Test 1] OK'); + +-- 3) + DBMS_OUTPUT.PUT_LINE('[Test 2] ====================================================================='); + DBMS_OUTPUT.PUT_LINE('Expected: '); + DBMS_OUTPUT.PUT_LINE(7 || ' ' || 'ggg' || ' ' || '777-7777'); + + INSERT INTO a_tbl1 SELECT * FROM a_tbl1 WHERE id=7 ON DUPLICATE KEY UPDATE name='ggg'; + + DBMS_OUTPUT.PUT_LINE('Actual: '); + for r in (SELECT id, name, phone FROM a_tbl1 WHERE id=7) loop + i := r.id; + n := r.name; + p := r.phone; + DBMS_OUTPUT.PUT_LINE(i || ' ' || n || ' ' || p); + end loop; + + DBMS_OUTPUT.PUT_LINE('[Test 2] OK'); +end; diff --git a/demo/plcsql/test_dml_truncate.sql b/demo/plcsql/test_dml_truncate.sql new file mode 100644 index 00000000000..c15666cc59e --- /dev/null +++ b/demo/plcsql/test_dml_truncate.sql @@ -0,0 +1,8 @@ +/* https://www.cubrid.org/manual/en/11.2/sql/query/truncate.html */ +/* + +*/ +create or replace procedure test_dml_truncate() as +begin + truncate TABLE a_tbl1; +end; diff --git a/demo/plcsql/test_query_cursor_hostvar.sql b/demo/plcsql/test_query_cursor_hostvar.sql new file mode 100644 index 00000000000..c87a288df2a --- /dev/null +++ b/demo/plcsql/test_query_cursor_hostvar.sql @@ -0,0 +1,22 @@ +create or replace function test_query_cursor_hostvar() return varchar as + g char(1) := 'M'; + n char(3) := 'KOR'; + + i int; + m varchar; +begin + i := 0; + for r in (select code, name from athlete where gender = g and nation_code = n) loop + i := r.code; + m := r.name; + end loop; + + return m; +exception +when no_data_found then + return 'no_data'; +when too_many_rows then + return 'too_many'; +when others then + return 'others'; +end; diff --git a/demo/plcsql/test_query_cursor_simple.sql b/demo/plcsql/test_query_cursor_simple.sql new file mode 100644 index 00000000000..75c86dc67e8 --- /dev/null +++ b/demo/plcsql/test_query_cursor_simple.sql @@ -0,0 +1,11 @@ +create or replace function test_query_cursor_simple() return int as +i int; +begin + i := 0; + for r in (select code, name from athlete where gender = 'M' and nation_code = 'KOR') loop + i := r.code; + EXIT; + end loop; + + return i; +end; diff --git a/demo/plcsql/test_query_cursor_simple_nocond.sql b/demo/plcsql/test_query_cursor_simple_nocond.sql new file mode 100644 index 00000000000..3f0ca2a8b3d --- /dev/null +++ b/demo/plcsql/test_query_cursor_simple_nocond.sql @@ -0,0 +1,11 @@ +create or replace function test_query_cursor_simple_nocond() return int as +i int; +begin + i := 0; + for r in (select code, name from athlete) loop + i := r.code; + EXIT; + end loop; + + return i; +end; \ No newline at end of file diff --git a/demo/plcsql/test_query_single_row.sql b/demo/plcsql/test_query_single_row.sql new file mode 100644 index 00000000000..fa20469f932 --- /dev/null +++ b/demo/plcsql/test_query_single_row.sql @@ -0,0 +1,16 @@ +create or replace function test_query_single_row(c int) return string as + g char(1) := 'M'; + n char(3) := 'KOR'; + + m varchar; +begin + select name into m from athlete where gender = g and nation_code = n and code = c; + return m; +exception +when no_data_found then + return 'no_data_found'; +when too_many_rows then + return 'too_many_rows'; +when others then + return 'others'; +end; diff --git a/demo/plcsql/test_query_single_row_const.sql b/demo/plcsql/test_query_single_row_const.sql new file mode 100644 index 00000000000..02c8fe4c59b --- /dev/null +++ b/demo/plcsql/test_query_single_row_const.sql @@ -0,0 +1,14 @@ +create or replace function test_query_single_row_const() return int as + c int; + m varchar; +begin + select code, name INTO c, m from athlete where gender = 'M' and nation_code = 'KOR' LIMIT 1; + return c; +exception +when no_data_found then + return 0; +when too_many_rows then + return 100; +when others then + return -1; +end; diff --git a/demo/plcsql/test_semantic_error_unknown_tbl.sql b/demo/plcsql/test_semantic_error_unknown_tbl.sql new file mode 100644 index 00000000000..942665b2f8f --- /dev/null +++ b/demo/plcsql/test_semantic_error_unknown_tbl.sql @@ -0,0 +1,4 @@ +create or replace procedure test_semantic_error_unknown_tbl() as +begin + insert into unknown_tbl(t) values (time'12:13:14'); +end; diff --git a/demo/plcsql/test_semantic_error_wrong_literal.sql b/demo/plcsql/test_semantic_error_wrong_literal.sql new file mode 100644 index 00000000000..1577716389a --- /dev/null +++ b/demo/plcsql/test_semantic_error_wrong_literal.sql @@ -0,0 +1,7 @@ +/* + create table test_insert(t time); +*/ +create or replace procedure test_wrong_literal() as +begin + insert into test_insert(t) values (time'12:13:14.123'); -- wrong time literal +end; diff --git a/demo/plcsql/test_tcl_commit.sql b/demo/plcsql/test_tcl_commit.sql new file mode 100644 index 00000000000..5b5dca1fa68 --- /dev/null +++ b/demo/plcsql/test_tcl_commit.sql @@ -0,0 +1,30 @@ +/* +csql -u public demodb +DROP TABLE IF EXISTS test_tcl_tbl; +CREATE TABLE test_tcl_tbl (code INT, name STRING); + +csql -u public demodb +;autocommit off +;server-output on +TRUNCATE test_tcl_tbl; +CALL test_tcl_commit (); +ROLLBACK; -- rollback in csql session +SELECT * FROM test_tcl_tbl; -- committed rows should be displayed +*/ +create or replace procedure test_tcl_commit() as + i int; + n varchar; +begin + INSERT INTO test_tcl_tbl VALUES (1,'aaa'); + INSERT INTO test_tcl_tbl VALUES (2,'bbb'); + INSERT INTO test_tcl_tbl VALUES (3,'ccc'); + INSERT INTO test_tcl_tbl VALUES (4,'ddd'); + COMMIT; + + for r in (SELECT code, name FROM test_tcl_tbl WHERE code > 2) loop + i := r.code; + n := r.name; + DBMS_OUTPUT.PUT_LINE(i); + DBMS_OUTPUT.PUT_LINE('code = ' || i || ' name = ' || n); + end loop; +end; diff --git a/demo/plcsql/test_tcl_rollback.sql b/demo/plcsql/test_tcl_rollback.sql new file mode 100644 index 00000000000..64304b7a9b0 --- /dev/null +++ b/demo/plcsql/test_tcl_rollback.sql @@ -0,0 +1,45 @@ +/* +=====[PREAPRE SCHEMA]======================================= +DROP TABLE IF EXISTS test_tcl_tbl2; +CREATE TABLE test_tcl_tbl2 (code INT, name STRING); + +=====[TEST]================================================= +;set autocommit off +;server-output on + +TRUNCATE test_tcl_tbl2; +CALL test_tcl_rollback (); +COMMIT; +SELECT * FROM test_tcl_tbl2; + +=====[Expected]============================================= + Expected: + === === + + code name + =================================== + 1 'aaa' + 2 'bbb' + 3 'ccc' + 4 'ddd' +*/ +create or replace procedure test_tcl_rollback () as + i int; + n varchar; +begin + INSERT INTO test_tcl_tbl2 VALUES (1,'aaa'); + INSERT INTO test_tcl_tbl2 VALUES (2,'bbb'); + INSERT INTO test_tcl_tbl2 VALUES (3,'ccc'); + INSERT INTO test_tcl_tbl2 VALUES (4,'ddd'); + COMMIT; + + INSERT INTO test_tcl_tbl2 VALUES (6,'daf'); + INSERT INTO test_tcl_tbl2 VALUES (7,'qwe'); + ROLLBACK; + + for r in (SELECT code, name FROM test_tcl_tbl2 WHERE code > 2) loop + i := r.code; + n := r.name; + DBMS_OUTPUT.PUT_LINE('code = ' || i || ', name = ' || n); + end loop; +end; diff --git a/docs/install_build_requirements.md b/docs/install_build_requirements.md index b92d730b54f..3ee6cb158bc 100644 --- a/docs/install_build_requirements.md +++ b/docs/install_build_requirements.md @@ -1,4 +1,4 @@ -# Installing Build Requiements +# Installing Build Requirements ## Build Requirements diff --git a/jsp/CMakeLists.txt b/jsp/CMakeLists.txt deleted file mode 100644 index a3500952f33..00000000000 --- a/jsp/CMakeLists.txt +++ /dev/null @@ -1,72 +0,0 @@ -# -# Copyright 2008 Search Solution Corporation -# Copyright 2016 CUBRID Corporation -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -include(FindJava) -find_package(Java 1.6 COMPONENTS Development) - -find_program(ANT ant PATHS $ENV{ANT_HOME} ENV PATH) -if(NOT ANT) - message(FATAL_ERROR "The ANT was not found. check PATH or install ant to build JDBC") -endif(NOT ANT) - -add_custom_target(jsp_build ALL) - -if (EXISTS ${CMAKE_SOURCE_DIR}/cubrid-jdbc/src) - set(JDBC_DIR ${CMAKE_SOURCE_DIR}/cubrid-jdbc) - set(JSP_LIB_DIR ${CMAKE_BINARY_DIR}/jsp/lib) - - add_custom_command(TARGET jsp_build - COMMAND ${CMAKE_COMMAND} -E make_directory ${JSP_LIB_DIR} - COMMAND ${CMAKE_COMMAND} -DJDBC_DIR=${JDBC_DIR} -DJSP_LIB_DIR=${JSP_LIB_DIR} -P ${CMAKE_SOURCE_DIR}/jsp/cmake/copy_submodule_jdbc.cmake - ) - - add_dependencies(jsp_build jdbc_build) -endif(EXISTS ${CMAKE_SOURCE_DIR}/cubrid-jdbc/src) - -# download ivy -message("Download ivy ...") -set(IVY_VERSION "2.4.0") -set(IVY_URL "https://archive.apache.org/dist/ant/ivy/${IVY_VERSION}/maven2/${IVY_VERSION}/ivy-${IVY_VERSION}.jar") -set(IVY_DIR "${CMAKE_BINARY_DIR}/jsp/external") -set(IVY_FILENAME "${IVY_DIR}/ivy.jar") -file(DOWNLOAD ${IVY_URL} ${IVY_FILENAME}) - -add_custom_command(TARGET jsp_build - COMMAND ${CMAKE_COMMAND} -E echo "copying ivy.xml to ${CMAKE_BINARY_DIR}/jsp/ivy.xml" - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/jsp/ivy.xml ${CMAKE_BINARY_DIR}/jsp/ivy.xml - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/jsp/ivysettings.xml ${CMAKE_BINARY_DIR}/jsp/ivysettings.xml - COMMAND ${ANT} dist -buildfile ${CMAKE_SOURCE_DIR}/jsp/build.xml -Dbasedir=. -Dversion=${BUILD_NUMBER} -Dsrc.dir=${JSP_DIR} -Divy.install.dir="${IVY_DIR}" - COMMENT "Build Java SP Server with Ant ..." -) - -add_custom_target(jsp_unittest) -add_custom_command(TARGET jsp_unittest - COMMAND ${ANT} test-junit -buildfile ${CMAKE_SOURCE_DIR}/jsp/build.xml -Dbasedir=. -Dversion=${BUILD_NUMBER} -Dsrc.dir=${JSP_DIR} -Divy.install.dir="${IVY_DIR}" - COMMENT "Unit Test Java SP Server with JUnit ..." -) - -install(FILES - ${CMAKE_CURRENT_BINARY_DIR}/jspserver.jar - ${JSP_DIR}/logging.properties - DESTINATION ${CUBRID_JAVADIR} -) - -install(DIRECTORY - ${CMAKE_CURRENT_BINARY_DIR}/lib/ - DESTINATION ${CUBRID_JAVADIR}/lib - FILES_MATCHING PATTERN "*.jar" -) diff --git a/jsp/build.xml b/jsp/build.xml deleted file mode 100644 index 8fed82736ff..00000000000 --- a/jsp/build.xml +++ /dev/null @@ -1,124 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jsp/ivy.xml b/jsp/ivy.xml deleted file mode 100644 index 0bd0c40f03d..00000000000 --- a/jsp/ivy.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/jsp/ivysettings.xml b/jsp/ivysettings.xml deleted file mode 100644 index e2b72d20e36..00000000000 --- a/jsp/ivysettings.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/msg/de_DE.utf8/cubrid.msg b/msg/de_DE.utf8/cubrid.msg index 6bdfa12e374..1fb6a8f1114 100644 --- a/msg/de_DE.utf8/cubrid.msg +++ b/msg/de_DE.utf8/cubrid.msg @@ -1444,8 +1444,9 @@ $ LOADDB 1358 Die Anzahl der betroffenen Zeilen ist unbekannt. 1359 Java VM crashed: %1$s +1360 In line %1$d, column %2$d\nStored procedure compile error: %3$s -1360 Letzter Fehler +1361 Letzter Fehler $set 6 MSGCAT_SET_INTERNAL 1 Fehler in Fehler-Subsystem (Zeile %1$d): @@ -1507,8 +1508,8 @@ $set 7 MSGCAT_SET_PARSER_SYNTAX 31 Ungültiges create Benutzer\n CREATE BENUTZER identifier {PASSWORD 'STRING'} {GROUPS identifier {, identifier}* } {MEMBERS identifier {, identifier}* } 32 Ungültiges create trigger\n CREATE TRIGGER identifier {STATE [ACTIVE|INACTIVE]} {PRIORITY unsigned_real}\n [BEFORE|AFTER|DEFERRED] event_spec {IF trigger_condition}\n EXECUTE {AFTER|DEFERRED} trigger_action 33 Ungültiges create serial\n CREATE SERIAL identifier {START WITH integer} {INCREMENT BY integer}\n serial_min_max {CYCLE|NOCYCLE} {CACHE unsigned_integer|NOCACHE} -34 Ungültiges create procedure\n CREATE PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} LANGUAGE JAVA NAME 'STRING' -35 Ungültiges create Funktion\n CREATE FUNKTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} LANGUAGE JAVA NAME 'STRING' +34 Ungültiges create procedure\n CREATE [OR REPLACE] PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {procedure_source|procedure_spec} +35 Ungültiges create Funktion\n CREATE [OR REPLACE] FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {function_source|function_spec} 36 Ungültiges groups\n groups spec: GROUPS identifier {, identifier}* 37 Ungültiges members\n member spec: MEMBERS identifier {, identifier}* 38 Ungültiges password\n password spec: PASSWORD 'STRING' @@ -1930,6 +1931,7 @@ $set 8 MSGCAT_SET_PARSER_SEMANTIC 314 Synonym "%1$s" does not exist. 315 Rename cannot change owner. 316 Rename cannot be changed to the same name. +317 Identifiers cannot be in a LIMIT clause. $set 9 MSGCAT_SET_PARSER_RUNTIME 1 Außer virtuellem Speicher: %1$d Bytes können nicht zugewiesen werden. diff --git a/msg/de_DE.utf8/utils.msg b/msg/de_DE.utf8/utils.msg index 4c0ea9cbf0a..00182234623 100644 --- a/msg/de_DE.utf8/utils.msg +++ b/msg/de_DE.utf8/utils.msg @@ -914,7 +914,9 @@ $set 34 MSGCAT_UTIL_SET_LOADJAVA Usage: loadjava [OPTION] database-name java-class-file\n\ \n\ valid options:\n\ - -y, --overwrite Klassendatei, wenn vorhanden, überschreiben, Standard nein\n + -y, --overwrite Klassendatei, wenn vorhanden, überschreiben, Standard nein\n\ + -p, --package Java-Paketname, leer, wenn nicht angegeben\n\ + -j, --jni add a Class or Jar to static loading for JNI\n $set 37 MSGCAT_UTIL_SET_PLANDUMP 15 Ausgangdatei '%1$s' kann nicht geöffnet werden\n diff --git a/msg/en_US.utf8/cubrid.msg b/msg/en_US.utf8/cubrid.msg index 406dfc61edd..29ee3cafd22 100644 --- a/msg/en_US.utf8/cubrid.msg +++ b/msg/en_US.utf8/cubrid.msg @@ -1444,8 +1444,9 @@ Check the path of the key file (_keys) and make sure that it includes proper key 1358 Number of rows affected is unknown. 1359 Java VM crashed: %1$s +1360 In line %1$d, column %2$d\nStored procedure compile error: %3$s -1360 Last Error +1361 Last Error $set 6 MSGCAT_SET_INTERNAL 1 Error in error subsystem (line %1$d): @@ -1507,8 +1508,8 @@ $set 7 MSGCAT_SET_PARSER_SYNTAX 31 invalid create user\n CREATE USER identifier {PASSWORD 'STRING'} {GROUPS identifier {, identifier}* } {MEMBERS identifier {, identifier}* } 32 invalid create trigger\n CREATE TRIGGER identifier {STATE [ACTIVE|INACTIVE]} {PRIORITY unsigned_real}\n [BEFORE|AFTER|DEFERRED] event_spec {IF trigger_condition}\n EXECUTE {AFTER|DEFERRED} trigger_action 33 invalid create serial\n CREATE SERIAL identifier {START WITH integer} {INCREMENT BY integer}\n serial_min_max {CYCLE|NOCYCLE} {CACHE unsigned_integer|NOCACHE} -34 invalid create procedure\n CREATE PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} LANGUAGE JAVA NAME 'STRING' -35 invalid create function\n CREATE FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} LANGUAGE JAVA NAME 'STRING' +34 invalid create procedure\n CREATE [OR REPLACE] PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {procedure_source|procedure_spec} +35 invalid create function\n CREATE [OR REPLACE] FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {function_source|function_spec} 36 invalid groups\n groups spec: GROUPS identifier {, identifier}* 37 invalid members\n member spec: MEMBERS identifier {, identifier}* 38 invalid password\n password spec: PASSWORD 'STRING' @@ -1930,6 +1931,7 @@ $set 8 MSGCAT_SET_PARSER_SEMANTIC 314 Synonym "%1$s" does not exist. 315 Rename cannot change owner. 316 Rename cannot be changed to the same name. +317 Identifiers cannot be in a LIMIT clause. $set 9 MSGCAT_SET_PARSER_RUNTIME 1 Out of virtual memory: unable to allocate %1$d bytes. diff --git a/msg/en_US.utf8/utils.msg b/msg/en_US.utf8/utils.msg index 507f5fbdf35..d39c1903c1d 100644 --- a/msg/en_US.utf8/utils.msg +++ b/msg/en_US.utf8/utils.msg @@ -915,7 +915,9 @@ $set 34 MSGCAT_UTIL_SET_LOADJAVA Usage: loadjava [OPTION] database-name java-class-file\n\ \n\ valid options:\n\ - -y, --overwrite overwrite class file if exist, default no\n + -y, --overwrite overwrite class file if exist, default no\n\ + -p, --package java package name, empty if not specified\n\ + -j, --jni add a Class or Jar to static loading for JNI\n $set 37 MSGCAT_UTIL_SET_PLANDUMP 15 Cannot open output file '%1$s'\n diff --git a/msg/en_US/cubrid.msg b/msg/en_US/cubrid.msg index a374f63c74e..dacb8ee924f 100644 --- a/msg/en_US/cubrid.msg +++ b/msg/en_US/cubrid.msg @@ -1445,8 +1445,9 @@ Check the path of the key file (_keys) and make sure that it includes proper key 1358 Number of rows affected is unknown. 1359 Java VM crashed: %1$s +1360 In line %1$d, column %2$d\nStored procedure compile error: %3$s -1360 Last Error +1361 Last Error $set 6 MSGCAT_SET_INTERNAL 1 Error in error subsystem (line %1$d): @@ -1508,8 +1509,8 @@ $set 7 MSGCAT_SET_PARSER_SYNTAX 31 invalid create user\n CREATE USER identifier {PASSWORD 'STRING'} {GROUPS identifier {, identifier}* } {MEMBERS identifier {, identifier}* } 32 invalid create trigger\n CREATE TRIGGER identifier {STATE [ACTIVE|INACTIVE]} {PRIORITY unsigned_real}\n [BEFORE|AFTER|DEFERRED] event_spec {IF trigger_condition}\n EXECUTE {AFTER|DEFERRED} trigger_action 33 invalid create serial\n CREATE SERIAL identifier {START WITH integer} {INCREMENT BY integer}\n serial_min_max {CYCLE|NOCYCLE} {CACHE unsigned_integer|NOCACHE} -34 invalid create procedure\n CREATE PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} LANGUAGE JAVA NAME 'STRING' -35 invalid create function\n CREATE FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} LANGUAGE JAVA NAME 'STRING' +34 invalid create procedure\n CREATE [OR REPLACE] PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {procedure_source|procedure_spec} +35 invalid create function\n CREATE [OR REPLACE] FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {function_source|function_spec} 36 invalid groups\n groups spec: GROUPS identifier {, identifier}* 37 invalid members\n member spec: MEMBERS identifier {, identifier}* 38 invalid password\n password spec: PASSWORD 'STRING' @@ -1931,6 +1932,7 @@ $set 8 MSGCAT_SET_PARSER_SEMANTIC 314 Synonym "%1$s" does not exist. 315 Rename cannot change owner. 316 Rename cannot be changed to the same name. +317 Identifiers cannot be in a LIMIT clause. $set 9 MSGCAT_SET_PARSER_RUNTIME 1 Out of virtual memory: unable to allocate %1$d bytes. diff --git a/msg/en_US/utils.msg b/msg/en_US/utils.msg index bd10407ed59..f8f60d43ef1 100644 --- a/msg/en_US/utils.msg +++ b/msg/en_US/utils.msg @@ -915,7 +915,9 @@ $set 34 MSGCAT_UTIL_SET_LOADJAVA Usage: loadjava [OPTION] database-name java-class-file\n\ \n\ valid options:\n\ - -y, --overwrite overwrite class file if exist, default no\n + -y, --overwrite overwrite class file if exist, default no\n\ + -p, --package java package name, empty if not specified\n\ + -j, --jni add a Class or Jar to static loading for JNI\n $set 37 MSGCAT_UTIL_SET_PLANDUMP 15 Cannot open output file '%1$s'\n diff --git a/msg/es_ES.utf8/cubrid.msg b/msg/es_ES.utf8/cubrid.msg index 6b041d5690c..28477edff4e 100644 --- a/msg/es_ES.utf8/cubrid.msg +++ b/msg/es_ES.utf8/cubrid.msg @@ -1444,8 +1444,9 @@ Verifique la ruta del archivo de claves (_keys) y asegúrese de que incluya la c 1358 Se desconoce el número de filas afectadas. 1359 Java VM crashed: %1$s +1360 In line %1$d, column %2$d\nStored procedure compile error: %3$s -1360 Ultimo error +1361 Ultimo error $set 6 MSGCAT_SET_INTERNAL 1 Error en subsistema de error (linea %1$d): @@ -1507,8 +1508,8 @@ $set 7 MSGCAT_SET_PARSER_SYNTAX 31 Crear utilizador no valido\n CREATE USER identifier {PASSWORD 'STRING'} {GROUPS identifier {, identifier}* } {MEMBERS identifier {, identifier}* } 32 Crear trigger no valido\n CREATE TRIGGER identifier {STATE [ACTIVE|INACTIVE]} {PRIORITY unsigned_real}\n [BEFORE|AFTER|DEFERRED] event_spec {IF trigger_condition}\n EXECUTE {AFTER|DEFERRED} trigger_action 33 Crear serial no valido\n CREATE SERIAL identifier {START WITH integer} {INCREMENT BY integer}\n serial_min_max {CYCLE|NOCYCLE} {CACHE unsigned_integer|NOCACHE} -34 Crear procedimiento no valido\n CREATE PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} LANGUAGE JAVA NAME 'STRING' -35 Crear funcion no valido\n CREATE FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} LANGUAGE JAVA NAME 'STRING' +34 Crear procedimiento no valido\n CREATE [OR REPLACE] PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {procedure_source|procedure_spec} +35 Crear funcion no valido\n CREATE [OR REPLACE] FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {function_source|function_spec} 36 Grupos no validos\n groups spec: GROUPS identifier {, identifier}* 37 Miembros no validos\n member spec: MEMBERS identifier {, identifier}* 38 Contraseña no valida\n password spec: PASSWORD 'STRING' @@ -1930,6 +1931,7 @@ $set 8 MSGCAT_SET_PARSER_SEMANTIC 314 Synonym "%1$s" does not exist. 315 Rename cannot change owner. 316 Rename cannot be changed to the same name. +317 Identifiers cannot be in a LIMIT clause. $set 9 MSGCAT_SET_PARSER_RUNTIME 1 Sin memoria virtual: incapaz de asignar %1$d bytes. diff --git a/msg/es_ES.utf8/utils.msg b/msg/es_ES.utf8/utils.msg index 8e7db57826d..cb63fdfe8e8 100644 --- a/msg/es_ES.utf8/utils.msg +++ b/msg/es_ES.utf8/utils.msg @@ -914,7 +914,9 @@ $set 34 MSGCAT_UTIL_SET_LOADJAVA Usage: loadjava [OPTION] database-name java-class-file\n\ \n\ valid options:\n\ - -y, --overwrite sobrescribir archivo de clase si existe, estandar no\n + -y, --overwrite sobrescribir archivo de clase si existe, estandar no\n\ + -p, --package nombre del paquete java, vacío si no se especifica\n\ + -j, --jni add a Class or Jar to static loading for JNI\n $set 37 MSGCAT_UTIL_SET_PLANDUMP 15 No se puede abrir archivo de salida '%1$s'\n diff --git a/msg/fr_FR.utf8/cubrid.msg b/msg/fr_FR.utf8/cubrid.msg index 97d482d6881..4a7bfcf03b0 100644 --- a/msg/fr_FR.utf8/cubrid.msg +++ b/msg/fr_FR.utf8/cubrid.msg @@ -1444,8 +1444,9 @@ Vérifiez le chemin du fichier de clé (_keys) et assurez-vous qu'il inclut la c 1358 Le nombre de lignes affectées est inconnu. 1359 Java VM crashed: %1$s +1360 In line %1$d, column %2$d\nStored procedure compile error: %3$s -1360 Dernière erreur +1361 Dernière erreur $set 6 MSGCAT_SET_INTERNAL 1 Erreur dans le sous-système d'erreur (ligne %1$d): @@ -1507,8 +1508,8 @@ $set 7 MSGCAT_SET_PARSER_SYNTAX 31 instruction non valide: create user\n CREATE USER identifier {PASSWORD 'STRING'} {GROUPS identifier {, identifier}* } {MEMBERS identifier {, identifier}* } 32 instruction non valide: create trigger\n CREATE TRIGGER identifier {STATE [ACTIVE|INACTIVE]} {PRIORITY unsigned_real}\n [BEFORE|AFTER|DEFERRED] event_spec {IF trigger_condition}\n EXECUTE {AFTER|DEFERRED} trigger_action 33 instruction non valide: create serial\n CREATE SERIAL identifier {START WITH integer} {INCREMENT BY integer}\n serial_min_max {CYCLE|NOCYCLE} {CACHE unsigned_integer|NOCACHE} -34 instruction non valide: create procedure\n CREATE PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} LANGUAGE JAVA NAME 'STRING' -35 instruction non valide: create function\n CREATE FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} LANGUAGE JAVA NAME 'STRING' +34 instruction non valide: create procedure\n CREATE [OR REPLACE] PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {procedure_source|procedure_spec} +35 instruction non valide: create function\n CREATE [OR REPLACE] FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {function_source|function_spec} 36 instruction non valide: groups\n groups spec: GROUPS identifier {, identifier}* 37 instruction non valide: members\n member spec: MEMBERS identifier {, identifier}* 38 instruction non valide: password\n password spec: PASSWORD 'STRING' @@ -1930,6 +1931,7 @@ $set 8 MSGCAT_SET_PARSER_SEMANTIC 314 Synonym "%1$s" does not exist. 315 Rename cannot change owner. 316 Rename cannot be changed to the same name. +317 Identifiers cannot be in a LIMIT clause. $set 9 MSGCAT_SET_PARSER_RUNTIME 1 Mémoire virtuelle épuisée: impossible d'allouer %1$d octets. diff --git a/msg/fr_FR.utf8/utils.msg b/msg/fr_FR.utf8/utils.msg index 007069d4f13..b077cdcf617 100644 --- a/msg/fr_FR.utf8/utils.msg +++ b/msg/fr_FR.utf8/utils.msg @@ -917,7 +917,9 @@ $set 34 MSGCAT_UTIL_SET_LOADJAVA Usage: loadjava [OPTION] database-name java-class-file\n\ \n\ valid options:\n\ - -y, --overwrite remplace le fichier de classe si lui existe, par défaut non\n + -y, --overwrite remplace le fichier de classe si lui existe, par défaut non\n\ + -p, --package nom du package java, vide s'il n'est pas spécifié\n\ + -j, --jni add a Class or Jar to static loading for JNI\n $set 37 MSGCAT_UTIL_SET_PLANDUMP 15 Impossible d'ouvrir le fichier de sortie '%1$s'\n diff --git a/msg/it_IT.utf8/cubrid.msg b/msg/it_IT.utf8/cubrid.msg index fc1e77f23d7..dac6ef310b9 100644 --- a/msg/it_IT.utf8/cubrid.msg +++ b/msg/it_IT.utf8/cubrid.msg @@ -1444,8 +1444,9 @@ Controllare il percorso del file della chiave (_keys) e assicurarsi che includa 1358 Il numero di righe interessate è sconosciuto. 1359 Java VM crashed: %1$s +1360 In line %1$d, column %2$d\nStored procedure compile error: %3$s -1360 Ultimo errore +1361 Ultimo errore $set 6 MSGCAT_SET_INTERNAL 1 Errore nel sottosistema di errore (linea %1$d): @@ -1507,8 +1508,8 @@ $set 7 MSGCAT_SET_PARSER_SYNTAX 31 Istruzione non valida "create user"\n CREATE USER identifier {PASSWORD 'STRING'} {GROUPS identifier {, identifier}* } {MEMBERS identifier {, identifier}* } 32 Istruzione non valida "create trigger"\n CREATE TRIGGER identifier {STATE [ACTIVE|INACTIVE]} {PRIORITY unsigned_real}\n [BEFORE|AFTER|DEFERRED] event_spec {IF trigger_condition} EXECUTE {AFTER|DEFERRED} trigger_action 33 Istruzione non valida "create serial"\n CREATE SERIAL identifier {START WITH integer} {INCREMENT BY integer}\n serial_min_max {CYCLE|NOCYCLE} {CACHE unsigned_integer|NOCACHE} -34 Istruzione non valida "create procedure"\n CREATE PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} LANGUAGE JAVA NAME 'STRING' -35 Istruzione non valida "create function"\n CREATE FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} LANGUAGE JAVA NAME 'STRING' +34 Istruzione non valida "create procedure"\n CREATE [OR REPLACE] PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {procedure_source|procedure_spec} +35 Istruzione non valida "create function"\n CREATE [OR REPLACE] FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {function_source|function_spec} 36 Istruzione non valida "groups"\n groups spec: GROUPS identifier {, identifier}* 37 Istruzione non valida "members"\n member spec: MEMBERS identifier {, identifier}* 38 Istruzione non valida "password"\n password spec: PASSWORD 'STRING' @@ -1930,6 +1931,7 @@ $set 8 MSGCAT_SET_PARSER_SEMANTIC 314 Synonym "%1$s" does not exist. 315 Rename cannot change owner. 316 Rename cannot be changed to the same name. +317 Identifiers cannot be in a LIMIT clause. $set 9 MSGCAT_SET_PARSER_RUNTIME 1 Fuori di memoria virtuale: Impossibile allocare %1$d byte. diff --git a/msg/it_IT.utf8/utils.msg b/msg/it_IT.utf8/utils.msg index 3dc3a6eceae..291fd39a8a4 100644 --- a/msg/it_IT.utf8/utils.msg +++ b/msg/it_IT.utf8/utils.msg @@ -914,7 +914,9 @@ $set 34 MSGCAT_UTIL_SET_LOADJAVA Usage: loadjava [OPTION] database-name java-class-file\n\ \n\ valid options:\n\ - -y, --overwrite sovrascrivere class file, se esiste, niente predefinito\n + -y, --overwrite sovrascrivere class file, se esiste, niente predefinito\n\ + -p, --package nome pacchetto java, vuoto se non specificato\n\ + -j, --jni add a Class or Jar to static loading for JNI\n $set 37 MSGCAT_UTIL_SET_PLANDUMP 15 Impossibile aprire il file di output '%1$s'\n diff --git a/msg/ja_JP.utf8/cubrid.msg b/msg/ja_JP.utf8/cubrid.msg index 944c3abd574..4f693b70096 100644 --- a/msg/ja_JP.utf8/cubrid.msg +++ b/msg/ja_JP.utf8/cubrid.msg @@ -1444,8 +1444,9 @@ $ LOADDB 1358 影響を受ける行数は不明です。 1359 Java VM crashed: %1$s +1360 In line %1$d, column %2$d\nStored procedure compile error: %3$s -1360 ラストエラー +1361 ラストエラー $set 6 MSGCAT_SET_INTERNAL 1 エラーサブシステムにエラー発生(ライン %1$d): @@ -1507,8 +1508,8 @@ $set 7 MSGCAT_SET_PARSER_SYNTAX 31 正しくないcreate userステートメントです。\n CREATE USER identifier {PASSWORD 'STRING'} {GROUPS identifier {, identifier}* } {MEMBERS identifier {, identifier}* } 32 正しくないcreate triggerステートメントです。\n CREATE TRIGGER identifier {STATE [ACTIVE|INACTIVE]} {PRIORITY unsigned_real}\n [BEFORE|AFTER|DEFERRED] event_spec {IF trigger_condition}\n EXECUTE {AFTER|DEFERRED} trigger_action 33 正しくないcreate シリアルステートメントです。\n CREATE シリアル identifier {START WITH integer} {INCREMENT BY integer}\n シリアル_min_max {CYCLE|NOCYCLE} {CACHE unsigned_integer|NOCACHE} -34 正しくないcreate procedureステートメントです。\n CREATE PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} LANGUAGE JAVA NAME 'STRING' -35 正しくないcreate functionステートメントです。\n CREATE FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} LANGUAGE JAVA NAME 'STRING' +34 正しくないcreate procedureステートメントです。\n CREATE [OR REPLACE] PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {procedure_source|procedure_spec} +35 正しくないcreate functionステートメントです。\n CREATE [OR REPLACE] FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {function_source|function_spec} 36 正しくないgroupsステートメントです。\n groups spec: GROUPS identifier {, identifier}* 37 正しくないmembersステートメントです。\n member spec: MEMBERS identifier {, identifier}* 38 正しくないpasswordステートメントです。\n password spec: PASSWORD 'STRING' @@ -1930,6 +1931,7 @@ $set 8 MSGCAT_SET_PARSER_SEMANTIC 314 Synonym "%1$s" does not exist. 315 Rename cannot change owner. 316 Rename cannot be changed to the same name. +317 Identifiers cannot be in a LIMIT clause. $set 9 MSGCAT_SET_PARSER_RUNTIME 1 バチャールメモリーが足りません。: %1$dバイトがアロケーションできません。 diff --git a/msg/ja_JP.utf8/utils.msg b/msg/ja_JP.utf8/utils.msg index 4ed89490bf1..0d4ada2ddaf 100644 --- a/msg/ja_JP.utf8/utils.msg +++ b/msg/ja_JP.utf8/utils.msg @@ -914,7 +914,9 @@ $set 34 MSGCAT_UTIL_SET_LOADJAVA Usage: loadjava [OPTION] database-name java-class-file\n\ \n\ valid options:\n\ - -y, --overwrite クラスファイルがもう存在したらオーバーライトする。; デフォルト: オーバーライトしない\n + -y, --overwrite クラスファイルがもう存在したらオーバーライトする。; デフォルト: オーバーライトしない\n\ + -p, --package Javaパッケージ名、指定されていない場合は空\n\ + -j, --jni add a Class or Jar to static loading for JNI\n $set 37 MSGCAT_UTIL_SET_PLANDUMP 15 出力ファイル「%1$s」が開けません。\n diff --git a/msg/km_KH.utf8/cubrid.msg b/msg/km_KH.utf8/cubrid.msg index 7072353024e..c7c699208a3 100644 --- a/msg/km_KH.utf8/cubrid.msg +++ b/msg/km_KH.utf8/cubrid.msg @@ -1444,8 +1444,9 @@ Check the path of the key file (_keys) and make sure that it includes proper key 1358 Number of rows affected is unknown. 1359 Java VM crashed: %1$s +1360 In line %1$d, column %2$d\nStored procedure compile error: %3$s -1360 Last Error +1361 Last Error $set 6 MSGCAT_SET_INTERNAL 1 Error in error subsystem (line %1$d): @@ -1507,8 +1508,8 @@ $set 7 MSGCAT_SET_PARSER_SYNTAX 31 invalid create user\n CREATE USER identifier {PASSWORD 'STRING'} {GROUPS identifier {, identifier}* } {MEMBERS identifier {, identifier}* } 32 invalid create trigger\n CREATE TRIGGER identifier {STATE [ACTIVE|INACTIVE]} {PRIORITY unsigned_real}\n [BEFORE|AFTER|DEFERRED] event_spec {IF trigger_condition}\n EXECUTE {AFTER|DEFERRED} trigger_action 33 invalid create serial\n CREATE SERIAL identifier {START WITH integer} {INCREMENT BY integer}\n serial_min_max {CYCLE|NOCYCLE} {CACHE unsigned_integer|NOCACHE} -34 invalid create procedure\n CREATE PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} LANGUAGE JAVA NAME 'STRING' -35 invalid create function\n CREATE FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} LANGUAGE JAVA NAME 'STRING' +34 invalid create procedure\n CREATE [OR REPLACE] PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {procedure_source|procedure_spec} +35 invalid create function\n CREATE [OR REPLACE] FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {function_source|function_spec} 36 invalid groups\n groups spec: GROUPS identifier {, identifier}* 37 invalid members\n member spec: MEMBERS identifier {, identifier}* 38 invalid password\n password spec: PASSWORD 'STRING' @@ -1930,6 +1931,7 @@ $set 8 MSGCAT_SET_PARSER_SEMANTIC 314 Synonym "%1$s" does not exist. 315 Rename cannot change owner. 316 Rename cannot be changed to the same name. +317 Identifiers cannot be in a LIMIT clause. $set 9 MSGCAT_SET_PARSER_RUNTIME 1 Out of virtual memory: unable to allocate %1$d bytes. diff --git a/msg/km_KH.utf8/utils.msg b/msg/km_KH.utf8/utils.msg index 4304adcee4d..8772b601318 100644 --- a/msg/km_KH.utf8/utils.msg +++ b/msg/km_KH.utf8/utils.msg @@ -916,7 +916,9 @@ $set 34 MSGCAT_UTIL_SET_LOADJAVA Usage: loadjava [OPTION] database-name java-class-file\n\ \n\ valid options:\n\ - -y, --overwrite overwrite class file if exist, default no\n + -y, --overwrite overwrite class file if exist, default no\n\ + -p, --package java package name, empty if not specified\n\ + -j, --jni add a Class or Jar to static loading for JNI\n $set 37 MSGCAT_UTIL_SET_PLANDUMP 15 Cannot open output file '%1$s'\n diff --git a/msg/ko_KR.euckr/cubrid.msg b/msg/ko_KR.euckr/cubrid.msg index f00cb98177e..c81017672bb 100644 --- a/msg/ko_KR.euckr/cubrid.msg +++ b/msg/ko_KR.euckr/cubrid.msg @@ -1444,8 +1444,9 @@ $ LOADDB 1358 . 1359 Java VM ְ ߻. : %1$s +1360 In line %1$d, column %2$d\nStored procedure compile error: %3$s -1360 +1361 $set 6 MSGCAT_SET_INTERNAL 1 ýۿ ߻( %1$d): @@ -1930,6 +1931,7 @@ $set 8 MSGCAT_SET_PARSER_SEMANTIC 314 Ǿ "%1$s"() ʽϴ. 315 ̸ ٲٱ ڸ ϴ. 316 ̸ ٲٱ ̸ ϴ. +317 ĺڴ LIMIT ȿ ϴ. $set 9 MSGCAT_SET_PARSER_RUNTIME 1 ޸ : %1$d Ʈ Ҵ ϴ. diff --git a/msg/ko_KR.euckr/utils.msg b/msg/ko_KR.euckr/utils.msg index 69f28d5c989..a49b2c85f42 100644 --- a/msg/ko_KR.euckr/utils.msg +++ b/msg/ko_KR.euckr/utils.msg @@ -914,7 +914,9 @@ $set 34 MSGCAT_UTIL_SET_LOADJAVA Usage: loadjava [OPTION] database-name java-class-file\n\ \n\ valid options:\n\ - -y, --overwrite Ŭ ̹ ϸ ; ⺻:  \n + -y, --overwrite Ŭ ̹ ϸ ; ⺻:  \n\ + -p, --package Java Ű ̸; ڿ\n\ + -j, --jni JNI ε Ŭ Ǵ Jar ߰\n $set 37 MSGCAT_UTIL_SET_PLANDUMP 15 '%1$s' ϴ\n diff --git a/msg/ko_KR.utf8/cubrid.msg b/msg/ko_KR.utf8/cubrid.msg index b947be8afcd..e3e32c456bb 100644 --- a/msg/ko_KR.utf8/cubrid.msg +++ b/msg/ko_KR.utf8/cubrid.msg @@ -1444,8 +1444,9 @@ $ LOADDB 1358 영향을 받은 행 수를 알 수 없음. 1359 Java VM 에 장애가 발생함. : %1$s +1360 In line %1$d, column %2$d\nStored procedure compile error: %3$s -1360 마지막 에러 +1361 마지막 에러 $set 6 MSGCAT_SET_INTERNAL 1 에러 서브 시스템에 에러 발생(라인 %1$d): @@ -1507,8 +1508,8 @@ $set 7 MSGCAT_SET_PARSER_SYNTAX 31 잘못된 형식의 create user 구문입니다.\n CREATE USER identifier {PASSWORD 'STRING'} {GROUPS identifier {, identifier}* } {MEMBERS identifier {, identifier}* } 32 잘못된 형식의 create trigger 구문입니다.\n CREATE TRIGGER identifier {STATE [ACTIVE|INACTIVE]} {PRIORITY unsigned_real}\n [BEFORE|AFTER|DEFERRED] event_spec {IF trigger_condition}\n EXECUTE {AFTER|DEFERRED} trigger_action 33 잘못된 형식의 create serial 구문입니다.\n CREATE SERIAL identifier {START WITH integer} {INCREMENT BY integer}\n serial_min_max {CYCLE|NOCYCLE} {CACHE unsigned_integer|NOCACHE} -34 잘못된 형식의 create procedure 구문입니다.\n CREATE PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} LANGUAGE JAVA NAME 'STRING' -35 잘못된 형식의 create function 구문입니다.\n CREATE FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} LANGUAGE JAVA NAME 'STRING' +34 잘못된 형식의 create procedure 구문입니다.\n CREATE [OR REPLACE] PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {procedure_source|procedure_spec} +35 잘못된 형식의 create function 구문입니다.\n CREATE [OR REPLACE] FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {function_source|function_spec} 36 잘못된 형식의 groups 구문입니다.\n groups spec: GROUPS identifier {, identifier}* 37 잘못된 형식의 members 구문입니다.\n member spec: MEMBERS identifier {, identifier}* 38 잘못된 형식의 password 구문입니다.\n password spec: PASSWORD 'STRING' @@ -1930,6 +1931,7 @@ $set 8 MSGCAT_SET_PARSER_SEMANTIC 314 동의어 "%1$s"이(가) 존재하지 않습니다. 315 이름 바꾸기는 소유자를 변경할 수 없습니다. 316 이름 바꾸기는 같은 이름으로 변경할 수 없습니다. +317 식별자는 LIMIT 절 안에 있을 수 없습니다. $set 9 MSGCAT_SET_PARSER_RUNTIME 1 가상 메모리 없음: %1$d 바이트를 할당할 수 없습니다. diff --git a/msg/ko_KR.utf8/utils.msg b/msg/ko_KR.utf8/utils.msg index 1983cdb6c34..1c02ba7556f 100644 --- a/msg/ko_KR.utf8/utils.msg +++ b/msg/ko_KR.utf8/utils.msg @@ -912,7 +912,9 @@ $set 34 MSGCAT_UTIL_SET_LOADJAVA Usage: loadjava [OPTION] database-name java-class-file\n\ \n\ valid options:\n\ - -y, --overwrite 클래스 파일이 이미 존재하면 덮어씀; 기본값: 덮어쓰지 않음\n + -y, --overwrite 클래스 파일이 이미 존재하면 덮어씀; 기본값: 덮어쓰지 않음\n\ + -p, --package Java 패키지 이름; 지정하지 않으면 빈 문자열\n\ + -j, --jni JNI 사용을 위해 정적 로딩 영역에 클래스 또는 Jar를 추가함\n $set 37 MSGCAT_UTIL_SET_PLANDUMP 15 출력 파일 '%1$s'을 열 수 없습니다\n diff --git a/msg/ro_RO.utf8/cubrid.msg b/msg/ro_RO.utf8/cubrid.msg index c49db51dc57..46d111804dc 100644 --- a/msg/ro_RO.utf8/cubrid.msg +++ b/msg/ro_RO.utf8/cubrid.msg @@ -1444,8 +1444,9 @@ Verificați calea fișierului cheie (_keys) și asigurați-vă că acesta includ 1358 Numărul de rânduri afectate este necunoscut. 1359 Java VM crashed: %1$s +1360 In line %1$d, column %2$d\nStored procedure compile error: %3$s -1360 Ultima eroare +1361 Ultima eroare $set 6 MSGCAT_SET_INTERNAL 1 Eroare în subsistemul de erori (linia %1$d): @@ -1507,8 +1508,8 @@ $set 7 MSGCAT_SET_PARSER_SYNTAX 31 instrucţiune invalidă: create user\n CREATE USER identifier {PASSWORD 'STRING'} {GROUPS identifier {, identifier}* } {MEMBERS identifier {, identifier}* } 32 instrucţiune invalidă: create trigger\n CREATE TRIGGER identifier {STATE [ACTIVE|INACTIVE]} {PRIORITY unsigned_real}\n [BEFORE|AFTER|DEFERRED] event_spec {IF trigger_condition}\n EXECUTE {AFTER|DEFERRED} trigger_action 33 instrucţiune invalidă: create serial\n CREATE SERIAL identifier {START WITH integer} {INCREMENT BY integer}\n serial_min_max {CYCLE|NOCYCLE} {CACHE unsigned_integer|NOCACHE} -34 instrucţiune invalidă: create procedure\n CREATE PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} LANGUAGE JAVA NAME 'STRING' -35 instrucţiune invalidă: create function\n CREATE FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} LANGUAGE JAVA NAME 'STRING' +34 instrucţiune invalidă: create procedure\n CREATE [OR REPLACE] PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {procedure_source|procedure_spec} +35 instrucţiune invalidă: create function\n CREATE [OR REPLACE] FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {function_source|function_spec} 36 instrucţiune invalidă: groups\n groups spec: GROUPS identifier {, identifier}* 37 instrucţiune invalidă: members\n member spec: MEMBERS identifier {, identifier}* 38 instrucţiune invalidă: password\n password spec: PASSWORD 'STRING' @@ -1930,6 +1931,7 @@ $set 8 MSGCAT_SET_PARSER_SEMANTIC 314 Synonym "%1$s" does not exist. 315 Rename cannot change owner. 316 Rename cannot be changed to the same name. +317 Identifiers cannot be in a LIMIT clause. $set 9 MSGCAT_SET_PARSER_RUNTIME 1 Memorie virtuală epuizată: nu s-au putut aloca %1$d bytes. diff --git a/msg/ro_RO.utf8/utils.msg b/msg/ro_RO.utf8/utils.msg index 58998eb3ce0..3c968d7a54b 100644 --- a/msg/ro_RO.utf8/utils.msg +++ b/msg/ro_RO.utf8/utils.msg @@ -931,7 +931,9 @@ $set 34 MSGCAT_UTIL_SET_LOADJAVA Usage: loadjava [OPTION] database-name java-class-file\n\ \n\ valid options:\n\ - -y, --overwrite suprascrie fişierul de clasă dacă exista, implicit nu\n + -y, --overwrite suprascrie fişierul de clasă dacă exista, implicit nu\n\ + -p, --package Numele pachetului Java, gol dacă nu este specificat\n\ + -j, --jni add a Class or Jar to static loading for JNI\n $set 37 MSGCAT_UTIL_SET_PLANDUMP 15 Fişierul de ieşire '%1$s' nu a putut fi deschis\n diff --git a/msg/tr_TR.utf8/cubrid.msg b/msg/tr_TR.utf8/cubrid.msg index 621f66ba7a8..10e179ea88c 100644 --- a/msg/tr_TR.utf8/cubrid.msg +++ b/msg/tr_TR.utf8/cubrid.msg @@ -1444,8 +1444,9 @@ Anahtar dosyasının (_keys) yolunu kontrol edin ve uygun anahtarı içerdiğind 1358 Etkilenen satır sayısı bilinmiyor. 1359 Java VM crashed: %1$s +1360 In line %1$d, column %2$d\nStored procedure compile error: %3$s -1360 Son Hata +1361 Son Hata $set 6 MSGCAT_SET_INTERNAL 1 Alt Hata içinde hata (satır %1$d): @@ -1507,8 +1508,8 @@ $set 7 MSGCAT_SET_PARSER_SYNTAX 31 geçersiz create user\n CREATE USER identifier {PASSWORD 'STRING'} {GROUPS identifier {, identifier}* } {MEMBERS identifier {, identifier}* } 32 geçersiz create trigger\n CREATE TRIGGER identifier {STATE [ACTIVE|INACTIVE]} {PRIORITY unsigned_real}\n [BEFORE|AFTER|DEFERRED] event_spec {IF trigger_condition}\n EXECUTE {AFTER|DEFERRED} trigger_action 33 geçersiz create serial\n CREATE SERIAL identifier {START WITH integer} {INCREMENT BY integer}\n serial_min_max {CYCLE|NOCYCLE} {CACHE unsigned_integer|NOCACHE} -34 geçersiz create procedure\n CREATE PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} LANGUAGE JAVA NAME 'STRING' -35 geçersiz create function\n CREATE FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} LANGUAGE JAVA NAME 'STRING' +34 geçersiz create procedure\n CREATE [OR REPLACE] PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {procedure_source|procedure_spec} +35 geçersiz create function\n CREATE [OR REPLACE] FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {function_source|function_spec} 36 geçersiz groups\n groups spec: GROUPS identifier {, identifier}* 37 geçersiz members\n member spec: MEMBERS identifier {, identifier}* 38 geçersiz password\n password spec: PASSWORD 'STRING' @@ -1930,6 +1931,7 @@ $set 8 MSGCAT_SET_PARSER_SEMANTIC 314 Synonym "%1$s" does not exist. 315 Rename cannot change owner. 316 Rename cannot be changed to the same name. +317 Identifiers cannot be in a LIMIT clause. $set 9 MSGCAT_SET_PARSER_RUNTIME 1 Sanal bellek yetersiz: %1$d bayt bölüm ayıramadı. diff --git a/msg/tr_TR.utf8/utils.msg b/msg/tr_TR.utf8/utils.msg index 36aa370a320..980af904340 100644 --- a/msg/tr_TR.utf8/utils.msg +++ b/msg/tr_TR.utf8/utils.msg @@ -914,7 +914,9 @@ $set 34 MSGCAT_UTIL_SET_LOADJAVA Usage: loadjava [OPTION] database-name java-class-file\n\ \n\ valid options:\n\ - -y, --overwrite varsa sınıf dosyanın üzerine yazmak, varsayılan yok\n + -y, --overwrite varsa sınıf dosyanın üzerine yazmak, varsayılan yok\n\ + -p, --package Java paket adı, belirtilmemişse boş\n\ + -j, --jni add a Class or Jar to static loading for JNI\n $set 37 MSGCAT_UTIL_SET_PLANDUMP 15 Çıktı dosyası '%1$s' açılamıyor \n diff --git a/msg/vi_VN.utf8/cubrid.msg b/msg/vi_VN.utf8/cubrid.msg index 1592070be66..4ba4950ea02 100644 --- a/msg/vi_VN.utf8/cubrid.msg +++ b/msg/vi_VN.utf8/cubrid.msg @@ -1451,8 +1451,9 @@ Check the path of the key file (_keys) and make sure that it includes proper key 1358 Number of rows affected is unknown. 1359 Java VM crashed: %1$s +1360 In line %1$d, column %2$d\nStored procedure compile error: %3$s -1360 Last Error +1361 Last Error $set 6 MSGCAT_SET_INTERNAL 1 Error in error subsystem (line %1$d): @@ -1514,8 +1515,8 @@ $set 7 MSGCAT_SET_PARSER_SYNTAX 31 invalid create user\n CREATE USER identifier {PASSWORD 'STRING'} {GROUPS identifier {, identifier}* } {MEMBERS identifier {, identifier}* } 32 invalid create trigger\n CREATE TRIGGER identifier {STATE [ACTIVE|INACTIVE]} {PRIORITY unsigned_real}\n [BEFORE|AFTER|DEFERRED] event_spec {IF trigger_condition}\n EXECUTE {AFTER|DEFERRED} trigger_action 33 invalid create serial\n CREATE SERIAL identifier {START WITH integer} {INCREMENT BY integer}\n serial_min_max {CYCLE|NOCYCLE} {CACHE unsigned_integer|NOCACHE} -34 invalid create procedure\n CREATE PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} LANGUAGE JAVA NAME 'STRING' -35 invalid create function\n CREATE FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} LANGUAGE JAVA NAME 'STRING' +34 invalid create procedure\n CREATE [OR REPLACE] PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {procedure_source|procedure_spec} +35 invalid create function\n CREATE [OR REPLACE] FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {function_source|function_spec} 36 invalid groups\n groups spec: GROUPS identifier {, identifier}* 37 invalid members\n member spec: MEMBERS identifier {, identifier}* 38 invalid password\n password spec: PASSWORD 'STRING' @@ -1937,6 +1938,7 @@ $set 8 MSGCAT_SET_PARSER_SEMANTIC 314 Synonym "%1$s" does not exist. 315 Rename cannot change owner. 316 Rename cannot be changed to the same name. +317 Identifiers cannot be in a LIMIT clause. $set 9 MSGCAT_SET_PARSER_RUNTIME 1 Out of virtual memory: unable to allocate %1$d bytes. diff --git a/msg/vi_VN.utf8/utils.msg b/msg/vi_VN.utf8/utils.msg index cd1c9556e85..5b7ee0a3e26 100644 --- a/msg/vi_VN.utf8/utils.msg +++ b/msg/vi_VN.utf8/utils.msg @@ -916,7 +916,9 @@ $set 34 MSGCAT_UTIL_SET_LOADJAVA Usage: loadjava [OPTION] database-name java-class-file\n\ \n\ valid options:\n\ - -y, --overwrite overwrite class file if exist, default no\n + -y, --overwrite overwrite class file if exist, default no\n\ + -p, --package java package name, empty if not specified\n\ + -j, --jni add a Class or Jar to static loading for JNI\n $set 37 MSGCAT_UTIL_SET_PLANDUMP 15 Cannot open output file '%1$s'\n diff --git a/msg/zh_CN.utf8/cubrid.msg b/msg/zh_CN.utf8/cubrid.msg index db33d149f4e..97c91fc89f2 100644 --- a/msg/zh_CN.utf8/cubrid.msg +++ b/msg/zh_CN.utf8/cubrid.msg @@ -1445,8 +1445,9 @@ $ LOADDB 1358 受影响的行数未知。 1359 Java VM crashed: %1$s +1360 In line %1$d, column %2$d\nStored procedure compile error: %3$s -1360 最后一个错误. +1361 最后一个错误. $set 6 MSGCAT_SET_INTERNAL 1 在错误子系统中错误 (line %1$d): @@ -1508,8 +1509,8 @@ $set 7 MSGCAT_SET_PARSER_SYNTAX 31 无效的 create user\n CREATE USER identifier {PASSWORD 'STRING'} {GROUPS identifier {, identifier}* } {MEMBERS identifier {, identifier}* } 32 无效的 create trigger\n CREATE TRIGGER identifier {STATE [ACTIVE|INACTIVE]} {PRIORITY unsigned_real}\n [BEFORE|AFTER|DEFERRED] event_spec {IF trigger_condition}\n EXECUTE {AFTER|DEFERRED} trigger_action 33 无效的 create serial\n CREATE SERIAL identifier {START WITH integer} {INCREMENT BY integer}\n serial_min_max {CYCLE|NOCYCLE} {CACHE unsigned_integer|NOCACHE} -34 无效的 create procedure\n CREATE PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} LANGUAGE JAVA NAME 'STRING' -35 无效的 create function\n CREATE FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} LANGUAGE JAVA NAME 'STRING' +34 无效的 create procedure\n CREATE [OR REPLACE] PROCEDURE identifier '(' {sp_param_list} ')' {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {procedure_source|procedure_spec} +35 无效的 create function\n CREATE [OR REPLACE] FUNCTION identifier '(' {sp_param_list} ')' RETURN {data_type|CURSOR} {IS|AS} {[LANGUAGE PLCSQL|LANGUAGE JAVA]} {function_source|function_spec} 36 无效的组\n groups spec: GROUPS identifier {, identifier}* 37 无效的成员\n member spec: MEMBERS identifier {, identifier}* 38 无效的密码\n password spec : PASSWORD 'STRING' @@ -1931,6 +1932,7 @@ $set 8 MSGCAT_SET_PARSER_SEMANTIC 314 Synonym "%1$s" does not exist. 315 Rename cannot change owner. 316 Rename cannot be changed to the same name. +317 Identifiers cannot be in a LIMIT clause. $set 9 MSGCAT_SET_PARSER_RUNTIME 1 虚拟内存耗尽: 无法申请 %1$d 字节. diff --git a/msg/zh_CN.utf8/utils.msg b/msg/zh_CN.utf8/utils.msg index 0c249007aff..16f19d84f14 100644 --- a/msg/zh_CN.utf8/utils.msg +++ b/msg/zh_CN.utf8/utils.msg @@ -913,7 +913,9 @@ $set 34 MSGCAT_UTIL_SET_LOADJAVA Usage: loadjava [OPTION] database-name java-class-file\n\ \n\ valid options:\n\ - -y, --overwrite 如果类存在则进行重写, 默认 不\n + -y, --overwrite 如果类存在则进行重写, 默认 不\n\ + -p, --package Java包名,不指定则为空\n\ + -j, --jni add a Class or Jar to static loading for JNI\n $set 37 MSGCAT_UTIL_SET_PLANDUMP 15 无法打开输出文件 '%1$s'\n diff --git a/pl_engine/.gitattributes b/pl_engine/.gitattributes new file mode 100644 index 00000000000..097f9f98d9e --- /dev/null +++ b/pl_engine/.gitattributes @@ -0,0 +1,9 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + diff --git a/pl_engine/.gitignore b/pl_engine/.gitignore new file mode 100644 index 00000000000..4a305d7d24a --- /dev/null +++ b/pl_engine/.gitignore @@ -0,0 +1,6 @@ +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build +bin \ No newline at end of file diff --git a/pl_engine/CMakeLists.txt b/pl_engine/CMakeLists.txt new file mode 100644 index 00000000000..86020ea20d1 --- /dev/null +++ b/pl_engine/CMakeLists.txt @@ -0,0 +1,65 @@ +# +# Copyright 2008 Search Solution Corporation +# Copyright 2016 CUBRID Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +include(FindJava) +find_package(Java 1.6 COMPONENTS Development) + +set(PL_ENGINE_SOURCE_DIR ${CMAKE_SOURCE_DIR}/pl_engine) +set(PL_ENGINE_BUILD_DIR ${CMAKE_BINARY_DIR}/pl_engine) + +# Find gradlew +if(UNIX) + set(GRADLE_EXECUTABLE ${PL_ENGINE_SOURCE_DIR}/gradlew) +else(UNIX) + set(GRADLE_EXECUTABLE ${PL_ENGINE_SOURCE_DIR}/gradlew.bat) +endif(UNIX) + +set(LOCAL_JDBC_PATH_COMMAND) + +add_custom_target(pl_build ALL) + +if (EXISTS ${CMAKE_SOURCE_DIR}/cubrid-jdbc/src) + set(JDBC_DIR ${CMAKE_SOURCE_DIR}/cubrid-jdbc) + set(PL_LIB_DIR ${PL_ENGINE_BUILD_DIR}/lib) + + add_custom_command(TARGET pl_build + COMMAND ${CMAKE_COMMAND} -E make_directory ${PL_LIB_DIR} + COMMAND ${CMAKE_COMMAND} -DJDBC_DIR=${JDBC_DIR} -DPL_LIB_DIR=${PL_LIB_DIR} -P ${PL_ENGINE_SOURCE_DIR}/cmake/copy_submodule_jdbc.cmake + ) + + set(LOCAL_JDBC_PATH_COMMAND "-PcubridJdbcPath=${PL_LIB_DIR}") + message ("Add cubrid jdbc dependency from cubrid-jdbc submodule path: ${LOCAL_JDBC_PATH_COMMAND}") + + add_dependencies(pl_build jdbc_build) +endif(EXISTS ${CMAKE_SOURCE_DIR}/cubrid-jdbc/src) + +add_custom_command(TARGET pl_build + COMMAND ${CMAKE_COMMAND} -E make_directory ${PL_ENGINE_BUILD_DIR} + COMMAND ${GRADLE_EXECUTABLE} build -x test -p ${PL_ENGINE_SOURCE_DIR} -PbuildDir=${PL_ENGINE_BUILD_DIR} ${LOCAL_JDBC_PATH_COMMAND} +) + +add_custom_target(pl_unittest) +add_custom_command(TARGET pl_unittest + COMMAND ${GRADLE_EXECUTABLE} cleanTest test -p ${PL_ENGINE_SOURCE_DIR} -DbuildDir=${PL_ENGINE_BUILD_DIR} ${LOCAL_JDBC_PATH_COMMAND} +) +add_dependencies(pl_unittest pl_build) + +install(FILES + ${PL_ENGINE_BUILD_DIR}/libs/pl_server.jar + ${PL_ENGINE_BUILD_DIR}/resources/main/logging.properties + DESTINATION ${CUBRID_JAVADIR} +) \ No newline at end of file diff --git a/jsp/cmake/copy_submodule_jdbc.cmake b/pl_engine/cmake/copy_submodule_jdbc.cmake similarity index 81% rename from jsp/cmake/copy_submodule_jdbc.cmake rename to pl_engine/cmake/copy_submodule_jdbc.cmake index 875d8273bb6..52b6acfaf04 100644 --- a/jsp/cmake/copy_submodule_jdbc.cmake +++ b/pl_engine/cmake/copy_submodule_jdbc.cmake @@ -21,9 +21,9 @@ message ("[INFO] JDBC Driver built at cubrid-jdbc submodule") set(JDBC_VERSION_FILE ${JDBC_DIR}/output/VERSION-DIST) file(STRINGS ${JDBC_VERSION_FILE} JDBC_VERSION_STR) execute_process ( - COMMAND ${CMAKE_COMMAND} -E copy ${JDBC_DIR}/JDBC-${JDBC_VERSION_STR}-cubrid.jar ${JSP_LIB_DIR}/cubrid-jdbc-${JDBC_VERSION_STR}.jar + COMMAND ${CMAKE_COMMAND} -E copy ${JDBC_DIR}/JDBC-${JDBC_VERSION_STR}-cubrid.jar ${PL_LIB_DIR}/cubrid-jdbc-${JDBC_VERSION_STR}.jar ) -if (NOT EXISTS ${JSP_LIB_DIR}/cubrid-jdbc-${JDBC_VERSION_STR}.jar) +if (NOT EXISTS ${PL_LIB_DIR}/cubrid-jdbc-${JDBC_VERSION_STR}.jar) message (FATAL_ERROR "Could not copy JDBC driver") -endif (NOT EXISTS ${JSP_LIB_DIR}/cubrid-jdbc-${JDBC_VERSION_STR}.jar) +endif (NOT EXISTS ${PL_LIB_DIR}/cubrid-jdbc-${JDBC_VERSION_STR}.jar) diff --git a/pl_engine/gradle/wrapper/gradle-wrapper.jar b/pl_engine/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..c1962a79e29 Binary files /dev/null and b/pl_engine/gradle/wrapper/gradle-wrapper.jar differ diff --git a/pl_engine/gradle/wrapper/gradle-wrapper.properties b/pl_engine/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..37aef8d3f0c --- /dev/null +++ b/pl_engine/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/pl_engine/gradlew b/pl_engine/gradlew new file mode 100755 index 00000000000..dafd1297742 --- /dev/null +++ b/pl_engine/gradlew @@ -0,0 +1,245 @@ +#!/bin/sh +# +# +# Copyright 2016 CUBRID Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/pl_engine/gradlew.bat b/pl_engine/gradlew.bat new file mode 100644 index 00000000000..dbe840bb8c7 --- /dev/null +++ b/pl_engine/gradlew.bat @@ -0,0 +1,95 @@ +@echo off + +@rem +@rem +@rem Copyright 2016 CUBRID Corporation +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/pl_engine/pl_server/build.gradle.kts b/pl_engine/pl_server/build.gradle.kts new file mode 100644 index 00000000000..8ee0fbf52c2 --- /dev/null +++ b/pl_engine/pl_server/build.gradle.kts @@ -0,0 +1,150 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * This generated file contains a sample Java application project to get you started. + * For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle + * User Manual available at https://docs.gradle.org/8.1.1/userguide/building_java_projects.html + */ + +import org.gradle.api.tasks.testing.logging.TestExceptionFormat +import org.gradle.api.tasks.testing.logging.TestLogEvent + +plugins { + // Apply the application plugin to add support for building a CLI application in Java. + antlr + java + application +} + +repositories { + mavenLocal() + + // Use Maven Central for resolving dependencies. + mavenCentral() + + // CUBRID JDBC + var jdbc_path = project.properties["cubridJdbcPath"] + if (jdbc_path != null) { + // find cubrid-jdbc in local submodule path + flatDir { + dirs("$jdbc_path") + } + } else { + // find in cubrid's artifactory repository + maven { + url = uri("http://maven.cubrid.org/") + isAllowInsecureProtocol = true + } + } +} + +dependencies { + // Use JUnit Jupiter for testing. + testImplementation("org.junit.jupiter:junit-jupiter:5.9.1") + + // Unix Domain Socket + implementation("com.kohlschutter.junixsocket:junixsocket-core:2.8.3") + implementation("com.kohlschutter.junixsocket:junixsocket-server:2.8.3") + + // ANTLR + antlr("org.antlr:antlr4:4.9.3") + + implementation("org.apache.commons:commons-text:1.10.0") + implementation("org.apache.commons:commons-collections4:4.4") + implementation("org.apache.commons:commons-lang3:3.13.0") + implementation("org.antlr:antlr4-runtime:4.9.3") + + // CUBRID JDBC + implementation("cubrid:cubrid-jdbc:latest.integration") + + // netty + implementation("io.netty:netty-buffer:4.1.95.Final") +} + +// Antlr +tasks.generateGrammarSource { + // outputDirectory = file("${project.buildDir}/generated-src/antlr") + arguments = arguments + listOf("-listener","-visitor") +} + +// Apply a specific Java toolchain to ease working on different environments. +java { + toolchain { + languageVersion.set(JavaLanguageVersion.of(8)) + } +} + +application { + // Define the main class for the application. + mainClass.set("com.cubrid.jsp.Server") +} + +tasks.test { + // Use JUnit Platform for unit tests. + useJUnitPlatform() + + testLogging { + lifecycle { + events = mutableSetOf(TestLogEvent.FAILED, TestLogEvent.PASSED, TestLogEvent + .SKIPPED) + exceptionFormat = TestExceptionFormat.FULL + + showExceptions = true + showCauses = true + showStackTraces = true + showStandardStreams = true + } + info.events = lifecycle.events + info.exceptionFormat = lifecycle.exceptionFormat + } + + val failedTests = mutableListOf() + val skippedTests = mutableListOf() + + addTestListener(object : TestListener { + override fun beforeSuite(suite: TestDescriptor) {} + + override fun beforeTest(testDescriptor: TestDescriptor) {} + + override fun afterTest(testDescriptor: TestDescriptor, result: TestResult) { + when (result.resultType) { + TestResult.ResultType.FAILURE -> failedTests.add(testDescriptor) + TestResult.ResultType.SKIPPED -> skippedTests.add(testDescriptor) + else -> Unit + } + } + + override fun afterSuite(suite: TestDescriptor, result: TestResult) { + if (suite.parent == null) { + logger.lifecycle("\n################ Summary::Start ################") + logger.lifecycle("Test result: ${result.resultType}") + logger.lifecycle( + "Test summary: ${result.testCount} tests, " + + "${result.successfulTestCount} succeeded, " + + "${result.failedTestCount} failed, " + + "${result.skippedTestCount} skipped") + failedTests.takeIf { it.isNotEmpty() }?.prefixedSummary("\tFailed Tests") + skippedTests.takeIf { it.isNotEmpty() }?.prefixedSummary("\tSkipped Tests:") + logger.lifecycle("################ Summary::End ##################") + } + } + + private infix fun List.prefixedSummary(subject: String) { + logger.lifecycle(subject) + forEach { test -> logger.lifecycle("\t\t${test.displayName()}") } + } + + private fun TestDescriptor.displayName() = parent?.let { "${it.name} - $name" } ?: "$name" + + }) +} + +tasks.jar { + // To make fat Jar + val dependencies = configurations + .runtimeClasspath + .get() + .map(::zipTree) // OR .map { zipTree(it) } + from(dependencies) + duplicatesStrategy = DuplicatesStrategy.EXCLUDE +} diff --git a/pl_engine/pl_server/src/main/antlr/PlcLexer.g4 b/pl_engine/pl_server/src/main/antlr/PlcLexer.g4 new file mode 100644 index 00000000000..abe1c7bfa33 --- /dev/null +++ b/pl_engine/pl_server/src/main/antlr/PlcLexer.g4 @@ -0,0 +1,297 @@ +/** + * CUBRID PL/CSQL Parser grammar based on and updated from + * Oracle(c) PL/SQL 11g Parser (https://github.com/antlr/grammars-v4/tree/master/sql/plsql) + * + * Copyright (c) 2009-2011 Alexandre Porcelli + * Copyright (c) 2015-2019 Ivan Kochurkin (KvanTTT, kvanttt@gmail.com, Positive Technologies). + * Copyright (c) 2017 Mark Adams + * Copyright (c) 2016 CUBRID Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +lexer grammar PlcLexer; + +@header { +package com.cubrid.plcsql.compiler.antlrgen; +} + +@members { +private int staticSqlParenMatch = -1; +private boolean checkFirstLParen = false; // to detect that it is actually not a static sql but a built-in function call +} + +// keywords that starts Static SQL +// INSERT, REPLACE, TRAUNCATE: also a built-in function +WITH: W I T H { staticSqlParenMatch++; mode(STATIC_SQL); }; +SELECT: S E L E C T { staticSqlParenMatch++; mode(STATIC_SQL); }; +INSERT: I N S E R T { staticSqlParenMatch++; checkFirstLParen = true; mode(STATIC_SQL); }; +UPDATE: U P D A T E { staticSqlParenMatch++; mode(STATIC_SQL); }; +DELETE: D E L E T E { staticSqlParenMatch++; mode(STATIC_SQL); }; +REPLACE: R E P L A C E { staticSqlParenMatch++; checkFirstLParen = true; mode(STATIC_SQL); }; +MERGE: M E R G E { staticSqlParenMatch++; mode(STATIC_SQL); }; +TRUNCATE: T R U N C A T E { staticSqlParenMatch++; checkFirstLParen = true; mode(STATIC_SQL); }; + +// other keywords +AND: A N D ; +AS: A S ; +AUTONOMOUS_TRANSACTION: A U T O N O M O U S '_' T R A N S A C T I O N ; +BEGIN: B E G I N ; +BETWEEN: B E T W E E N ; +BIGINT: B I G I N T ; +BOOLEAN: B O O L E A N ; +BY: B Y ; +CASE: C A S E ; +CHARACTER: C H A R A C T E R ; +CHAR: C H A R ; +CLOSE: C L O S E ; +COMMENT: C O M M E N T ; +COMMIT: C O M M I T ; +CONSTANT: C O N S T A N T ; +CONTINUE: C O N T I N U E ; +CREATE: C R E A T E ; +CURSOR: C U R S O R ; +DATE: D A T E ; +DATETIME: D A T E T I M E ; +DATETIMELTZ: D A T E T I M E L T Z ; +DATETIMETZ: D A T E T I M E T Z ; +DBMS_OUTPUT: D B M S '_' O U T P U T ; +DEC: D E C ; +DECIMAL: D E C I M A L ; +DECLARE: D E C L A R E ; +DEFAULT: D E F A U L T ; +DIV: D I V ; +DOUBLE: D O U B L E ; +ELSE: E L S E ; +ELSIF: E L S I F ; +END: E N D ; +ESCAPE: E S C A P E ; +EXCEPTION: E X C E P T I O N ; +EXECUTE: E X E C U T E ; +EXIT: E X I T ; +FALSE: F A L S E ; +FETCH: F E T C H ; +FLOAT: F L O A T ; +FOR: F O R ; +FUNCTION: F U N C T I O N ; +IF: I F ; +IMMEDIATE: I M M E D I A T E ; +IN: I N ; +INOUT: I N O U T ; +INTEGER: I N T E G E R ; +INT: I N T ; +INTO: I N T O ; +IS: I S ; +LANGUAGE: L A N G U A G E ; +LIKE: L I K E ; +LIST: L I S T ; +LOOP: L O O P ; +MOD: ( M O D | '%' ) ; +MULTISET: M U L T I S E T ; +NOT: N O T ; +NULL_: N U L L ; +NUMERIC: N U M E R I C ; +OF: O F ; +OPEN: O P E N ; +OR_REPLACE: O R SPACE+ R E P L A C E ; +OR: O R ; +OUT: O U T ; +PERCENT_FOUND: '%' SPACE* F O U N D ; +PERCENT_ISOPEN: '%' SPACE* I S O P E N ; +PERCENT_NOTFOUND: '%' SPACE* N O T F O U N D ; +PERCENT_ROWCOUNT: '%' SPACE* R O W C O U N T ; +PERCENT_TYPE: '%' SPACE* T Y P E ; +PLCSQL: P L C S Q L ; +PRAGMA: P R A G M A ; +PRECISION: P R E C I S I O N ; +PROCEDURE: P R O C E D U R E ; +RAISE: R A I S E ; +RAISE_APPLICATION_ERROR: R A I S E '_' A P P L I C A T I O N '_' E R R O R ; +REAL: R E A L ; +RETURN: R E T U R N ; +REVERSE: R E V E R S E ; +ROLLBACK: R O L L B A C K ; +SEQUENCE: S E Q U E N C E ; +SET: S E T ; +SETEQ: S E T E Q ; +SETNEQ: S E T N E Q ; +SHORT: S H O R T ; +SMALLINT: S M A L L I N T ; +SQL: S Q L ; +SQLCODE: S Q L C O D E ; +SQLERRM: S Q L E R R M ; +STRING: S T R I N G ; +SUBSET: S U B S E T ; +SUBSETEQ: S U B S E T E Q ; +SUPERSET: S U P E R S E T ; +SUPERSETEQ: S U P E R S E T E Q ; +SYS_REFCURSOR: S Y S '_' R E F C U R S O R ; +THEN: T H E N ; +TIMESTAMP: T I M E S T A M P ; +TIMESTAMPLTZ: T I M E S T A M P L T Z ; +TIMESTAMPTZ: T I M E S T A M P T Z ; +TIME: T I M E ; +TRUE: T R U E ; +USING: U S I N G ; +VARCHAR: V A R C H A R ; +WHEN: W H E N ; +WHILE: W H I L E ; +WORK: W O R K ; +XOR: X O R ; +VARYING: V A R Y I N G ; + +PERIOD2: '..'; +PERIOD: '.'; + +// NOTE: a literal with 'e/E' notation is deemed to be a DOUBLE type numeric literal in CUBRID even when +// it does not have a floating point +FLOATING_POINT_NUM: FPNUM_W_POINT | FPNUM_WO_POINT; +UNSIGNED_INTEGER: BASIC_UINT; + +DELIMITED_ID: ('"' REGULAR_ID '"') | ('[' REGULAR_ID ']') | ('`' REGULAR_ID '`') ; +CHAR_STRING: '\'' (~('\'' | '\r' | '\n') | '\'' '\'' | NEWLINE)* '\''; + +NULL_SAFE_EQUALS_OP: '<=>'; + +GE: '>='; +LE: '<='; +CONCAT_OP: '||'; +LT2: '<<'; +GT2: '>>'; +ASTERISK2: '**'; + +LPAREN: '('; +RPAREN: ')'; +ASTERISK: '*'; +PLUS_SIGN: '+'; +MINUS_SIGN: '-'; +BIT_COMPLI: '~'; +COMMA: ','; +SOLIDUS: '/'; +AT_SIGN: '@'; +ASSIGN_OP: ':='; + +NOT_EQUAL_OP: '!=' + | '<>' + ; + +AMPERSAND: '&'; +CARRET_OP: '^'; +EXCLAMATION_OP: '!'; +GT: '>'; +LT: '<'; +COLON: ':'; +SEMICOLON: ';'; + +BAR: '|'; +EQUALS_OP: '='; + +LEFT_BRACKET: '['; +RIGHT_BRACKET: ']'; + +LEFT_BRACE: '{'; +RIGHT_BRACE: '}'; + +INTRODUCER: '_'; + +SINGLE_LINE_COMMENT: '--' ~('\r' | '\n')* NEWLINE_EOF -> channel(HIDDEN); +SINGLE_LINE_COMMENT2: '//' ~('\r' | '\n')* NEWLINE_EOF -> channel(HIDDEN); +MULTI_LINE_COMMENT: '/*' .*? '*/' -> channel(HIDDEN); + +REGULAR_ID: (SIMPLE_LETTER | '_') (SIMPLE_LETTER | '_' | [0-9])*; + +SPACES: [ \t\r\n]+ -> channel(HIDDEN); + +// ************************ +mode STATIC_SQL; +// ************************ + +// Do not drop comments because they can have a hint. +SS_SINGLE_LINE_COMMENT: '--' ~('\r' | '\n')* NEWLINE_EOF { setType(PlcParser.SS_NON_STR); } ; +SS_SINGLE_LINE_COMMENT2: '//' ~('\r' | '\n')* NEWLINE_EOF { setType(PlcParser.SS_NON_STR); } ; +SS_MULTI_LINE_COMMENT: '/*' .*? '*/' { setType(PlcParser.SS_NON_STR); } ; + +SS_SEMICOLON : ';' { + setType(PlcParser.SEMICOLON); + staticSqlParenMatch = -1; + checkFirstLParen = false; + mode(DEFAULT_MODE); + }; +SS_STR : '\'' (~('\'' | '\r' | '\n') | '\'' '\'' | NEWLINE)* '\'' { + checkFirstLParen = false; + }; +SS_WS : [ \t\r\n]+ ; +SS_LPAREN : '(' { + if (checkFirstLParen) { + setType(PlcParser.LPAREN); + staticSqlParenMatch = -1; + checkFirstLParen = false; + mode(DEFAULT_MODE); + } else { + staticSqlParenMatch++; + setType(PlcParser.SS_NON_STR); + } + }; +SS_RPAREN : ')' { + checkFirstLParen = false; + staticSqlParenMatch--; + if (staticSqlParenMatch == -1) { + mode(DEFAULT_MODE); + setType(PlcParser.RPAREN); + } else { + setType(PlcParser.SS_NON_STR); + } + }; +SS_NON_STR: ~( ';' | '\'' | ' ' | '\t' | '\r' | '\n' | '(' | ')' )+ { + checkFirstLParen = false; + }; + +// ************************ +// Fragment rules +// ************************ + +fragment FPNUM_W_POINT : (BASIC_UINT? '.' [0-9]+ | BASIC_UINT '.') ([eE] ('+'|'-')? BASIC_UINT)? [fF]?; +fragment FPNUM_WO_POINT : BASIC_UINT [eE] ('+'|'-')? BASIC_UINT [fF]?; +fragment BASIC_UINT : '0'|[1-9][0-9]*; +fragment NEWLINE_EOF : NEWLINE | EOF; +fragment SIMPLE_LETTER : [A-Za-z] | [\uAC00-\uD7A3]; // English letters and Korean letters +fragment NEWLINE : '\r'? '\n'; +fragment SPACE : [ \t]; + +fragment A : [aA]; // match either an 'a' or 'A' +fragment B : [bB]; +fragment C : [cC]; +fragment D : [dD]; +fragment E : [eE]; +fragment F : [fF]; +fragment G : [gG]; +fragment H : [hH]; +fragment I : [iI]; +fragment J : [jJ]; +fragment K : [kK]; +fragment L : [lL]; +fragment M : [mM]; +fragment N : [nN]; +fragment O : [oO]; +fragment P : [pP]; +fragment Q : [qQ]; +fragment R : [rR]; +fragment S : [sS]; +fragment T : [tT]; +fragment U : [uU]; +fragment V : [vV]; +fragment W : [wW]; +fragment X : [xX]; +fragment Y : [yY]; +fragment Z : [zZ]; + diff --git a/pl_engine/pl_server/src/main/antlr/PlcParser.g4 b/pl_engine/pl_server/src/main/antlr/PlcParser.g4 new file mode 100644 index 00000000000..e2167cb1b46 --- /dev/null +++ b/pl_engine/pl_server/src/main/antlr/PlcParser.g4 @@ -0,0 +1,571 @@ +/** + * CUBRID PL/CSQL Parser grammar based on and updated from + * Oracle(c) PL/SQL 11g Parser (https://github.com/antlr/grammars-v4/tree/master/sql/plsql) + * + * Copyright (c) 2009-2011 Alexandre Porcelli + * Copyright (c) 2015-2019 Ivan Kochurkin (KvanTTT, kvanttt@gmail.com, Positive Technologies). + * Copyright (c) 2017 Mark Adams + * Copyright (c) 2016 CUBRID Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +parser grammar PlcParser; + +@header { +package com.cubrid.plcsql.compiler.antlrgen; +} + +options { + tokenVocab=PlcLexer; +} + +sql_script + : create_routine EOF + ; + +create_routine + : CREATE (OR_REPLACE)? routine_definition (COMMENT CHAR_STRING)? + ; + +routine_definition + : (PROCEDURE | FUNCTION) identifier ( (LPAREN parameter_list RPAREN)? | LPAREN RPAREN ) (RETURN type_spec)? + (IS | AS) (LANGUAGE PLCSQL)? seq_of_declare_specs? body (SEMICOLON)? + ; + +parameter_list + : parameter (',' parameter)* + ; + +parameter + : parameter_name IN? type_spec # parameter_in + | parameter_name ( IN? OUT | INOUT ) type_spec # parameter_out + ; + +default_value_part + : (':=' | DEFAULT) expression + ; + +seq_of_declare_specs + : declare_spec+ + ; + +declare_spec + : pragma_declaration + | item_declaration + | cursor_definition + | routine_definition + ; + +item_declaration + : constant_declaration + | exception_declaration + | variable_declaration + ; + +variable_declaration + : identifier type_spec ((NOT NULL_)? default_value_part)? SEMICOLON + ; + +constant_declaration + : identifier CONSTANT type_spec (NOT NULL_)? default_value_part SEMICOLON + ; + +cursor_definition + : CURSOR identifier ( (LPAREN parameter_list RPAREN)? | LPAREN RPAREN ) IS static_sql SEMICOLON + ; + +exception_declaration + : identifier EXCEPTION SEMICOLON + ; + +pragma_declaration + : PRAGMA AUTONOMOUS_TRANSACTION SEMICOLON + ; + +seq_of_statements + : (statement SEMICOLON)+ + ; + +label_declaration + : '<<' label_name '>>' + ; + +statement + : block # stmt_block + | sql_statement # stmt_sql // must go before procedure_call + | raise_application_error_statement # stmt_raise_app_err // must go before procedure_call + | execute_immediate # stmt_exec_imme + | assignment_statement # stmt_assign + | continue_statement # stmt_continue + | exit_statement # stmt_exit + | null_statement # stmt_null + | raise_statement # stmt_raise + | return_statement # stmt_return + | procedure_call # stmt_proc_call + | if_statement # stmt_if + | loop_statement # stmt_loop + | case_statement # stmt_case + ; + +execute_immediate + : EXECUTE IMMEDIATE dyn_sql (into_clause? restricted_using_clause? | restricted_using_clause into_clause) + ; + +dyn_sql + : expression + ; + +into_clause + : INTO identifier (',' identifier)* + ; + +assignment_statement + : identifier ':=' expression + ; + +continue_statement + : CONTINUE label_name? (WHEN expression)? + ; + +exit_statement + : EXIT label_name? (WHEN expression)? + ; + +if_statement + : IF expression THEN seq_of_statements elsif_part* else_part? END IF + ; + +elsif_part + : ELSIF expression THEN seq_of_statements + ; + +else_part + : ELSE seq_of_statements + ; + +loop_statement + : label_declaration? LOOP seq_of_statements END LOOP label_name? # stmt_basic_loop + | label_declaration? WHILE expression LOOP seq_of_statements END LOOP label_name? # stmt_while_loop + | label_declaration? FOR iterator LOOP seq_of_statements END LOOP label_name? # stmt_for_iter_loop + | label_declaration? FOR for_cursor LOOP seq_of_statements END LOOP label_name? # stmt_for_cursor_loop + | label_declaration? FOR for_static_sql LOOP seq_of_statements END LOOP label_name? # stmt_for_static_sql_loop + | label_declaration? FOR for_dynamic_sql LOOP seq_of_statements END LOOP label_name? # stmt_for_dynamic_sql_loop + ; + + // actually far more complicated according to the Spec. +iterator + : index_name IN REVERSE? lower_bound '..' upper_bound (BY step)? + ; + +for_cursor + : record_name IN cursor_exp (LPAREN expressions? RPAREN)? + ; + +for_static_sql + : record_name IN LPAREN static_sql RPAREN + ; + +for_dynamic_sql + : record_name IN LPAREN EXECUTE IMMEDIATE dyn_sql restricted_using_clause? RPAREN + ; + +lower_bound + : concatenation + ; + +upper_bound + : concatenation + ; + +step + : concatenation + ; + +null_statement + : NULL_ + ; + +raise_statement + : RAISE exception_name? + ; + +return_statement + : RETURN expression? + ; + +procedure_call + : (DBMS_OUTPUT '.')? routine_name function_argument? + ; + +body + : BEGIN seq_of_statements (EXCEPTION exception_handler+)? END label_name? + ; + +exception_handler + : WHEN exception_name (OR exception_name)* THEN seq_of_statements + ; + +block + : (DECLARE seq_of_declare_specs)? body + ; + +sql_statement + : static_sql + | cursor_manipulation_statement + | transaction_control_statement + ; + +static_sql + : static_sql_begin (SS_STR | SS_WS | SS_NON_STR)+ + ; + +static_sql_begin + : WITH + | SELECT + | INSERT + | UPDATE + | DELETE + | REPLACE + | MERGE + | TRUNCATE + ; + +cursor_manipulation_statement + : close_statement + | open_statement + | fetch_statement + | open_for_statement + ; + +close_statement + : CLOSE cursor_exp + ; + +open_statement + : OPEN cursor_exp (LPAREN expressions? RPAREN)? + ; + +fetch_statement + : FETCH cursor_exp INTO identifier (',' identifier)* + ; + +open_for_statement + : OPEN identifier FOR static_sql + ; + +transaction_control_statement + : commit_statement + | rollback_statement + ; + +commit_statement + : COMMIT WORK? + ; + +rollback_statement + : ROLLBACK WORK? + ; + +expressions + : expression (',' expression)* + ; + +expression + : unary_logical_expression # expression_prime + | expression AND expression # and_exp + | expression XOR expression # xor_exp + | expression OR expression # or_exp + ; + +unary_logical_expression + : relational_expression # unary_logical_expression_prime + | NOT unary_logical_expression # not_exp + ; + +relational_expression + : between_expression # relational_expression_prime + | relational_expression relational_operator relational_expression # rel_exp + ; + +between_expression + : in_expression # between_expression_prime + | between_expression NOT? BETWEEN between_elements # between_exp + ; + +in_expression + : like_expression # in_expression_prime + | in_expression NOT? IN in_elements # in_exp + ; + +like_expression + : is_null_expression # like_expression_prime + | like_expression NOT? LIKE pattern=concatenation (ESCAPE escape=quoted_string)? # like_exp + ; + +is_null_expression + : concatenation # is_null_expression_prime + | is_null_expression IS NOT? NULL_ # is_null_exp + ; + +concatenation + : unary_expression # concatenation_prime + | concatenation ('*' | '/' | DIV | MOD) concatenation # mult_exp + | concatenation ('+' | '-' ) concatenation # add_exp + | concatenation '||' concatenation # str_concat_exp + | concatenation ('<<' | '>>') concatenation # bit_shift_exp + | concatenation ('&') concatenation # bit_and_exp + | concatenation ('^') concatenation # bit_xor_exp + | concatenation ('|') concatenation # bit_or_exp + ; + +unary_expression + : atom # unary_expression_prime + | ('-' | '+') unary_expression # sign_exp + | '~' unary_expression # bit_compli_exp + ; + +atom + : literal # literal_exp + | record=identifier '.' field=identifier # field_exp + | function_call # call_exp + | identifier # id_exp + | case_expression # case_exp + | SQL PERCENT_ROWCOUNT # sql_rowcount_exp // this must go before the cursor_attr_exp line + | cursor_exp ( PERCENT_ISOPEN | PERCENT_FOUND | PERCENT_NOTFOUND | PERCENT_ROWCOUNT ) # cursor_attr_exp + | LPAREN expression RPAREN # paren_exp + | SQLCODE # sqlcode_exp + | SQLERRM # sqlerrm_exp + ; + +function_call + : function_name function_argument + ; + +relational_operator + : '=' + | NULL_SAFE_EQUALS_OP + | NOT_EQUAL_OP + | '<=' + | '>=' + | '<' + | '>' + ; + +in_elements + : LPAREN in_expression (',' in_expression)* RPAREN + ; + +between_elements + : between_expression AND between_expression + ; + +case_expression + : searched_case_expression + | simple_case_expression + ; + +simple_case_expression + : CASE expression simple_case_expression_when_part+ case_expression_else_part? END + ; + +simple_case_expression_when_part + : WHEN expression THEN expression + ; + +searched_case_expression + : CASE searched_case_expression_when_part+ case_expression_else_part? END + ; + +searched_case_expression_when_part + : WHEN expression THEN expression + ; + +case_expression_else_part + : ELSE expression + ; + +case_statement + : searched_case_statement + | simple_case_statement + ; + +raise_application_error_statement + : RAISE_APPLICATION_ERROR LPAREN err_code ',' err_msg RPAREN + ; + +err_code + : concatenation + ; + +err_msg + : concatenation + ; + +simple_case_statement + : CASE expression simple_case_statement_when_part+ case_statement_else_part? END CASE label_name? + ; + +simple_case_statement_when_part + : WHEN expression THEN seq_of_statements + ; + +searched_case_statement + : CASE searched_case_statement_when_part+ case_statement_else_part? END CASE label_name? + ; + +searched_case_statement_when_part + : WHEN expression THEN seq_of_statements + ; + +case_statement_else_part + : ELSE seq_of_statements + ; + +restricted_using_clause + : USING restricted_using_element (',' restricted_using_element)* + ; + +restricted_using_element + : (IN)? expression + ; + +routine_name + : identifier + ; + +parameter_name + : identifier + ; + +label_name + : identifier + ; + +exception_name + : identifier + ; + +index_name + : identifier + ; + +cursor_exp + //: function_call TODO + : identifier + ; + +record_name + : identifier + ; + +table_name + : (identifier '.')? identifier + ; + +column_name + : identifier + ; + +function_argument + : LPAREN (argument (',' argument)*)? RPAREN + ; + +argument + : expression + ; + +type_spec + : native_datatype # native_type_spec + | (table_name '.')? identifier PERCENT_TYPE # percent_type_spec + ; + +native_datatype + : numeric_type + | char_type + | varchar_type + | simple_type + ; + +numeric_type + : (NUMERIC | DECIMAL | DEC) (LPAREN precision=UNSIGNED_INTEGER (',' scale=UNSIGNED_INTEGER)? RPAREN)? + ; + +char_type + : (CHAR | CHARACTER) ( LPAREN length=UNSIGNED_INTEGER RPAREN )? + ; + +varchar_type + : (VARCHAR | CHAR VARYING | CHARACTER VARYING) ( LPAREN length=UNSIGNED_INTEGER RPAREN )? + | STRING + ; + +simple_type + : BOOLEAN + | SHORT | SMALLINT + | INT | INTEGER + | BIGINT + | FLOAT | REAL + | DOUBLE PRECISION? + | DATE + | TIME + | TIMESTAMP + | DATETIME + | SYS_REFCURSOR + ; + +literal + : DATE quoted_string # date_exp + | TIME quoted_string # time_exp + | TIMESTAMP quoted_string # timestamp_exp + | DATETIME quoted_string # datetime_exp + | numeric # num_exp + | quoted_string # str_exp + | NULL_ # null_exp + | TRUE # true_exp + | FALSE # false_exp + ; + +numeric + : UNSIGNED_INTEGER # uint_exp + | FLOATING_POINT_NUM # fp_num_exp + ; + +numeric_negative + : '-' numeric + ; + +quoted_string + : CHAR_STRING + ; + +identifier + : REGULAR_ID + | DELIMITED_ID + ; + +function_name + : identifier + | DATE + | DEFAULT + | IF + | INSERT + | MOD + | REPLACE + | REVERSE + | TIME + | TIMESTAMP + | TRUNCATE + ; + + diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/ExecuteThread.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/ExecuteThread.java new file mode 100644 index 00000000000..e3ebaa780cc --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/ExecuteThread.java @@ -0,0 +1,461 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. + * Copyright (c) 2016 CUBRID Corporation. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * - Neither the name of the nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + */ + +package com.cubrid.jsp; + +import com.cubrid.jsp.classloader.ClassLoaderManager; +import com.cubrid.jsp.context.Context; +import com.cubrid.jsp.context.ContextManager; +import com.cubrid.jsp.data.CUBRIDPacker; +import com.cubrid.jsp.data.CUBRIDUnpacker; +import com.cubrid.jsp.data.CompileInfo; +import com.cubrid.jsp.data.DataUtilities; +import com.cubrid.jsp.exception.ExecuteException; +import com.cubrid.jsp.exception.TypeMismatchException; +import com.cubrid.jsp.protocol.Header; +import com.cubrid.jsp.protocol.PrepareArgs; +import com.cubrid.jsp.protocol.RequestCode; +import com.cubrid.jsp.value.Value; +import com.cubrid.jsp.value.ValueUtilities; +import com.cubrid.plcsql.compiler.PlcsqlCompilerMain; +import com.cubrid.plcsql.predefined.PlcsqlRuntimeError; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.file.Path; +import java.sql.SQLException; +import java.util.List; +import javax.tools.JavaCompiler; +import javax.tools.ToolProvider; + +public class ExecuteThread extends Thread { + + public static String charSet = "UTF-8"; + + private Socket client; + + private DataInputStream input; + private DataOutputStream output; + + /* + * TODO: It will be replaced with DirectByteBuffer-based new buffer which + * dynamically extended if overflow exists + */ + /* + * Since DirectByteBuffer's allocation time is slow, DirectByteBuffer pooling + * should be implemented + */ + private ByteBuffer resultBuffer; + + private CUBRIDUnpacker unpacker = new CUBRIDUnpacker(); + private CUBRIDPacker packer; + + private StoredProcedure storedProcedure = null; + private PrepareArgs prepareArgs = null; + + private Context ctx = null; + + ExecuteThread(Socket client) throws IOException { + super(); + this.client = client; + output = new DataOutputStream(new BufferedOutputStream(this.client.getOutputStream())); + + resultBuffer = ByteBuffer.allocate(4096); + + packer = new CUBRIDPacker(resultBuffer); + } + + public Socket getSocket() { + return client; + } + + public Context getCurrentContext() { + return ctx; + } + + public void closeSocket() { + try { + output.close(); + client.close(); + } catch (IOException e) { + } + + client = null; + output = null; + // charSet = null; + } + + public void setCharSet(String conCharsetName) { + // this.charSet = conCharsetName; + } + + @Override + public void run() { + /* main routine handling stored procedure */ + Header header = null; + while (!Thread.interrupted()) { + try { + header = listenCommand(); + ContextManager.registerThread(Thread.currentThread().getId(), ctx.getSessionId()); + switch (header.code) { + /* + * the following two request codes are for processing java stored procedure + * routine + */ + case RequestCode.PREPARE_ARGS: + { + processPrepare(); + break; + } + case RequestCode.INVOKE_SP: + { + processStoredProcedure(); + ctx = null; + break; + } + + case RequestCode.COMPILE: + { + processCompile(); + break; + } + + /* the following request codes are for javasp utility */ + case RequestCode.UTIL_PING: + { + String ping = Server.getServer().getServerName(); + + resultBuffer.clear(); /* prepare to put */ + packer.setBuffer(resultBuffer); + packer.packString(ping); + + resultBuffer = packer.getBuffer(); + writeBuffer(resultBuffer); + break; + } + case RequestCode.UTIL_STATUS: + { + // TODO: create a packable class for status + resultBuffer.clear(); /* prepare to put */ + packer.setBuffer(resultBuffer); + + packer.packInt(Server.getServer().getServerPort()); + packer.packString(Server.getServer().getServerName()); + List vm_args = Server.getJVMArguments(); + packer.packInt(vm_args.size()); + for (String arg : vm_args) { + packer.packString(arg); + } + + resultBuffer = packer.getBuffer(); + writeBuffer(resultBuffer); + break; + } + case RequestCode.UTIL_TERMINATE_THREAD: + { + // hacky way.. If thread is terminated and socket is closed immediately, + // "ping" or "status" command does not work properly + sleep(100); + Thread.currentThread().interrupt(); + break; + } + case RequestCode.UTIL_TERMINATE_SERVER: + { + Server.stop(0); + break; + } + + /* invalid request */ + default: + { + // throw new ExecuteException ("invalid request code: " + requestCode); + } + } + ContextManager.deregisterThread(Thread.currentThread().getId()); + } catch (Throwable e) { + if (e instanceof IOException) { + /* + * CAS disconnects socket + * 1) end of the procedure successfully by calling jsp_close_internal_connection + * 2) socket is in invalid status. we do not have to deal with it here. + */ + break; + } else { + Throwable throwable = e; + if (e instanceof InvocationTargetException) { + throwable = ((InvocationTargetException) e).getTargetException(); + } + Server.log(throwable); + try { + // TODO: error managing module + if (throwable instanceof SQLException) { + sendError(throwable.toString()); + } else if (throwable instanceof PlcsqlRuntimeError) { + PlcsqlRuntimeError plcsqlError = (PlcsqlRuntimeError) throwable; + String errMsg = + String.format( + "\n (line %d, column %d) %s", + plcsqlError.getLine(), + plcsqlError.getColumn(), + plcsqlError.getMessage()); + sendError(errMsg); + } else { + sendError(throwable.toString()); + } + } catch (IOException e1) { + Server.log(e1); + } + } + } finally { + ContextManager.deregisterThread(Thread.currentThread().getId()); + ctx = null; + } + } + closeSocket(); + } + + private Header listenCommand() throws Exception { + ByteBuffer inputBuffer = receiveBuffer(); + + unpacker.setBuffer(inputBuffer); + + /* read header */ + Header header = new Header(unpacker); + ctx = ContextManager.getContext(header.id); + ctx.checkHeader(header); + + ByteBuffer payloadBuffer = + ByteBuffer.wrap( + inputBuffer.array(), + unpacker.getCurrentPosition(), + unpacker.getCurrentLimit() - unpacker.getCurrentPosition()); + ctx.getInboundQueue().add(payloadBuffer); + return header; + } + + public ByteBuffer receiveBuffer() throws IOException { + if (input == null) { + input = new DataInputStream(new BufferedInputStream(this.client.getInputStream())); + } + + int size = input.readInt(); // size + byte[] bytes = new byte[size]; + input.readFully(bytes); + + return ByteBuffer.wrap(bytes); + } + + private void writeBuffer(ByteBuffer buffer) throws IOException { + output.writeInt(buffer.position()); + output.write(buffer.array(), 0, buffer.position()); + output.flush(); + } + + public CUBRIDUnpacker getUnpacker() { + return unpacker; + } + + private void processPrepare() throws Exception { + unpacker.setBuffer(ctx.getInboundQueue().take()); + if (prepareArgs == null) { + prepareArgs = new PrepareArgs(unpacker); + } else { + prepareArgs.readArgs(unpacker); + } + ctx.checkTranId(prepareArgs.getTranId()); + } + + private void processStoredProcedure() throws Exception { + unpacker.setBuffer(ctx.getInboundQueue().take()); + long id = unpacker.unpackBigint(); + int tid = unpacker.unpackInt(); + + ctx.checkTranId(tid); + + StoredProcedure procedure = makeStoredProcedure(unpacker); + Value result = procedure.invoke(); + + /* send results */ + sendResult(result, procedure); + } + + private void processCompile() throws Exception { + unpacker.setBuffer(ctx.getInboundQueue().take()); + boolean verbose = unpacker.unpackBool(); + String inSource = unpacker.unpackCString(); + + CompileInfo info = null; + try { + info = PlcsqlCompilerMain.compilePLCSQL(inSource, verbose); + if (info.errCode == 0) { + Path javaFilePath = + ClassLoaderManager.getDynamicPath().resolve(info.className + ".java"); + File file = javaFilePath.toFile(); + if (file.exists()) { + file.delete(); + } + new FileWriter(file).append(info.translated).close(); + + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + if (compiler == null) { + throw new IllegalStateException( + "Cannot find the system Java compiler. Check that your class path includes tools.jar"); + } + + Path cubrid_env_root = Server.getServer().getRootPath(); + String javacOpts[] = { + "-classpath", cubrid_env_root + "/java/pl_server.jar", file.getPath() + }; + + if (compiler.run(null, null, null, javacOpts) != 0) { + String command = + "javac " + + javaFilePath + + " -cp " + + cubrid_env_root + + "/java/pl_server.jar"; + throw new RuntimeException(command); + } + } + } catch (Exception e) { + info = + new CompileInfo( + -1, 0, 0, e.getMessage().isEmpty() ? "unknown error" : e.getMessage()); + throw new RuntimeException(e); + } finally { + CUBRIDPacker packer = new CUBRIDPacker(ByteBuffer.allocate(1024)); + info.pack(packer); + Context.getCurrentExecuteThread().sendCommand(RequestCode.COMPILE, packer.getBuffer()); + } + } + + private StoredProcedure makeStoredProcedure(CUBRIDUnpacker unpacker) throws Exception { + String methodSig = unpacker.unpackCString(); + int paramCount = unpacker.unpackInt(); + + Value[] arguments = prepareArgs.getArgs(); + Value[] methodArgs = new Value[paramCount]; + for (int i = 0; i < paramCount; i++) { + int pos = unpacker.unpackInt(); + int mode = unpacker.unpackInt(); + int type = unpacker.unpackInt(); + + Value val = arguments[pos]; + val.setMode(mode); + val.setDbType(type); + + methodArgs[i] = val; + } + int returnType = unpacker.unpackInt(); + + boolean transactionControl = unpacker.unpackBool(); + getCurrentContext().setTransactionControl(transactionControl); + + storedProcedure = new StoredProcedure(methodSig, methodArgs, returnType); + return storedProcedure; + } + + private void returnOutArgs(StoredProcedure sp, CUBRIDPacker packer) + throws IOException, ExecuteException, TypeMismatchException { + Value[] args = sp.getArgs(); + for (int i = 0; i < args.length; i++) { + if (args[i].getMode() > Value.IN) { + Value v = sp.makeOutValue(args[i].getResolved()); + packer.packValue( + ValueUtilities.resolveValue(args[i].getDbType(), v), + args[i].getDbType(), + this.charSet); + } + } + } + + private void sendResult(Value result, StoredProcedure procedure) + throws IOException, ExecuteException, TypeMismatchException { + Object resolvedResult = null; + if (result != null) { + resolvedResult = ValueUtilities.resolveValue(procedure.getReturnType(), result); + } + + resultBuffer.clear(); /* prepare to put */ + packer.setBuffer(resultBuffer); + + packer.packInt(RequestCode.RESULT); + packer.align(DataUtilities.MAX_ALIGNMENT); + packer.packValue(resolvedResult, procedure.getReturnType(), this.charSet); + returnOutArgs(procedure, packer); + + resultBuffer = packer.getBuffer(); + writeBuffer(resultBuffer); + } + + public void sendCommand(int code, ByteBuffer buffer) throws IOException { + resultBuffer.clear(); /* prepare to put */ + packer.setBuffer(resultBuffer); + + packer.packInt(code); + packer.align(DataUtilities.MAX_ALIGNMENT); + packer.packPrimitiveBytes(buffer); + + resultBuffer = packer.getBuffer(); + writeBuffer(resultBuffer); + } + + public void sendCommand(ByteBuffer buffer) throws IOException { + resultBuffer.clear(); /* prepare to put */ + packer.setBuffer(resultBuffer); + + packer.packInt(RequestCode.INTERNAL_JDBC); + packer.align(DataUtilities.MAX_ALIGNMENT); + packer.packPrimitiveBytes(buffer); + + resultBuffer = packer.getBuffer(); + writeBuffer(resultBuffer); + } + + private void sendError(String exception) throws IOException { + resultBuffer.clear(); + packer.setBuffer(resultBuffer); + + packer.packInt(RequestCode.ERROR); + packer.align(DataUtilities.MAX_ALIGNMENT); + packer.packString(exception); + + resultBuffer = packer.getBuffer(); + writeBuffer(resultBuffer); + } +} diff --git a/src/jsp/com/cubrid/jsp/ListenerThread.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/ListenerThread.java similarity index 100% rename from src/jsp/com/cubrid/jsp/ListenerThread.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/ListenerThread.java diff --git a/src/jsp/com/cubrid/jsp/LoggingThread.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/LoggingThread.java similarity index 88% rename from src/jsp/com/cubrid/jsp/LoggingThread.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/LoggingThread.java index 6a1bad2714b..818b6b19b14 100644 --- a/src/jsp/com/cubrid/jsp/LoggingThread.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/LoggingThread.java @@ -32,6 +32,7 @@ package com.cubrid.jsp; import java.io.IOException; +import java.nio.file.Path; import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.FileHandler; import java.util.logging.Level; @@ -40,18 +41,20 @@ public class LoggingThread extends Thread { private final Logger logger = Logger.getLogger("com.cubrid.jsp"); + private boolean isRunning = false; private FileHandler logHandler = null; private LinkedBlockingQueue logQueue = new LinkedBlockingQueue(); private Level logginLevel = Level.SEVERE; - public LoggingThread(String path) throws SecurityException, IOException { + public LoggingThread(Path path) throws SecurityException, IOException { super(); - logHandler = new FileHandler(path, true); + logHandler = new FileHandler(path.toAbsolutePath().toString(), true); logger.addHandler(logHandler); } @Override public void run() { + isRunning = true; while (Thread.interrupted() == false) { try { String logString = logQueue.take(); @@ -63,6 +66,7 @@ public void run() { if (logHandler != null) { try { + isRunning = false; logHandler.close(); logger.removeHandler(logHandler); } catch (Throwable e) { @@ -76,4 +80,8 @@ public void log(String str) { } catch (InterruptedException e) { } } + + public boolean isRunning() { + return isRunning; + } } diff --git a/src/jsp/com/cubrid/jsp/OSValidator.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/OSValidator.java similarity index 100% rename from src/jsp/com/cubrid/jsp/OSValidator.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/OSValidator.java diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/Server.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/Server.java new file mode 100644 index 00000000000..b97b1589169 --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/Server.java @@ -0,0 +1,267 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. + * Copyright (c) 2016 CUBRID Corporation. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * - Neither the name of the nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + */ + +package com.cubrid.jsp; + +import com.cubrid.jsp.classloader.ClassLoaderManager; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; +import java.net.ServerSocket; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Logger; +import org.newsclub.net.unix.AFUNIXServerSocket; +import org.newsclub.net.unix.AFUNIXSocketAddress; + +public class Server { + private static final Logger logger = Logger.getLogger("com.cubrid.jsp"); + + public static final int PORT_NUMBER_UNKNOWN = -2; + public static final int PORT_NUMBER_UDS = -1; + + private static AtomicBoolean shutdown = new AtomicBoolean(false); + + private static ServerConfig config = null; + + private static List jvmArguments = null; + private static int portNumber = PORT_NUMBER_UNKNOWN; + + private static Server serverInstance = null; + + private static Thread socketListener = null; + private static LoggingThread loggingThread = null; + + private Server(ServerConfig conf) throws IOException, ClassNotFoundException { + config = conf; + + // Server's security manager should be set first + System.setSecurityManager(new SpSecurityManager()); + + // initialize env + initailizeEnvironments(config); + + // initialize logger + initializeLogger(config); + + // initialize class loader + Files.createDirectories(ClassLoaderManager.getRootPath()); + + // initialize socket + initializeSocket(config); + + System.setProperty("cubrid.server.version", config.getVersion()); + Class.forName("com.cubrid.jsp.jdbc.CUBRIDServerSideDriver"); + + // store JVM options + getJVMArguments(); + } + + private synchronized void initailizeEnvironments(ServerConfig config) { + System.setProperty("java.io.tmpdir", config.getTmpPath()); + } + + private synchronized void initializeLogger(ServerConfig config) + throws SecurityException, IOException { + Path logPath = Paths.get(config.getLogPath()); + if (Files.notExists(logPath)) { + Files.createDirectories(logPath.getParent()); + Files.createFile(logPath); + } + + loggingThread = new LoggingThread(logPath); + loggingThread.start(); + } + + private synchronized void initializeSocket(ServerConfig config) throws IOException { + ServerSocket serverSocket = null; + if (config.getSocketType().equals("UDS")) { + final Path socketFile = Paths.get(config.getSocketInfo()); + + // create parent directory if exists + if (!Files.exists(socketFile.getParent())) { + Files.createDirectories(socketFile.getParent()); + } + + // remove previous socket file + Files.deleteIfExists(socketFile); + + AFUNIXSocketAddress sockAddr = AFUNIXSocketAddress.of(socketFile); + serverSocket = AFUNIXServerSocket.bindOn(sockAddr); + portNumber = PORT_NUMBER_UDS; + } else { + portNumber = Integer.parseInt(config.getSocketInfo()); + serverSocket = new ServerSocket(portNumber); + portNumber = serverSocket.getLocalPort(); + } + + socketListener = new ListenerThread(serverSocket); + } + + private void startSocketListener() { + if (socketListener != null) { + socketListener.setDaemon(true); + socketListener.start(); + } + } + + private void stopSocketListener() { + if (socketListener != null) { + socketListener.interrupt(); + socketListener = null; + } + } + + public static Server getServer() { + return serverInstance; + } + + public static ServerConfig getServerConfig() { + return config; + } + + public String getServerName() { + return config.getName(); + } + + public int getServerPort() { + return portNumber; + } + + public Path getRootPath() { + if (getServer() != null) { + return Paths.get(config.getRootPath()); + } else { + return null; + } + } + + public Path getDatabasePath() { + if (getServer() != null) { + return Paths.get(config.getDatabasePath()); + } else { + return null; + } + } + + public static List getJVMArguments() { + if (jvmArguments == null) { + RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); + jvmArguments = runtimeMxBean.getInputArguments(); + } + + return jvmArguments; + } + + /* For JNI */ + public static int start(String[] args) throws Exception { + try { + String name = args[0]; + String dbPath = args[1]; + String version = args[2]; + String envRoot = args[3]; + String udsPath = args[4]; + String port = args[5]; + + String socketInfo = null; + int port_number = Integer.parseInt(port); + if (OSValidator.IS_UNIX && port_number == PORT_NUMBER_UDS) { + socketInfo = udsPath; + } else { + socketInfo = port; + } + + ServerConfig config = new ServerConfig(name, version, envRoot, dbPath, socketInfo); + + return startWithConfig(config); + } catch (Exception e) { + /* error, serverSocket is not properly initialized */ + shutdown.set(true); + if (loggingThread != null && loggingThread.isRunning()) { + log(e); + loggingThread.interrupt(); + } + throw e; + } + } + + /* Entry point (main) */ + public static int startWithConfig(ServerConfig config) + throws ClassNotFoundException, IOException { + if (config == null) { + throw new IllegalArgumentException("ServerConfig is null"); + } + + serverInstance = new Server(config); + serverInstance.startSocketListener(); + + return Server.getServer().getServerPort(); + } + + public static void stop(int status) { + if (serverInstance != null) { + serverInstance.setShutdown(); + serverInstance.stopSocketListener(); + + loggingThread.interrupt(); + + serverInstance = null; + } + } + + public static void main(String[] args) throws Exception { + Server.start(args); + } + + public static void log(Throwable ex) { + StringWriter sw = new StringWriter(); + ex.printStackTrace(new PrintWriter(sw)); + String exceptionAsString = sw.toString(); + loggingThread.log(exceptionAsString); + } + + public static void log(String str) { + loggingThread.log(str); + } + + public void setShutdown() { + shutdown.set(true); + } + + public boolean getShutdown() { + return shutdown.get(); + } +} diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/ServerConfig.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/ServerConfig.java new file mode 100644 index 00000000000..4f71ee1ad76 --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/ServerConfig.java @@ -0,0 +1,73 @@ +package com.cubrid.jsp; + +import java.io.File; +import org.apache.commons.lang3.StringUtils; + +public class ServerConfig { + + private static final String LOG_DIR = "log"; + + private final String name; + private final String version; + + /* Paths */ + private final String rootPath; // $CUBRID + private final String dbPath; // $CUBRID_DATABASES + + private final String logPath; + private final String tmpPath; + + private final String socketType; // TCP or UDS + private final String socketInfo; // port number or socket file path + + public ServerConfig( + String name, String version, String rPath, String dbPath, String socketInfo) { + this.name = name; + this.version = version; + + this.rootPath = rPath; + this.dbPath = dbPath; + + this.logPath = + rootPath + File.separatorChar + LOG_DIR + File.separatorChar + name + "_java.log"; + + String cubridTmpEnv = System.getenv("CUBRID_TMP"); + this.tmpPath = + (cubridTmpEnv != null) ? cubridTmpEnv : this.rootPath + File.separatorChar + "tmp"; + + this.socketInfo = socketInfo; + this.socketType = StringUtils.isNumeric(socketInfo) ? "TCP" : "UDS"; + } + + public String getName() { + return name; + } + + public String getVersion() { + return version; + } + + public String getRootPath() { + return rootPath; + } + + public String getLogPath() { + return logPath; + } + + public String getTmpPath() { + return tmpPath; + } + + public String getSocketType() { + return socketType; + } + + public String getDatabasePath() { + return dbPath; + } + + public String getSocketInfo() { + return socketInfo; + } +} diff --git a/src/jsp/com/cubrid/jsp/SpSecurityManager.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/SpSecurityManager.java similarity index 95% rename from src/jsp/com/cubrid/jsp/SpSecurityManager.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/SpSecurityManager.java index c6e33a498b5..41f04732c2b 100644 --- a/src/jsp/com/cubrid/jsp/SpSecurityManager.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/SpSecurityManager.java @@ -37,7 +37,10 @@ public class SpSecurityManager extends SecurityManager { public void checkExit(int status) { - if (Server.getServer().getShutdown() == false) { + super.checkExit(status); + + Server instance = Server.getServer(); + if (instance != null && instance.getShutdown() == false) { throw new SecurityException(); } } diff --git a/src/jsp/com/cubrid/jsp/StoredProcedure.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/StoredProcedure.java similarity index 98% rename from src/jsp/com/cubrid/jsp/StoredProcedure.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/StoredProcedure.java index 0eed06c7785..e14f485a731 100644 --- a/src/jsp/com/cubrid/jsp/StoredProcedure.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/StoredProcedure.java @@ -31,6 +31,7 @@ package com.cubrid.jsp; +import com.cubrid.jsp.context.ContextManager; import com.cubrid.jsp.exception.ExecuteException; import com.cubrid.jsp.exception.TypeMismatchException; import com.cubrid.jsp.value.BooleanValue; @@ -40,6 +41,7 @@ import com.cubrid.jsp.value.FloatValue; import com.cubrid.jsp.value.IntValue; import com.cubrid.jsp.value.LongValue; +import com.cubrid.jsp.value.NumericValue; import com.cubrid.jsp.value.OidValue; import com.cubrid.jsp.value.ResultSetValue; import com.cubrid.jsp.value.SetValue; @@ -68,7 +70,8 @@ public StoredProcedure(String signature, Value[] args, int returnType) throws Ex this.signature = signature; this.args = args; this.returnType = returnType; - this.target = TargetMethodCache.getInstance().get(signature); + this.target = + ContextManager.getContextofCurrentThread().getTargetMethodCache().get(signature); this.cachedResolved = null; checkArgs(); @@ -329,7 +332,7 @@ public Value makeReturnValue(Object o) throws ExecuteException { } else if (o instanceof Double) { val = new DoubleValue(((Double) o).doubleValue()); } else if (o instanceof BigDecimal) { - val = new DoubleValue(((BigDecimal) o).doubleValue()); + val = new NumericValue(((BigDecimal) o)); } else if (o instanceof String) { val = new StringValue((String) o); } else if (o instanceof java.sql.Date) { diff --git a/src/jsp/com/cubrid/jsp/TargetMethod.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/TargetMethod.java similarity index 85% rename from src/jsp/com/cubrid/jsp/TargetMethod.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/TargetMethod.java index 2d9d113272f..2867fe91b7c 100644 --- a/src/jsp/com/cubrid/jsp/TargetMethod.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/TargetMethod.java @@ -31,6 +31,8 @@ package com.cubrid.jsp; +import com.cubrid.jsp.context.Context; +import com.cubrid.jsp.context.ContextManager; import com.cubrid.jsp.exception.ExecuteException; import cubrid.sql.CUBRIDOID; import java.lang.reflect.Method; @@ -65,19 +67,36 @@ public TargetMethod(String signature) throws Exception { int nameStart = signature.substring(0, argStart).lastIndexOf('.') + 1; if (signature.charAt(0) == '\'') { - className = signature.substring(1, nameStart - 1); + className = signature.substring(1, nameStart - 1).trim(); } else { - className = signature.substring(0, nameStart - 1); + className = signature.substring(0, nameStart - 1).trim(); } - methodName = signature.substring(nameStart, argStart - 1); + methodName = signature.substring(nameStart, argStart - 1).trim(); String args = signature.substring(argStart, argEnd); argsTypes = classesFor(args); } private Class getClass(String name) throws ClassNotFoundException { - ClassLoader cl = StoredProcedureClassLoader.getInstance(); - return cl.loadClass(name); + Context ctx = ContextManager.getContextofCurrentThread(); + ClassLoader cl = ctx.getClassLoader(); + Class c = null; + try { + c = cl.loadClass(name); + return c; + } catch (ClassNotFoundException e) { + // + } + + // TODO: CBRD-24514 + try { + c = Server.class.getClassLoader().loadClass(name); + return c; + } catch (ClassNotFoundException e) { + // + } + + return c; } private Class[] classesFor(String args) throws ClassNotFoundException, ExecuteException { @@ -205,10 +224,26 @@ public Method getMethod() throws SecurityException, NoSuchMethodException, ClassNotFoundException { Class c = getClass(className); if (c == null) { - throw new ClassNotFoundException (className); + throw new ClassNotFoundException(className); + } + try { + return c.getMethod(methodName, argsTypes); + } catch (NoSuchMethodException e) { + String argsTypeNames; + int len = argsTypes.length; + if (len > 0) { + String[] arr = new String[len]; + for (int i = 0; i < len; i++) { + arr[i] = argsTypes[i].getTypeName(); + } + argsTypeNames = String.join(", ", arr); + } else { + argsTypeNames = ""; + } + + throw new NoSuchMethodException( + String.format("%s.%s(%s)", className, methodName, argsTypeNames)); } - Method m = c.getMethod(methodName, argsTypes); - return m; } public Class[] getArgsTypes() { diff --git a/src/jsp/com/cubrid/jsp/TargetMethodCache.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/TargetMethodCache.java similarity index 84% rename from src/jsp/com/cubrid/jsp/TargetMethodCache.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/TargetMethodCache.java index 48da94962d8..60a6c500e2b 100644 --- a/src/jsp/com/cubrid/jsp/TargetMethodCache.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/TargetMethodCache.java @@ -36,9 +36,7 @@ public class TargetMethodCache { private HashMap methods; - private static volatile TargetMethodCache instance = null; - - private TargetMethodCache() { + public TargetMethodCache() { methods = new HashMap(); } @@ -54,15 +52,7 @@ public TargetMethod get(String signature) throws Exception { return method; } - public static TargetMethodCache getInstance() { - if (instance == null) { - synchronized (TargetMethodCache.class) { - if (instance == null) { - instance = new TargetMethodCache(); - } - } - } - - return instance; + public void clear() { + methods.clear(); } } diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/classloader/BaseClassLoader.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/classloader/BaseClassLoader.java new file mode 100644 index 00000000000..9d02036fd94 --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/classloader/BaseClassLoader.java @@ -0,0 +1,105 @@ +/* + * + * Copyright (c) 2016 CUBRID Corporation. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * - Neither the name of the nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + */ + +package com.cubrid.jsp.classloader; + +import com.cubrid.jsp.Server; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.util.stream.Stream; + +public abstract class BaseClassLoader extends URLClassLoader { + + public BaseClassLoader(Path path, URL[] urls, ClassLoader parent) { + super(urls, parent); + init(path); + } + + private void init(Path path) { + try { + addURL(path.toUri().toURL()); + initJar(path); + } catch (Exception e) { + Server.log(e); + } + } + + private void initJar(Path path) throws IOException { + try (Stream files = Files.list(path)) { + files.filter((file) -> !Files.isDirectory(file) && (file.toString().endsWith(".jar"))) + .forEach( + jar -> { + try { + addURL(jar.toUri().toURL()); + } catch (MalformedURLException e) { + Server.log(e); + } + }); + } catch (NoSuchFileException e) { + // ignore + } + } + + public Class loadClass(String name) { + Class c = findLoadedClass(name); + if (c == null) { + // find child first + try { + c = super.loadClass(name); + } catch (ClassNotFoundException e) { + // ignore + } + } + + if (c == null && getParent() != null) { + try { + c = getParent().loadClass(name); + } catch (ClassNotFoundException e) { + // ignore + } + } + + if (c == null) { + try { + c = getSystemClassLoader().loadClass(name); + } catch (ClassNotFoundException e) { + // ignore + } + } + + return c; + } +} diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/classloader/ClassLoaderManager.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/classloader/ClassLoaderManager.java new file mode 100644 index 00000000000..7b3c4ac451d --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/classloader/ClassLoaderManager.java @@ -0,0 +1,116 @@ +/* + * + * Copyright (c) 2016 CUBRID Corporation. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * - Neither the name of the nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + */ + +package com.cubrid.jsp.classloader; + +import com.cubrid.jsp.Server; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.FileTime; +import java.time.Instant; +import java.util.Hashtable; + +public class ClassLoaderManager { + private static Hashtable lastModifiedMap = new Hashtable<>(); + + private static Path rootPath = null; + private static Path staticPath = null; + private static Path dynamicPath = null; + + public static Path getRootPath() { + if (rootPath == null) { + rootPath = Paths.get(Server.getServerConfig().getDatabasePath()); + createDirIfNotExists(rootPath); + } + return rootPath; + } + + public static Path getDynamicPath() { + if (dynamicPath == null) { + dynamicPath = getRootPath().resolve("java/"); + createDirIfNotExists(dynamicPath); + } + return dynamicPath; + } + + public static Path getStaticPath() { + if (staticPath == null) { + staticPath = getRootPath().resolve("java_static/"); + createDirIfNotExists(staticPath); + } + return staticPath; + } + + public static boolean isModified(Path path) { + Instant currentModified = getLastModifiedTimeOfPath(path).toInstant(); + Instant prevModified = lastModifiedMap.get(path); + if (prevModified != null && currentModified.compareTo(prevModified) == 0) { + return false; + } else { + lastModifiedMap.put(path, currentModified); + return true; + } + } + + public static FileTime getLastModifiedTimeOfPath(Path path) { + FileTime lastModifiedTime; + try { + lastModifiedTime = Files.getLastModifiedTime(path); + } catch (IOException e) { + // should not be here... + return null; + } + return lastModifiedTime; + } + + public static FileTime setLastModifiedTime(Path path, FileTime lastModifiedTime) { + try { + lastModifiedTime = Files.getLastModifiedTime(path); + } catch (IOException e) { + // should not be here... + return null; + } + return lastModifiedTime; + } + + private static void createDirIfNotExists(Path path) { + if (path.toFile().exists() == false) { + try { + Files.createDirectories(path); + } catch (IOException e) { + Server.log(e); + System.exit(1); + } + } + } +} diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/classloader/ContextClassLoader.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/classloader/ContextClassLoader.java new file mode 100644 index 00000000000..53a9c8d2d11 --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/classloader/ContextClassLoader.java @@ -0,0 +1,54 @@ +/* + * + * Copyright (c) 2016 CUBRID Corporation. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * - Neither the name of the nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + */ + +package com.cubrid.jsp.classloader; + +import java.net.URL; +import java.nio.file.attribute.FileTime; + +public class ContextClassLoader extends BaseClassLoader { + private FileTime initializedTime = null; + + public ContextClassLoader(ClassLoader parent) { + super(ClassLoaderManager.getDynamicPath(), new URL[0], parent); + initializedTime = + ClassLoaderManager.getLastModifiedTimeOfPath(ClassLoaderManager.getDynamicPath()); + ClassLoaderManager.isModified(ClassLoaderManager.getDynamicPath()); + } + + public ContextClassLoader() { + this(ServerClassLoader.getInstance()); + } + + public FileTime getInitializedTime() { + return initializedTime; + } +} diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/classloader/ServerClassLoader.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/classloader/ServerClassLoader.java new file mode 100644 index 00000000000..dd2e90603a9 --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/classloader/ServerClassLoader.java @@ -0,0 +1,50 @@ +/* + * + * Copyright (c) 2016 CUBRID Corporation. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * - Neither the name of the nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + */ + +package com.cubrid.jsp.classloader; + +import java.net.URL; + +public class ServerClassLoader extends BaseClassLoader { + + // singleton + private static class LazyHolder { + private static final ServerClassLoader INSTANCE = new ServerClassLoader(); + } + + public static ServerClassLoader getInstance() { + return LazyHolder.INSTANCE; + } + + private ServerClassLoader() { + super(ClassLoaderManager.getStaticPath(), new URL[0], null); + } +} diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/context/Context.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/context/Context.java new file mode 100644 index 00000000000..9403ccbf4ba --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/context/Context.java @@ -0,0 +1,207 @@ +/* + * + * Copyright (c) 2016 CUBRID Corporation. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * - Neither the name of the nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + */ + +package com.cubrid.jsp.context; + +import com.cubrid.jsp.ExecuteThread; +import com.cubrid.jsp.TargetMethodCache; +import com.cubrid.jsp.classloader.ClassLoaderManager; +import com.cubrid.jsp.classloader.ContextClassLoader; +import com.cubrid.jsp.jdbc.CUBRIDServerSideConnection; +import com.cubrid.jsp.protocol.Header; +import com.cubrid.plcsql.builtin.MessageBuffer; +import java.nio.ByteBuffer; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Properties; +import java.util.concurrent.LinkedBlockingQueue; + +public class Context { + // To recognize unique DB session + private long sessionId = -1; + + // transaction Id + private int tranactionId = -1; + + // request Id (for future) + private int prevRequestId = 0; + + // charset + private String charSet = "UTF-8"; + + // single server-side connection per Context + private CUBRIDServerSideConnection connection = null; + + private LinkedBlockingQueue inBound = null; + + // CAS client information connecting with this Context + private Properties clientInfo = null; + + // dynamic classLoader for a session + private ContextClassLoader classLoader = null; + + // method cache + private TargetMethodCache methodCache = null; + + // Whether SP is able to process TCL (commit, rollback). (default: false) + private boolean transactionControl = false; + + // Connection Properties + private Properties connectionInfo = null; + + // message buffer for DBMS_OUTPUT + private MessageBuffer messageBuffer; + + public Context(long id) { + sessionId = id; + } + + public long getSessionId() { + return sessionId; + } + + public synchronized Connection getConnection(Properties prop) { + if (this.connection == null) { + this.connectionInfo = prop; + this.connection = new CUBRIDServerSideConnection(this); + } + return connection; + } + + public void closeConnection(Connection conn) throws SQLException { + if (connection != null) { + connection.close(); + } + } + + public Properties getClientInfo() { + if (clientInfo == null) { + clientInfo = new Properties(); + } + return clientInfo; + } + + public LinkedBlockingQueue getInboundQueue() { + if (inBound == null) { + inBound = new LinkedBlockingQueue(); + } + return inBound; + } + + public String getCharset() { + return charSet; + } + + public void checkHeader(Header header) { + if (prevRequestId > header.requestId) { + // not incremented + // a new session is started with the same session Id or the trasaction is ended + clear(); + } + prevRequestId = header.requestId; + } + + public void checkTranId(int tid) { + if (tranactionId == -1) { + tranactionId = tid; + } + + if (tranactionId != tid) { + // re-cretae dynamic class loader + if (classLoader + .getInitializedTime() + .compareTo( + ClassLoaderManager.getLastModifiedTimeOfPath( + ClassLoaderManager.getDynamicPath())) + != 0) { + classLoader = new ContextClassLoader(); + methodCache.clear(); + } + clear(); + tranactionId = tid; + } + } + + public void clear() { + try { + closeConnection(connection); + } catch (Exception e) { + // ignore + } finally { + connection = null; + } + } + + public MessageBuffer getMessageBuffer() { + if (messageBuffer == null) { + messageBuffer = new MessageBuffer(); + } + return messageBuffer; + } + + public ClassLoader getClassLoader() { + if (classLoader == null) { + classLoader = new ContextClassLoader(); + } + + return classLoader; + } + + public TargetMethodCache getTargetMethodCache() { + if (methodCache == null) { + methodCache = new TargetMethodCache(); + } + + return methodCache; + } + + public void setTransactionControl(boolean tc) { + this.transactionControl = tc; + } + + public boolean canTransactionControl() { + if (transactionControl) { + return true; + } + + String tcProp = connectionInfo.getProperty("transaction_control"); + if (tcProp != null && "true".equalsIgnoreCase(tcProp)) { + return true; + } + + return false; + } + + // TODO: move this function to proper place + public static ExecuteThread getCurrentExecuteThread() { + return (ExecuteThread) Thread.currentThread(); + } +} diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/context/ContextManager.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/context/ContextManager.java new file mode 100644 index 00000000000..e81f0689a02 --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/context/ContextManager.java @@ -0,0 +1,90 @@ +/* + * + * Copyright (c) 2016 CUBRID Corporation. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * - Neither the name of the nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + */ + +package com.cubrid.jsp.context; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +public class ContextManager { + + // singleton + private ContextManager() { + // + } + + // Context ID => Context Object + private static ConcurrentMap contextMap = new ConcurrentHashMap(); + + public static boolean hasContext(long id) { + return contextMap.containsKey(id); + } + + public static Context getContext(long id) { + if (hasContext(id)) { + return contextMap.get(id); + } else { + synchronized (ContextManager.class) { + Context newCtx = new Context(id); + contextMap.put(id, newCtx); + return newCtx; + } + } + } + + // Java Thread ID => Context ID + private static ConcurrentMap contextThreadMap = new ConcurrentHashMap(); + + public static void registerThread(long threadId, long ctxId) { + if (contextThreadMap.containsKey(threadId) == false) { + contextThreadMap.put(threadId, ctxId); + } + } + + public static void deregisterThread(long threadId) { + if (contextThreadMap.containsKey(threadId) == true) { + contextThreadMap.remove(threadId); + } + } + + public static Long getContextIdByThreadId(long threadId) { + if (contextThreadMap.containsKey(threadId)) { + return contextThreadMap.get(threadId); + } + return null; + } + + public static Context getContextofCurrentThread() { + Thread t = Thread.currentThread(); + Long ctxId = ContextManager.getContextIdByThreadId(t.getId()); + return ContextManager.getContext(ctxId); + } +} diff --git a/src/jsp/com/cubrid/jsp/data/CUBRIDPacker.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/CUBRIDPacker.java similarity index 95% rename from src/jsp/com/cubrid/jsp/data/CUBRIDPacker.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/CUBRIDPacker.java index e00cced3957..9233d792b8a 100644 --- a/src/jsp/com/cubrid/jsp/data/CUBRIDPacker.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/CUBRIDPacker.java @@ -32,6 +32,7 @@ package com.cubrid.jsp.data; import com.cubrid.jsp.jdbc.CUBRIDServerSideResultSet; +import com.cubrid.jsp.protocol.PackableObject; import cubrid.sql.CUBRIDOID; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; @@ -138,6 +139,15 @@ public void packCString(byte[] value) { } } + public void packPackableObject(PackableObject o) { + o.pack(this); + } + + public void packPrimitiveBytes(ByteBuffer b) { + ensureSpace(b.position()); + buffer.put(b.array(), 0, b.position()); + } + // TODO: legacy implementation, this function will be modified public void packValue(Object result, int ret_type, String charset) throws UnsupportedEncodingException { @@ -160,7 +170,7 @@ public void packValue(Object result, int ret_type, String charset) packDouble(((Double) result).doubleValue()); } else if (result instanceof BigDecimal) { packInt(DBType.DB_NUMERIC); - packString(((BigDecimal) result).toString(), charset); + packString(((BigDecimal) result).toPlainString(), charset); } else if (result instanceof String) { packInt(DBType.DB_STRING); packString((String) result, charset); @@ -234,9 +244,9 @@ public void packValue(Object result, int ret_type, String charset) } } - private void align(int size) { + public void align(int size) { int currentPosition = buffer.position(); - int newPosition = DataUtilities.alignedPosition(buffer, size); + int newPosition = DataUtilities.alignedPosition(currentPosition, size); ensureSpace(newPosition - currentPosition); if (newPosition - currentPosition > 0) { diff --git a/src/jsp/com/cubrid/jsp/data/CUBRIDUnpacker.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/CUBRIDUnpacker.java similarity index 95% rename from src/jsp/com/cubrid/jsp/data/CUBRIDUnpacker.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/CUBRIDUnpacker.java index 7aace497b24..27e3d03f36a 100644 --- a/src/jsp/com/cubrid/jsp/data/CUBRIDUnpacker.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/CUBRIDUnpacker.java @@ -39,6 +39,10 @@ public class CUBRIDUnpacker { private ByteBuffer buffer; + public CUBRIDUnpacker() { + this.buffer = null; + } + public CUBRIDUnpacker(ByteBuffer buffer) { this.buffer = buffer; } @@ -130,6 +134,21 @@ public int unpackStringSize() { return len; } + public ByteBuffer unpackBuffer() { + align(DataUtilities.INT_ALIGNMENT); + + int size = buffer.getInt(); + if (size > 0) { + byte[] buf = new byte[size]; + buffer.get(buf); + + align(DataUtilities.INT_ALIGNMENT); + return ByteBuffer.wrap(buf); + } else { + return ByteBuffer.allocate(0); + } + } + public SOID unpackOID() { align(DataUtilities.INT_ALIGNMENT); int pageId = buffer.getInt(); @@ -354,4 +373,12 @@ private Value[] unpackSetValue(int paramCount) throws TypeMismatchException { public void align(int size) { DataUtilities.align(buffer, size); } + + public int getCurrentPosition() { + return buffer.position(); + } + + public int getCurrentLimit() { + return buffer.limit(); + } } diff --git a/src/jsp/com/cubrid/jsp/data/CallInfo.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/CallInfo.java similarity index 100% rename from src/jsp/com/cubrid/jsp/data/CallInfo.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/CallInfo.java diff --git a/src/jsp/com/cubrid/jsp/data/ClientIds.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/ClientIds.java similarity index 100% rename from src/jsp/com/cubrid/jsp/data/ClientIds.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/ClientIds.java diff --git a/src/jsp/com/cubrid/jsp/data/ColumnInfo.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/ColumnInfo.java similarity index 97% rename from src/jsp/com/cubrid/jsp/data/ColumnInfo.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/ColumnInfo.java index 728870ab3c7..dca264dda6e 100644 --- a/src/jsp/com/cubrid/jsp/data/ColumnInfo.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/ColumnInfo.java @@ -22,6 +22,8 @@ public class ColumnInfo { public byte shared; public String defaultValueString; + public ColumnInfo() {} // for mock server API + public ColumnInfo(CUBRIDUnpacker unpacker) { type = unpacker.unpackInt(); setType = unpacker.unpackInt(); diff --git a/src/jsp/com/cubrid/jsp/data/ColumnMeta.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/ColumnMeta.java similarity index 100% rename from src/jsp/com/cubrid/jsp/data/ColumnMeta.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/ColumnMeta.java diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/CompileInfo.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/CompileInfo.java new file mode 100644 index 00000000000..b09e349f862 --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/CompileInfo.java @@ -0,0 +1,78 @@ +/* + * + * Copyright (c) 2016 CUBRID Corporation. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * - Neither the name of the nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + */ + +package com.cubrid.jsp.data; + +import com.cubrid.jsp.protocol.PackableObject; + +public class CompileInfo implements PackableObject { + public int errCode = -1; // 0: no error, < 0: error + public int errLine = 0; + public int errColumn = 0; + public String errMsg = null; + + public String translated = null; + public String createStmt = null; + public String className = null; + public String signature = null; + + public CompileInfo(int code, int line, int column, String msg) { + assert code < 0; + + errCode = code; + errLine = line; + errColumn = column; + errMsg = msg; + } + + public CompileInfo(String translated, String stmt, String name, String sig) { + errCode = 0; + this.translated = translated; + this.createStmt = stmt; + this.className = name; + this.signature = sig; + } + + @Override + public void pack(CUBRIDPacker packer) { + packer.packInt(errCode); + if (errCode < 0) { + packer.packInt(errLine); + packer.packInt(errColumn); + packer.packString(errMsg); + } else { + packer.packString(translated); + packer.packString(createStmt); + packer.packString(className); + packer.packString(signature); + } + } +} diff --git a/src/jsp/com/cubrid/jsp/data/DBParameterInfo.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/DBParameterInfo.java similarity index 100% rename from src/jsp/com/cubrid/jsp/data/DBParameterInfo.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/DBParameterInfo.java diff --git a/src/jsp/com/cubrid/jsp/data/DBType.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/DBType.java similarity index 98% rename from src/jsp/com/cubrid/jsp/data/DBType.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/DBType.java index 301407fc395..b8537a73861 100644 --- a/src/jsp/com/cubrid/jsp/data/DBType.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/DBType.java @@ -42,7 +42,7 @@ import java.sql.Time; import java.sql.Timestamp; -public class DBType { +public class DBType { // see src/compat/dbtype_def.h public static final int DB_NULL = 0; public static final int DB_INT = 1; public static final int DB_FLOAT = 2; @@ -56,6 +56,7 @@ public class DBType { public static final int DB_TIMESTAMP = 11; public static final int DB_DATE = 12; public static final int DB_MONETARY = 13; + public static final int DB_VARIABLE = 14; public static final int DB_SHORT = 18; public static final int DB_NUMERIC = 22; public static final int DB_OID = 20; diff --git a/src/jsp/com/cubrid/jsp/data/DataUtilities.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/DataUtilities.java similarity index 100% rename from src/jsp/com/cubrid/jsp/data/DataUtilities.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/DataUtilities.java diff --git a/src/jsp/com/cubrid/jsp/data/ErrorInfo.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/ErrorInfo.java similarity index 100% rename from src/jsp/com/cubrid/jsp/data/ErrorInfo.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/ErrorInfo.java diff --git a/src/jsp/com/cubrid/jsp/data/ExecuteInfo.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/ExecuteInfo.java similarity index 100% rename from src/jsp/com/cubrid/jsp/data/ExecuteInfo.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/ExecuteInfo.java diff --git a/src/jsp/com/cubrid/jsp/data/FetchInfo.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/FetchInfo.java similarity index 100% rename from src/jsp/com/cubrid/jsp/data/FetchInfo.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/FetchInfo.java diff --git a/src/jsp/com/cubrid/jsp/data/GetByOIDInfo.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/GetByOIDInfo.java similarity index 100% rename from src/jsp/com/cubrid/jsp/data/GetByOIDInfo.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/GetByOIDInfo.java diff --git a/src/jsp/com/cubrid/jsp/data/GetGeneratedKeysInfo.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/GetGeneratedKeysInfo.java similarity index 100% rename from src/jsp/com/cubrid/jsp/data/GetGeneratedKeysInfo.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/GetGeneratedKeysInfo.java diff --git a/src/jsp/com/cubrid/jsp/data/GetSchemaInfo.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/GetSchemaInfo.java similarity index 100% rename from src/jsp/com/cubrid/jsp/data/GetSchemaInfo.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/GetSchemaInfo.java diff --git a/src/jsp/com/cubrid/jsp/data/MakeOutResultSetInfo.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/MakeOutResultSetInfo.java similarity index 100% rename from src/jsp/com/cubrid/jsp/data/MakeOutResultSetInfo.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/MakeOutResultSetInfo.java diff --git a/src/jsp/com/cubrid/jsp/data/PrepareInfo.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/PrepareInfo.java similarity index 100% rename from src/jsp/com/cubrid/jsp/data/PrepareInfo.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/PrepareInfo.java diff --git a/src/jsp/com/cubrid/jsp/data/QueryResultInfo.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/QueryResultInfo.java similarity index 100% rename from src/jsp/com/cubrid/jsp/data/QueryResultInfo.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/QueryResultInfo.java diff --git a/src/jsp/com/cubrid/jsp/data/SOID.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/SOID.java similarity index 100% rename from src/jsp/com/cubrid/jsp/data/SOID.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/data/SOID.java diff --git a/src/jsp/com/cubrid/jsp/exception/CUBRIDServerSideException.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/exception/CUBRIDServerSideException.java similarity index 100% rename from src/jsp/com/cubrid/jsp/exception/CUBRIDServerSideException.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/exception/CUBRIDServerSideException.java diff --git a/src/jsp/com/cubrid/jsp/exception/ExecuteException.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/exception/ExecuteException.java similarity index 100% rename from src/jsp/com/cubrid/jsp/exception/ExecuteException.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/exception/ExecuteException.java diff --git a/src/jsp/com/cubrid/jsp/exception/TypeMismatchException.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/exception/TypeMismatchException.java similarity index 100% rename from src/jsp/com/cubrid/jsp/exception/TypeMismatchException.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/exception/TypeMismatchException.java diff --git a/src/jsp/com/cubrid/jsp/impl/SUBindParameter.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/impl/SUBindParameter.java similarity index 100% rename from src/jsp/com/cubrid/jsp/impl/SUBindParameter.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/impl/SUBindParameter.java diff --git a/src/jsp/com/cubrid/jsp/impl/SUConnection.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/impl/SUConnection.java similarity index 89% rename from src/jsp/com/cubrid/jsp/impl/SUConnection.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/impl/SUConnection.java index b7399b9914f..36c8fdbe6f0 100644 --- a/src/jsp/com/cubrid/jsp/impl/SUConnection.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/impl/SUConnection.java @@ -31,7 +31,7 @@ package com.cubrid.jsp.impl; -import com.cubrid.jsp.ExecuteThread; +import com.cubrid.jsp.context.Context; import com.cubrid.jsp.data.CUBRIDPacker; import com.cubrid.jsp.data.CUBRIDUnpacker; import com.cubrid.jsp.data.DBParameterInfo; @@ -49,6 +49,7 @@ import com.cubrid.jsp.jdbc.CUBRIDServerSideConstants; import com.cubrid.jsp.jdbc.CUBRIDServerSideJDBCErrorCode; import com.cubrid.jsp.jdbc.CUBRIDServerSideJDBCErrorManager; +import com.cubrid.jsp.protocol.Header; import cubrid.sql.CUBRIDOID; import java.io.IOException; import java.nio.ByteBuffer; @@ -56,17 +57,26 @@ public class SUConnection { - ExecuteThread thread = null; + Context ctx = null; ByteBuffer outputBuffer = ByteBuffer.allocate(4096); - public SUConnection(ExecuteThread t) { - thread = t; + public SUConnection(Context t) { + ctx = t; } public CUBRIDUnpacker request(ByteBuffer buffer) throws IOException, SQLException { - thread.sendCommand(buffer); + Context.getCurrentExecuteThread().sendCommand(buffer); buffer.clear(); - CUBRIDUnpacker unpacker = thread.receiveBuffer(); + + ByteBuffer responseBuffer = Context.getCurrentExecuteThread().receiveBuffer(); + + CUBRIDUnpacker unpacker = new CUBRIDUnpacker(responseBuffer); + + /* read header, dummy */ + Header header = new Header(unpacker); + + ByteBuffer payload = unpacker.unpackBuffer(); + unpacker.setBuffer(payload); int responseCode = unpacker.unpackInt(); if (responseCode != 0) { @@ -79,7 +89,7 @@ public CUBRIDUnpacker request(ByteBuffer buffer) throws IOException, SQLExceptio return unpacker; } - // UFunctionCode.GET_DB_PARAMETER + // SUFunctionCode.GET_DB_PARAMETER public DBParameterInfo getDBParameter() throws IOException, SQLException { CUBRIDPacker packer = new CUBRIDPacker(outputBuffer); packer.packInt(SUFunctionCode.GET_DB_PARAMETER.getCode()); @@ -89,7 +99,7 @@ public DBParameterInfo getDBParameter() throws IOException, SQLException { return info; } - // UFunctionCode.PREPARE + // SUFunctionCode.PREPARE public SUStatement prepare(String sql, byte flag) throws IOException, SQLException { return prepare(sql, flag, false); } @@ -114,7 +124,7 @@ public SUStatement prepare(String sql, byte flag, boolean recompile) return stmt; } - // UFunctionCode.GET_SCHEMA_INFO + // SUFunctionCode.GET_SCHEMA_INFO public SUStatement getSchemaInfo(int type, String arg1, String arg2, byte flag) throws IOException, SQLException { CUBRIDPacker packer = new CUBRIDPacker(outputBuffer); @@ -130,7 +140,7 @@ public SUStatement getSchemaInfo(int type, String arg1, String arg2, byte flag) return stmt; } - // UFunctionCode.EXECUTE + // SUFunctionCode.EXECUTE public ExecuteInfo execute( int handlerId, byte executeFlag, @@ -161,7 +171,7 @@ public ExecuteInfo execute( return info; } - // UFunctionCode.FETCH + // SUFunctionCode.FETCH public FetchInfo fetch(long queryId, int currentRowIndex, int fetchSize, int fetchFlag) throws IOException, TypeMismatchException, SQLException { CUBRIDPacker packer = new CUBRIDPacker(outputBuffer); @@ -176,7 +186,7 @@ public FetchInfo fetch(long queryId, int currentRowIndex, int fetchSize, int fet return info; } - // UFunctionCode.MAKE_OUT_RS + // SUFunctionCode.MAKE_OUT_RS public MakeOutResultSetInfo makeOutResult(long queryId) throws IOException, SQLException { CUBRIDPacker packer = new CUBRIDPacker(outputBuffer); packer.packInt(SUFunctionCode.MAKE_OUT_RS.getCode()); @@ -187,7 +197,7 @@ public MakeOutResultSetInfo makeOutResult(long queryId) throws IOException, SQLE return info; } - // UFunctionCode.NEXT_RESULT + // SUFunctionCode.NEXT_RESULT public ExecuteInfo nextResult(int handlerId) throws IOException, SQLException { CUBRIDPacker packer = new CUBRIDPacker(outputBuffer); packer.packInt(SUFunctionCode.NEXT_RESULT.getCode()); @@ -198,7 +208,7 @@ public ExecuteInfo nextResult(int handlerId) throws IOException, SQLException { return info; } - // UFunctionCode.GET_BY_OID + // SUFunctionCode.GET_BY_OID public SUStatement getByOID(CUBRIDOID oid, String[] attributeName) throws IOException, SQLException { CUBRIDPacker packer = new CUBRIDPacker(outputBuffer); @@ -224,7 +234,7 @@ public SUStatement getByOID(CUBRIDOID oid, String[] attributeName) return stmt; } - // UFunctionCode.GET_GENERATED_KEYS + // SUFunctionCode.GET_GENERATED_KEYS public SUStatement getGeneratedKeys(int handlerId) throws IOException, SQLException, TypeMismatchException { CUBRIDPacker packer = new CUBRIDPacker(outputBuffer); @@ -237,7 +247,7 @@ public SUStatement getGeneratedKeys(int handlerId) return stmt; } - // UFunctionCode.PUT_BY_OID + // SUFunctionCode.PUT_BY_OID public void putByOID(CUBRIDOID oid, String[] attributeName, Object values[]) throws IOException, SQLException { CUBRIDPacker packer = new CUBRIDPacker(outputBuffer); @@ -264,7 +274,7 @@ public void putByOID(CUBRIDOID oid, String[] attributeName, Object values[]) int result = unpacker.unpackInt(); } - // UFunctionCode.RELATED_TO_OID + // SUFunctionCode.RELATED_TO_OID public Object oidCmd(CUBRIDOID oid, int command) throws IOException, SQLException { CUBRIDPacker packer = new CUBRIDPacker(outputBuffer); packer.packInt(SUFunctionCode.RELATED_TO_OID.getCode()); @@ -284,7 +294,7 @@ public Object oidCmd(CUBRIDOID oid, int command) throws IOException, SQLExceptio return null; } - // UFunctionCode.RELATED_TO_COLLECTION + // SUFunctionCode.RELATED_TO_COLLECTION protected CUBRIDUnpacker collectionCmd( int cmd, CUBRIDOID oid, String attributeName, Object value, int index) throws IOException, SQLException { @@ -312,6 +322,18 @@ protected CUBRIDUnpacker collectionCmd( return unpacker; } + // SUFunctionCode.END_TRANSACTION + public void endTransaction(boolean type) throws IOException, SQLException { + CUBRIDPacker packer = new CUBRIDPacker(outputBuffer); + packer.packInt(SUFunctionCode.END_TRANSACTION.getCode()); + packer.packInt( + (type == true) + ? CUBRIDServerSideConstants.END_TRAN_COMMIT + : CUBRIDServerSideConstants.END_TRAN_ROLLBACK); + CUBRIDUnpacker unpacker = request(packer.getBuffer()); + unpacker.unpackInt(); + } + public void addElementToSet(CUBRIDOID oid, String attributeName, Object value) throws IOException, SQLException { collectionCmd(CUBRIDServerSideConstants.ADD_ELEMENT_TO_SET, oid, attributeName, value, -1); @@ -367,7 +389,7 @@ public int getSizeOfCollection(CUBRIDOID oid, String attributeName) return size; } - // UFunctionCode.NEW_LOB - // UFunctionCode.WRITE_LOB - // UFunctionCode.READ_LOB + // SUFunctionCode.NEW_LOB + // SUFunctionCode.WRITE_LOB + // SUFunctionCode.READ_LOB } diff --git a/src/jsp/com/cubrid/jsp/impl/SUFunctionCode.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/impl/SUFunctionCode.java similarity index 99% rename from src/jsp/com/cubrid/jsp/impl/SUFunctionCode.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/impl/SUFunctionCode.java index d7637481b36..3100618fa6c 100644 --- a/src/jsp/com/cubrid/jsp/impl/SUFunctionCode.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/impl/SUFunctionCode.java @@ -37,6 +37,7 @@ * added in UFunctionCode, it should be added below. */ public enum SUFunctionCode { + END_TRANSACTION(1), PREPARE(2), EXECUTE(3), GET_DB_PARAMETER(4), diff --git a/src/jsp/com/cubrid/jsp/impl/SUParameter.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/impl/SUParameter.java similarity index 100% rename from src/jsp/com/cubrid/jsp/impl/SUParameter.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/impl/SUParameter.java diff --git a/src/jsp/com/cubrid/jsp/impl/SUResultTuple.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/impl/SUResultTuple.java similarity index 100% rename from src/jsp/com/cubrid/jsp/impl/SUResultTuple.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/impl/SUResultTuple.java diff --git a/src/jsp/com/cubrid/jsp/impl/SUStatement.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/impl/SUStatement.java similarity index 99% rename from src/jsp/com/cubrid/jsp/impl/SUStatement.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/impl/SUStatement.java index 2c9f0252356..49f0dfbe9d7 100644 --- a/src/jsp/com/cubrid/jsp/impl/SUStatement.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/impl/SUStatement.java @@ -239,8 +239,8 @@ public void execute(int maxRow, int maxField, boolean isSensitive, boolean isScr } if (bindParameter != null && !bindParameter.checkAllBinded()) { - // TODO: error handling - return; + throw CUBRIDServerSideJDBCErrorManager.createCUBRIDException( + CUBRIDServerSideJDBCErrorCode.ER_NOT_BIND, null); } setExecuteFlags(maxRow, isSensitive); diff --git a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideCallableStatement.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideCallableStatement.java similarity index 100% rename from src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideCallableStatement.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideCallableStatement.java diff --git a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideConnection.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideConnection.java similarity index 84% rename from src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideConnection.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideConnection.java index bf08de00fc8..93db90e3cdf 100644 --- a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideConnection.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideConnection.java @@ -31,7 +31,7 @@ package com.cubrid.jsp.jdbc; -import com.cubrid.jsp.ExecuteThread; +import com.cubrid.jsp.context.Context; import com.cubrid.jsp.data.DBParameterInfo; import com.cubrid.jsp.impl.SUConnection; import cubrid.jdbc.jci.CUBRIDIsolationLevel; @@ -64,7 +64,7 @@ * @version 2.0 */ public class CUBRIDServerSideConnection implements Connection { - private ExecuteThread thread = null; + private Context context = null; protected CUBRIDServerSideDatabaseMetaData mdata = null; protected List statements = null; @@ -72,10 +72,9 @@ public class CUBRIDServerSideConnection implements Connection { private int transactionIsolation; private int holdability; - private Properties clientInfo = null; - public CUBRIDServerSideConnection(ExecuteThread thread) { - this.thread = thread; + public CUBRIDServerSideConnection(Context ctx) { + this.context = ctx; holdability = ResultSet.HOLD_CURSORS_OVER_COMMIT; // default value, there is no meaning for the @@ -87,42 +86,42 @@ public CUBRIDServerSideConnection(ExecuteThread thread) { public SUConnection getSUConnection() { if (suConn == null) { - suConn = new SUConnection(thread); + suConn = new SUConnection(context); } return suConn; } protected void requestDBParameter() throws IOException, SQLException { - DBParameterInfo info = getSUConnection().getDBParameter(); - - switch (info.tran_isolation) { - case CUBRIDIsolationLevel.TRAN_READ_COMMITTED: - transactionIsolation = TRANSACTION_READ_COMMITTED; - break; - - case CUBRIDIsolationLevel.TRAN_REPEATABLE_READ: - transactionIsolation = TRANSACTION_REPEATABLE_READ; - break; - - case CUBRIDIsolationLevel.TRAN_SERIALIZABLE: - transactionIsolation = TRANSACTION_SERIALIZABLE; - break; + Properties clientInfo = context.getClientInfo(); + if (clientInfo.contains("type") == false) { + DBParameterInfo info = getSUConnection().getDBParameter(); + + switch (info.tran_isolation) { + case CUBRIDIsolationLevel.TRAN_READ_COMMITTED: + transactionIsolation = TRANSACTION_READ_COMMITTED; + break; + + case CUBRIDIsolationLevel.TRAN_REPEATABLE_READ: + transactionIsolation = TRANSACTION_REPEATABLE_READ; + break; + + case CUBRIDIsolationLevel.TRAN_SERIALIZABLE: + transactionIsolation = TRANSACTION_SERIALIZABLE; + break; + + default: + transactionIsolation = TRANSACTION_NONE; + break; + } - default: - transactionIsolation = TRANSACTION_NONE; - break; + clientInfo.put("type", String.valueOf(info.clientIds.clientType)); + clientInfo.put("program", info.clientIds.programName); + clientInfo.put("host", info.clientIds.hostName); + clientInfo.put("login", info.clientIds.loginName); + clientInfo.put("user", info.clientIds.dbUser); + clientInfo.put("ip", info.clientIds.clientIp); + clientInfo.put("pid", String.valueOf(info.clientIds.processId)); } - - // TODO: lock timeout? - - clientInfo = new Properties(); - clientInfo.put("type", String.valueOf(info.clientIds.clientType)); - clientInfo.put("program", info.clientIds.programName); - clientInfo.put("host", info.clientIds.hostName); - clientInfo.put("login", info.clientIds.loginName); - clientInfo.put("user", info.clientIds.dbUser); - clientInfo.put("ip", info.clientIds.clientIp); - clientInfo.put("pid", String.valueOf(info.clientIds.processId)); } /* To manage List statements */ @@ -170,17 +169,39 @@ public boolean getAutoCommit() throws SQLException { } public void commit() throws SQLException { - /* do nothing */ + if (context.canTransactionControl()) { + try { + close(); + getSUConnection().endTransaction(true); + } catch (IOException e) { + throw CUBRIDServerSideJDBCErrorManager.createCUBRIDException( + CUBRIDServerSideJDBCErrorCode.ER_COMMUNICATION, e); + } + } } public void rollback() throws SQLException { - /* do nothing */ + if (context.canTransactionControl()) { + try { + close(); + getSUConnection().endTransaction(false); + } catch (IOException e) { + throw CUBRIDServerSideJDBCErrorManager.createCUBRIDException( + CUBRIDServerSideJDBCErrorCode.ER_COMMUNICATION, e); + } + } } public void close() throws SQLException { - /* Becuase It is assume that Java SP Server always connecting with DB Server directly, It should not be closed */ + /* + * Becuase It is assume that Java SP Server always connecting with DB Server + * directly, It should not be closed + */ /* Here, only the JDBC resources are cleaned up */ - /* The connection is not actually terminated or database resources such as query handlers and result sets are removed. */ + /* + * The connection is not actually terminated or database resources such as query + * handlers and result sets are removed. + */ if (statements != null) { for (Statement s : statements) { s.close(); @@ -225,13 +246,11 @@ public void setTransactionIsolation(int level) throws SQLException { } public int getTransactionIsolation() throws SQLException { - if (transactionIsolation == TRANSACTION_NONE) { - try { - requestDBParameter(); - } catch (IOException e) { - throw CUBRIDServerSideJDBCErrorManager.createCUBRIDException( - CUBRIDServerSideJDBCErrorCode.ER_COMMUNICATION, e); - } + try { + requestDBParameter(); + } catch (IOException e) { + throw CUBRIDServerSideJDBCErrorManager.createCUBRIDException( + CUBRIDServerSideJDBCErrorCode.ER_COMMUNICATION, e); } return transactionIsolation; @@ -405,16 +424,14 @@ public void setClientInfo(String arg0, String arg1) throws SQLClientInfoExceptio /* JDK 1.6 */ public Properties getClientInfo() throws SQLException { - if (clientInfo == null) { - try { - requestDBParameter(); - } catch (IOException e) { - throw CUBRIDServerSideJDBCErrorManager.createCUBRIDException( - CUBRIDServerSideJDBCErrorCode.ER_COMMUNICATION, e); - } + try { + requestDBParameter(); + } catch (IOException e) { + throw CUBRIDServerSideJDBCErrorManager.createCUBRIDException( + CUBRIDServerSideJDBCErrorCode.ER_COMMUNICATION, e); } - return clientInfo; + return context.getClientInfo(); } /* JDK 1.6 */ diff --git a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideConstants.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideConstants.java similarity index 95% rename from src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideConstants.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideConstants.java index bef3dba9363..fbce70377e6 100644 --- a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideConstants.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideConstants.java @@ -69,4 +69,8 @@ public class CUBRIDServerSideConstants { DROP_ELEMENT_IN_SEQUENCE = 5, INSERT_ELEMENT_INTO_SEQUENCE = 6, PUT_ELEMENT_ON_SEQUENCE = 7; + + /* end transaction constants */ + public static final byte END_TRAN_COMMIT = 1; + public static final byte END_TRAN_ROLLBACK = 2; } diff --git a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideDatabaseMetaData.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideDatabaseMetaData.java similarity index 100% rename from src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideDatabaseMetaData.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideDatabaseMetaData.java diff --git a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideDriver.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideDriver.java similarity index 71% rename from src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideDriver.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideDriver.java index c4fdfb55332..fa3fe5d560f 100644 --- a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideDriver.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideDriver.java @@ -31,7 +31,7 @@ package com.cubrid.jsp.jdbc; -import java.lang.reflect.Method; +import com.cubrid.jsp.context.ContextManager; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; @@ -40,11 +40,16 @@ import java.util.Properties; import java.util.StringTokenizer; import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; public class CUBRIDServerSideDriver implements Driver { private static final String JDBC_DEFAULT_CONNECTION = "jdbc:default:connection"; + private static final String JDBC_DEFAULT_CONNECTION_PATTERN = + "jdbc:default:connection(::\\?[a-zA-Z_0-9]+=[^&=?]+(&[a-zA-Z_0-9]+=[^&=?]+)*)?"; + private static String VERSION_STRING; private static int VERSION_MAJOR; private static int VERSION_MINOR; @@ -78,22 +83,25 @@ public Connection connect(String url, Properties info) throws SQLException { return null; } - Connection conn = null; - try { - Thread t = Thread.currentThread(); - conn = - (Connection) - invoke( - "com.cubrid.jsp.ExecuteThread", - "createConnection", - null, - t, - null); - } catch (Exception e) { - /* do nothing. The exception will be dealt with in ExecuteThread */ + Pattern pattern = + Pattern.compile(JDBC_DEFAULT_CONNECTION_PATTERN, Pattern.CASE_INSENSITIVE); + Matcher matcher = pattern.matcher(url); + if (!matcher.find()) { + // TODO: error? + return null; } - return conn; + setDefaultProperties(info); + + // parse property + String prop = matcher.group(1); + if (prop != null) { + setProperties(prop, info); + } + + Thread t = Thread.currentThread(); + Long ctxId = ContextManager.getContextIdByThreadId(t.getId()); + return ContextManager.getContext(ctxId).getConnection(info); } @Override @@ -109,6 +117,25 @@ public boolean acceptsURL(String url) throws SQLException { return false; } + private void setProperties(String propertyString, Properties info) { + StringTokenizer st = new StringTokenizer(propertyString, "?&;"); + while (st.hasMoreTokens()) { + String propString = st.nextToken(); + StringTokenizer pt = new StringTokenizer(propString, "="); + if (pt.hasMoreTokens()) { + String name = pt.nextToken().toLowerCase(); + if (pt.hasMoreTokens()) { + String value = pt.nextToken(); + info.put(name, value); + } + } + } + } + + private void setDefaultProperties(Properties info) { + info.setProperty("transaction_control", "false"); + } + @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return new DriverPropertyInfo[0]; @@ -133,15 +160,4 @@ public boolean jdbcCompliant() { public Logger getParentLogger() { throw new java.lang.UnsupportedOperationException(); } - - private Object invoke( - String cls_name, String method, Class[] param_cls, Object cls, Object[] params) { - try { - Class c = Class.forName(cls_name); - Method m = c.getMethod(method, param_cls); - return m.invoke(cls, params); - } catch (Exception e) { - throw new RuntimeException(e); - } - } } diff --git a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideJDBCErrorCode.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideJDBCErrorCode.java similarity index 100% rename from src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideJDBCErrorCode.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideJDBCErrorCode.java diff --git a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideJDBCErrorManager.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideJDBCErrorManager.java similarity index 100% rename from src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideJDBCErrorManager.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideJDBCErrorManager.java diff --git a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideOID.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideOID.java similarity index 100% rename from src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideOID.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideOID.java diff --git a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideOutResultSet.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideOutResultSet.java similarity index 100% rename from src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideOutResultSet.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideOutResultSet.java diff --git a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSidePreparedStatement.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSidePreparedStatement.java similarity index 100% rename from src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSidePreparedStatement.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSidePreparedStatement.java diff --git a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideResultSet.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideResultSet.java similarity index 99% rename from src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideResultSet.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideResultSet.java index d1a9acac538..044308d884f 100644 --- a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideResultSet.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideResultSet.java @@ -451,7 +451,7 @@ public Object getObject(String columnName) throws SQLException { public int findColumn(String columnName) throws SQLException { Integer index = statementHandler.getColNameIndex().get(columnName.toLowerCase()); if (index == null) { - CUBRIDServerSideJDBCErrorManager.createCUBRIDException( + throw CUBRIDServerSideJDBCErrorManager.createCUBRIDException( CUBRIDServerSideJDBCErrorCode.ER_INVALID_COLUMN_NAME, null); } diff --git a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideResultSetMetaData.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideResultSetMetaData.java similarity index 100% rename from src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideResultSetMetaData.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideResultSetMetaData.java diff --git a/src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideStatement.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideStatement.java similarity index 100% rename from src/jsp/com/cubrid/jsp/jdbc/CUBRIDServerSideStatement.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/jdbc/CUBRIDServerSideStatement.java diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/GlobalSemanticsRequest.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/GlobalSemanticsRequest.java new file mode 100644 index 00000000000..068c81a067f --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/GlobalSemanticsRequest.java @@ -0,0 +1,26 @@ +package com.cubrid.jsp.protocol; + +import com.cubrid.jsp.data.CUBRIDPacker; +import com.cubrid.plcsql.compiler.serverapi.ServerAPI.Question; +import java.util.List; + +public class GlobalSemanticsRequest implements PackableObject { + + public List questions = null; + + public GlobalSemanticsRequest(List questions) { + this.questions = questions; + } + + @Override + public void pack(CUBRIDPacker packer) { + if (questions != null) { + packer.packBigInt(questions.size()); + for (Question q : questions) { + q.pack(packer); + } + } else { + assert false; + } + } +} diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/GlobalSemanticsResponse.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/GlobalSemanticsResponse.java new file mode 100644 index 00000000000..300466d9785 --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/GlobalSemanticsResponse.java @@ -0,0 +1,31 @@ +package com.cubrid.jsp.protocol; + +import com.cubrid.jsp.data.CUBRIDUnpacker; +import com.cubrid.plcsql.compiler.serverapi.ServerAPI.Question; +import java.util.List; + +public class GlobalSemanticsResponse implements UnPackableObject { + + public List semantics = null; + + public GlobalSemanticsResponse(List semantics, CUBRIDUnpacker unpacker) { + this.semantics = semantics; + unpack(unpacker); + } + + @Override + public void unpack(CUBRIDUnpacker unpacker) { + int size = (int) unpacker.unpackBigint(); + if (size > 0) { + for (int i = 0; i < size; i++) { + semantics.get(i).unpack(unpacker); + } + } else { + assert false; + } + } + + public List getResponse() { + return semantics; + } +} diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/Header.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/Header.java new file mode 100644 index 00000000000..9f2efef85a5 --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/Header.java @@ -0,0 +1,38 @@ +package com.cubrid.jsp.protocol; + +import com.cubrid.jsp.data.CUBRIDUnpacker; + +public class Header { + + public static final int EMPTY_SESSION_ID = 0; + public static final int BYTES = getHeaderSize(); + + public long id; // DB SESSION ID + public int code; // code + public int requestId; // request Id + + /* for runtime */ + public int payloadSize = 0; + public boolean hasPayload = false; + + public Header(CUBRIDUnpacker unpacker) { + id = unpacker.unpackBigint(); + code = unpacker.unpackInt(); + requestId = unpacker.unpackInt(); + } + + public Header(long id, int code, int size) { + this.id = id; + this.code = code; + this.requestId = size; + } + + @Override + public String toString() { + return "Header [id=" + id + ", code=" + code + ", rid=" + requestId + "]"; + } + + public static int getHeaderSize() { + return 16; + } +} diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/PackableObject.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/PackableObject.java new file mode 100644 index 00000000000..7e8f90bcc58 --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/PackableObject.java @@ -0,0 +1,7 @@ +package com.cubrid.jsp.protocol; + +import com.cubrid.jsp.data.CUBRIDPacker; + +public interface PackableObject { + void pack(CUBRIDPacker packer); +} diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/PrepareArgs.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/PrepareArgs.java new file mode 100644 index 00000000000..d52e29d7270 --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/PrepareArgs.java @@ -0,0 +1,53 @@ +package com.cubrid.jsp.protocol; + +import com.cubrid.jsp.data.CUBRIDUnpacker; +import com.cubrid.jsp.exception.TypeMismatchException; +import com.cubrid.jsp.value.Value; + +public class PrepareArgs { + + private long groupId = -1; + private int tranId; + private Value[] arguments = null; + + public PrepareArgs(CUBRIDUnpacker unpacker) throws TypeMismatchException { + readArgs(unpacker); + } + + public void setArgs(Value[] args) { + this.arguments = args; + } + + public Value[] getArgs() { + return arguments; + } + + public int getArgCount() { + if (arguments == null) { + return -1; + } else { + return arguments.length; + } + } + + public int getTranId() { + return tranId; + } + + public void readArgs(CUBRIDUnpacker unpacker) throws TypeMismatchException { + groupId = unpacker.unpackBigint(); + tranId = unpacker.unpackInt(); + int argCount = unpacker.unpackInt(); + + if (arguments == null || argCount != arguments.length) { + arguments = new Value[argCount]; + } + + for (int i = 0; i < arguments.length; i++) { + int paramType = unpacker.unpackInt(); + + Value arg = unpacker.unpackValue(paramType); + arguments[i] = (arg); + } + } +} diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/RequestCode.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/RequestCode.java new file mode 100644 index 00000000000..59fc505d7bc --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/RequestCode.java @@ -0,0 +1,24 @@ +package com.cubrid.jsp.protocol; + +public class RequestCode { + public static final int INVOKE_SP = 0x01; + public static final int RESULT = 0x02; + public static final int ERROR = 0x04; + public static final int INTERNAL_JDBC = 0x08; + + // private static final int DESTROY = 0x10; + // private static final int END = 0x20; + + public static final int PREPARE_ARGS = 0x40; + + public static final int COMPILE = 0x80; + + public static final int REQUEST_SQL_SEMANTICS = 0xA0; + public static final int REQUEST_GLOBAL_SEMANTICS = 0xA1; + public static final int REQUEST_BUILTIN_FUNCTION = 0xA4; + + public static final int UTIL_PING = 0xDE; + public static final int UTIL_STATUS = 0xEE; + public static final int UTIL_TERMINATE_THREAD = 0xFE; + public static final int UTIL_TERMINATE_SERVER = 0xFF; // to shutdown javasp server +} diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/SqlSemanticsRequest.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/SqlSemanticsRequest.java new file mode 100644 index 00000000000..44e4886b868 --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/SqlSemanticsRequest.java @@ -0,0 +1,24 @@ +package com.cubrid.jsp.protocol; + +import com.cubrid.jsp.data.CUBRIDPacker; +import java.util.List; + +public class SqlSemanticsRequest implements PackableObject { + + public List sqlTexts = null; + + public SqlSemanticsRequest(List sqls) { + this.sqlTexts = sqls; + } + + public void pack(CUBRIDPacker packer) { + if (sqlTexts != null) { + packer.packInt(sqlTexts.size()); + for (String s : sqlTexts) { + packer.packString(s); + } + } else { + packer.packInt(0); + } + } +} diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/SqlSemanticsResponse.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/SqlSemanticsResponse.java new file mode 100644 index 00000000000..2b971a8544d --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/SqlSemanticsResponse.java @@ -0,0 +1,27 @@ +package com.cubrid.jsp.protocol; + +import com.cubrid.jsp.data.CUBRIDUnpacker; +import com.cubrid.plcsql.compiler.serverapi.SqlSemantics; +import java.util.ArrayList; +import java.util.List; + +public class SqlSemanticsResponse implements UnPackableObject { + + public List semantics = null; + + public SqlSemanticsResponse(CUBRIDUnpacker unpacker) { + unpack(unpacker); + } + + @Override + public void unpack(CUBRIDUnpacker unpacker) { + int size = unpacker.unpackInt(); + if (size > 0) { + semantics = new ArrayList(size); + for (int i = 0; i < size; i++) { + SqlSemantics s = new SqlSemantics(unpacker); + semantics.add(s); + } + } + } +} diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/UnPackableObject.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/UnPackableObject.java new file mode 100644 index 00000000000..210083d30b0 --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/protocol/UnPackableObject.java @@ -0,0 +1,7 @@ +package com.cubrid.jsp.protocol; + +import com.cubrid.jsp.data.CUBRIDUnpacker; + +public interface UnPackableObject { + void unpack(CUBRIDUnpacker packer); +} diff --git a/src/jsp/com/cubrid/jsp/value/BooleanValue.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/value/BooleanValue.java similarity index 96% rename from src/jsp/com/cubrid/jsp/value/BooleanValue.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/value/BooleanValue.java index a5865131382..8c948bbdc90 100644 --- a/src/jsp/com/cubrid/jsp/value/BooleanValue.java +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/value/BooleanValue.java @@ -70,6 +70,10 @@ public Double toDoubleObject() throws TypeMismatchException { return new Double(value); } + public Object toObject() { + return Boolean.valueOf(value == 1 ? true : false); + } + public String toString() { return "" + value; } diff --git a/src/jsp/com/cubrid/jsp/value/ByteValue.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/value/ByteValue.java similarity index 100% rename from src/jsp/com/cubrid/jsp/value/ByteValue.java rename to pl_engine/pl_server/src/main/java/com/cubrid/jsp/value/ByteValue.java diff --git a/pl_engine/pl_server/src/main/java/com/cubrid/jsp/value/DateTimeParser.java b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/value/DateTimeParser.java new file mode 100644 index 00000000000..7b6859dbf3f --- /dev/null +++ b/pl_engine/pl_server/src/main/java/com/cubrid/jsp/value/DateTimeParser.java @@ -0,0 +1,385 @@ +/* + * Copyright (c) 2016 CUBRID Corporation. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * - Neither the name of the nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + */ + +package com.cubrid.jsp.value; + +import java.text.ParsePosition; +import java.text.SimpleDateFormat; +import java.time.DateTimeException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Locale; + +public class DateTimeParser { + + private static final ZoneOffset TIMEZONE_0 = ZoneOffset.of("Z"); + // TODO: update the following value along with the server + private static final ZoneOffset TIMEZONE_SESSION = ZoneOffset.of("+09:00"); + + // zoneless part of min timestamp: 1970-01-01 00:00:01 + private static final LocalDateTime minTimestampLocal = LocalDateTime.of(1970, 1, 1, 0, 0, 1); + // zoneless part of max timestamp local part: 2038-01-19 03:14:07 + private static final LocalDateTime maxTimestampLocal = LocalDateTime.of(2038, 1, 19, 3, 14, 7); + // min datetime: 0001-01-01 00:00:00.000 + private static final LocalDateTime minDatetime = LocalDateTime.of(1, 1, 1, 0, 0, 0, 0); + // max datetime: 9999-12-31 23:59:59.999 + private static final LocalDateTime maxDatetime = + LocalDateTime.of(9999, 12, 31, 23, 59, 59, 999); + + private static final ZonedDateTime minTimestamp = + ZonedDateTime.of(minTimestampLocal, TIMEZONE_0); + private static final ZonedDateTime maxTimestamp = + ZonedDateTime.of(maxTimestampLocal, TIMEZONE_0); + private static final ZonedDateTime minDatetimeUTC = ZonedDateTime.of(minDatetime, TIMEZONE_0); + private static final ZonedDateTime maxDatetimeUTC = ZonedDateTime.of(maxDatetime, TIMEZONE_0); + + public static final LocalDate nullDate = LocalDate.MAX; + public static final LocalDateTime nullDatetime = LocalDateTime.MAX; + public static final ZonedDateTime nullDatetimeUTC = ZonedDateTime.of(nullDatetime, TIMEZONE_0); + + public static class DateLiteral { + + public static LocalDate parse(String s) { + LocalDate ret = parseDateFragment(s); + + if (ret != null + && ret != nullDate + && (ret.compareTo(minDate) < 0 || ret.compareTo(maxDate) > 0)) { + return null; + } + + return ret; + } + + // --------------------------------------- + // Private + // --------------------------------------- + + private static final LocalDate minDate = LocalDate.of(1, 1, 1); // 0001-01-01 + private static final LocalDate maxDate = LocalDate.of(9999, 12, 31); // 9999-12-31 + } + + public static class TimeLiteral { + + public static LocalTime parse(String s) { + return parseTimeFragment(s, false); + } + } + + public static class TimestampLiteral { + + public static ZonedDateTime parse(String s) { + return ZonedDateTimeLiteral.parse( + s, false); // same as TIMESTAMPLTZ with timezone omitted + } + } + + public static class DatetimeLiteral { + + public static LocalDateTime parse(String s) { + + LocalDateTime ret = parseDateAndTime(s, true); + if (ret != null + && ret != nullDatetime + && (ret.compareTo(minDatetime) < 0 || ret.compareTo(maxDatetime) > 0)) { + return null; + } + + return ret; + } + } + + public static class ZonedDateTimeLiteral { + public static ZonedDateTime parse(String s, boolean forDatetime) { + return parseZonedDateAndTime(s, forDatetime); + } + } + + // --------------------------------------- + // Private + // --------------------------------------- + + // returns a ZonedDateTime when a timezone offset is given, otherwise returns a LocalDateTime + public static ZonedDateTime parseZonedDateAndTime(String s, boolean forDatetime) { + + // get timezone offset + LocalDateTime localPart; + ZoneOffset zone; + int delim = s.lastIndexOf(" "); + if (delim < 0) { + // no timezone offset + localPart = parseDateAndTime(s, forDatetime); + zone = TIMEZONE_SESSION; + } else { + String dt = s.substring(0, delim); + String z = s.substring(delim + 1); + try { + localPart = parseDateAndTime(dt, forDatetime); + zone = ZoneOffset.of(z); + } catch (DateTimeException e) { + // z turn out not to be a timezone offset. try timezone omitted string + localPart = parseDateAndTime(s, forDatetime); + zone = TIMEZONE_SESSION; + } + } + + if (localPart == null) { + return null; + } + if (localPart == nullDatetime) { + return nullDatetimeUTC; + } + + ZonedDateTime ret = ZonedDateTime.of(localPart, zone); + if (forDatetime) { + if (ret.compareTo(minDatetimeUTC) < 0 || ret.compareTo(maxDatetimeUTC) > 0) { + return null; + } + } else { + // in this case, for TIMESTAMP* + if (ret.compareTo(minTimestamp) < 0 || ret.compareTo(maxTimestamp) > 0) { + return null; + } + } + + return ret; + } + + private static LocalDateTime parseDateAndTime(String s, boolean millis) { + + s = s.trim(); + + String timeStr, dateStr; + int colonIdx = s.indexOf(":"); + if (colonIdx == 1 || colonIdx == 2) { + // order: