├── .github └── workflows │ └── ci.yaml ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── client ├── aggregate_executor.go ├── aggregate_result.go ├── batch_executor.go ├── batch_result.go ├── batch_result_test.go ├── client.go ├── filter │ ├── compare_operator.go │ ├── table_filter.go │ ├── table_filter_list.go │ ├── table_filter_list_test.go │ ├── table_in_filter.go │ ├── table_in_filter_test.go │ ├── table_notin_filter.go │ ├── table_notin_filter_test.go │ ├── table_value_filter.go │ └── table_value_filter_test.go ├── hfilter │ └── hfilter.go ├── obaggregate.go ├── obbatch.go ├── obbatch_test.go ├── obclient.go ├── obclient_test.go ├── option │ ├── batch_option.go │ ├── operation_option.go │ └── query_option.go ├── query.go ├── query_result.go ├── query_result_iterator.go ├── query_result_test.go ├── single_result.go ├── single_result_test.go ├── util.go └── util_test.go ├── config ├── client_config.go ├── client_config_test.go └── toml_config.go ├── configurations └── obkv-table-default.toml ├── error └── error_code.go ├── example ├── aggregate │ └── aggregate.go ├── auto_increment │ ├── auto_inc_not_rowkey.go │ └── auto_inc_rowkey.go ├── batch_operation │ └── batch.go ├── filter_operation │ ├── append.go │ ├── delete.go │ ├── filter.go │ ├── increment.go │ ├── insert.go │ └── update.go ├── query │ └── query.go └── single_operation │ ├── append.go │ ├── delete.go │ ├── get.go │ ├── increment.go │ ├── insert.go │ ├── insert_or_update.go │ ├── replace.go │ └── update.go ├── go.mod ├── go.sum ├── log ├── logger.go └── logger_test.go ├── obkvrpc ├── buffer_pool.go ├── compressor.go ├── compressor_test.go ├── connection.go ├── connection_lifecycle_mgr.go ├── connection_mgr.go ├── connection_pool.go ├── rpc_client.go ├── rpc_server.go └── slb_loader.go ├── protocol ├── addr.go ├── aggregation_single.go ├── aggregation_single_test.go ├── async_query_request.go ├── async_query_response.go ├── batch_operation.go ├── batch_operation_request.go ├── batch_operation_request_test.go ├── batch_operation_response.go ├── batch_operation_response_test.go ├── batch_operation_test.go ├── border_flag.go ├── codec.go ├── constants.go ├── election_role.go ├── entity.go ├── entity_test.go ├── error.go ├── ezheader.go ├── ezheader_test.go ├── htable_filter.go ├── htable_filter_test.go ├── index_type.go ├── login_request.go ├── login_request_test.go ├── login_response.go ├── login_response_test.go ├── move_replica_info.go ├── move_response.go ├── object.go ├── object_meta.go ├── operation.go ├── operation_request.go ├── operation_request_test.go ├── operation_response.go ├── operation_response_test.go ├── operation_test.go ├── operation_type.go ├── packet_code.go ├── payload.go ├── payload_base.go ├── query.go ├── query_and_mutate.go ├── query_and_mutate_request.go ├── query_and_mutate_request_test.go ├── query_and_mutate_response.go ├── query_and_mutate_response_test.go ├── query_and_mutate_test.go ├── query_request.go ├── query_request_test.go ├── query_response.go ├── query_response_test.go ├── query_test.go ├── range.go ├── range_test.go ├── replica_type.go ├── response.go ├── response_test.go ├── rpc_header.go ├── rpc_header_test.go ├── rpc_response_code.go ├── rpc_response_code_test.go ├── rpc_response_warning_message.go ├── rpc_response_warning_message_test.go ├── stream_request.go ├── stream_response.go ├── uni_version_header.go └── uni_version_header_test.go ├── route ├── authentic.go ├── authentic_test.go ├── column.go ├── config_server_info.go ├── config_server_info_test.go ├── generate_column.go ├── generate_column_test.go ├── hash_partition.go ├── hash_partition_test.go ├── hash_sort_utf8mb4.go ├── hash_sort_utf8mb4_test.go ├── indexInfo.go ├── key_partion_test.go ├── key_partition.go ├── location.go ├── part_desc.go ├── partition_function_type.go ├── partition_function_type_test.go ├── partition_infomation_test.go ├── partition_information.go ├── partition_location.go ├── partition_location_entry.go ├── partition_location_entry_test.go ├── partition_location_test.go ├── range_partition.go ├── range_partition_test.go ├── replica_location.go ├── replica_location_test.go ├── route_info.go ├── route_task_info.go ├── rslist.go ├── server_address.go ├── server_roster.go ├── server_roster_test.go ├── server_status.go ├── server_status_test.go ├── simple_column.go ├── simple_column_test.go ├── sql_driver.go ├── sql_driver_test.go ├── table.go ├── table_entry.go ├── table_entry_key.go ├── table_entry_test.go ├── table_location.go ├── table_mutex.go ├── table_param.go ├── table_param_test.go ├── table_roster.go ├── table_test.go ├── util.go └── util_test.go ├── table ├── column.go ├── column_test.go ├── extremum.go ├── kv_mode.go ├── range_pair.go ├── scan_order.go ├── type.go ├── util.go └── util_test.go ├── test ├── aggregate │ ├── aggregate_test.go │ └── all_test.go ├── autoinc │ ├── all_test.go │ ├── auto_increment_normal_fill_nil_test.go │ ├── auto_increment_normal_fill_test.go │ ├── auto_increment_normal_not_fill_test.go │ ├── auto_increment_rowkey_fill_nil_test.go │ ├── auto_increment_rowkey_fill_zero_test.go │ └── auto_increment_rowkey_not_fill_test.go ├── batch │ ├── all_test.go │ └── batch_operation_test.go ├── compress_rpc_result │ ├── all_test.go │ └── query_with_compress_test.go ├── connection_balance │ ├── all_test.go │ └── connection_balance_test.go ├── current_timestamp │ ├── all_test.go │ └── current_timestamp_test.go ├── error_message │ ├── all_test.go │ └── error_message_test.go ├── filter │ ├── all_test.go │ └── filter_operation_test.go ├── generate_column │ ├── all_test.go │ ├── stored_generate_column_test.go │ └── virtual_generate_column_test.go ├── global_index │ ├── all_test.go │ └── global_index_test.go ├── logger │ ├── all_test.go │ └── logger_file_test.go ├── login │ ├── all_test.go │ └── login_test.go ├── nullable │ ├── all_test.go │ └── nullable_test.go ├── obkvrpc │ └── rpc_server_test.go ├── partition │ ├── all_test.go │ ├── partition_one_hash_test.go │ ├── partition_one_key_test.go │ ├── partition_two_hash_test.go │ ├── partition_two_key_test.go │ └── partition_zero_test.go ├── primary_key_order │ ├── all_test.go │ └── primary_key_order_test.go ├── query │ ├── all_test.go │ ├── query_hash_test.go │ ├── query_key_test.go │ ├── query_lob_test.go │ └── query_zero_test.go ├── route │ ├── all_test.go │ ├── reroute_test.go │ ├── route_test.go │ └── util │ │ ├── partition.go │ │ ├── replica.go │ │ └── replica_operation.go ├── single │ ├── all_test.go │ ├── blob_table_test.go │ ├── clob_table_test.go │ ├── datetime_table_test.go │ ├── double_table_test.go │ ├── float_table_test.go │ ├── int32_table_test.go │ ├── int64_table_test.go │ ├── smallint_table_test.go │ ├── smalluint_table_test.go │ ├── timestamp_table_test.go │ ├── tinyint_table_test.go │ ├── tinyuint_table_test.go │ ├── uint32_table_test.go │ ├── uint64_table_test.go │ ├── varbinary_table_test.go │ └── varchar_table_test.go ├── ttl │ ├── all_test.go │ └── ttl_test.go └── util.go └── util ├── binary.go ├── binary_test.go ├── concurrent_map.go ├── concurrent_map_test.go ├── local_time_origin.go ├── obversion.go ├── purecrc32c.go ├── purecrc32c_test.go ├── security.go ├── security_test.go ├── serialization.go ├── serialization_test.go ├── time_zone.go ├── util.go └── util_test.go /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | #- 2 | # #%L 3 | # OBKV Table Client Framework 4 | # %% 5 | # Copyright (C) 2023 OceanBase 6 | # %% 7 | # OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | # You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | # You may obtain a copy of Mulan PSL v2 at: 10 | # http://license.coscl.org.cn/MulanPSL2 11 | # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | # See the Mulan PSL v2 for more details. 15 | # #L% 16 | 17 | name: CI 18 | 19 | on: 20 | workflow_dispatch: 21 | push: 22 | branches: 23 | - main 24 | pull_request: 25 | branches: 26 | - main 27 | 28 | jobs: 29 | build: 30 | name: Build 31 | runs-on: ubuntu-latest 32 | steps: 33 | - name: Check out code into the Go module directory 34 | uses: actions/checkout@v2 35 | 36 | - name: Set up Go 37 | uses: actions/setup-go@v3 38 | with: 39 | go-version-file: 'go.mod' 40 | 41 | - name: Cache Go modules 42 | uses: actions/cache@v2 43 | with: 44 | path: ~/go/pkg/mod 45 | key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} 46 | restore-keys: | 47 | ${{ runner.os }}-go- 48 | 49 | - name: Install dependencies 50 | run: go mod download 51 | 52 | - name: Build 53 | run: | 54 | go list ./... | grep -v /example/ | grep -v /test/ | xargs -L 1 go build -v 55 | 56 | - name: Run unit tests 57 | run: | 58 | go test -v $(go list ./... | grep -v /test/ | grep -v /example/) 59 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea 3 | .vscode 4 | ./logs 5 | -------------------------------------------------------------------------------- /client/aggregate_executor.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package client 19 | 20 | import ( 21 | "context" 22 | ) 23 | 24 | type AggExecutor interface { 25 | // Min add a min operation to the agg executor. 26 | Min(columnName string) AggExecutor 27 | // Max add a max operation to the agg executor. 28 | Max(columnName string) AggExecutor 29 | // Count add a count operation to the agg executor. 30 | Count() AggExecutor 31 | // Sum add a sum operation to the agg executor. 32 | Sum(columnName string) AggExecutor 33 | // Avg add an avg operation to the agg executor. 34 | Avg(columnName string) AggExecutor 35 | // Execute an agg operation. 36 | // AggregateResult contains the results of all operations. 37 | Execute(ctx context.Context) (AggregateResult, error) 38 | } 39 | -------------------------------------------------------------------------------- /client/aggregate_result.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package client 19 | 20 | type AggregateResult interface { 21 | // Value returns the value of the specified aggregate name, such as Value("min(c1)"). 22 | Value(columnName string) interface{} 23 | // Values returns all aggregation values. 24 | Values() []interface{} 25 | } 26 | 27 | func newObAggregateResult(aggResultSet QueryResult) *obAggregateResult { 28 | return &obAggregateResult{aggResultSet} 29 | } 30 | 31 | type obAggregateResult struct { 32 | result QueryResult 33 | } 34 | 35 | // Value returns the value of the specified aggregate name, such as Value("min(c1)"). 36 | func (r *obAggregateResult) Value(aggregateName string) interface{} { 37 | if r.result == nil { 38 | return nil 39 | } 40 | return r.result.Value(aggregateName) 41 | } 42 | 43 | // Values returns all aggregation values. 44 | func (r *obAggregateResult) Values() []interface{} { 45 | if r.result == nil { 46 | return nil 47 | } 48 | return r.result.Values() 49 | } 50 | -------------------------------------------------------------------------------- /client/batch_result.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package client 19 | 20 | type BatchOperationResult interface { 21 | // IsEmptySet result is empty or not. 22 | IsEmptySet() bool 23 | // GetResults get all results. 24 | GetResults() []SingleResult 25 | // Size batch operation size. 26 | Size() int 27 | // SuccessIdx indexes of successful operation. 28 | SuccessIdx() []int 29 | // ErrorIdx indexes of unsuccessful operation. 30 | ErrorIdx() []int 31 | } 32 | 33 | type obBatchOperationResult struct { 34 | results []SingleResult 35 | } 36 | 37 | func newObBatchOperationResult(results []SingleResult) *obBatchOperationResult { 38 | return &obBatchOperationResult{results} 39 | } 40 | 41 | func (r *obBatchOperationResult) IsEmptySet() bool { 42 | if len(r.results) == 0 { 43 | return true 44 | } 45 | for _, result := range r.results { 46 | if !result.IsEmptySet() { 47 | return false 48 | } 49 | } 50 | return true 51 | } 52 | 53 | func (r *obBatchOperationResult) GetResults() []SingleResult { 54 | return r.results 55 | } 56 | 57 | func (r *obBatchOperationResult) Size() int { 58 | return len(r.results) 59 | } 60 | 61 | func (r *obBatchOperationResult) SuccessIdx() []int { 62 | var successIdx []int 63 | for i, result := range r.results { 64 | if result != nil { 65 | successIdx = append(successIdx, i) 66 | } 67 | } 68 | return successIdx 69 | } 70 | 71 | func (r *obBatchOperationResult) ErrorIdx() []int { 72 | var errorIdx []int 73 | for i, result := range r.results { 74 | if result == nil { 75 | errorIdx = append(errorIdx, i) 76 | } 77 | } 78 | return errorIdx 79 | } 80 | -------------------------------------------------------------------------------- /client/batch_result_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package client 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestObBatchOperationResult_Size(t *testing.T) { 27 | result := newObSingleResult(1, nil) 28 | emptyResult := make([]SingleResult, 0) 29 | batchResult := newObBatchOperationResult(emptyResult) 30 | assert.EqualValues(t, 0, batchResult.Size()) 31 | batchResult = newObBatchOperationResult([]SingleResult{result}) 32 | assert.EqualValues(t, 1, batchResult.Size()) 33 | } 34 | -------------------------------------------------------------------------------- /client/filter/compare_operator.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package filter 19 | 20 | type ObCompareOperator uint8 21 | 22 | const ( 23 | LessThan ObCompareOperator = iota 24 | GreaterThan 25 | LessOrEqualThan 26 | GreaterOrEqualThan 27 | NotEqual 28 | Equal 29 | IsNull 30 | IsNotNull 31 | ) 32 | 33 | const ( 34 | LessThanStr string = "<" 35 | GreaterThanStr string = ">" 36 | LessOrEqualThanStr string = "<=" 37 | GreaterOrEqualThanStr string = ">=" 38 | NotEqualStr string = "!=" 39 | EqualStr string = "=" 40 | IsNullStr string = "IS" 41 | IsNotNullStr string = "IS_NOT" 42 | ) 43 | 44 | var ObCompareOperatorStrings = []string{ 45 | LessThan: LessThanStr, 46 | GreaterThan: GreaterThanStr, 47 | LessOrEqualThan: LessOrEqualThanStr, 48 | GreaterOrEqualThan: GreaterOrEqualThanStr, 49 | NotEqual: NotEqualStr, 50 | Equal: EqualStr, 51 | IsNull: IsNullStr, 52 | IsNotNull: IsNotNullStr, 53 | } 54 | 55 | func (o ObCompareOperator) String() string { 56 | if o > IsNotNull { 57 | return "" 58 | } 59 | return ObCompareOperatorStrings[o] 60 | } 61 | -------------------------------------------------------------------------------- /client/filter/table_filter.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package filter 19 | 20 | type ObTableFilter interface { 21 | String() string 22 | } 23 | 24 | const tableCompareFilter = "TableCompareFilter" 25 | 26 | func AndList(filters ...ObTableFilter) *ObTableFilterList { 27 | return NewObTableFilterListWithOperatorAndTableFilter(OperatorAnd, filters...) 28 | } 29 | 30 | func OrList(filters ...ObTableFilter) *ObTableFilterList { 31 | return NewObTableFilterListWithOperatorAndTableFilter(OperatorOr, filters...) 32 | } 33 | 34 | func CompareVal(op ObCompareOperator, columnName string, value interface{}) *ObTableValueFilter { 35 | return NewObTableValueFilter(op, columnName, value) 36 | } 37 | 38 | func In(columnName string, values ...interface{}) *ObTableInFilter { 39 | return NewObTableInFilter(columnName, values...) 40 | } 41 | 42 | func NotIn(columnName string, values ...interface{}) *ObTableNotInFilter { 43 | return NewObTableNotInFilter(columnName, values...) 44 | } 45 | -------------------------------------------------------------------------------- /client/filter/table_filter_list_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package filter 19 | 20 | import ( 21 | "math/rand" 22 | "testing" 23 | 24 | "github.com/stretchr/testify/assert" 25 | ) 26 | 27 | func TestObTableFilterListString(t *testing.T) { 28 | testColumnName := "testColumnName" 29 | value := rand.Intn(100) 30 | 31 | var filterList []ObTableFilter 32 | filterList = append(filterList, In(testColumnName, value)) 33 | filterList = append(filterList, NotIn(testColumnName, value)) 34 | filterList = append(filterList, CompareVal(LessThan, testColumnName, value)) 35 | filterList = append(filterList, CompareVal(GreaterThan, testColumnName, value)) 36 | filterList = append(filterList, CompareVal(LessOrEqualThan, testColumnName, value)) 37 | filterList = append(filterList, CompareVal(GreaterOrEqualThan, testColumnName, value)) 38 | filterList = append(filterList, CompareVal(NotEqual, testColumnName, value)) 39 | filterList = append(filterList, CompareVal(Equal, testColumnName, value)) 40 | filterList = append(filterList, CompareVal(IsNull, testColumnName, value)) 41 | filterList = append(filterList, CompareVal(IsNotNull, testColumnName, value)) 42 | 43 | obTableFilterList := NewObTableFilterListWithOperatorAndTableFilter(OperatorAnd) 44 | obTableFilterList.AddFilter(filterList...) 45 | 46 | tableFilterList := AndList() 47 | tableFilterList.AddFilter(filterList...) 48 | 49 | assert.EqualValues(t, tableFilterList.Size(), obTableFilterList.Size()) 50 | assert.EqualValues(t, tableFilterList.String(), obTableFilterList.String()) 51 | assert.EqualValues(t, tableFilterList, obTableFilterList) 52 | 53 | obTableFilterList = NewObTableFilterListWithOperatorAndTableFilter(OperatorAnd) 54 | assert.EqualValues(t, 0, obTableFilterList.Size()) 55 | assert.EqualValues(t, "", obTableFilterList.String()) 56 | } 57 | -------------------------------------------------------------------------------- /client/filter/table_in_filter.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package filter 19 | 20 | type ObTableInFilter struct { 21 | columnName string 22 | values []interface{} 23 | } 24 | 25 | func NewObTableInFilter(columnName string, values ...interface{}) *ObTableInFilter { 26 | return &ObTableInFilter{ 27 | columnName: columnName, 28 | values: values, 29 | } 30 | } 31 | 32 | func (f *ObTableInFilter) ColumnName() string { 33 | return f.columnName 34 | } 35 | 36 | func (f *ObTableInFilter) String() string { 37 | filterList := OrList() 38 | for _, value := range f.values { 39 | filterList.AddFilter(CompareVal(Equal, f.columnName, value)) 40 | } 41 | return filterList.String() 42 | } 43 | -------------------------------------------------------------------------------- /client/filter/table_in_filter_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package filter 19 | 20 | import ( 21 | "math/rand" 22 | "testing" 23 | 24 | "github.com/stretchr/testify/assert" 25 | ) 26 | 27 | func TestObTableInFilterString(t *testing.T) { 28 | testColumnName := "testColumnName" 29 | value := rand.Intn(100) 30 | obTableInFilter := In(testColumnName, value) 31 | newObTableInFilter := NewObTableInFilter(testColumnName, value) 32 | assert.EqualValues(t, obTableInFilter.ColumnName(), newObTableInFilter.ColumnName()) 33 | assert.EqualValues(t, obTableInFilter.String(), newObTableInFilter.String()) 34 | assert.EqualValues(t, obTableInFilter, newObTableInFilter) 35 | } 36 | -------------------------------------------------------------------------------- /client/filter/table_notin_filter.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package filter 19 | 20 | type ObTableNotInFilter struct { 21 | columnName string 22 | values []interface{} 23 | } 24 | 25 | func NewObTableNotInFilter(columnName string, values ...interface{}) *ObTableNotInFilter { 26 | return &ObTableNotInFilter{ 27 | columnName: columnName, 28 | values: values, 29 | } 30 | } 31 | 32 | func (f *ObTableNotInFilter) ColumnName() string { 33 | return f.columnName 34 | } 35 | 36 | func (f *ObTableNotInFilter) String() string { 37 | filterList := AndList() 38 | for _, value := range f.values { 39 | filterList.AddFilter(CompareVal(NotEqual, f.columnName, value)) 40 | } 41 | return filterList.String() 42 | } 43 | -------------------------------------------------------------------------------- /client/filter/table_notin_filter_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package filter 19 | 20 | import ( 21 | "math/rand" 22 | "testing" 23 | 24 | "github.com/stretchr/testify/assert" 25 | ) 26 | 27 | func TestObTableNotInFilterString(t *testing.T) { 28 | testColumnName := "testColumnName" 29 | value := rand.Intn(100) 30 | obTableNotInFilter := NotIn(testColumnName, value) 31 | newObTableNotInFilter := NewObTableNotInFilter(testColumnName, value) 32 | assert.EqualValues(t, obTableNotInFilter.ColumnName(), newObTableNotInFilter.ColumnName()) 33 | assert.EqualValues(t, obTableNotInFilter.String(), newObTableNotInFilter.String()) 34 | assert.EqualValues(t, obTableNotInFilter, newObTableNotInFilter) 35 | } 36 | -------------------------------------------------------------------------------- /client/filter/table_value_filter.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package filter 19 | 20 | import ( 21 | "strings" 22 | 23 | "github.com/oceanbase/obkv-table-client-go/util" 24 | ) 25 | 26 | type ObTableValueFilter struct { 27 | op ObCompareOperator 28 | columnName string 29 | value interface{} 30 | } 31 | 32 | func NewObTableValueFilter(op ObCompareOperator, columnName string, value interface{}) *ObTableValueFilter { 33 | return &ObTableValueFilter{ 34 | op: op, 35 | columnName: columnName, 36 | value: value, 37 | } 38 | } 39 | 40 | func (f *ObTableValueFilter) Set(op ObCompareOperator, columnName string, value interface{}) { 41 | f.op = op 42 | f.columnName = columnName 43 | f.value = value 44 | } 45 | 46 | func (f *ObTableValueFilter) ColumnName() string { 47 | return f.columnName 48 | } 49 | 50 | func (f *ObTableValueFilter) String() string { 51 | var builder strings.Builder 52 | if f.columnName == "" { 53 | return "" 54 | } 55 | builder.WriteString(tableCompareFilter) 56 | builder.WriteString("(") 57 | builder.WriteString(f.op.String()) 58 | builder.WriteString(", '") 59 | builder.WriteString(f.columnName) 60 | builder.WriteString(":") 61 | if f.value != nil { 62 | builder.WriteString(util.InterfaceToString(f.value)) 63 | } 64 | builder.WriteString("')") 65 | return builder.String() 66 | } 67 | -------------------------------------------------------------------------------- /client/option/batch_option.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2023 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LimitED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package option 19 | 20 | import ( 21 | "github.com/oceanbase/obkv-table-client-go/table" 22 | ) 23 | 24 | type ObBatchOption interface { 25 | Apply(opts *ObBatchOptions) 26 | } 27 | 28 | type ObBatchOptionFunc func(opts *ObBatchOptions) 29 | 30 | func NewObBatchOption() *ObBatchOptions { 31 | return &ObBatchOptions{ 32 | SamePropertiesNames: false, 33 | KeyValueMode: table.DynamicMode, 34 | } 35 | } 36 | 37 | type ObBatchOptions struct { 38 | SamePropertiesNames bool 39 | KeyValueMode table.ObKeyValueMode 40 | } 41 | 42 | func (f ObBatchOptionFunc) Apply(opts *ObBatchOptions) { 43 | f(opts) 44 | } 45 | 46 | // WithBatchSamePropertiesNames set samePropertiesNames 47 | func WithBatchSamePropertiesNames(samePropertiesNames bool) ObBatchOption { 48 | return ObBatchOptionFunc(func(opts *ObBatchOptions) { 49 | opts.SamePropertiesNames = samePropertiesNames 50 | }) 51 | } 52 | 53 | // WithBatchKeyValueMode set keyValueMode 54 | func WithBatchKeyValueMode(keyValueMode table.ObKeyValueMode) ObBatchOption { 55 | return ObBatchOptionFunc(func(opts *ObBatchOptions) { 56 | opts.KeyValueMode = keyValueMode 57 | }) 58 | } 59 | -------------------------------------------------------------------------------- /client/query_result.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package client 19 | 20 | import ( 21 | "strings" 22 | 23 | "github.com/oceanbase/obkv-table-client-go/protocol" 24 | ) 25 | 26 | type QueryResult interface { 27 | Value(columnName string) interface{} 28 | Values() []interface{} 29 | } 30 | 31 | func newObQueryResult(columnNames []string, values []*protocol.ObObject) *obQueryResult { 32 | return &obQueryResult{columnNames, values} 33 | } 34 | 35 | type obQueryResult struct { 36 | columnNames []string 37 | values []*protocol.ObObject 38 | } 39 | 40 | // Value returns the value of the specified column. 41 | func (r *obQueryResult) Value(columnName string) interface{} { 42 | if r.columnNames == nil { 43 | return nil 44 | } 45 | if r.values == nil { 46 | return nil 47 | } 48 | 49 | for i, resColumnName := range r.columnNames { 50 | if strings.EqualFold(columnName, resColumnName) { 51 | return r.values[i].Value() 52 | } 53 | } 54 | return nil 55 | } 56 | 57 | // Values returns all values in the query result. 58 | func (r *obQueryResult) Values() []interface{} { 59 | if r.values == nil { 60 | return nil 61 | } 62 | 63 | values := make([]interface{}, len(r.values)) 64 | for i, obObject := range r.values { 65 | values[i] = obObject.Value() 66 | } 67 | return values 68 | } 69 | -------------------------------------------------------------------------------- /client/query_result_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package client 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | 25 | "github.com/oceanbase/obkv-table-client-go/protocol" 26 | ) 27 | 28 | func TestQueryResult(t *testing.T) { 29 | columnNames := []string{"c1", "c2"} 30 | res := newObQueryResult(columnNames, nil) 31 | assert.Equal(t, nil, res.Value("c1")) 32 | 33 | obj1 := protocol.NewObObject() 34 | obj1.SetValue(1) 35 | obj2 := protocol.NewObObject() 36 | obj2.SetValue("str") 37 | v := []*protocol.ObObject{obj1, obj2} 38 | res = newObQueryResult(columnNames, v) 39 | assert.EqualValues(t, 1, res.Value("c1")) 40 | assert.EqualValues(t, 1, res.Value("C1")) 41 | assert.EqualValues(t, "str", res.Value("C2")) 42 | 43 | } 44 | -------------------------------------------------------------------------------- /client/single_result_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package client 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | 25 | "github.com/oceanbase/obkv-table-client-go/protocol" 26 | ) 27 | 28 | func TestSingleResult(t *testing.T) { 29 | res := newObSingleResult(1, nil) 30 | assert.EqualValues(t, 1, res.AffectedRows()) 31 | assert.Equal(t, nil, res.Value("c1")) 32 | 33 | obj := protocol.NewObObject() 34 | obj.SetValue(1) 35 | m := make(map[string]*protocol.ObObject, 1) 36 | m["c1"] = obj 37 | entity := protocol.NewObTableEntity() 38 | entity.SetProperties(m) 39 | res.affectedEntity = entity 40 | assert.EqualValues(t, 1, res.Value("c1")) 41 | assert.EqualValues(t, 1, res.Value("C1")) 42 | assert.EqualValues(t, nil, res.Value("C2")) 43 | assert.EqualValues(t, 1, len(res.Values())) 44 | for k, v := range res.Values() { 45 | assert.EqualValues(t, "c1", k) 46 | assert.EqualValues(t, 1, v) 47 | } 48 | assert.EqualValues(t, false, res.IsEmptySet()) 49 | 50 | assert.EqualValues(t, []interface{}(nil), res.RowKey()) 51 | 52 | rowKey := make([]*protocol.ObObject, 0, 1) 53 | obj = protocol.NewObObject() 54 | obj.SetValue(2) 55 | entity = protocol.NewObTableEntity() 56 | entity.SetRowKey(rowKey) 57 | entity.AppendRowKeyElement(obj) 58 | res.affectedEntity = entity 59 | assert.EqualValues(t, 2, res.RowKey()[0]) 60 | } 61 | -------------------------------------------------------------------------------- /client/util.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package client 19 | 20 | import ( 21 | "github.com/oceanbase/obkv-table-client-go/protocol" 22 | "github.com/oceanbase/obkv-table-client-go/table" 23 | "github.com/pkg/errors" 24 | ) 25 | 26 | // TransferQueryRange sets the query range into tableQuery. 27 | func TransferQueryRange(rangePair []*table.RangePair) ([]*protocol.ObNewRange, error) { 28 | queryRanges := make([]*protocol.ObNewRange, 0, len(rangePair)) 29 | for _, rangePair := range rangePair { 30 | if len(rangePair.Start()) != len(rangePair.End()) { 31 | return nil, errors.New("startRange and endRange key length is not equal") 32 | } 33 | startObjs := make([]*protocol.ObObject, 0, len(rangePair.Start())) 34 | endObjs := make([]*protocol.ObObject, 0, len(rangePair.End())) 35 | for i := 0; i < len(rangePair.Start()); i++ { 36 | // append start obj 37 | objMeta, err := protocol.DefaultObjMeta(rangePair.Start()[i].Value()) 38 | if err != nil { 39 | return nil, errors.WithMessage(err, "create obj meta by Range key") 40 | } 41 | startObjs = append(startObjs, protocol.NewObObjectWithParams(objMeta, rangePair.Start()[i].Value())) 42 | 43 | // append end obj 44 | objMeta, err = protocol.DefaultObjMeta(rangePair.End()[i].Value()) 45 | if err != nil { 46 | return nil, errors.WithMessage(err, "create obj meta by Range key") 47 | } 48 | endObjs = append(endObjs, protocol.NewObObjectWithParams(objMeta, rangePair.End()[i].Value())) 49 | } 50 | borderFlag := protocol.NewObBorderFlag() 51 | if !rangePair.IncludeStart() { 52 | borderFlag.UnSetInclusiveStart() 53 | } 54 | if !rangePair.IncludeEnd() { 55 | borderFlag.UnSetInclusiveEnd() 56 | } 57 | queryRanges = append(queryRanges, protocol.NewObNewRangeWithParams(startObjs, endObjs, borderFlag)) 58 | } 59 | return queryRanges, nil 60 | } 61 | -------------------------------------------------------------------------------- /client/util_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package client 19 | 20 | import ( 21 | "github.com/oceanbase/obkv-table-client-go/table" 22 | "github.com/stretchr/testify/assert" 23 | "math/rand" 24 | "testing" 25 | ) 26 | 27 | func TestObTransferRange(t *testing.T) { 28 | 29 | start := rand.Uint64() 30 | end := start + rand.Uint64() 31 | 32 | inclusiveStart := true 33 | 34 | inclusiveEnd := false 35 | 36 | startRowKey := []*table.Column{table.NewColumn("c1", start), table.NewColumn("c2", start)} 37 | endRowKey := []*table.Column{table.NewColumn("c1", end), table.NewColumn("c2", end)} 38 | keyRanges := []*table.RangePair{table.NewRangePair(startRowKey, endRowKey, inclusiveStart, inclusiveEnd)} 39 | 40 | transferRanges, err := TransferQueryRange(keyRanges) 41 | 42 | assert.Equal(t, nil, err) 43 | assert.Equal(t, 1, len(transferRanges)) 44 | 45 | transferRange := transferRanges[0] 46 | 47 | flag := transferRange.BorderFlag() 48 | 49 | assert.Equal(t, true, flag.IsInclusiveStart()) 50 | assert.Equal(t, false, flag.IsInclusiveEnd()) 51 | 52 | for _, startKey := range transferRange.StartKey() { 53 | assert.Equal(t, start, startKey.Value().(uint64)) 54 | } 55 | 56 | for _, endKey := range transferRange.EndKey() { 57 | assert.Equal(t, end, endKey.Value().(uint64)) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /config/client_config_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package config 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestClientConfig_String(t *testing.T) { 27 | cfg := &ClientConfig{} 28 | assert.Equal(t, "ClientConfig{"+ 29 | "ConnPoolMaxConnSize:0, "+ 30 | "ConnConnectTimeOut:0s, "+ 31 | "ConnLoginTimeout:0s, "+ 32 | "OperationTimeOut:0s, "+ 33 | "LogLevel:0, "+ 34 | "TableEntryRefreshLockTimeout:0s, "+ 35 | "TableEntryRefreshTryTimes:0, "+ 36 | "TableEntryRefreshIntervalBase:0s, "+ 37 | "TableEntryRefreshIntervalCeiling:0s, "+ 38 | "MetadataRefreshInterval:0s, "+ 39 | "MetadataRefreshLockTimeout:0s, "+ 40 | "RsListLocalFileLocation:, "+ 41 | "RsListHttpGetTimeout:0s, "+ 42 | "RsListHttpGetRetryTimes:0, "+ 43 | "RsListHttpGetRetryInterval:0s, "+ 44 | "EnableRerouting:false, "+ 45 | "MaxConnectionAge:0s, "+ 46 | "EnableSLBLoadBalance:false"+ 47 | "}", cfg.String()) 48 | cfg = NewDefaultClientConfig() 49 | assert.Equal(t, "ClientConfig{"+ 50 | "ConnPoolMaxConnSize:1, "+ 51 | "ConnConnectTimeOut:1s, "+ 52 | "ConnLoginTimeout:5s, "+ 53 | "OperationTimeOut:10s, "+ 54 | "LogLevel:1, "+ 55 | "TableEntryRefreshLockTimeout:4s, "+ 56 | "TableEntryRefreshTryTimes:3, "+ 57 | "TableEntryRefreshIntervalBase:100ms, "+ 58 | "TableEntryRefreshIntervalCeiling:1.6s, "+ 59 | "MetadataRefreshInterval:1m0s, "+ 60 | "MetadataRefreshLockTimeout:8s, "+ 61 | "RsListLocalFileLocation:, "+ 62 | "RsListHttpGetTimeout:1s, "+ 63 | "RsListHttpGetRetryTimes:3, "+ 64 | "RsListHttpGetRetryInterval:100ms, "+ 65 | "EnableRerouting:true, "+ 66 | "MaxConnectionAge:0s, "+ 67 | "EnableSLBLoadBalance:false"+ 68 | "}", cfg.String()) 69 | } 70 | -------------------------------------------------------------------------------- /configurations/obkv-table-default.toml: -------------------------------------------------------------------------------- 1 | # Client Mode - `direct` or `proxy` 2 | # log is not use toml config 3 | mode = "log" 4 | 5 | ## Direct Mode 6 | [DirectClientConfig] 7 | ConfigUrl = "" 8 | FullUserName = "" 9 | Password = "" 10 | SysUserName = "root" 11 | SysPassword= "" 12 | 13 | 14 | ## ODP Mode 15 | [OdpClientConfig] 16 | OdpIp = "" 17 | OdpRpcPort = 0 18 | FullUserName = "" 19 | Password = "" 20 | Database = "" 21 | 22 | 23 | # Normal Configuration 24 | [ConnConfig] 25 | PoolMaxConnSize = 1 26 | ConnectTimeOut = 1000 27 | LoginTimeout = 1000 28 | 29 | 30 | [TableEntryConfig] 31 | RefreshLockTimeout = 4000 32 | RefreshTryTimes = 3 33 | RefreshIntervalBase = 100 34 | RefreshIntervalCeiling = 1600 35 | 36 | 37 | [RouteMetaDataConfig] 38 | RefreshInterval = 60000 39 | RefreshLockTimeout = 8000 40 | 41 | [RsListConfig] 42 | LocalFileLocation = "" 43 | HttpGetTimeout = 1000 44 | HttpGetRetryTimes = 3 45 | HttpGetRetryInterval = 100 46 | 47 | 48 | [ExtraConfig] 49 | OperationTimeOut = 10000 50 | LogLevel = "info" 51 | EnableRerouting = false 52 | MaxConnectionAge = 0 53 | EnableSLBLoadBalance = false 54 | 55 | [LogConfig] 56 | LogFileName = "./" 57 | SingleFileMaxSize = 256 ## MB 58 | MaxBackupFileSize = 10 ## 0 is not delete 59 | MaxAgeFileRem = 30 ## 30 day 60 | Compress = false ## default not 61 | SlowQueryThreshold = 40 ## ms 62 | -------------------------------------------------------------------------------- /example/aggregate/aggregate.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package aggregate 19 | 20 | import ( 21 | "context" 22 | "github.com/oceanbase/obkv-table-client-go/client" 23 | "github.com/oceanbase/obkv-table-client-go/config" 24 | "github.com/oceanbase/obkv-table-client-go/table" 25 | ) 26 | 27 | // create table if not exists test(`c1` bigint(20) not null, c2 bigint(20) not null, c3 varchar(20) default 'hello', c4 double default null, primary key (`c1`, `c2`)) 28 | func main() { 29 | const ( 30 | configUrl = "xxx" 31 | fullUserName = "user@tenant#cluster" 32 | passWord = "" 33 | sysUserName = "sysUser" 34 | sysPassWord = "" 35 | tableName = "test" 36 | ) 37 | cfg := config.NewDefaultClientConfig() 38 | cli, err := client.NewClient(configUrl, fullUserName, passWord, sysUserName, sysPassWord, cfg) 39 | if err != nil { 40 | panic(err) 41 | } 42 | 43 | startRowKey := []*table.Column{table.NewColumn("c1", int64(0)), table.NewColumn("c2", table.Min)} 44 | endRowKey := []*table.Column{table.NewColumn("c1", int64(100)), table.NewColumn("c2", table.Max)} 45 | keyRanges := []*table.RangePair{table.NewRangePair(startRowKey, endRowKey)} 46 | 47 | // create agg executor 48 | aggExecutor := cli.NewAggExecutor(tableName, keyRanges).Sum("c3").Min("c2").Max("c1").Count() 49 | 50 | // get agg result 51 | res, err := aggExecutor.Execute(context.TODO()) 52 | 53 | if err != nil { 54 | panic(err) 55 | } 56 | 57 | // get agg result value 58 | println(res.Value("sum(c3)").(int64)) 59 | println(res.Value("min(c2)").(int64)) 60 | println(res.Value("max(c1)").(int64)) 61 | println(res.Value("count(*)").(int64)) 62 | } 63 | -------------------------------------------------------------------------------- /example/filter_operation/append.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package main 19 | 20 | import ( 21 | "context" 22 | "fmt" 23 | "github.com/oceanbase/obkv-table-client-go/client/option" 24 | "time" 25 | 26 | "github.com/oceanbase/obkv-table-client-go/client" 27 | "github.com/oceanbase/obkv-table-client-go/client/filter" 28 | "github.com/oceanbase/obkv-table-client-go/config" 29 | "github.com/oceanbase/obkv-table-client-go/table" 30 | ) 31 | 32 | // CREATE TABLE test(c1 bigint, c2 varchar(20), PRIMARY KEY(c1)) PARTITION BY hash(c1) partitions 2; 33 | func main() { 34 | const ( 35 | configUrl = "xxx" 36 | fullUserName = "user@tenant#cluster" 37 | passWord = "" 38 | sysUserName = "sysUser" 39 | sysPassWord = "" 40 | tableName = "test" 41 | ) 42 | 43 | cfg := config.NewDefaultClientConfig() 44 | cli, err := client.NewClient(configUrl, fullUserName, passWord, sysUserName, sysPassWord, cfg) 45 | if err != nil { 46 | panic(err) 47 | } 48 | 49 | // insert 50 | ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) // 10s 51 | rowKey := []*table.Column{table.NewColumn("c1", int64(1))} 52 | insertColumns := []*table.Column{table.NewColumn("c2", "hello")} 53 | affectRows, err := cli.InsertOrUpdate( 54 | ctx, 55 | tableName, 56 | rowKey, 57 | insertColumns, 58 | ) 59 | if err != nil { 60 | panic(err) 61 | } 62 | fmt.Println(affectRows) 63 | 64 | // append c2(2) -> c2("hello") + (" oceanbase") = c2("hello oceanbase") 65 | ctx, _ = context.WithTimeout(context.Background(), 10*time.Second) // 10s 66 | appendColumns := []*table.Column{table.NewColumn("c2", " oceanbase")} 67 | res, err := cli.Append( 68 | ctx, 69 | tableName, 70 | rowKey, 71 | appendColumns, 72 | option.WithFilter(filter.CompareVal(filter.Equal, "c2", "hello")), // where c2 = hello 73 | ) 74 | if err != nil { 75 | panic(err) 76 | } 77 | fmt.Println(res.AffectedRows()) 78 | } 79 | -------------------------------------------------------------------------------- /example/filter_operation/delete.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package main 19 | 20 | import ( 21 | "context" 22 | "fmt" 23 | "github.com/oceanbase/obkv-table-client-go/client/option" 24 | "time" 25 | 26 | "github.com/oceanbase/obkv-table-client-go/client" 27 | "github.com/oceanbase/obkv-table-client-go/client/filter" 28 | "github.com/oceanbase/obkv-table-client-go/config" 29 | "github.com/oceanbase/obkv-table-client-go/table" 30 | ) 31 | 32 | // CREATE TABLE test(c1 bigint, c2 varchar(20), PRIMARY KEY(c1)) PARTITION BY hash(c1) partitions 2; 33 | func main() { 34 | const ( 35 | configUrl = "xxx" 36 | fullUserName = "user@tenant#cluster" 37 | passWord = "" 38 | sysUserName = "sysUser" 39 | sysPassWord = "" 40 | tableName = "test" 41 | ) 42 | 43 | cfg := config.NewDefaultClientConfig() 44 | cli, err := client.NewClient(configUrl, fullUserName, passWord, sysUserName, sysPassWord, cfg) 45 | if err != nil { 46 | panic(err) 47 | } 48 | 49 | // insert 50 | ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) // 10s 51 | rowKey := []*table.Column{table.NewColumn("c1", int64(1))} 52 | insertColumns := []*table.Column{table.NewColumn("c2", "2")} 53 | affectRows, err := cli.InsertOrUpdate( 54 | ctx, 55 | tableName, 56 | rowKey, 57 | insertColumns, 58 | ) 59 | if err != nil { 60 | panic(err) 61 | } 62 | fmt.Println(affectRows) 63 | 64 | // delete 65 | ctx, _ = context.WithTimeout(context.Background(), 10*time.Second) // 10s 66 | affectRows, err = cli.Delete( 67 | ctx, 68 | tableName, 69 | rowKey, 70 | option.WithFilter(filter.CompareVal(filter.Equal, "c2", "2")), // where c2 = 2 71 | ) 72 | if err != nil { 73 | panic(err) 74 | } 75 | fmt.Println(affectRows) 76 | } 77 | -------------------------------------------------------------------------------- /example/filter_operation/increment.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package main 19 | 20 | import ( 21 | "context" 22 | "fmt" 23 | "github.com/oceanbase/obkv-table-client-go/client/option" 24 | "time" 25 | 26 | "github.com/oceanbase/obkv-table-client-go/client" 27 | "github.com/oceanbase/obkv-table-client-go/client/filter" 28 | "github.com/oceanbase/obkv-table-client-go/config" 29 | "github.com/oceanbase/obkv-table-client-go/table" 30 | ) 31 | 32 | // CREATE TABLE test(c1 bigint, c2 bigint, PRIMARY KEY(c1)) PARTITION BY hash(c1) partitions 2; 33 | func main() { 34 | const ( 35 | configUrl = "xxx" 36 | fullUserName = "user@tenant#cluster" 37 | passWord = "" 38 | sysUserName = "sysUser" 39 | sysPassWord = "" 40 | tableName = "test" 41 | ) 42 | 43 | cfg := config.NewDefaultClientConfig() 44 | cli, err := client.NewClient(configUrl, fullUserName, passWord, sysUserName, sysPassWord, cfg) 45 | if err != nil { 46 | panic(err) 47 | } 48 | 49 | // insert 50 | ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) // 10s 51 | rowKey := []*table.Column{table.NewColumn("c1", int64(1))} 52 | insertColumns := []*table.Column{table.NewColumn("c2", int64(2))} 53 | affectRows, err := cli.InsertOrUpdate( 54 | ctx, 55 | tableName, 56 | rowKey, 57 | insertColumns, 58 | ) 59 | if err != nil { 60 | panic(err) 61 | } 62 | fmt.Println(affectRows) 63 | 64 | // increment c2(2) -> c2(2) + (3) = c2(5) 65 | ctx, _ = context.WithTimeout(context.Background(), 10*time.Second) // 10s 66 | incrementColumns := []*table.Column{table.NewColumn("c2", int64(3))} 67 | res, err := cli.Increment( 68 | ctx, 69 | tableName, 70 | rowKey, 71 | incrementColumns, 72 | option.WithFilter(filter.CompareVal(filter.Equal, "c2", int64(2))), // where c2 = 2 73 | ) 74 | if err != nil { 75 | panic(err) 76 | } 77 | fmt.Println(res.AffectedRows()) 78 | } 79 | -------------------------------------------------------------------------------- /example/filter_operation/update.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package main 19 | 20 | import ( 21 | "context" 22 | "fmt" 23 | "github.com/oceanbase/obkv-table-client-go/client/option" 24 | "time" 25 | 26 | "github.com/oceanbase/obkv-table-client-go/client" 27 | "github.com/oceanbase/obkv-table-client-go/client/filter" 28 | "github.com/oceanbase/obkv-table-client-go/config" 29 | "github.com/oceanbase/obkv-table-client-go/table" 30 | ) 31 | 32 | // CREATE TABLE test(c1 bigint, c2 bigint, PRIMARY KEY(c1)) PARTITION BY hash(c1) partitions 2; 33 | func main() { 34 | const ( 35 | configUrl = "xxx" 36 | fullUserName = "user@tenant#cluster" 37 | passWord = "" 38 | sysUserName = "sysUser" 39 | sysPassWord = "" 40 | tableName = "test" 41 | ) 42 | 43 | cfg := config.NewDefaultClientConfig() 44 | cli, err := client.NewClient(configUrl, fullUserName, passWord, sysUserName, sysPassWord, cfg) 45 | if err != nil { 46 | panic(err) 47 | } 48 | 49 | // insert 50 | ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) // 10s 51 | rowKey := []*table.Column{table.NewColumn("c1", int64(1))} 52 | insertColumns := []*table.Column{table.NewColumn("c2", int64(2))} 53 | affectRows, err := cli.InsertOrUpdate( 54 | ctx, 55 | tableName, 56 | rowKey, 57 | insertColumns, 58 | ) 59 | if err != nil { 60 | panic(err) 61 | } 62 | fmt.Println(affectRows) 63 | 64 | // update c2(2) -> c2(3) 65 | ctx, _ = context.WithTimeout(context.Background(), 10*time.Second) // 10s 66 | updateColumns := []*table.Column{table.NewColumn("c2", int64(3))} 67 | affectRows, err = cli.Update( 68 | ctx, 69 | tableName, 70 | rowKey, 71 | updateColumns, 72 | option.WithFilter(filter.CompareVal(filter.Equal, "c2", int64(2))), // where c2 = 2 73 | ) 74 | if err != nil { 75 | panic(err) 76 | } 77 | fmt.Println(affectRows) 78 | } 79 | -------------------------------------------------------------------------------- /example/single_operation/delete.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package main 19 | 20 | import ( 21 | "context" 22 | "fmt" 23 | "time" 24 | 25 | "github.com/oceanbase/obkv-table-client-go/client" 26 | "github.com/oceanbase/obkv-table-client-go/config" 27 | "github.com/oceanbase/obkv-table-client-go/table" 28 | ) 29 | 30 | // CREATE TABLE test(c1 bigint, c2 varchar(20), PRIMARY KEY(c1)) PARTITION BY hash(c1) partitions 2; 31 | func main() { 32 | const ( 33 | configUrl = "xxx" 34 | fullUserName = "user@tenant#cluster" 35 | passWord = "" 36 | sysUserName = "sysUser" 37 | sysPassWord = "" 38 | tableName = "test" 39 | ) 40 | 41 | cfg := config.NewDefaultClientConfig() 42 | cli, err := client.NewClient(configUrl, fullUserName, passWord, sysUserName, sysPassWord, cfg) 43 | if err != nil { 44 | panic(err) 45 | } 46 | 47 | // insert 48 | ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) // 10s 49 | rowKey := []*table.Column{table.NewColumn("c1", int64(1))} 50 | insertColumns := []*table.Column{table.NewColumn("c2", "2")} 51 | affectRows, err := cli.Insert( 52 | ctx, 53 | tableName, 54 | rowKey, 55 | insertColumns, 56 | ) 57 | if err != nil { 58 | panic(err) 59 | } 60 | fmt.Println(affectRows) 61 | 62 | // delete 63 | ctx, _ = context.WithTimeout(context.Background(), 10*time.Second) // 10s 64 | affectRows, err = cli.Delete( 65 | ctx, 66 | tableName, 67 | rowKey, 68 | ) 69 | if err != nil { 70 | panic(err) 71 | } 72 | fmt.Println(affectRows) 73 | } 74 | -------------------------------------------------------------------------------- /example/single_operation/get.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package main 19 | 20 | import ( 21 | "context" 22 | "fmt" 23 | "time" 24 | 25 | "github.com/oceanbase/obkv-table-client-go/client" 26 | "github.com/oceanbase/obkv-table-client-go/config" 27 | "github.com/oceanbase/obkv-table-client-go/table" 28 | ) 29 | 30 | // CREATE TABLE test(c1 bigint, c2 varchar(20), PRIMARY KEY(c1)) PARTITION BY hash(c1) partitions 2; 31 | func main() { 32 | const ( 33 | configUrl = "xxx" 34 | fullUserName = "user@tenant#cluster" 35 | passWord = "" 36 | sysUserName = "sysUser" 37 | sysPassWord = "" 38 | tableName = "test" 39 | ) 40 | 41 | cfg := config.NewDefaultClientConfig() 42 | cli, err := client.NewClient(configUrl, fullUserName, passWord, sysUserName, sysPassWord, cfg) 43 | if err != nil { 44 | panic(err) 45 | } 46 | 47 | // insert 48 | ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) // 10s 49 | rowKey := []*table.Column{table.NewColumn("c1", int64(1))} 50 | insertColumns := []*table.Column{table.NewColumn("c2", "2")} 51 | affectRows, err := cli.Insert( 52 | ctx, 53 | tableName, 54 | rowKey, 55 | insertColumns, 56 | ) 57 | if err != nil { 58 | panic(err) 59 | } 60 | fmt.Println(affectRows) 61 | 62 | // get 63 | ctx, _ = context.WithTimeout(context.Background(), 10*time.Second) // 10s 64 | selectColumns := []string{"c1", "c2"} 65 | result, err := cli.Get( 66 | ctx, 67 | tableName, 68 | rowKey, 69 | selectColumns, 70 | ) 71 | if err != nil { 72 | panic(err) 73 | } 74 | fmt.Println(result.Value("c1")) 75 | fmt.Println(result.Value("c2")) 76 | } 77 | -------------------------------------------------------------------------------- /example/single_operation/insert.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package main 19 | 20 | import ( 21 | "context" 22 | "fmt" 23 | "time" 24 | 25 | "github.com/oceanbase/obkv-table-client-go/client" 26 | "github.com/oceanbase/obkv-table-client-go/config" 27 | "github.com/oceanbase/obkv-table-client-go/table" 28 | ) 29 | 30 | // CREATE TABLE test(c1 bigint, c2 bigint, PRIMARY KEY(c1)) PARTITION BY hash(c1) partitions 2; 31 | func main() { 32 | const ( 33 | configUrl = "xxx" 34 | fullUserName = "user@tenant#cluster" 35 | passWord = "" 36 | sysUserName = "sysUser" 37 | sysPassWord = "" 38 | tableName = "test" 39 | ) 40 | 41 | cfg := config.NewDefaultClientConfig() 42 | cli, err := client.NewClient(configUrl, fullUserName, passWord, sysUserName, sysPassWord, cfg) 43 | if err != nil { 44 | panic(err) 45 | } 46 | 47 | ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) // 10s 48 | rowKey := []*table.Column{table.NewColumn("c1", int64(1))} 49 | mutateColumns := []*table.Column{table.NewColumn("c2", int64(1))} 50 | affectRows, err := cli.Insert( 51 | ctx, 52 | tableName, 53 | rowKey, 54 | mutateColumns, 55 | ) 56 | if err != nil { 57 | panic(err) 58 | } 59 | fmt.Println(affectRows) 60 | } 61 | -------------------------------------------------------------------------------- /example/single_operation/insert_or_update.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package main 19 | 20 | import ( 21 | "context" 22 | "fmt" 23 | "time" 24 | 25 | "github.com/oceanbase/obkv-table-client-go/client" 26 | "github.com/oceanbase/obkv-table-client-go/config" 27 | "github.com/oceanbase/obkv-table-client-go/table" 28 | ) 29 | 30 | // CREATE TABLE test(c1 bigint, c2 bigint, PRIMARY KEY(c1)) PARTITION BY hash(c1) partitions 2; 31 | func main() { 32 | const ( 33 | configUrl = "xxx" 34 | fullUserName = "user@tenant#cluster" 35 | passWord = "" 36 | sysUserName = "sysUser" 37 | sysPassWord = "" 38 | tableName = "test" 39 | ) 40 | 41 | cfg := config.NewDefaultClientConfig() 42 | cli, err := client.NewClient(configUrl, fullUserName, passWord, sysUserName, sysPassWord, cfg) 43 | if err != nil { 44 | panic(err) 45 | } 46 | 47 | // insert 48 | ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) // 10s 49 | rowKey := []*table.Column{table.NewColumn("c1", int64(1))} 50 | mutateColumns := []*table.Column{table.NewColumn("c2", int64(2))} 51 | affectRows, err := cli.InsertOrUpdate( 52 | ctx, 53 | tableName, 54 | rowKey, 55 | mutateColumns, 56 | ) 57 | if err != nil { 58 | panic(err) 59 | } 60 | fmt.Println(affectRows) 61 | 62 | // update 63 | ctx, _ = context.WithTimeout(context.Background(), 10*time.Second) // 10s 64 | mutateColumns = []*table.Column{table.NewColumn("c2", int64(3))} 65 | affectRows, err = cli.InsertOrUpdate( 66 | ctx, 67 | tableName, 68 | rowKey, 69 | mutateColumns, 70 | ) 71 | if err != nil { 72 | panic(err) 73 | } 74 | fmt.Println(affectRows) 75 | } 76 | -------------------------------------------------------------------------------- /example/single_operation/replace.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package main 19 | 20 | import ( 21 | "context" 22 | "fmt" 23 | "time" 24 | 25 | "github.com/oceanbase/obkv-table-client-go/client" 26 | "github.com/oceanbase/obkv-table-client-go/config" 27 | "github.com/oceanbase/obkv-table-client-go/table" 28 | ) 29 | 30 | // CREATE TABLE test(c1 bigint, c2 bigint, PRIMARY KEY(c1)) PARTITION BY hash(c1) partitions 2; 31 | func main() { 32 | const ( 33 | configUrl = "xxx" 34 | fullUserName = "user@tenant#cluster" 35 | passWord = "" 36 | sysUserName = "sysUser" 37 | sysPassWord = "" 38 | tableName = "test" 39 | ) 40 | 41 | cfg := config.NewDefaultClientConfig() 42 | cli, err := client.NewClient(configUrl, fullUserName, passWord, sysUserName, sysPassWord, cfg) 43 | if err != nil { 44 | panic(err) 45 | } 46 | 47 | // insert 48 | ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) // 10s 49 | rowKey := []*table.Column{table.NewColumn("c1", int64(1))} 50 | insertColumns := []*table.Column{table.NewColumn("c2", int64(2))} 51 | affectRows, err := cli.Insert( 52 | ctx, 53 | tableName, 54 | rowKey, 55 | insertColumns, 56 | ) 57 | if err != nil { 58 | panic(err) 59 | } 60 | fmt.Println(affectRows) 61 | 62 | // replace c2(2) -> c2(3) 63 | ctx, _ = context.WithTimeout(context.Background(), 10*time.Second) // 10s 64 | replaceColumns := []*table.Column{table.NewColumn("c2", int64(3))} 65 | affectRows, err = cli.Replace( 66 | ctx, 67 | tableName, 68 | rowKey, 69 | replaceColumns, 70 | ) 71 | if err != nil { 72 | panic(err) 73 | } 74 | fmt.Println(affectRows) 75 | } 76 | -------------------------------------------------------------------------------- /example/single_operation/update.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package main 19 | 20 | import ( 21 | "context" 22 | "fmt" 23 | "time" 24 | 25 | "github.com/oceanbase/obkv-table-client-go/client" 26 | "github.com/oceanbase/obkv-table-client-go/config" 27 | "github.com/oceanbase/obkv-table-client-go/table" 28 | ) 29 | 30 | // CREATE TABLE test(c1 bigint, c2 bigint, PRIMARY KEY(c1)) PARTITION BY hash(c1) partitions 2; 31 | func main() { 32 | const ( 33 | configUrl = "xxx" 34 | fullUserName = "user@tenant#cluster" 35 | passWord = "" 36 | sysUserName = "sysUser" 37 | sysPassWord = "" 38 | tableName = "test" 39 | ) 40 | 41 | cfg := config.NewDefaultClientConfig() 42 | cli, err := client.NewClient(configUrl, fullUserName, passWord, sysUserName, sysPassWord, cfg) 43 | if err != nil { 44 | panic(err) 45 | } 46 | 47 | // insert 48 | ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) // 10s 49 | rowKey := []*table.Column{table.NewColumn("c1", int64(1))} 50 | insertColumns := []*table.Column{table.NewColumn("c2", int64(2))} 51 | affectRows, err := cli.Insert( 52 | ctx, 53 | tableName, 54 | rowKey, 55 | insertColumns, 56 | ) 57 | if err != nil { 58 | panic(err) 59 | } 60 | fmt.Println(affectRows) 61 | 62 | // update c2(2) -> c2(3) 63 | ctx, _ = context.WithTimeout(context.Background(), 10*time.Second) // 10s 64 | updateColumns := []*table.Column{table.NewColumn("c2", int64(3))} 65 | affectRows, err = cli.Update( 66 | ctx, 67 | tableName, 68 | rowKey, 69 | updateColumns, 70 | ) 71 | if err != nil { 72 | panic(err) 73 | } 74 | fmt.Println(affectRows) 75 | } 76 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/oceanbase/obkv-table-client-go 2 | 3 | go 1.19 4 | 5 | require ( 6 | github.com/go-sql-driver/mysql v1.7.0 7 | github.com/golang/snappy v0.0.4 8 | github.com/klauspost/compress v1.17.2 9 | github.com/naoina/toml v0.1.1 10 | github.com/pierrec/lz4 v2.6.1+incompatible 11 | github.com/pierrec/lz4/v4 v4.1.18 12 | github.com/pkg/errors v0.9.1 13 | github.com/scylladb/go-set v1.0.2 14 | github.com/stretchr/testify v1.9.0 15 | go.uber.org/zap v1.24.0 16 | golang.org/x/crypto v0.17.0 17 | ) 18 | 19 | require github.com/frankban/quicktest v1.14.6 // indirect 20 | 21 | require ( 22 | go.uber.org/goleak v1.3.0 // indirect 23 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect 24 | ) 25 | 26 | require ( 27 | github.com/davecgh/go-spew v1.1.1 // indirect 28 | github.com/google/uuid v1.6.0 29 | github.com/kylelemons/godebug v1.1.0 // indirect 30 | github.com/naoina/go-stringutil v0.1.0 // indirect 31 | github.com/panjf2000/ants/v2 v2.9.1 32 | github.com/pmezard/go-difflib v1.0.0 // indirect 33 | go.uber.org/atomic v1.10.0 // indirect 34 | go.uber.org/multierr v1.11.0 // indirect 35 | golang.org/x/sys v0.15.0 36 | gopkg.in/natefinch/lumberjack.v2 v2.2.1 37 | gopkg.in/yaml.v3 v3.0.1 // indirect 38 | ) 39 | -------------------------------------------------------------------------------- /protocol/aggregation_single_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | import ( 21 | "bytes" 22 | "math/rand" 23 | "testing" 24 | 25 | "github.com/stretchr/testify/assert" 26 | 27 | "github.com/oceanbase/obkv-table-client-go/util" 28 | ) 29 | 30 | func TestObTableAggregationEncodeDecode(t *testing.T) { 31 | ObTableAggregation := NewObTableAggregation() 32 | ObTableAggregation.SetVersion(1) 33 | ObTableAggregation.SetContentLength(0) 34 | ObTableAggregation.SetAggType(ObTableAggregationType(rand.Intn(255))) 35 | ObTableAggregation.SetAggColumn(util.String(10)) 36 | 37 | payloadLen := ObTableAggregation.PayloadLen() 38 | buf := make([]byte, payloadLen) 39 | buffer := bytes.NewBuffer(buf) 40 | ObTableAggregation.Encode(buffer) 41 | 42 | newObTableAggregation := NewObTableAggregation() 43 | newBuffer := bytes.NewBuffer(buf) 44 | newObTableAggregation.Decode(newBuffer) 45 | 46 | assert.EqualValues(t, ObTableAggregation.Version(), newObTableAggregation.Version()) 47 | assert.EqualValues(t, ObTableAggregation.ContentLength(), newObTableAggregation.ContentLength()) 48 | assert.EqualValues(t, ObTableAggregation.AggType(), newObTableAggregation.AggType()) 49 | assert.EqualValues(t, ObTableAggregation.AggColumn(), newObTableAggregation.AggColumn()) 50 | assert.EqualValues(t, ObTableAggregation, newObTableAggregation) 51 | } 52 | -------------------------------------------------------------------------------- /protocol/batch_operation_response_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | import ( 21 | "bytes" 22 | "math/rand" 23 | "testing" 24 | 25 | "github.com/stretchr/testify/assert" 26 | ) 27 | 28 | func TestObTableBatchOperationResponseEncodeDecode(t *testing.T) { 29 | randomLen := rand.Intn(10) 30 | obTableOperations := make([]*ObTableOperationResponse, 0, randomLen) 31 | 32 | for i := 0; i < randomLen; i++ { 33 | obTableOperations = append(obTableOperations, NewObTableOperationResponse()) 34 | } 35 | 36 | obTableBatchOperationResponse := NewObTableBatchOperationResponse() 37 | obTableBatchOperationResponse.SetVersion(1) 38 | obTableBatchOperationResponse.SetContentLength(0) 39 | obTableBatchOperationResponse.SetObTableOperationResponses(obTableOperations) 40 | 41 | payloadLen := obTableBatchOperationResponse.PayloadLen() 42 | buf := make([]byte, payloadLen) 43 | buffer := bytes.NewBuffer(buf) 44 | obTableBatchOperationResponse.Encode(buffer) 45 | 46 | newObTableBatchOperationResponse := NewObTableBatchOperationResponse() 47 | newBuffer := bytes.NewBuffer(buf) 48 | newObTableBatchOperationResponse.Decode(newBuffer) 49 | 50 | assert.EqualValues(t, obTableBatchOperationResponse.Version(), newObTableBatchOperationResponse.Version()) 51 | assert.EqualValues(t, obTableBatchOperationResponse.ContentLength(), newObTableBatchOperationResponse.ContentLength()) 52 | assert.EqualValues(t, len(obTableBatchOperationResponse.ObTableOperationResponses()), len(newObTableBatchOperationResponse.ObTableOperationResponses())) 53 | } 54 | -------------------------------------------------------------------------------- /protocol/codec.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | import ( 21 | "bytes" 22 | ) 23 | 24 | type ProtoEncoder interface { 25 | Encode(*bytes.Buffer) 26 | } 27 | 28 | type ProtoDecoder interface { 29 | Decode(*bytes.Buffer) 30 | } 31 | -------------------------------------------------------------------------------- /protocol/constants.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | type ObTableConsistencyLevel uint8 21 | 22 | const ( 23 | ObTableConsistencyLevelStrong ObTableConsistencyLevel = iota 24 | ObTableConsistencyLevelEventual 25 | ) 26 | 27 | type ObTableEntityType uint8 28 | 29 | const ( 30 | ObTableEntityTypeDynamic ObTableEntityType = iota 31 | ObTableEntityTypeKV 32 | ObTableEntityTypeHKV 33 | ) 34 | 35 | type ObScanOrder uint8 36 | 37 | const ( 38 | ObScanOrderImplementedOrder ObScanOrder = iota 39 | ObScanOrderForward 40 | ObScanOrderReverse 41 | ObScanOrderKeepOrder 42 | ) 43 | -------------------------------------------------------------------------------- /protocol/election_role.go: -------------------------------------------------------------------------------- 1 | package protocol 2 | 3 | type ObRole uint8 4 | 5 | const ( 6 | ObRoleInvalid ObRole = iota 7 | ObRoleLeader 8 | ObRoleFollower 9 | ObRoleStandbyFollower 10 | ObRoleRestoreFollower 11 | ) 12 | -------------------------------------------------------------------------------- /protocol/error.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | import ( 21 | "fmt" 22 | 23 | error2 "github.com/oceanbase/obkv-table-client-go/error" 24 | ) 25 | 26 | type ObProtocolError struct { 27 | server string 28 | trace string 29 | errCode error2.ObErrorCode 30 | errCodeName string 31 | errMsg string 32 | } 33 | 34 | // NewProtocolError construct ObProtocolError 35 | func NewProtocolError( 36 | server string, 37 | code error2.ObErrorCode, 38 | errMsg string, 39 | sequence uint64, 40 | uniqueId uint64) *ObProtocolError { 41 | 42 | trace := fmt.Sprintf("Y%X-%016X", uniqueId, sequence) 43 | errCodeName := code.GetErrorCodeName() 44 | msg := errMsg 45 | if errMsg == "" { 46 | msg = "error occur in server" 47 | } 48 | return &ObProtocolError{server, trace, code, errCodeName, msg} 49 | } 50 | 51 | func (e *ObProtocolError) Error() string { 52 | return fmt.Sprintf( 53 | "errCode:%d, errCodeName:%s, errMsg:%s, server:%s, trace:%s", 54 | e.errCode, 55 | e.errCodeName, 56 | e.errMsg, 57 | e.server, 58 | e.trace, 59 | ) 60 | } 61 | -------------------------------------------------------------------------------- /protocol/ezheader.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | import ( 21 | "bytes" 22 | "encoding/binary" 23 | 24 | "github.com/pkg/errors" 25 | ) 26 | 27 | const ( 28 | EzHeaderLength = 16 29 | version uint8 = 1 30 | ) 31 | 32 | var ( 33 | magicHeaderFlag = []uint8{version, 0xDB, 0xDB, 0xCE} 34 | reserved = []uint8{0, 0, 0, 0} 35 | 36 | ErrHeaderNotMatch = errors.New("magic header flag not match") 37 | ) 38 | 39 | // EzHeader ... 40 | type EzHeader struct { 41 | contentLen uint32 // ContentLen = ObRpcHeader + ObPayload 42 | channelId uint32 43 | } 44 | 45 | func (h *EzHeader) ContentLen() uint32 { 46 | return h.contentLen 47 | } 48 | 49 | func (h *EzHeader) SetContentLen(contentLen uint32) { 50 | h.contentLen = contentLen 51 | } 52 | 53 | func (h *EzHeader) ChannelId() uint32 { 54 | return h.channelId 55 | } 56 | 57 | func (h *EzHeader) SetChannelId(channelId uint32) { 58 | h.channelId = channelId 59 | } 60 | 61 | func (h *EzHeader) Encode(ezHeaderBuf []byte) { 62 | copy(ezHeaderBuf[:4], magicHeaderFlag) 63 | binary.BigEndian.PutUint32(ezHeaderBuf[4:8], h.contentLen) 64 | binary.BigEndian.PutUint32(ezHeaderBuf[8:12], h.channelId) 65 | copy(ezHeaderBuf[12:16], reserved) 66 | } 67 | 68 | func (h *EzHeader) Decode(ezHeaderBuf []byte) error { 69 | if ok := bytes.Equal(magicHeaderFlag, ezHeaderBuf[0:4]); !ok { 70 | return ErrHeaderNotMatch 71 | } 72 | h.contentLen = binary.BigEndian.Uint32(ezHeaderBuf[4:8]) 73 | h.channelId = binary.BigEndian.Uint32(ezHeaderBuf[8:12]) 74 | _ = ezHeaderBuf[12:16] // reserved 75 | return nil 76 | } 77 | -------------------------------------------------------------------------------- /protocol/ezheader_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | import ( 21 | "math/rand" 22 | "testing" 23 | 24 | "github.com/stretchr/testify/assert" 25 | ) 26 | 27 | func TestEzHeaderEncodeDecode(t *testing.T) { 28 | var ezHeader = EzHeader{} 29 | ezHeader.SetContentLen(rand.Uint32()) 30 | ezHeader.SetChannelId(rand.Uint32()) 31 | 32 | buf := make([]byte, EzHeaderLength) 33 | ezHeader.Encode(buf) 34 | 35 | newEzHeader := EzHeader{} 36 | err := newEzHeader.Decode(buf) 37 | 38 | assert.Equal(t, nil, err) 39 | assert.EqualValues(t, ezHeader.ContentLen(), newEzHeader.ContentLen()) 40 | assert.EqualValues(t, ezHeader.ChannelId(), newEzHeader.ChannelId()) 41 | } 42 | -------------------------------------------------------------------------------- /protocol/index_type.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | type ObIndexType uint8 21 | 22 | const ( 23 | IndexTypeIsNot ObIndexType = iota 24 | IndexTypeNormalLocal 25 | IndexTypeUniqueLocal 26 | IndexTypeNormalGlobal 27 | IndexTypeUniqueGlobal 28 | IndexTypePrimary 29 | IndexTypeDomainCtxcat 30 | IndexTypeNormalGlobalLocalStorage 31 | IndexTypeUniqueGlobalLocalStorage 32 | IndexTypeSpatialLocal = 10 33 | IndexTypeSpatialGlobal = 11 34 | IndexTypeSpatialGlobalLocalStorage = 12 35 | IndexTypeMax = 13 36 | ) 37 | 38 | func (t ObIndexType) IsGlobalIndex() bool { 39 | return t == IndexTypeNormalGlobal || t == IndexTypeUniqueGlobal || t == IndexTypeSpatialGlobal 40 | } 41 | -------------------------------------------------------------------------------- /protocol/login_response_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | import ( 21 | "bytes" 22 | "math/rand" 23 | "testing" 24 | 25 | "github.com/stretchr/testify/assert" 26 | 27 | "github.com/oceanbase/obkv-table-client-go/util" 28 | ) 29 | 30 | func TestObLoginResponseEncodeDecode(t *testing.T) { 31 | obLoginResponse := NewObLoginResponse() 32 | obLoginResponse.SetServerCapabilities(int32(rand.Intn(100))) 33 | obLoginResponse.SetReserved1(int32(rand.Intn(100))) 34 | obLoginResponse.SetReserved2(int64(rand.Intn(100))) 35 | obLoginResponse.SetServerVersion(util.String(10)) 36 | obLoginResponse.SetCredential([]byte(util.String(10))) 37 | obLoginResponse.SetUserId(int64(rand.Intn(100))) 38 | obLoginResponse.SetDatabaseId(int64(rand.Intn(100))) 39 | 40 | payloadLen := obLoginResponse.PayloadLen() 41 | buf := make([]byte, payloadLen) 42 | buffer := bytes.NewBuffer(buf) 43 | obLoginResponse.Encode(buffer) 44 | 45 | newObLoginResponse := NewObLoginResponse() 46 | newBuffer := bytes.NewBuffer(buf) 47 | newObLoginResponse.Decode(newBuffer) 48 | 49 | assert.EqualValues(t, obLoginResponse.ServerCapabilities(), newObLoginResponse.ServerCapabilities()) 50 | assert.EqualValues(t, obLoginResponse.Reserved1(), newObLoginResponse.Reserved1()) 51 | assert.EqualValues(t, obLoginResponse.Reserved2(), newObLoginResponse.Reserved2()) 52 | assert.EqualValues(t, obLoginResponse.ServerVersion(), newObLoginResponse.ServerVersion()) 53 | assert.EqualValues(t, obLoginResponse.Credential(), newObLoginResponse.Credential()) 54 | assert.EqualValues(t, obLoginResponse.UserId(), newObLoginResponse.UserId()) 55 | assert.EqualValues(t, obLoginResponse.DatabaseId(), newObLoginResponse.DatabaseId()) 56 | assert.EqualValues(t, obLoginResponse, obLoginResponse) 57 | } 58 | -------------------------------------------------------------------------------- /protocol/object.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | import ( 21 | "bytes" 22 | "github.com/oceanbase/obkv-table-client-go/util" 23 | ) 24 | 25 | type ObObject struct { 26 | meta ObObjectMeta 27 | value interface{} 28 | } 29 | 30 | func NewObObject() *ObObject { 31 | return &ObObject{ 32 | meta: ObObjectMeta{}, 33 | value: nil, 34 | } 35 | } 36 | 37 | func NewObObjectWithParams(meta ObObjectMeta, value interface{}) *ObObject { 38 | return &ObObject{ 39 | meta: meta, 40 | value: value, 41 | } 42 | } 43 | 44 | func (o *ObObject) Meta() ObObjectMeta { 45 | return o.meta 46 | } 47 | 48 | func (o *ObObject) SetMeta(meta ObObjectMeta) { 49 | o.meta = meta 50 | } 51 | 52 | func (o *ObObject) Value() interface{} { 53 | return o.value 54 | } 55 | 56 | func (o *ObObject) SetValue(value interface{}) { 57 | o.value = value 58 | } 59 | 60 | func (o *ObObject) Encode(buffer *bytes.Buffer) { 61 | o.meta.Encode(buffer) 62 | o.meta.ObjType().Encode(buffer, o.value) 63 | } 64 | 65 | func (o *ObObject) Decode(buffer *bytes.Buffer) { 66 | o.meta.Decode(buffer) 67 | o.value = o.meta.ObjType().Decode(buffer, o.meta.CollationType()) 68 | } 69 | 70 | func (o *ObObject) EncodedLength() int { 71 | return o.meta.EncodedLength() + o.meta.ObjType().EncodedLength(o.value) 72 | } 73 | 74 | func (o *ObObject) String() string { 75 | var metaStr = "nil" 76 | if o.meta != (ObObjectMeta{}) { 77 | metaStr = o.meta.String() 78 | } 79 | return "ObObject{" + 80 | "meta:" + metaStr + ", " + 81 | "value:" + util.InterfaceToString(o.value) + 82 | "}" 83 | } 84 | -------------------------------------------------------------------------------- /protocol/operation_type.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2023 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at 10 | * http//license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | type ObQueryOperationType int32 21 | 22 | const ( 23 | QueryStart ObQueryOperationType = iota 24 | QueryNext 25 | 26 | QueryMax 27 | ) 28 | -------------------------------------------------------------------------------- /protocol/payload.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | import ( 21 | "net" 22 | "time" 23 | ) 24 | 25 | // ObPayload ... 26 | type ObPayload interface { 27 | ProtoEncoder 28 | ProtoDecoder 29 | 30 | PCode() ObTablePacketCode 31 | 32 | PayloadLen() int 33 | 34 | PayloadContentLen() int 35 | 36 | Credential() []byte 37 | SetCredential(credential []byte) 38 | 39 | Version() int64 40 | SetVersion(version int64) 41 | 42 | UniqueId() uint64 43 | SetUniqueId(uniqueId uint64) 44 | 45 | Sequence() uint64 46 | SetSequence(sequence uint64) 47 | 48 | Flag() uint16 49 | SetFlag(flag uint16) 50 | 51 | TenantId() uint64 52 | SetTenantId(tenantId uint64) 53 | 54 | SessionId() uint64 55 | SetSessionId(sessionId uint64) 56 | 57 | Timeout() time.Duration 58 | SetTimeout(timeout time.Duration) 59 | 60 | RemoteAddr() net.Addr 61 | SetRemoteAddr(remoteAddr net.Addr) 62 | } 63 | -------------------------------------------------------------------------------- /protocol/payload_base.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | import ( 21 | "net" 22 | "time" 23 | ) 24 | 25 | // ObPayloadBase payload base 26 | type ObPayloadBase struct { 27 | uniqueId uint64 // rpc header traceId0 28 | sequence uint64 // rpc header traceId1 29 | 30 | flag uint16 31 | tenantId uint64 32 | sessionId uint64 33 | 34 | timeout time.Duration 35 | 36 | remoteAddr net.Addr // for debug 37 | } 38 | 39 | func (p *ObPayloadBase) UniqueId() uint64 { 40 | return p.uniqueId 41 | } 42 | 43 | func (p *ObPayloadBase) SetUniqueId(uniqueId uint64) { 44 | p.uniqueId = uniqueId 45 | } 46 | 47 | func (p *ObPayloadBase) Sequence() uint64 { 48 | return p.sequence 49 | } 50 | 51 | func (p *ObPayloadBase) SetSequence(sequence uint64) { 52 | p.sequence = sequence 53 | } 54 | 55 | func (p *ObPayloadBase) Flag() uint16 { 56 | return p.flag 57 | } 58 | 59 | func (p *ObPayloadBase) SetFlag(flag uint16) { 60 | p.flag = flag 61 | } 62 | 63 | func (p *ObPayloadBase) TenantId() uint64 { 64 | return p.tenantId 65 | } 66 | 67 | func (p *ObPayloadBase) SetTenantId(tenantId uint64) { 68 | p.tenantId = tenantId 69 | } 70 | 71 | func (p *ObPayloadBase) SessionId() uint64 { 72 | return p.sessionId 73 | } 74 | 75 | func (p *ObPayloadBase) SetSessionId(sessionId uint64) { 76 | p.sessionId = sessionId 77 | } 78 | 79 | func (p *ObPayloadBase) Timeout() time.Duration { 80 | return p.timeout 81 | } 82 | 83 | func (p *ObPayloadBase) SetTimeout(timeout time.Duration) { 84 | p.timeout = timeout 85 | } 86 | 87 | func (p *ObPayloadBase) RemoteAddr() net.Addr { 88 | return p.remoteAddr 89 | } 90 | 91 | func (p *ObPayloadBase) SetRemoteAddr(remoteAddr net.Addr) { 92 | p.remoteAddr = remoteAddr 93 | } 94 | -------------------------------------------------------------------------------- /protocol/replica_type.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | type ObReplicaType int 21 | 22 | const ( 23 | ReplicaTypeInvalid ObReplicaType = -1 24 | ReplicaTypeFull ObReplicaType = 0 25 | ReplicaTypeLogOnly ObReplicaType = 5 26 | ReplicaTypeReadOnly ObReplicaType = 16 27 | ) 28 | -------------------------------------------------------------------------------- /protocol/response_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | import ( 21 | "bytes" 22 | "math/rand" 23 | "testing" 24 | 25 | "github.com/stretchr/testify/assert" 26 | 27 | "github.com/oceanbase/obkv-table-client-go/util" 28 | ) 29 | 30 | func TestObTableResponseEncodeDecode(t *testing.T) { 31 | obTableResponse := NewObTableResponse() 32 | obTableResponse.SetVersion(1) 33 | obTableResponse.SetContentLength(0) 34 | obTableResponse.SetErrorNo(int32(rand.Uint32())) 35 | obTableResponse.SetSqlState([]byte(util.String(20))) 36 | obTableResponse.SetMsg([]byte(util.String(20))) 37 | 38 | payloadLen := obTableResponse.PayloadLen() 39 | buf := make([]byte, payloadLen) 40 | buffer := bytes.NewBuffer(buf) 41 | obTableResponse.Encode(buffer) 42 | 43 | newObTableResponse := NewObTableResponse() 44 | 45 | newBuffer := bytes.NewBuffer(buf) 46 | newObTableResponse.Decode(newBuffer) 47 | 48 | assert.EqualValues(t, obTableResponse.Version(), newObTableResponse.Version()) 49 | assert.EqualValues(t, obTableResponse.ContentLength(), newObTableResponse.ContentLength()) 50 | assert.EqualValues(t, obTableResponse.ErrorNo(), newObTableResponse.ErrorNo()) 51 | assert.EqualValues(t, obTableResponse.SqlState(), newObTableResponse.SqlState()) 52 | assert.EqualValues(t, obTableResponse.Msg(), newObTableResponse.Msg()) 53 | assert.EqualValues(t, obTableResponse, newObTableResponse) 54 | } 55 | -------------------------------------------------------------------------------- /protocol/rpc_response_warning_message_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | import ( 21 | "bytes" 22 | "math/rand" 23 | "testing" 24 | 25 | "github.com/stretchr/testify/assert" 26 | 27 | "github.com/oceanbase/obkv-table-client-go/util" 28 | ) 29 | 30 | func TestObRpcResponseWarningMsgEncodeDecode(t *testing.T) { 31 | obRpcResponseWarningMsg := NewObRpcResponseWarningMsg() 32 | obRpcResponseWarningMsg.SetVersion(1) 33 | obRpcResponseWarningMsg.SetContentLength(0) 34 | obRpcResponseWarningMsg.SetMsg([]byte(util.String(20))) 35 | obRpcResponseWarningMsg.SetTimestamp(int64(rand.Uint64())) 36 | obRpcResponseWarningMsg.SetLogLevel(int32(rand.Uint32())) 37 | obRpcResponseWarningMsg.SetLineNo(int32(rand.Uint32())) 38 | obRpcResponseWarningMsg.SetCode(int32(rand.Uint32())) 39 | 40 | payloadLen := obRpcResponseWarningMsg.PayloadLen() 41 | buf := make([]byte, payloadLen) 42 | buffer := bytes.NewBuffer(buf) 43 | obRpcResponseWarningMsg.Encode(buffer) 44 | 45 | newObRpcResponseWarningMsg := NewObRpcResponseWarningMsg() 46 | 47 | newBuffer := bytes.NewBuffer(buf) 48 | newObRpcResponseWarningMsg.Decode(newBuffer) 49 | assert.EqualValues(t, obRpcResponseWarningMsg.Version(), newObRpcResponseWarningMsg.Version()) 50 | assert.EqualValues(t, obRpcResponseWarningMsg.ContentLength(), newObRpcResponseWarningMsg.ContentLength()) 51 | assert.EqualValues(t, obRpcResponseWarningMsg.Timestamp(), newObRpcResponseWarningMsg.Timestamp()) 52 | assert.EqualValues(t, obRpcResponseWarningMsg.LogLevel(), newObRpcResponseWarningMsg.LogLevel()) 53 | assert.EqualValues(t, obRpcResponseWarningMsg.LineNo(), newObRpcResponseWarningMsg.LineNo()) 54 | assert.EqualValues(t, obRpcResponseWarningMsg.Code(), newObRpcResponseWarningMsg.Code()) 55 | assert.EqualValues(t, obRpcResponseWarningMsg, newObRpcResponseWarningMsg) 56 | } 57 | -------------------------------------------------------------------------------- /protocol/stream_request.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at 10 | * http//license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | import ( 21 | "bytes" 22 | ) 23 | 24 | type ObTableStreamRequest struct { 25 | ObUniVersionHeader 26 | ObPayloadBase 27 | sessionId uint64 28 | flag uint16 29 | } 30 | 31 | func (r *ObTableStreamRequest) SessionId() uint64 { 32 | return r.sessionId 33 | } 34 | 35 | func (r *ObTableStreamRequest) SetSessionId(sessionId uint64) { 36 | r.sessionId = sessionId 37 | } 38 | 39 | func (r *ObTableStreamRequest) Flag() uint16 { 40 | return r.flag 41 | } 42 | 43 | func (r *ObTableStreamRequest) SetFlag(flag uint16) { 44 | r.flag = flag 45 | } 46 | 47 | func (r *ObTableStreamRequest) PCode() ObTablePacketCode { 48 | return ObTableApiExecuteQuery 49 | } 50 | 51 | func (r *ObTableStreamRequest) PayloadLen() int { 52 | return r.PayloadContentLen() + r.ObUniVersionHeader.UniVersionHeaderLen() // Do not change the order 53 | } 54 | 55 | func (r *ObTableStreamRequest) PayloadContentLen() int { 56 | r.ObUniVersionHeader.SetContentLength(0) 57 | return r.ObUniVersionHeader.ContentLength() 58 | } 59 | 60 | func (r *ObTableStreamRequest) Credential() []byte { 61 | return nil 62 | } 63 | 64 | func (r *ObTableStreamRequest) SetCredential(credential []byte) { 65 | return 66 | } 67 | 68 | func (r *ObTableStreamRequest) Encode(buffer *bytes.Buffer) { 69 | r.ObUniVersionHeader.Encode(buffer) 70 | } 71 | 72 | func (r *ObTableStreamRequest) Decode(buffer *bytes.Buffer) { 73 | r.ObUniVersionHeader.Decode(buffer) 74 | } 75 | -------------------------------------------------------------------------------- /protocol/stream_response.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at 10 | * http//license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | type ObTableStreamResponse struct { 21 | ObUniVersionHeader 22 | ObPayloadBase 23 | } 24 | -------------------------------------------------------------------------------- /protocol/uni_version_header.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | import ( 21 | "bytes" 22 | "strconv" 23 | 24 | "github.com/oceanbase/obkv-table-client-go/util" 25 | ) 26 | 27 | // ObUniVersionHeader ... 28 | type ObUniVersionHeader struct { 29 | version int64 30 | contentLength int 31 | } 32 | 33 | func (h *ObUniVersionHeader) Version() int64 { 34 | return h.version 35 | } 36 | 37 | func (h *ObUniVersionHeader) SetVersion(version int64) { 38 | h.version = version 39 | } 40 | 41 | func (h *ObUniVersionHeader) ContentLength() int { 42 | return h.contentLength 43 | } 44 | 45 | func (h *ObUniVersionHeader) SetContentLength(contentLength int) { 46 | h.contentLength = contentLength 47 | } 48 | 49 | func (h *ObUniVersionHeader) UniVersionHeaderLen() int { 50 | return util.EncodedLengthByVi64(h.version) + util.EncodedLengthByVi64(int64(h.contentLength)) 51 | } 52 | 53 | func (h *ObUniVersionHeader) Encode(buffer *bytes.Buffer) { 54 | util.EncodeVi64(buffer, h.version) 55 | util.EncodeVi64(buffer, int64(h.contentLength)) // payloadLen 56 | } 57 | 58 | func (h *ObUniVersionHeader) Decode(buffer *bytes.Buffer) { 59 | h.version = util.DecodeVi64(buffer) 60 | h.contentLength = int(util.DecodeVi64(buffer)) // contentLength useless right now 61 | } 62 | 63 | func (h *ObUniVersionHeader) String() string { 64 | return "ObUniVersionHeader{" + 65 | "version:" + strconv.Itoa(int(h.version)) + ", " + 66 | "contentLength:" + strconv.Itoa(h.contentLength) + 67 | "}" 68 | } 69 | -------------------------------------------------------------------------------- /protocol/uni_version_header_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package protocol 19 | 20 | import ( 21 | "bytes" 22 | "math/rand" 23 | "testing" 24 | 25 | "github.com/stretchr/testify/assert" 26 | ) 27 | 28 | func TestObUniVersionHeaderEncodeDecode(t *testing.T) { 29 | obUniVersionHeader := ObUniVersionHeader{} 30 | obUniVersionHeader.SetVersion(int64(rand.Uint64())) 31 | obUniVersionHeader.SetContentLength(int(rand.Uint64())) 32 | 33 | uniVersionHeaderLen := obUniVersionHeader.UniVersionHeaderLen() 34 | buf := make([]byte, uniVersionHeaderLen) 35 | buffer := bytes.NewBuffer(buf) 36 | obUniVersionHeader.Encode(buffer) 37 | 38 | newObUniVersionHeader := ObUniVersionHeader{} 39 | buffer = bytes.NewBuffer(buf) 40 | newObUniVersionHeader.Decode(buffer) 41 | 42 | assert.EqualValues(t, obUniVersionHeader.Version(), newObUniVersionHeader.Version()) 43 | assert.EqualValues(t, obUniVersionHeader.ContentLength(), newObUniVersionHeader.ContentLength()) 44 | assert.EqualValues(t, obUniVersionHeader.UniVersionHeaderLen(), newObUniVersionHeader.UniVersionHeaderLen()) 45 | assert.EqualValues(t, obUniVersionHeader.String(), newObUniVersionHeader.String()) 46 | assert.EqualValues(t, obUniVersionHeader, newObUniVersionHeader) 47 | } 48 | -------------------------------------------------------------------------------- /route/authentic.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | // ObUserAuth user authentication information 21 | type ObUserAuth struct { 22 | userName string 23 | password string 24 | } 25 | 26 | func (a *ObUserAuth) Password() string { 27 | return a.password 28 | } 29 | 30 | func (a *ObUserAuth) UserName() string { 31 | return a.userName 32 | } 33 | 34 | // NewObUserAuth create a ObUserAuth by userName and password. 35 | func NewObUserAuth(userName string, password string) *ObUserAuth { 36 | return &ObUserAuth{userName, password} 37 | } 38 | 39 | func (a *ObUserAuth) String() string { 40 | return "ObUserAuth{" + 41 | "userName:" + a.userName + ", " + 42 | "password:" + a.password + 43 | "}" 44 | } 45 | -------------------------------------------------------------------------------- /route/authentic_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestObUserAuth(t *testing.T) { 27 | au := &ObUserAuth{} 28 | assert.Equal(t, "ObUserAuth{userName:, password:}", au.String()) 29 | au = NewObUserAuth("sys", "pass") 30 | assert.EqualValues(t, "sys", au.UserName()) 31 | assert.EqualValues(t, "pass", au.Password()) 32 | assert.Equal(t, "ObUserAuth{userName:sys, password:pass}", au.String()) 33 | } 34 | -------------------------------------------------------------------------------- /route/column.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "github.com/oceanbase/obkv-table-client-go/protocol" 22 | "github.com/oceanbase/obkv-table-client-go/table" 23 | ) 24 | 25 | // obColumn represents a column in the table and contains the column meta-information. 26 | // obColumn represents obSimpleColumn or obGeneratedColumn. 27 | type obColumn interface { 28 | ColumnName() string 29 | ObjType() protocol.ObObjType 30 | CollationType() protocol.ObCollationType 31 | // EvalValue calculate the value of the partition column. 32 | eval(rowKey []*table.Column) (interface{}, error) 33 | extractColumn(rowKey []*table.Column) (*table.Column, error) 34 | String() string 35 | } 36 | -------------------------------------------------------------------------------- /route/config_server_info_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestObConfigServerInfo_GetServerAddressRandomly(t *testing.T) { 27 | server1 := NewObServerAddr("127.0.0.1", 1, 1) 28 | server2 := NewObServerAddr("127.0.0.1", 1, 2) 29 | server3 := NewObServerAddr("127.0.0.1", 1, 3) 30 | server4 := NewObServerAddr("127.0.0.1", 1, 4) 31 | server5 := NewObServerAddr("127.0.0.1", 1, 5) 32 | servers := []*ObServerAddr{server1, server2, server3, server4, server5} 33 | info := NewConfigServerInfo() 34 | for _, server := range servers { 35 | info.rslist.Append(server) 36 | } 37 | for i := 0; i < 10; i++ { 38 | _, err := info.GetServerAddressRandomly() 39 | assert.NotEqual(t, nil, err) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /route/generate_column_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | 25 | "github.com/oceanbase/obkv-table-client-go/protocol" 26 | "github.com/oceanbase/obkv-table-client-go/table" 27 | ) 28 | 29 | func TestObGeneratedColumn_String(t *testing.T) { 30 | col := &obGeneratedColumn{} 31 | assert.Equal(t, "obGeneratedColumn{columnName:, objType:nil, collationType:0, refColumnNames:[], columnExpress:nil}", col.String()) 32 | objType, _ := protocol.NewObjType(protocol.ObObjTypeInt64TypeValue) 33 | col = newObGeneratedColumn("c1", objType, protocol.ObCollationTypeBinary, nil, nil) 34 | assert.Equal(t, "obGeneratedColumn{columnName:c1, objType:ObObjType{type:ObInt64Type}, collationType:63, refColumnNames:[], columnExpress:nil}", col.String()) 35 | 36 | col = newObGeneratedColumn("c1", objType, protocol.ObCollationTypeBinary, []string{"c1"}, nil) 37 | assert.Equal(t, "obGeneratedColumn{columnName:c1, objType:ObObjType{type:ObInt64Type}, collationType:63, refColumnNames:[c1], columnExpress:nil}", col.String()) 38 | } 39 | 40 | func TestObGeneratedColumn_eval(t *testing.T) { 41 | objType, _ := protocol.NewObjType(protocol.ObObjTypeInt64TypeValue) 42 | col := newObGeneratedColumn("c1", objType, protocol.ObCollationTypeBinary, nil, nil) 43 | _, err := col.eval([]*table.Column{table.NewColumn("c1", int64(1))}) 44 | assert.NotEqual(t, nil, err) 45 | } 46 | -------------------------------------------------------------------------------- /route/hash_sort_utf8mb4_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func Test_hashSortUtf8Mb4(t *testing.T) { 27 | data := []byte{1} 28 | hashCode := 0 29 | res := hashSortUtf8Mb4(data, int64(hashCode), 10, true) 30 | assert.Equal(t, int64(-7030129012826305577), res) 31 | res = hashSortUtf8Mb4(data, int64(hashCode), 10, false) 32 | assert.Equal(t, int64(2570), res) 33 | res = hashSortUtf8Mb4(data, int64(hashCode), 0xc6a4a7935bd1e995, true) 34 | assert.Equal(t, int64(-7030129012826305577), res) 35 | res = hashSortUtf8Mb4(data, int64(hashCode), 0xc6a4a7935bd1e995, false) 36 | assert.Equal(t, int64(7062546676564130965), res) 37 | data = []byte{1, 2, 3, 4, 5, 6, 7, 8, 9} 38 | res = hashSortUtf8Mb4(data, int64(hashCode), 10, true) 39 | assert.Equal(t, int64(-1916273894318764036), res) 40 | res = hashSortUtf8Mb4(data, int64(hashCode), 10, false) 41 | assert.Equal(t, int64(1013208367030014238), res) 42 | res = hashSortUtf8Mb4(data, int64(hashCode), 0xc6a4a7935bd1e995, true) 43 | assert.Equal(t, int64(-1916273894318764036), res) 44 | res = hashSortUtf8Mb4(data, int64(hashCode), 0xc6a4a7935bd1e995, false) 45 | assert.Equal(t, int64(7452881443849355883), res) 46 | } 47 | 48 | func Test_hashSortMbBin(t *testing.T) { 49 | data := []byte{1} 50 | hashCode := 0 51 | res := hashSortMbBin(data, int64(hashCode), 10) 52 | assert.Equal(t, int64(10), res) 53 | } 54 | -------------------------------------------------------------------------------- /route/indexInfo.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "github.com/oceanbase/obkv-table-client-go/protocol" 22 | ) 23 | 24 | type ObIndexInfo struct { 25 | dataTableId uint64 26 | indexTableId uint64 27 | indexTableName string 28 | indexType protocol.ObIndexType 29 | } 30 | 31 | func (i *ObIndexInfo) IndexTableName() string { 32 | return i.indexTableName 33 | } 34 | 35 | func (i *ObIndexInfo) IndexTableId() uint64 { 36 | return i.indexTableId 37 | } 38 | 39 | func (i *ObIndexInfo) DataTableId() uint64 { 40 | return i.dataTableId 41 | } 42 | 43 | func (i *ObIndexInfo) IndexType() protocol.ObIndexType { 44 | return i.indexType 45 | } 46 | 47 | func NewObIndexInfo() *ObIndexInfo { 48 | return &ObIndexInfo{ 49 | dataTableId: 0, 50 | indexTableId: 0, 51 | indexTableName: "", 52 | indexType: protocol.IndexTypeIsNot, 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /route/part_desc.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "github.com/pkg/errors" 22 | 23 | "github.com/oceanbase/obkv-table-client-go/table" 24 | ) 25 | 26 | const ( 27 | ObInvalidPartId = 0 28 | ObPartIdBitNum = 28 29 | ObPartIdShift = 32 30 | ObMask = (1 << ObPartIdBitNum) | 1<<(ObPartIdBitNum+ObPartIdShift) 31 | ObSubPartIdMask = 0xffffffff & 0xfffffff 32 | ) 33 | 34 | type obPartDesc interface { 35 | String() string 36 | PartFuncType() obPartFuncType 37 | SetPartColumns(partColumns []obColumn) 38 | PartColumns() []obColumn 39 | PartNum() int 40 | SetPartNum(partNum int) 41 | GetPartId(rowKey []*table.Column) (uint64, error) 42 | GetPartIds(rowKeyPair *table.RangePair) ([]uint64, error) 43 | } 44 | 45 | // evalPartKeyValues calculate the value of the partition key 46 | func evalPartKeyValues(desc obPartDesc, rowKey []*table.Column) ([]interface{}, error) { 47 | if desc == nil { 48 | return nil, errors.New("part desc is nil") 49 | } 50 | partValues := make([]interface{}, 0, len(desc.PartColumns())) 51 | for _, column := range desc.PartColumns() { 52 | value, err := column.eval(rowKey) 53 | if err != nil { 54 | return nil, errors.WithMessagef(err, "eval column, column:%s", column.String()) 55 | } 56 | partValues = append(partValues, value) 57 | } 58 | return partValues, nil 59 | } 60 | 61 | // generateSubPartId generate sub partition id 62 | // partId1 means level one partition idx(0,...,firstPartNum) 63 | // partId2 means level two partition idx(0,...,subPartNum) 64 | func generateSubPartId(partId1 uint64, partId2 uint64) uint64 { 65 | return (partId1 << ObPartIdShift) | partId2 | ObMask 66 | } 67 | -------------------------------------------------------------------------------- /route/partition_function_type.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | type obPartFuncType int 21 | 22 | // all partition function type, it should be updated with the server. 23 | const ( 24 | partFuncTypeUnknown obPartFuncType = -1 25 | partFuncTypeHash obPartFuncType = 0 26 | partFuncTypeKey obPartFuncType = 1 27 | partFuncTypeKeyImpl obPartFuncType = 2 28 | partFuncTypeRange obPartFuncType = 3 29 | partFuncTypeRangeCol obPartFuncType = 4 30 | partFuncTypeList obPartFuncType = 5 31 | partFuncTypeKeyV2 obPartFuncType = 6 32 | partFuncTypeListCol obPartFuncType = 7 33 | partFuncTypeHashV2 obPartFuncType = 8 34 | partFuncTypeKeyV3 obPartFuncType = 9 35 | partFuncTypeKeyImplV2 obPartFuncType = 10 36 | ) 37 | 38 | // isRangePart check is range partition or not. 39 | func isRangePart(partType obPartFuncType) bool { 40 | return partType == partFuncTypeRange || partType == partFuncTypeRangeCol 41 | } 42 | 43 | // isKeyPart check is key partition or not. 44 | func isKeyPart(partType obPartFuncType) bool { 45 | return partType == partFuncTypeKey || 46 | partType == partFuncTypeKeyImpl || 47 | partType == partFuncTypeKeyV2 || 48 | partType == partFuncTypeKeyV3 || 49 | partType == partFuncTypeKeyImplV2 50 | } 51 | 52 | // isHashPart check is hash partition or not. 53 | func isHashPart(partType obPartFuncType) bool { 54 | return partType == partFuncTypeHash || partType == partFuncTypeHashV2 55 | } 56 | 57 | // isListPart check is list partition or not. 58 | func isListPart(partType obPartFuncType) bool { 59 | return partType == partFuncTypeList || partType == partFuncTypeListCol 60 | } 61 | -------------------------------------------------------------------------------- /route/partition_infomation_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestObPartitionInfo(t *testing.T) { 27 | info := newObPartitionInfo(PartLevelTwo) 28 | assert.EqualValues(t, PartLevelTwo, info.Level()) 29 | assert.Equal(t, "obPartitionInfo{level:2, firstPartDesc:nil, subPartDesc:nil, partTabletIdMap:{}}", info.String()) 30 | 31 | m := make(map[uint64]uint64, 1) 32 | m[0] = 500032 33 | first := &obHashPartDesc{} 34 | sub := &obRangePartDesc{} 35 | info.firstPartDesc = first 36 | info.subPartDesc = sub 37 | info.partTabletIdMap = m 38 | assert.Equal(t, first, info.FirstPartDesc()) 39 | assert.Equal(t, sub, info.SubPartDesc()) 40 | tabletId, err := info.GetTabletId(0) 41 | assert.Equal(t, nil, err) 42 | assert.EqualValues(t, 500032, tabletId) 43 | } 44 | -------------------------------------------------------------------------------- /route/partition_location.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | type ObConsistency int8 21 | 22 | const ( 23 | ConsistencyStrong ObConsistency = 0 24 | ConsistencyWeak ObConsistency = 1 25 | ) 26 | 27 | // obPartitionLocation indicates the location of a partition, 28 | // including a leader replica and other read replicas 29 | type obPartitionLocation struct { 30 | leader *obReplicaLocation 31 | replicas []*obReplicaLocation 32 | } 33 | 34 | // addReplicaLocation add a replica to obPartitionLocation 35 | func (l *obPartitionLocation) addReplicaLocation(replica *obReplicaLocation) { 36 | if replica.isLeader() { 37 | l.leader = replica 38 | } 39 | l.replicas = append(l.replicas, replica) 40 | } 41 | 42 | // getReplica get the copy according to the consistency requirements you need, 43 | // strong consistency get the leader replica, weak consistency get the read replica (todo). 44 | func (l *obPartitionLocation) getReplica(consistency ObConsistency) *obReplicaLocation { 45 | if consistency == ConsistencyStrong { 46 | return l.leader 47 | } 48 | // todo: get read replica 49 | return l.leader 50 | } 51 | 52 | func (l *obPartitionLocation) String() string { 53 | var leaderStr = "nil" 54 | if l.leader != nil { 55 | leaderStr = l.leader.String() 56 | } 57 | 58 | var replicasStr string 59 | replicasStr = replicasStr + "[" 60 | for i := 0; i < len(l.replicas); i++ { 61 | if i > 0 { 62 | replicasStr += ", " 63 | } 64 | str := "nil" 65 | if l.replicas[i] != nil { 66 | str = l.replicas[i].String() 67 | } 68 | replicasStr += str 69 | } 70 | replicasStr += "]" 71 | return "obPartitionLocation{" + 72 | "leader:" + leaderStr + ", " + 73 | "replicas:" + replicasStr + 74 | "}" 75 | } 76 | -------------------------------------------------------------------------------- /route/partition_location_entry.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import "strconv" 21 | 22 | // ObPartLocationEntry store location information for all replicas. 23 | type ObPartLocationEntry struct { 24 | partLocations map[uint64]*obPartitionLocation 25 | } 26 | 27 | func newObPartLocationEntry(partNum int) *ObPartLocationEntry { 28 | entry := new(ObPartLocationEntry) 29 | entry.partLocations = make(map[uint64]*obPartitionLocation, partNum) 30 | return entry 31 | } 32 | 33 | func (e *ObPartLocationEntry) String() string { 34 | var partitionLocationStr string 35 | var i = 0 36 | partitionLocationStr = partitionLocationStr + "{" 37 | for k, v := range e.partLocations { 38 | if i > 0 { 39 | partitionLocationStr += ", " 40 | } 41 | i++ 42 | partitionLocationStr += "m[" + strconv.Itoa(int(k)) + "]=" 43 | if v != nil { 44 | partitionLocationStr += v.String() 45 | } else { 46 | partitionLocationStr += "nil" 47 | } 48 | } 49 | partitionLocationStr += "}" 50 | return "ObPartLocationEntry{" + 51 | "partLocations:" + partitionLocationStr + 52 | "}" 53 | } 54 | -------------------------------------------------------------------------------- /route/partition_location_entry_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | 25 | "github.com/oceanbase/obkv-table-client-go/protocol" 26 | ) 27 | 28 | func TestObPartLocationEntry(t *testing.T) { 29 | e := newObPartLocationEntry(1) 30 | assert.Equal(t, "ObPartLocationEntry{partLocations:{}}", e.String()) 31 | s1 := NewObServerAddr("127.0.0.1", 2001, 2000) 32 | s2 := NewObServerAddr("127.0.0.1", 2001, 2000) 33 | st := newServerStatus(0, "active") 34 | r1 := newReplicaLocation(s1, st, serverRoleLeader, protocol.ReplicaTypeFull) 35 | r2 := newReplicaLocation(s2, st, serverRoleFollower, protocol.ReplicaTypeFull) 36 | l := &obPartitionLocation{} 37 | l.addReplicaLocation(r1) 38 | l.addReplicaLocation(r2) 39 | e.partLocations[0] = l 40 | assert.Equal(t, "ObPartLocationEntry{partLocations:{m[0]=obPartitionLocation{leader:obReplicaLocation{addr:ObServerAddr{ip:127.0.0.1, sqlPort:2001, svrPort:2000}, info:obServerStatus{stopTime:0, status:active}, role:1, replicaType:0}, replicas:[obReplicaLocation{addr:ObServerAddr{ip:127.0.0.1, sqlPort:2001, svrPort:2000}, info:obServerStatus{stopTime:0, status:active}, role:1, replicaType:0}, obReplicaLocation{addr:ObServerAddr{ip:127.0.0.1, sqlPort:2001, svrPort:2000}, info:obServerStatus{stopTime:0, status:active}, role:2, replicaType:0}]}}}", e.String()) 41 | } 42 | -------------------------------------------------------------------------------- /route/partition_location_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | 25 | "github.com/oceanbase/obkv-table-client-go/protocol" 26 | ) 27 | 28 | func TestObPartitionLocation(t *testing.T) { 29 | l := &obPartitionLocation{} 30 | assert.Equal(t, "obPartitionLocation{leader:nil, replicas:[]}", l.String()) 31 | s1 := NewObServerAddr("127.0.0.1", 2001, 2000) 32 | s2 := NewObServerAddr("127.0.0.1", 2001, 2000) 33 | st := newServerStatus(0, "active") 34 | r1 := newReplicaLocation(s1, st, serverRoleLeader, protocol.ReplicaTypeFull) 35 | r2 := newReplicaLocation(s2, st, serverRoleFollower, protocol.ReplicaTypeFull) 36 | l.addReplicaLocation(r1) 37 | l.addReplicaLocation(r2) 38 | assert.Equal(t, r1, l.getReplica(ConsistencyStrong)) 39 | assert.Equal(t, r1, l.getReplica(ConsistencyWeak)) 40 | assert.Equal(t, "obPartitionLocation{leader:obReplicaLocation{addr:ObServerAddr{ip:127.0.0.1, sqlPort:2001, svrPort:2000}, info:obServerStatus{stopTime:0, status:active}, role:1, replicaType:0}, replicas:[obReplicaLocation{addr:ObServerAddr{ip:127.0.0.1, sqlPort:2001, svrPort:2000}, info:obServerStatus{stopTime:0, status:active}, role:1, replicaType:0}, obReplicaLocation{addr:ObServerAddr{ip:127.0.0.1, sqlPort:2001, svrPort:2000}, info:obServerStatus{stopTime:0, status:active}, role:2, replicaType:0}]}", l.String()) 41 | } 42 | -------------------------------------------------------------------------------- /route/range_partition_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | 25 | "github.com/oceanbase/obkv-table-client-go/protocol" 26 | "github.com/oceanbase/obkv-table-client-go/table" 27 | ) 28 | 29 | func TestObRangePartDesc_String(t *testing.T) { 30 | desc := &obRangePartDesc{} 31 | assert.Equal(t, "obRangePartDesc{partSpace:0, partNum:0, partColumns[]}", desc.String()) 32 | desc = newObRangePartDesc(0, 10, partFuncTypeRange) 33 | assert.Equal(t, "obRangePartDesc{partSpace:0, partNum:10, partColumns[]}", desc.String()) 34 | 35 | desc = newObRangePartDesc(0, 10, partFuncTypeHash) 36 | objType, _ := protocol.NewObjType(protocol.ObObjTypeInt64TypeValue) 37 | col := newObSimpleColumn("c1", objType, protocol.ObCollationTypeBinary) 38 | desc.SetPartColumns([]obColumn{col}) 39 | assert.Equal(t, "obRangePartDesc{partSpace:0, partNum:10, partColumns[obSimpleColumn{columnName:c1, objType:ObObjType{type:ObInt64Type}, collationType:63}]}", desc.String()) 40 | } 41 | 42 | func TestObRangePartDesc_GetPartId(t *testing.T) { 43 | desc := &obRangePartDesc{} 44 | partId, err := desc.GetPartId([]*table.Column{}) 45 | assert.NotEqual(t, nil, err) 46 | assert.EqualValues(t, ObInvalidPartId, partId) 47 | } 48 | -------------------------------------------------------------------------------- /route/replica_location.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "strconv" 22 | 23 | "github.com/oceanbase/obkv-table-client-go/protocol" 24 | ) 25 | 26 | type obServerRole int 27 | 28 | const ( 29 | serverRoleInvalid obServerRole = -1 30 | serverRoleLeader obServerRole = 1 31 | serverRoleFollower obServerRole = 2 32 | ) 33 | 34 | type obReplicaLocation struct { 35 | addr *ObServerAddr 36 | svrStatus *obServerStatus 37 | role obServerRole 38 | replicaType protocol.ObReplicaType 39 | } 40 | 41 | func (l *obReplicaLocation) SvrStatus() *obServerStatus { 42 | return l.svrStatus 43 | } 44 | 45 | func newReplicaLocation(addr *ObServerAddr, svrStatus *obServerStatus, role obServerRole, replicaType protocol.ObReplicaType) *obReplicaLocation { 46 | return &obReplicaLocation{addr, svrStatus, role, replicaType} 47 | } 48 | 49 | func (l *obReplicaLocation) Addr() *ObServerAddr { 50 | return l.addr 51 | } 52 | 53 | func (l *obReplicaLocation) isValid() bool { 54 | return (l.addr != nil) && (l.role != serverRoleInvalid) && (l.svrStatus != nil) && 55 | l.svrStatus.IsActive() && (l.replicaType != protocol.ReplicaTypeInvalid) 56 | } 57 | 58 | func (l *obReplicaLocation) isLeader() bool { 59 | return l.role == serverRoleLeader 60 | } 61 | 62 | func (l *obReplicaLocation) String() string { 63 | var addrStr string 64 | if l.addr == nil { 65 | addrStr = "nil" 66 | } else { 67 | addrStr = l.addr.String() 68 | } 69 | var statusStr string 70 | if l.svrStatus == nil { 71 | statusStr = "nil" 72 | } else { 73 | statusStr = l.svrStatus.String() 74 | } 75 | return "obReplicaLocation{" + 76 | "addr:" + addrStr + ", " + 77 | "info:" + statusStr + ", " + 78 | "role:" + strconv.Itoa(int(l.role)) + ", " + 79 | "replicaType:" + strconv.Itoa(int(l.replicaType)) + 80 | "}" 81 | } 82 | -------------------------------------------------------------------------------- /route/route_task_info.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "time" 22 | 23 | "github.com/oceanbase/obkv-table-client-go/util" 24 | ) 25 | 26 | type ObRouteTaskInfo struct { 27 | refreshTableChan chan bool 28 | configServerChan chan bool 29 | createConnPoolChan chan bool 30 | dropConnPoolChan chan bool 31 | tables *util.ConcurrentMap // The tables need to be refreshed 32 | createConnPoolServers *util.ConcurrentMap // The servers need to create connection pool 33 | dropConnPoolServers *util.ConcurrentMap // The servers need to drop connection pool 34 | checkRslistTicker *time.Ticker 35 | } 36 | 37 | func NewRouteTaskInfo() *ObRouteTaskInfo { 38 | return &ObRouteTaskInfo{ 39 | refreshTableChan: make(chan bool), 40 | configServerChan: make(chan bool), 41 | createConnPoolChan: make(chan bool), 42 | dropConnPoolChan: make(chan bool), 43 | tables: util.NewConcurrentMap(), 44 | createConnPoolServers: util.NewConcurrentMap(), 45 | dropConnPoolServers: util.NewConcurrentMap(), 46 | checkRslistTicker: time.NewTicker(rslistCheckInterval), 47 | } 48 | } 49 | 50 | func (i *ObRouteTaskInfo) TriggerRefreshTable() { 51 | if len(i.refreshTableChan) == 0 { 52 | i.refreshTableChan <- true 53 | } 54 | } 55 | 56 | func (i *ObRouteTaskInfo) TriggerCheckRslist() { 57 | if len(i.configServerChan) == 0 { 58 | i.configServerChan <- true 59 | } 60 | } 61 | 62 | func (i *ObRouteTaskInfo) TriggerCreateConnectionPool() { 63 | if len(i.createConnPoolChan) == 0 { 64 | i.createConnPoolChan <- true 65 | } 66 | } 67 | 68 | func (i *ObRouteTaskInfo) TriggerDropConnectionPool() { 69 | if len(i.dropConnPoolChan) == 0 { 70 | i.dropConnPoolChan <- true 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /route/rslist.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "fmt" 22 | "math/rand" 23 | 24 | "github.com/pkg/errors" 25 | ) 26 | 27 | type ObRslist struct { 28 | list []*ObServerAddr 29 | } 30 | 31 | func NewRslist() *ObRslist { 32 | return &ObRslist{ 33 | list: make([]*ObServerAddr, 0), 34 | } 35 | } 36 | 37 | // GetServerRandomly get one randomly server from all the servers 38 | func (l *ObRslist) GetServerRandomly() (*ObServerAddr, error) { 39 | if len(l.list) == 0 { 40 | return nil, errors.New("list is empty") 41 | } 42 | 43 | idx := rand.Intn(len(l.list)) 44 | addr := l.list[idx] 45 | if addr.IsConnectionFine() { 46 | return addr, nil 47 | } 48 | 49 | for _, serverAddr := range l.list { 50 | if serverAddr.IsConnectionFine() { 51 | return serverAddr, nil 52 | } 53 | } 54 | 55 | return nil, errors.New("has no valid server node") 56 | } 57 | 58 | func (l *ObRslist) Append(addr *ObServerAddr) { 59 | l.list = append(l.list, addr) 60 | } 61 | 62 | func (l *ObRslist) Size() int { 63 | return len(l.list) 64 | } 65 | 66 | func (l *ObRslist) Equal(other *ObRslist) bool { 67 | if l.Size() != other.Size() { 68 | return false 69 | } 70 | for i := 0; i < l.Size(); i++ { 71 | if !l.list[i].Equal(other.list[i]) { 72 | return false 73 | } 74 | } 75 | return true 76 | } 77 | 78 | func (l *ObRslist) FindMissingElements(other *ObRslist) []*ObServerAddr { 79 | missingElements := make([]*ObServerAddr, 0) 80 | 81 | bMap := make(map[string]bool) 82 | for _, element := range other.list { 83 | key := fmt.Sprintf("%s:%d", element.ip, element.port) 84 | bMap[key] = true 85 | } 86 | 87 | for _, element := range l.list { 88 | key := fmt.Sprintf("%s:%d", element.ip, element.port) 89 | if _, found := bMap[key]; !found { 90 | missingElements = append(missingElements, element) 91 | } 92 | } 93 | 94 | return missingElements 95 | } 96 | -------------------------------------------------------------------------------- /route/server_address.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "fmt" 22 | "net" 23 | "strconv" 24 | "time" 25 | ) 26 | 27 | type tcpAddr struct { 28 | ip string 29 | port int 30 | } 31 | 32 | func (a *tcpAddr) Equal(other *tcpAddr) bool { 33 | return a.ip == other.ip && a.port == other.port 34 | } 35 | 36 | func (a *tcpAddr) String() string { 37 | return "tcpAddr{" + 38 | "ip:" + a.ip + ", " + 39 | "port:" + strconv.Itoa(a.port) + 40 | "}" 41 | } 42 | 43 | type ObServerAddr struct { 44 | tcpAddr 45 | sqlPort int 46 | } 47 | 48 | func (a *ObServerAddr) SvrPort() int { 49 | return a.port 50 | } 51 | 52 | func (a *ObServerAddr) Ip() string { 53 | return a.ip 54 | } 55 | 56 | func (a *ObServerAddr) Equal(other *ObServerAddr) bool { 57 | return a.tcpAddr.Equal(&other.tcpAddr) && a.sqlPort == other.sqlPort 58 | } 59 | 60 | func (a *ObServerAddr) IsConnectionFine() bool { 61 | addr := fmt.Sprintf("%s:%d", a.tcpAddr.ip, a.tcpAddr.port) 62 | conn, err := net.DialTimeout("tcp", addr, time.Second*1) 63 | if err != nil { 64 | return false 65 | } 66 | defer conn.Close() 67 | return true 68 | } 69 | 70 | func NewObServerAddr(ip string, sqlPort int, svrPort int) *ObServerAddr { 71 | return &ObServerAddr{ 72 | tcpAddr{ip, svrPort}, 73 | sqlPort} 74 | } 75 | 76 | func (a *ObServerAddr) String() string { 77 | return "ObServerAddr{" + 78 | "ip:" + a.ip + ", " + 79 | "sqlPort:" + strconv.Itoa(a.sqlPort) + ", " + 80 | "svrPort:" + strconv.Itoa(a.port) + 81 | "}" 82 | } 83 | -------------------------------------------------------------------------------- /route/server_roster.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "math/rand" 22 | ) 23 | 24 | type ObServerRoster struct { 25 | servers []*ObServerAddr 26 | } 27 | 28 | func (r *ObServerRoster) GetServer() *ObServerAddr { 29 | idx := rand.Intn(len(r.servers)) 30 | return r.servers[idx] 31 | } 32 | 33 | func (r *ObServerRoster) Size() int { 34 | return len(r.servers) 35 | } 36 | 37 | func (r *ObServerRoster) String() string { 38 | var rostersStr string 39 | rostersStr = rostersStr + "[" 40 | for i := 0; i < len(r.servers); i++ { 41 | if i > 0 { 42 | rostersStr += ", " 43 | } 44 | if r.servers[i] != nil { 45 | rostersStr += r.servers[i].String() 46 | } else { 47 | rostersStr += "nil" 48 | } 49 | } 50 | rostersStr += "]" 51 | return "ObServerRoster{" + 52 | "roster:" + rostersStr + 53 | "}" 54 | } 55 | -------------------------------------------------------------------------------- /route/server_roster_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestObServerRoster(t *testing.T) { 27 | r := &ObServerRoster{} 28 | assert.Equal(t, "ObServerRoster{roster:[]}", r.String()) 29 | s1 := NewObServerAddr("127.0.0.1", 4001, 4000) 30 | s2 := NewObServerAddr("127.0.0.2", 4001, 4000) 31 | s3 := NewObServerAddr("127.0.0.3", 4001, 4000) 32 | servers := []*ObServerAddr{s1, s2, s3} 33 | 34 | r = &ObServerRoster{servers: servers} 35 | assert.EqualValues(t, 3, r.Size()) 36 | assert.NotEqual(t, nil, r.GetServer()) 37 | assert.Equal(t, "ObServerRoster{roster:[ObServerAddr{ip:127.0.0.1, sqlPort:4001, svrPort:4000}, ObServerAddr{ip:127.0.0.2, sqlPort:4001, svrPort:4000}, ObServerAddr{ip:127.0.0.3, sqlPort:4001, svrPort:4000}]}", r.String()) 38 | } 39 | -------------------------------------------------------------------------------- /route/server_status.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "strconv" 22 | "strings" 23 | ) 24 | 25 | // obServerStatus is obtained by accessing the system routing table on the server. 26 | type obServerStatus struct { 27 | stopTime int64 28 | status string // Active/InActive/Deleting 29 | } 30 | 31 | func newServerStatus(stopTime int64, status string) *obServerStatus { 32 | return &obServerStatus{stopTime, status} 33 | } 34 | 35 | func (i *obServerStatus) IsActive() bool { 36 | return i.stopTime == 0 && strings.EqualFold(i.status, "active") // ignore case 37 | } 38 | 39 | func (i *obServerStatus) String() string { 40 | return "obServerStatus{" + 41 | "stopTime:" + strconv.Itoa(int(i.stopTime)) + ", " + 42 | "status:" + i.status + 43 | "}" 44 | } 45 | -------------------------------------------------------------------------------- /route/server_status_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestObServerStatus_IsActive(t *testing.T) { 27 | status := &obServerStatus{} 28 | assert.False(t, status.IsActive()) 29 | status = newServerStatus(0, "Active") 30 | assert.True(t, status.IsActive()) 31 | status = newServerStatus(0, "active") 32 | assert.True(t, status.IsActive()) 33 | status = newServerStatus(1, "active") 34 | assert.False(t, status.IsActive()) 35 | status = newServerStatus(0, "InActive") 36 | assert.False(t, status.IsActive()) 37 | status = newServerStatus(1, "InActive") 38 | assert.False(t, status.IsActive()) 39 | } 40 | 41 | func TestObServerStatus_String(t *testing.T) { 42 | status := &obServerStatus{} 43 | assert.Equal(t, "obServerStatus{stopTime:0, status:}", status.String()) 44 | status = newServerStatus(0, "Active") 45 | assert.Equal(t, "obServerStatus{stopTime:0, status:Active}", status.String()) 46 | } 47 | -------------------------------------------------------------------------------- /route/simple_column_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | 25 | "github.com/oceanbase/obkv-table-client-go/protocol" 26 | "github.com/oceanbase/obkv-table-client-go/table" 27 | ) 28 | 29 | func TestObSimpleColumn_String(t *testing.T) { 30 | col := &obSimpleColumn{} 31 | assert.Equal(t, "obSimpleColumn{columnName:, objType:nil, collationType:0}", col.String()) 32 | objType, _ := protocol.NewObjType(protocol.ObObjTypeInt64TypeValue) 33 | col = newObSimpleColumn("c1", objType, protocol.ObCollationTypeBinary) 34 | assert.Equal(t, "obSimpleColumn{columnName:c1, objType:ObObjType{type:ObInt64Type}, collationType:63}", col.String()) 35 | } 36 | 37 | func TestObSimpleColumn_eval(t *testing.T) { 38 | objType, _ := protocol.NewObjType(protocol.ObObjTypeInt64TypeValue) 39 | col := newObSimpleColumn("c1", objType, protocol.ObCollationTypeBinary) 40 | value, err := col.eval([]*table.Column{table.NewColumn("c1", int64(1))}) 41 | assert.Equal(t, nil, err) 42 | assert.EqualValues(t, 1, value) 43 | value, err = col.eval([]*table.Column{table.NewColumn("C1", int64(1))}) 44 | assert.Equal(t, nil, err) 45 | assert.EqualValues(t, 1, value) 46 | 47 | value, err = col.eval([]*table.Column{}) 48 | assert.NotEqual(t, nil, err) 49 | value, err = col.eval([]*table.Column{ 50 | table.NewColumn("C1", int64(1)), 51 | table.NewColumn("C2", int64(2)), 52 | }) 53 | assert.Equal(t, nil, err) 54 | assert.EqualValues(t, 1, value) 55 | } 56 | -------------------------------------------------------------------------------- /route/sql_driver.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "database/sql" 22 | "strings" 23 | 24 | _ "github.com/go-sql-driver/mysql" 25 | "github.com/pkg/errors" 26 | ) 27 | 28 | type DB = sql.DB 29 | type Rows = sql.Rows 30 | 31 | // NewDB create a DB, remember call DB.close when exit. 32 | // Use the dsn connection mode. 33 | func NewDB( 34 | userName string, 35 | password string, 36 | ip string, 37 | port string, 38 | database string) (*DB, error) { 39 | // "userName:password@tcp(ip:port)/database?charset=utf8" 40 | dsn := strings.Join([]string{userName, ":", password, 41 | "@tcp(", ip, ":", port, ")/", database, "?charset=utf8"}, "") 42 | db, err := sql.Open("mysql", dsn) 43 | if err != nil { 44 | return nil, errors.WithMessagef(err, "open db, dsn:%s", dsn) 45 | } 46 | err = db.Ping() 47 | if err != nil { 48 | return nil, errors.WithMessagef(err, "ping db, dsn:%s", dsn) 49 | } 50 | return db, nil 51 | } 52 | -------------------------------------------------------------------------------- /route/sql_driver_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "strconv" 22 | "testing" 23 | 24 | "github.com/stretchr/testify/assert" 25 | ) 26 | 27 | func TestNewDB(t *testing.T) { 28 | const ( 29 | testUserName = "root" 30 | testPassword = "" 31 | testIp = "127.0.0.1" 32 | testSqlPort = 41101 33 | testDatabase = "test" 34 | ) 35 | _, err := NewDB(testUserName, testPassword, testIp, strconv.Itoa(testSqlPort), testDatabase) 36 | assert.NotEqual(t, nil, err) 37 | } 38 | -------------------------------------------------------------------------------- /route/table_entry_key.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | // ObTableEntryKey is used for getting ObTableEntry 21 | type ObTableEntryKey struct { 22 | clusterName string 23 | tenantName string 24 | databaseName string 25 | tableName string 26 | } 27 | 28 | func NewObTableEntryKey( 29 | clusterName string, 30 | tenantName string, 31 | databaseName string, 32 | tableName string) *ObTableEntryKey { 33 | return &ObTableEntryKey{clusterName, tenantName, databaseName, tableName} 34 | } 35 | 36 | func (k *ObTableEntryKey) String() string { 37 | return "ObTableEntryKey{" + 38 | "clusterName:" + k.clusterName + ", " + 39 | "tenantName:" + k.tenantName + ", " + 40 | "databaseName:" + k.databaseName + ", " + 41 | "tableName:" + k.tableName + 42 | "}" 43 | } 44 | -------------------------------------------------------------------------------- /route/table_entry_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestObTableEntry(t *testing.T) { 27 | entry := ObTableEntry{} 28 | assert.Equal(t, "ObTableEntry{"+ 29 | "tableId:0, "+ 30 | "partNum:0, "+ 31 | "replicaNum:0, "+ 32 | "refreshTime:0001-01-01 00:00:00 +0000 UTC, "+ 33 | "tableEntryKey:nil, "+ 34 | "partitionInfo:nil, "+ 35 | "tableLocation:nil"+ 36 | "}", entry.String()) 37 | info := newObPartitionInfo(PartLevelTwo) 38 | entry = ObTableEntry{ 39 | tableId: 500021, 40 | partNum: 10, 41 | replicaNum: 16, 42 | tableEntryKey: NewObTableEntryKey("cluster", "tenant", "database", "table"), 43 | partitionInfo: info, 44 | tableLocation: nil, 45 | partLocationEntry: nil, 46 | } 47 | entry.SetPartLocationEntry(newObPartLocationEntry(10)) 48 | assert.Equal(t, (*ObTableLocation)(nil), entry.TableLocation()) 49 | assert.EqualValues(t, 500021, entry.TableId()) 50 | assert.Equal(t, info, entry.PartitionInfo()) 51 | assert.Equal(t, true, entry.IsPartitionTable()) 52 | assert.Equal(t, "ObTableEntry{"+ 53 | "tableId:500021, "+ 54 | "partNum:10, "+ 55 | "replicaNum:16, "+ 56 | "refreshTime:0001-01-01 00:00:00 +0000 UTC, "+ 57 | "tableEntryKey:ObTableEntryKey{clusterName:cluster, tenantName:tenant, databaseName:database, tableName:table}, "+ 58 | "partitionInfo:obPartitionInfo{level:2, firstPartDesc:nil, subPartDesc:nil, partTabletIdMap:{}}, "+ 59 | "tableLocation:nil"+ 60 | "}", entry.String()) 61 | } 62 | -------------------------------------------------------------------------------- /route/table_location.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | // ObTableLocation represents the location information of all replaces of a table. 21 | type ObTableLocation struct { 22 | replicaLocations []*obReplicaLocation 23 | } 24 | 25 | func (l *ObTableLocation) ReplicaLocations() []*obReplicaLocation { 26 | return l.replicaLocations 27 | } 28 | 29 | func (l *ObTableLocation) String() string { 30 | var replicaLocationsStr string 31 | replicaLocationsStr = replicaLocationsStr + "[" 32 | for i := 0; i < len(l.replicaLocations); i++ { 33 | if i > 0 { 34 | replicaLocationsStr += ", " 35 | } 36 | replicaLocationsStr += l.replicaLocations[i].String() 37 | } 38 | replicaLocationsStr += "]" 39 | return "ObTableLocation{" + 40 | "replicaLocations:" + replicaLocationsStr + 41 | "}" 42 | } 43 | -------------------------------------------------------------------------------- /route/table_mutex.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "sync" 22 | ) 23 | 24 | type ObTableMutexes struct { 25 | m sync.Map 26 | } 27 | 28 | func (m *ObTableMutexes) Lock(tableName string) { 29 | mutex, _ := m.m.LoadOrStore(tableName, &sync.RWMutex{}) 30 | tableMutex := mutex.(*sync.RWMutex) 31 | tableMutex.Lock() 32 | } 33 | 34 | func (m *ObTableMutexes) Unlock(tableName string) { 35 | mutex, found := m.m.Load(tableName) 36 | if !found { 37 | return 38 | } 39 | tableMutex := mutex.(*sync.RWMutex) 40 | tableMutex.Unlock() 41 | } 42 | -------------------------------------------------------------------------------- /route/table_param.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "strconv" 22 | ) 23 | 24 | type ObTableParam struct { 25 | table *ObTable 26 | tableId uint64 27 | partitionId uint64 // partition id in 3.x aka tablet id in 4.x 28 | } 29 | 30 | func (p *ObTableParam) Table() *ObTable { 31 | return p.table 32 | } 33 | 34 | func (p *ObTableParam) TableId() uint64 { 35 | return p.tableId 36 | } 37 | 38 | func (p *ObTableParam) PartitionId() uint64 { 39 | return p.partitionId 40 | } 41 | 42 | func NewObTableParam(table *ObTable, tableId uint64, partitionId uint64) *ObTableParam { 43 | return &ObTableParam{table, tableId, partitionId} 44 | } 45 | 46 | func (p *ObTableParam) String() string { 47 | tableStr := "nil" 48 | if p.table != nil { 49 | tableStr = p.table.String() 50 | } 51 | return "ObTableParam{" + 52 | "table:" + tableStr + ", " + 53 | "tableId:" + strconv.Itoa(int(p.tableId)) + ", " + 54 | "partitionId:" + strconv.Itoa(int(p.partitionId)) + 55 | "}" 56 | } 57 | -------------------------------------------------------------------------------- /route/table_param_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | const ( 27 | testTableIdV3 uint64 = 1099511677791 28 | testTableIdV4 uint64 = 500039 29 | testPartIdV3 uint64 = 0 30 | testPartIdV4 uint64 = 500040 31 | ) 32 | 33 | func TestObTableParam_String(t *testing.T) { 34 | tableParam := NewObTableParam(&ObTable{}, testTableIdV3, testPartIdV3) 35 | assert.Equal( 36 | t, 37 | "ObTableParam{table:ObTable{ip:, port:0, tenantName:, userName:, password:, database:, isClosed:false}, tableId:1099511677791, partitionId:0}", 38 | tableParam.String(), 39 | ) 40 | tableParam = NewObTableParam(&ObTable{}, testTableIdV4, testPartIdV4) 41 | assert.Equal( 42 | t, 43 | "ObTableParam{table:ObTable{ip:, port:0, tenantName:, userName:, password:, database:, isClosed:false}, tableId:500039, partitionId:500040}", 44 | tableParam.String(), 45 | ) 46 | tb := NewObTable(testIp, testPort, testTenantName, testUserName, testPassword, testDatabase) 47 | tableParam = NewObTableParam(tb, testTableIdV4, testPartIdV4) 48 | assert.Equal( 49 | t, 50 | "ObTableParam{table:ObTable{ip:127.0.0.1, port:8080, tenantName:sys, userName:root, password:, database:test, isClosed:false}, tableId:500039, partitionId:500040}", 51 | tableParam.String(), 52 | ) 53 | } 54 | -------------------------------------------------------------------------------- /route/table_roster.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "sync" 22 | "time" 23 | ) 24 | 25 | type ObTableRoster struct { 26 | tenantName string 27 | userName string 28 | password string 29 | database string 30 | connPoolSize int 31 | connectTimeout time.Duration 32 | loginTimeout time.Duration 33 | m sync.Map 34 | } 35 | 36 | func (r *ObTableRoster) Add(addr tcpAddr, table *ObTable) { 37 | r.m.Store(addr, table) 38 | } 39 | 40 | func (r *ObTableRoster) Get(addr tcpAddr) (*ObTable, bool) { 41 | t, ok := r.m.Load(addr) 42 | if ok { 43 | return t.(*ObTable), ok 44 | } 45 | 46 | return nil, ok 47 | } 48 | 49 | func (r *ObTableRoster) Delete(addr tcpAddr) { 50 | r.m.Delete(addr) 51 | } 52 | 53 | func (r *ObTableRoster) LoadAndDelete(addr tcpAddr) (interface{}, bool) { 54 | return r.m.LoadAndDelete(addr) 55 | } 56 | 57 | func (r *ObTableRoster) Close() { 58 | r.m.Range(func(k, v interface{}) bool { 59 | r.Delete(k.(tcpAddr)) 60 | t := v.(*ObTable) 61 | if t != nil { 62 | t.Close() 63 | } 64 | return true 65 | }) 66 | } 67 | -------------------------------------------------------------------------------- /route/table_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "testing" 22 | "time" 23 | 24 | "github.com/stretchr/testify/assert" 25 | ) 26 | 27 | const ( 28 | testIp string = "127.0.0.1" 29 | testPort int = 8080 30 | testTenantName string = "sys" 31 | testUserName string = "root" 32 | testPassword string = "" 33 | testDatabase string = "test" 34 | ) 35 | 36 | func TestObTable_init(t *testing.T) { 37 | tb := NewObTable(testIp, testPort, testTenantName, testUserName, testPassword, testDatabase) 38 | err := tb.Init(1, time.Duration(1000)*time.Millisecond, 0) 39 | assert.NotEqual(t, nil, err) 40 | } 41 | 42 | func TestObTable_close(t *testing.T) { 43 | tb := NewObTable(testIp, testPort, testTenantName, testUserName, testPassword, testDatabase) 44 | tb.Close() 45 | assert.EqualValues(t, true, tb.isClosed) 46 | } 47 | 48 | func TestObTable_String(t *testing.T) { 49 | tb := &ObTable{} 50 | assert.Equal( 51 | t, 52 | "ObTable{ip:, port:0, tenantName:, userName:, password:, database:, isClosed:false}", 53 | tb.String(), 54 | ) 55 | tb = NewObTable(testIp, testPort, testTenantName, testUserName, testPassword, testDatabase) 56 | assert.Equal( 57 | t, 58 | "ObTable{ip:127.0.0.1, port:8080, tenantName:sys, userName:root, password:, database:test, isClosed:false}", 59 | tb.String(), 60 | ) 61 | } 62 | -------------------------------------------------------------------------------- /route/util_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestUtil_createInStatement(t *testing.T) { 27 | inStr := createInStatement(nil) 28 | assert.Equal(t, "();", inStr) 29 | inStr = createInStatement([]uint64{1}) 30 | assert.Equal(t, "(1);", inStr) 31 | inStr = createInStatement([]uint64{1, 2}) 32 | assert.Equal(t, "(1, 2);", inStr) 33 | } 34 | 35 | func TestUtil_murmurHash64A(t *testing.T) { 36 | result := murmurHash64A([]byte{1}, len([]byte{1}), int64(0)) 37 | assert.Equal(t, int64(-5720937396023583481), result) 38 | result = murmurHash64A([]byte{1}, len([]byte{1}), int64(1)) 39 | assert.Equal(t, int64(6351753276682545529), result) 40 | result = murmurHash64A([]byte{1, 2, 3}, len([]byte{1, 2, 3}), int64(123456789)) 41 | assert.Equal(t, int64(-4356950700900923028), result) 42 | } 43 | -------------------------------------------------------------------------------- /table/column.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package table 19 | 20 | import ( 21 | "github.com/oceanbase/obkv-table-client-go/util" 22 | "reflect" 23 | ) 24 | 25 | // Column represents a column in a table, 26 | // consisting of a column name and a column value. 27 | type Column struct { 28 | name string 29 | value interface{} 30 | } 31 | 32 | func NewColumn(name string, value interface{}) *Column { 33 | return &Column{name: name, value: value} 34 | } 35 | 36 | func (c *Column) Name() string { 37 | return c.name 38 | } 39 | 40 | func (c *Column) SetName(name string) { 41 | c.name = name 42 | } 43 | 44 | func (c *Column) Value() interface{} { 45 | return c.value 46 | } 47 | 48 | func (c *Column) SetValue(value interface{}) { 49 | c.value = value 50 | } 51 | 52 | func (c *Column) IsEqual(another *Column) bool { 53 | if c.name != another.name { 54 | return false 55 | } 56 | if !reflect.DeepEqual(c.value, another.value) { 57 | return false 58 | } 59 | return true 60 | } 61 | 62 | func (c *Column) String() string { 63 | return "column{" + 64 | "name:" + c.name + ", " + 65 | "value:" + util.InterfaceToString(c.value) + 66 | "}" 67 | } 68 | -------------------------------------------------------------------------------- /table/column_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package table 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestColumn_String(t *testing.T) { 27 | col := &Column{} 28 | assert.Equal(t, "column{name:, value:}", col.String()) 29 | 30 | col.SetName("c1") 31 | col.SetValue(1) 32 | assert.Equal(t, "column{name:c1, value:1}", col.String()) 33 | assert.EqualValues(t, "c1", col.Name()) 34 | assert.EqualValues(t, 1, col.Value()) 35 | 36 | col = NewColumn("c1", 1) 37 | assert.Equal(t, "column{name:c1, value:1}", col.String()) 38 | } 39 | -------------------------------------------------------------------------------- /table/extremum.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2023 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package table 19 | 20 | // Extremum to represent the minimum and maximum values of the key. 21 | type Extremum int64 22 | 23 | const ( 24 | // Min -> -3 = -1 - 2 = MaxUint64 - 2 25 | Min Extremum = -3 26 | // Max -> -2 = -1 - 1 = MaxUint64 - 1 27 | Max Extremum = -2 28 | ) 29 | 30 | func (e Extremum) String() string { 31 | switch e { 32 | case Min: 33 | return "Min" 34 | case Max: 35 | return "Max" 36 | default: 37 | return "unknown" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /table/kv_mode.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package table 19 | 20 | type ObKeyValueMode uint8 21 | 22 | const ( 23 | DynamicMode ObKeyValueMode = iota 24 | ObTableMode 25 | ObHBaseMode 26 | ) 27 | -------------------------------------------------------------------------------- /table/scan_order.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2023 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package table 19 | 20 | type ScanOrder uint8 21 | 22 | const ( 23 | ImplementedOrder ScanOrder = iota 24 | Forward 25 | Reverse 26 | KeepOrder 27 | ) 28 | -------------------------------------------------------------------------------- /table/type.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package table 19 | 20 | import ( 21 | "time" 22 | ) 23 | 24 | // DateTime from db will be recognize as local timezone, datetime send to server will ignore the timezone. 25 | type DateTime time.Time 26 | 27 | // TimeStamp store in UTC timezone, show in Local timezone. 28 | type TimeStamp time.Time 29 | -------------------------------------------------------------------------------- /table/util.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package table 19 | 20 | // ColumnsToString converts a column to a string 21 | func ColumnsToString(columns []*Column) string { 22 | var str string 23 | str = str + "[" 24 | for i := 0; i < len(columns); i++ { 25 | if i > 0 { 26 | str += ", " 27 | } 28 | str += columns[i].String() 29 | } 30 | str += "]" 31 | return str 32 | } 33 | 34 | // RangePairsToString converts a ranges pair to a string 35 | func RangePairsToString(rangesPairs []*RangePair) string { 36 | var str string 37 | str = str + "[" 38 | for i := 0; i < len(rangesPairs); i++ { 39 | if i > 0 { 40 | str += ", " 41 | } 42 | str += rangesPairs[i].String() 43 | } 44 | str += "]" 45 | return str 46 | } 47 | -------------------------------------------------------------------------------- /table/util_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package table 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestColumns_ToString(t *testing.T) { 27 | col := &Column{"c1", 123} 28 | var cols []*Column 29 | assert.Equal(t, "[]", ColumnsToString(cols)) 30 | cols = []*Column{col, col, col} 31 | assert.Equal(t, "[column{name:c1, value:123}, column{name:c1, value:123}, column{name:c1, value:123}]", ColumnsToString(cols)) 32 | } 33 | -------------------------------------------------------------------------------- /test/aggregate/all_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2023 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package aggregate 19 | 20 | import ( 21 | "os" 22 | "testing" 23 | 24 | "github.com/oceanbase/obkv-table-client-go/client" 25 | "github.com/oceanbase/obkv-table-client-go/test" 26 | ) 27 | 28 | var cli client.Client 29 | 30 | func setup() { 31 | cli = test.CreateClient() 32 | 33 | test.CreateDB() 34 | test.CreateTable(aggregateTableCreateStatement) 35 | } 36 | 37 | func teardown() { 38 | cli.Close() 39 | test.DropTable(aggregateTableName) 40 | test.CloseDB() 41 | } 42 | 43 | func TestMain(m *testing.M) { 44 | setup() 45 | code := m.Run() 46 | teardown() 47 | os.Exit(code) 48 | } 49 | -------------------------------------------------------------------------------- /test/autoinc/all_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package autoinc 19 | 20 | import ( 21 | "os" 22 | "testing" 23 | 24 | "github.com/oceanbase/obkv-table-client-go/client" 25 | "github.com/oceanbase/obkv-table-client-go/test" 26 | ) 27 | 28 | var cli client.Client 29 | 30 | func setup() { 31 | cli = test.CreateClient() 32 | 33 | test.CreateDB() 34 | test.CreateTable(autoIncRowkeyZeroFillTableCreateStatement) 35 | test.CreateTable(autoIncRowkeyNotFillTableCreateStatement) 36 | test.CreateTable(autoIncNormalNotFillTableCreateStatement) 37 | test.CreateTable(autoIncNormalFillTableCreateStatement) 38 | test.CreateTable(autoIncRowkeyNilFillTableCreateStatement) 39 | test.CreateTable(autoIncNormalNilFillTableCreateStatement) 40 | } 41 | 42 | func teardown() { 43 | cli.Close() 44 | 45 | test.DropTable(autoIncRowkeyZeroFillTableTableName) 46 | test.DropTable(autoIncRowkeyNotFillTableTableName) 47 | test.DropTable(autoIncNormalNotFillTableTableName) 48 | test.DropTable(autoIncNormalFillTableTableName) 49 | test.DropTable(autoIncRowkeyNilFillTableTableName) 50 | test.DropTable(autoIncNormalNilFillTableTableName) 51 | test.CloseDB() 52 | } 53 | 54 | func TestMain(m *testing.M) { 55 | setup() 56 | code := m.Run() 57 | teardown() 58 | os.Exit(code) 59 | } 60 | -------------------------------------------------------------------------------- /test/autoinc/auto_increment_normal_fill_nil_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package autoinc 19 | 20 | import ( 21 | "context" 22 | "testing" 23 | 24 | "github.com/stretchr/testify/assert" 25 | 26 | "github.com/oceanbase/obkv-table-client-go/table" 27 | "github.com/oceanbase/obkv-table-client-go/test" 28 | ) 29 | 30 | const ( 31 | autoIncNormalNilFillTableTableName = "autoIncNormalNilFillTable" 32 | autoIncNormalNilFillTableCreateStatement = "create table if not exists autoIncNormalNilFillTable(" + 33 | "c1 bigint(20) not null, " + 34 | "c2 bigint(20) not null, " + 35 | "c3 bigint(20) not null auto_increment, " + 36 | "primary key (`c1`, `c2`)) partition by hash(c2) partitions 15;" 37 | ) 38 | 39 | func TestAuto_InNormalFillNil(t *testing.T) { 40 | tableName := autoIncNormalNilFillTableTableName 41 | defer test.DeleteTable(tableName) 42 | 43 | // test insert. 44 | rowKey := []*table.Column{table.NewColumn("c1", int64(1)), table.NewColumn("c2", int64(1))} 45 | mutates := []*table.Column{table.NewColumn("c3", nil)} 46 | affectedRows, err := cli.Insert( 47 | context.TODO(), 48 | tableName, 49 | rowKey, 50 | mutates, 51 | ) 52 | assert.Equal(t, nil, err) 53 | assert.Equal(t, int64(1), affectedRows) 54 | 55 | rowKey = []*table.Column{table.NewColumn("c1", int64(1)), table.NewColumn("c2", int64(1))} 56 | selectColumns := []string{"c1", "c2", "c3"} 57 | result, err := cli.Get( 58 | context.TODO(), 59 | tableName, 60 | rowKey, 61 | selectColumns, 62 | ) 63 | 64 | assert.Equal(t, nil, err) 65 | assert.EqualValues(t, int64(1), result.Value("c1")) 66 | assert.EqualValues(t, int64(1), result.Value("c2")) 67 | assert.EqualValues(t, int64(1), result.Value("c3")) 68 | } 69 | -------------------------------------------------------------------------------- /test/autoinc/auto_increment_rowkey_fill_nil_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package autoinc 19 | 20 | import ( 21 | "context" 22 | "testing" 23 | 24 | "github.com/stretchr/testify/assert" 25 | 26 | "github.com/oceanbase/obkv-table-client-go/table" 27 | "github.com/oceanbase/obkv-table-client-go/test" 28 | ) 29 | 30 | const ( 31 | autoIncRowkeyNilFillTableTableName = "autoIncRowkeyNilFillTable" 32 | autoIncRowkeyNilFillTableCreateStatement = "create table if not exists autoIncRowkeyNilFillTable(" + 33 | "c1 bigint(20) not null auto_increment, " + 34 | "c2 bigint(20) not null, " + 35 | "c3 varchar(20) default 'hello', " + 36 | "primary key (`c1`, `c2`)) partition by hash(c2) partitions 15;" 37 | ) 38 | 39 | func TestAuto_IncRowkeyFillNil(t *testing.T) { 40 | tableName := autoIncRowkeyNilFillTableTableName 41 | defer test.DeleteTable(tableName) 42 | 43 | // test insert. 44 | rowKey := []*table.Column{table.NewColumn("c1", nil), table.NewColumn("c2", int64(1))} 45 | affectedRows, err := cli.Insert( 46 | context.TODO(), 47 | tableName, 48 | rowKey, 49 | nil, 50 | ) 51 | assert.Equal(t, nil, err) 52 | assert.Equal(t, int64(1), affectedRows) 53 | 54 | rowKey = []*table.Column{table.NewColumn("c1", int64(1)), table.NewColumn("c2", int64(1))} 55 | selectColumns := []string{"c1", "c2", "c3"} 56 | result, err := cli.Get( 57 | context.TODO(), 58 | tableName, 59 | rowKey, 60 | selectColumns, 61 | ) 62 | 63 | assert.Equal(t, nil, err) 64 | assert.EqualValues(t, int64(1), result.Value("c1")) 65 | assert.EqualValues(t, int64(1), result.Value("c2")) 66 | assert.EqualValues(t, "hello", result.Value("c3")) 67 | } 68 | -------------------------------------------------------------------------------- /test/batch/all_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package batch 19 | 20 | import ( 21 | "os" 22 | "testing" 23 | 24 | "github.com/oceanbase/obkv-table-client-go/client" 25 | "github.com/oceanbase/obkv-table-client-go/test" 26 | ) 27 | 28 | var cli client.Client 29 | 30 | func setup() { 31 | cli = test.CreateClient() 32 | 33 | test.CreateDB() 34 | test.CreateTable(batchOpTableCreateStatement) 35 | } 36 | 37 | func teardown() { 38 | cli.Close() 39 | 40 | test.DropTable(batchOpTableTableName) 41 | test.CloseDB() 42 | } 43 | 44 | func TestMain(m *testing.M) { 45 | setup() 46 | code := m.Run() 47 | teardown() 48 | os.Exit(code) 49 | } 50 | -------------------------------------------------------------------------------- /test/compress_rpc_result/all_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2023 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package compress_rpc_result 19 | 20 | import ( 21 | "fmt" 22 | "github.com/pkg/errors" 23 | "os" 24 | "testing" 25 | 26 | "github.com/oceanbase/obkv-table-client-go/client" 27 | "github.com/oceanbase/obkv-table-client-go/test" 28 | ) 29 | 30 | var cli client.Client 31 | 32 | const ( 33 | CompressFuncSql = "alter system set kv_transport_compress_func= '%s'" 34 | CompressThresholdSql = "alter system set kv_transport_compress_threshold= '%s'" 35 | ) 36 | 37 | func setup() { 38 | cli = test.CreateClient() 39 | test.CreateDB() 40 | test.CreateTable(createTableStat) 41 | } 42 | 43 | func setCompressType(compressTyepe string) error { 44 | if test.GlobalDB == nil { 45 | return errors.New("test GlobalDb is nil") 46 | } 47 | setCompressFunc := fmt.Sprintf(CompressFuncSql, compressTyepe) 48 | setCompressThreshold := fmt.Sprintf(CompressThresholdSql, "0K") 49 | _, err := test.GlobalDB.Exec(setCompressFunc) 50 | if err != nil { 51 | return errors.WithMessagef(err, "fail to set compress func %s", compressTyepe) 52 | } 53 | _, err = test.GlobalDB.Exec(setCompressThreshold) 54 | if err != nil { 55 | return errors.WithMessagef(err, "fail to set compress threshold %s", "0K") 56 | } 57 | return nil 58 | } 59 | 60 | func teardown() { 61 | cli.Close() 62 | test.DropTable(tableName) 63 | setCompressType("none") 64 | test.CloseDB() 65 | } 66 | 67 | func TestMain(m *testing.M) { 68 | setup() 69 | code := m.Run() 70 | teardown() 71 | os.Exit(code) 72 | } 73 | -------------------------------------------------------------------------------- /test/connection_balance/all_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package connection_balance 19 | 20 | import ( 21 | "fmt" 22 | "github.com/oceanbase/obkv-table-client-go/client" 23 | "github.com/oceanbase/obkv-table-client-go/test" 24 | "os" 25 | "testing" 26 | "time" 27 | ) 28 | 29 | var cli client.Client 30 | 31 | const ( 32 | testConnectionBalanceTableName = "test_connection_balance" 33 | // NOTE: cannot create table directly in obkv cluster 34 | testConnectionBalanceCreateStatement = "create table if not exists `test_connection_balance`(`c1` varchar(1024) primary key,`c2` int);" 35 | concurrencyNum = 300 36 | // NOTE: make sure test timeout is greatter than testDuration, e.g, go test -timeout 10m 37 | testDuration = time.Duration(8) * time.Minute 38 | maxConnectionAge = time.Duration(10) * time.Second 39 | connectionPoolSize = 150 40 | enableSLBLoadBalance = true 41 | ) 42 | 43 | func setup() { 44 | cli = test.CreateConnectionBalanceClient(maxConnectionAge, enableSLBLoadBalance, connectionPoolSize) 45 | fmt.Println("connection balance setup") 46 | } 47 | 48 | func teardown() { 49 | cli.Close() 50 | fmt.Println("connection balance teardown") 51 | } 52 | 53 | func TestMain(m *testing.M) { 54 | setup() 55 | code := m.Run() 56 | teardown() 57 | os.Exit(code) 58 | } 59 | -------------------------------------------------------------------------------- /test/connection_balance/connection_balance_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package connection_balance 19 | 20 | import ( 21 | "context" 22 | "fmt" 23 | "github.com/oceanbase/obkv-table-client-go/log" 24 | "github.com/oceanbase/obkv-table-client-go/table" 25 | "github.com/stretchr/testify/assert" 26 | "sync" 27 | "testing" 28 | "time" 29 | ) 30 | 31 | func run(i int, done chan bool, wg *sync.WaitGroup, t *testing.T) { 32 | defer wg.Done() 33 | executeNum := 0 34 | for { 35 | select { 36 | case <-done: 37 | log.Info("Runtime", nil, fmt.Sprintf("Finish %d worker, executeNum: %d", i, executeNum)) 38 | return 39 | default: 40 | rowKey := []*table.Column{table.NewColumn("c1", fmt.Sprintf("key%d", i))} 41 | mutateColumns := []*table.Column{table.NewColumn("c2", int32(1))} 42 | ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) // 10s 43 | affectRows, err := cli.InsertOrUpdate(ctx, testConnectionBalanceTableName, rowKey, mutateColumns) 44 | assert.Equal(t, nil, err) 45 | assert.EqualValues(t, 1, affectRows) 46 | executeNum++ 47 | } 48 | } 49 | } 50 | 51 | func TestMaxConnectionAge(t *testing.T) { 52 | println("Test begin") 53 | done := make(chan bool) 54 | var wg sync.WaitGroup 55 | for i := 0; i < concurrencyNum; i++ { 56 | wg.Add(1) 57 | go run(i, done, &wg, t) 58 | } 59 | time.Sleep(testDuration) 60 | close(done) 61 | println("Wait All Coroutine finish") 62 | wg.Wait() 63 | println("Test Finished") 64 | } 65 | -------------------------------------------------------------------------------- /test/current_timestamp/all_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package current_timestamp 19 | 20 | import ( 21 | "os" 22 | "testing" 23 | 24 | "github.com/oceanbase/obkv-table-client-go/client" 25 | "github.com/oceanbase/obkv-table-client-go/test" 26 | ) 27 | 28 | var cli client.Client 29 | 30 | func setup() { 31 | cli = test.CreateClient() 32 | 33 | test.CreateDB() 34 | 35 | test.CreateTable(testTimestampCurrentTimeCreateStatement) 36 | } 37 | 38 | func teardown() { 39 | cli.Close() 40 | 41 | test.DropTable(testTimestampCurrentTimeTableName) 42 | 43 | test.CloseDB() 44 | } 45 | 46 | func TestMain(m *testing.M) { 47 | setup() 48 | code := m.Run() 49 | teardown() 50 | os.Exit(code) 51 | } 52 | -------------------------------------------------------------------------------- /test/error_message/all_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package error_message 19 | 20 | import ( 21 | "os" 22 | "testing" 23 | 24 | "github.com/oceanbase/obkv-table-client-go/client" 25 | "github.com/oceanbase/obkv-table-client-go/test" 26 | ) 27 | 28 | var cli client.Client 29 | 30 | func setup() { 31 | cli = test.CreateClient() 32 | 33 | test.CreateDB() 34 | test.CreateTable(errMsgCreateStatement) 35 | } 36 | 37 | func teardown() { 38 | cli.Close() 39 | 40 | test.DropTable(errMsgTableName) 41 | test.CloseDB() 42 | } 43 | 44 | func TestMain(m *testing.M) { 45 | setup() 46 | code := m.Run() 47 | teardown() 48 | os.Exit(code) 49 | } 50 | -------------------------------------------------------------------------------- /test/filter/all_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package filter 19 | 20 | import ( 21 | "os" 22 | "testing" 23 | 24 | "github.com/oceanbase/obkv-table-client-go/client" 25 | "github.com/oceanbase/obkv-table-client-go/test" 26 | ) 27 | 28 | var cli client.Client 29 | 30 | func setup() { 31 | cli = test.CreateClient() 32 | 33 | test.CreateDB() 34 | 35 | test.CreateTable(testFilterOpCreateStatement) 36 | } 37 | 38 | func teardown() { 39 | cli.Close() 40 | 41 | test.DropTable(testFilterOpTableName) 42 | 43 | test.CloseDB() 44 | } 45 | 46 | func TestMain(m *testing.M) { 47 | setup() 48 | code := m.Run() 49 | teardown() 50 | os.Exit(code) 51 | } 52 | -------------------------------------------------------------------------------- /test/generate_column/all_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package current_timestamp 19 | 20 | import ( 21 | "os" 22 | "testing" 23 | 24 | "github.com/oceanbase/obkv-table-client-go/client" 25 | "github.com/oceanbase/obkv-table-client-go/test" 26 | ) 27 | 28 | var cli client.Client 29 | 30 | func setup() { 31 | cli = test.CreateClient() 32 | 33 | test.CreateDB() 34 | 35 | test.CreateTable(testStoredGenColumnTableNameCreateStatement) 36 | test.CreateTable(testVirtualGenColumnTableNameCreateStatement) 37 | test.CreateTable(testVirtualGenColumnWithGlobalIndexTableNameCreateStatement) 38 | } 39 | 40 | func teardown() { 41 | cli.Close() 42 | 43 | test.DropTable(testVirtualGenColumnTableName) 44 | test.DropTable(testStoredGenColumnTableName) 45 | test.DropTable(testVirtualGenColumnWithGlobalIndexTableName) 46 | 47 | test.CloseDB() 48 | } 49 | 50 | func TestMain(m *testing.M) { 51 | setup() 52 | code := m.Run() 53 | teardown() 54 | os.Exit(code) 55 | } 56 | -------------------------------------------------------------------------------- /test/logger/all_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package logger 19 | 20 | import ( 21 | "github.com/oceanbase/obkv-table-client-go/client" 22 | "github.com/oceanbase/obkv-table-client-go/test" 23 | "os" 24 | "testing" 25 | ) 26 | 27 | var cli client.Client 28 | 29 | func setup() { 30 | cli = test.CreateClient() 31 | test.CreateDB() 32 | } 33 | 34 | func teardown() { 35 | cli.Close() 36 | test.CloseDB() 37 | } 38 | 39 | func TestMain(m *testing.M) { 40 | setup() 41 | code := m.Run() 42 | teardown() 43 | os.Exit(code) 44 | } 45 | -------------------------------------------------------------------------------- /test/logger/logger_file_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package logger 19 | 20 | import ( 21 | "context" 22 | "github.com/oceanbase/obkv-table-client-go/config" 23 | "github.com/oceanbase/obkv-table-client-go/log" 24 | "os" 25 | "testing" 26 | ) 27 | 28 | func TestInitTraceId(t *testing.T) { 29 | file := "obclient-table-go.log" 30 | filePath := "../../configurations/obkv-table-default.toml" 31 | clientConfig, _ := config.GetClientConfigurationFromTOML(filePath) 32 | var logcon log.LogConfig 33 | logcon.LogFileName = clientConfig.LogConfig.LogFileName 34 | logcon.MaxAgeFileRem = clientConfig.LogConfig.MaxAgeFileRem 35 | logcon.MaxBackupFileSize = clientConfig.LogConfig.MaxBackupFileSize 36 | logcon.SingleFileMaxSize = clientConfig.LogConfig.SingleFileMaxSize 37 | logcon.Compress = clientConfig.LogConfig.Compress 38 | logcon.SlowQueryThreshold = clientConfig.LogConfig.SlowQueryThreshold 39 | ctx := context.TODO() 40 | 41 | log.InitLoggerWithConfig(logcon) 42 | ctx = context.TODO() 43 | log.InitTraceId(&ctx) 44 | log.Info("Default", ctx.Value(log.ObkvTraceIdName), "Info msg", log.String("Info", "second_Info")) 45 | for i := 0; i < 10; i++ { 46 | log.Error("BOOT", ctx.Value(log.ObkvTraceIdName), "Error msg", log.String("Error", "fourth_Error")) 47 | log.Debug("", ctx.Value(log.ObkvTraceIdName), "Debug msg", log.String("Debug", "first_Debug")) 48 | log.Warn("Default", nil, "Warn msg", log.String("Warn", "third_Warn")) 49 | } 50 | _ = log.Sync() 51 | _ = os.Remove(file) 52 | } 53 | -------------------------------------------------------------------------------- /test/nullable/all_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package nullable 19 | 20 | import ( 21 | "os" 22 | "testing" 23 | 24 | "github.com/oceanbase/obkv-table-client-go/client" 25 | "github.com/oceanbase/obkv-table-client-go/test" 26 | ) 27 | 28 | var cli client.Client 29 | 30 | func setup() { 31 | cli = test.CreateClient() 32 | 33 | test.CreateDB() 34 | test.CreateTable(nullableCreateStatement) 35 | } 36 | 37 | func teardown() { 38 | cli.Close() 39 | 40 | test.DropTable(nullableTableName) 41 | test.CloseDB() 42 | } 43 | 44 | func TestMain(m *testing.M) { 45 | setup() 46 | code := m.Run() 47 | teardown() 48 | os.Exit(code) 49 | } 50 | -------------------------------------------------------------------------------- /test/partition/partition_one_hash_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package partition 19 | 20 | import ( 21 | "context" 22 | "fmt" 23 | "testing" 24 | 25 | "github.com/stretchr/testify/assert" 26 | 27 | "github.com/oceanbase/obkv-table-client-go/table" 28 | "github.com/oceanbase/obkv-table-client-go/test" 29 | ) 30 | 31 | const ( 32 | hashBigintL1TableName = "hashBigintL1" 33 | hashBigintL1CreateStatement = "create table if not exists hashBigintL1(`c1` bigint(20) not null, c2 bigint(20) not null, primary key (`c1`)) partition by hash(c1) partitions 16;" 34 | ) 35 | 36 | func TestHashPartitionL1(t *testing.T) { 37 | tableName := hashBigintL1TableName 38 | defer test.DeleteTable(tableName) 39 | recordCount := 10 40 | 41 | // insert by sql 42 | for i := -recordCount; i < recordCount; i++ { 43 | insertStatement := fmt.Sprintf("insert into %s values(%d, %d);", tableName, i, i) 44 | test.InsertTable(insertStatement) 45 | } 46 | 47 | // get by obkv 48 | for i := -recordCount; i < recordCount; i++ { 49 | rowKey := []*table.Column{table.NewColumn("c1", int64(i))} 50 | res, err := cli.Get( 51 | context.TODO(), 52 | tableName, 53 | rowKey, 54 | nil, 55 | ) 56 | assert.Equal(t, nil, err) 57 | assert.EqualValues(t, i, res.Value("c1")) 58 | assert.EqualValues(t, i, res.Value("c2")) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /test/partition/partition_zero_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package partition 19 | 20 | import ( 21 | "context" 22 | "fmt" 23 | "testing" 24 | 25 | "github.com/stretchr/testify/assert" 26 | 27 | "github.com/oceanbase/obkv-table-client-go/table" 28 | "github.com/oceanbase/obkv-table-client-go/test" 29 | ) 30 | 31 | const ( 32 | hashBigintL0TableName = "hashBigintL0" 33 | hashBigintL0CreateStatement = "create table if not exists hashBigintL0(`c1` bigint(20) not null, c2 bigint(20) not null, primary key (`c1`));" 34 | ) 35 | 36 | func TestHashPartitionL0(t *testing.T) { 37 | tableName := hashBigintL0TableName 38 | defer test.DeleteTable(tableName) 39 | recordCount := 10 40 | 41 | // insert by sql 42 | for i := -recordCount; i < recordCount; i++ { 43 | insertStatement := fmt.Sprintf("insert into %s values(%d, %d);", tableName, i, i) 44 | test.InsertTable(insertStatement) 45 | } 46 | 47 | // get by obkv 48 | for i := -recordCount; i < recordCount; i++ { 49 | rowKey := []*table.Column{table.NewColumn("c1", int64(i))} 50 | res, err := cli.Get( 51 | context.TODO(), 52 | tableName, 53 | rowKey, 54 | nil, 55 | ) 56 | assert.Equal(t, nil, err) 57 | assert.EqualValues(t, i, res.Value("c1")) 58 | assert.EqualValues(t, i, res.Value("c2")) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /test/primary_key_order/all_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package primary_key_order 19 | 20 | import ( 21 | "os" 22 | "testing" 23 | 24 | "github.com/oceanbase/obkv-table-client-go/client" 25 | "github.com/oceanbase/obkv-table-client-go/test" 26 | ) 27 | 28 | var cli client.Client 29 | 30 | func setup() { 31 | cli = test.CreateClient() 32 | 33 | test.CreateDB() 34 | 35 | test.CreateTable(testPrimaryKeyTCreateStatement1) 36 | test.CreateTable(testPrimaryKeyTCreateStatement2) 37 | test.CreateTable(testPrimaryKeyTCreateStatement3) 38 | } 39 | 40 | func teardown() { 41 | cli.Close() 42 | 43 | test.DropTable(testPrimaryKeyTableName1) 44 | test.DropTable(testPrimaryKeyTableName2) 45 | test.DropTable(testPrimaryKeyTableName3) 46 | 47 | test.CloseDB() 48 | } 49 | 50 | func TestMain(m *testing.M) { 51 | setup() 52 | code := m.Run() 53 | teardown() 54 | os.Exit(code) 55 | } 56 | -------------------------------------------------------------------------------- /test/query/all_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2023 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package query 19 | 20 | import ( 21 | "os" 22 | "testing" 23 | 24 | "github.com/oceanbase/obkv-table-client-go/client" 25 | "github.com/oceanbase/obkv-table-client-go/test" 26 | ) 27 | 28 | var cli client.Client 29 | 30 | func setup() { 31 | cli = test.CreateClient() 32 | 33 | test.CreateDB() 34 | test.CreateTable(queryZeroTableCreateStatement) 35 | test.CreateTable(queryKeyTableCreateStatement) 36 | test.CreateTable(queryHashTableCreateStatement) 37 | test.CreateTable(queryLobTableCreateStatement) 38 | } 39 | 40 | func teardown() { 41 | cli.Close() 42 | 43 | test.DropTable(queryKeyTableName) 44 | test.DropTable(queryHashTableName) 45 | test.DropTable(queryZeroTableName) 46 | test.DropTable(queryLobTableName) 47 | test.CloseDB() 48 | } 49 | 50 | func TestMain(m *testing.M) { 51 | setup() 52 | code := m.Run() 53 | teardown() 54 | os.Exit(code) 55 | } 56 | -------------------------------------------------------------------------------- /test/route/all_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package route 19 | 20 | import ( 21 | "os" 22 | "testing" 23 | 24 | "github.com/oceanbase/obkv-table-client-go/client" 25 | "github.com/oceanbase/obkv-table-client-go/test" 26 | ) 27 | 28 | var cli client.Client 29 | 30 | var moveCli client.Client 31 | 32 | func setup() { 33 | cli = test.CreateClient() 34 | 35 | moveCli = test.CreateMoveClient() 36 | 37 | test.CreateDB() 38 | test.EnableRerouting() 39 | 40 | test.CreateTable(testInt32RerouteCreateStatement) 41 | test.CreateTable(testInt32RouteCreateStatement) 42 | } 43 | 44 | func teardown() { 45 | cli.Close() 46 | 47 | moveCli.Close() 48 | 49 | test.DropTable(testInt32RerouteTableName) 50 | test.DropTable(testInt32RouteTableName) 51 | 52 | test.CloseDB() 53 | } 54 | 55 | func TestMain(m *testing.M) { 56 | setup() 57 | code := m.Run() 58 | teardown() 59 | os.Exit(code) 60 | } 61 | -------------------------------------------------------------------------------- /test/route/util/partition.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at 10 | * http//license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package reroute 19 | 20 | type Partition struct { 21 | tableId uint64 22 | partId uint64 23 | replicaNum uint64 24 | leader *Replica 25 | follower []*Replica 26 | } 27 | 28 | func NewPartition(partId uint64) *Partition { 29 | return &Partition{ 30 | tableId: 0, 31 | partId: partId, 32 | replicaNum: 0, 33 | leader: nil, 34 | follower: make([]*Replica, 0, 2), 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /test/route/util/replica.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at 10 | * http//license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package reroute 19 | 20 | import ( 21 | "github.com/oceanbase/obkv-table-client-go/protocol" 22 | ) 23 | 24 | type Replica struct { 25 | TableId uint64 26 | PartId uint64 27 | Ip string 28 | Port int 29 | Role protocol.ObRole 30 | } 31 | -------------------------------------------------------------------------------- /test/ttl/all_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package ttl 19 | 20 | import ( 21 | "os" 22 | "testing" 23 | 24 | "github.com/oceanbase/obkv-table-client-go/client" 25 | "github.com/oceanbase/obkv-table-client-go/test" 26 | ) 27 | 28 | var cli client.Client 29 | 30 | func setup() { 31 | cli = test.CreateClient() 32 | 33 | test.CreateDB() 34 | 35 | test.CreateTable(testTTLCreateStatement) 36 | } 37 | 38 | func teardown() { 39 | cli.Close() 40 | 41 | test.DropTable(testTTLTableName) 42 | 43 | test.CloseDB() 44 | } 45 | 46 | func TestMain(m *testing.M) { 47 | setup() 48 | code := m.Run() 49 | teardown() 50 | os.Exit(code) 51 | } 52 | -------------------------------------------------------------------------------- /util/binary.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package util 19 | 20 | import ( 21 | "bytes" 22 | "encoding/binary" 23 | ) 24 | 25 | var endian = binary.BigEndian 26 | 27 | func PutUint8(buffer *bytes.Buffer, v uint8) { 28 | buffer.Next(1)[0] = v 29 | } 30 | 31 | func PutUint16(buffer *bytes.Buffer, v uint16) { 32 | endian.PutUint16(buffer.Next(2), v) 33 | } 34 | 35 | func PutUint32(buffer *bytes.Buffer, v uint32) { 36 | endian.PutUint32(buffer.Next(4), v) 37 | } 38 | 39 | func PutUint64(buffer *bytes.Buffer, v uint64) { 40 | endian.PutUint64(buffer.Next(8), v) 41 | } 42 | 43 | func Uint8(buffer *bytes.Buffer) uint8 { 44 | return buffer.Next(1)[0] 45 | } 46 | 47 | func Uint16(buffer *bytes.Buffer) uint16 { 48 | return endian.Uint16(buffer.Next(2)) 49 | } 50 | 51 | func Uint32(buffer *bytes.Buffer) uint32 { 52 | return endian.Uint32(buffer.Next(4)) 53 | } 54 | 55 | func Uint64(buffer *bytes.Buffer) uint64 { 56 | return endian.Uint64(buffer.Next(8)) 57 | } 58 | -------------------------------------------------------------------------------- /util/binary_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package util 19 | 20 | import ( 21 | "bytes" 22 | "math/rand" 23 | "testing" 24 | 25 | "github.com/stretchr/testify/assert" 26 | ) 27 | 28 | func TestBinary(t *testing.T) { 29 | var ( 30 | u8 uint8 = 1<<8 - 1 31 | u16 uint16 = 1<<16 - 1 32 | u32 uint32 = 1<<32 - 1 33 | u64 uint64 = 1<<64 - 1 34 | ) 35 | buf := make([]byte, 15) 36 | buffer := bytes.NewBuffer(buf) 37 | PutUint8(buffer, u8) 38 | PutUint16(buffer, u16) 39 | PutUint32(buffer, u32) 40 | PutUint64(buffer, u64) 41 | 42 | buffer = bytes.NewBuffer(buf) 43 | assert.EqualValues(t, Uint8(buffer), u8) 44 | assert.EqualValues(t, Uint16(buffer), u16) 45 | assert.EqualValues(t, Uint32(buffer), u32) 46 | assert.EqualValues(t, Uint64(buffer), u64) 47 | 48 | u8 = uint8(rand.Uint64()) 49 | u16 = uint16(rand.Uint64()) 50 | u32 = uint32(rand.Uint64()) 51 | u64 = rand.Uint64() 52 | buf = make([]byte, 15) 53 | buffer = bytes.NewBuffer(buf) 54 | PutUint8(buffer, u8) 55 | PutUint16(buffer, u16) 56 | PutUint32(buffer, u32) 57 | PutUint64(buffer, u64) 58 | 59 | buffer = bytes.NewBuffer(buf) 60 | assert.EqualValues(t, Uint8(buffer), u8) 61 | assert.EqualValues(t, Uint16(buffer), u16) 62 | assert.EqualValues(t, Uint32(buffer), u32) 63 | assert.EqualValues(t, Uint64(buffer), u64) 64 | } 65 | -------------------------------------------------------------------------------- /util/concurrent_map.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package util 19 | 20 | import ( 21 | "sync" 22 | ) 23 | 24 | type ConcurrentMap struct { 25 | items map[interface{}]interface{} 26 | mu sync.RWMutex 27 | } 28 | 29 | func NewConcurrentMap() *ConcurrentMap { 30 | return &ConcurrentMap{ 31 | items: make(map[interface{}]interface{}), 32 | } 33 | } 34 | 35 | func (c *ConcurrentMap) Add(key, value interface{}) { 36 | c.mu.Lock() 37 | defer c.mu.Unlock() 38 | 39 | c.items[key] = value 40 | } 41 | 42 | func (c *ConcurrentMap) AddIfAbsent(key interface{}, value interface{}) { 43 | c.mu.Lock() 44 | defer c.mu.Unlock() 45 | 46 | if _, found := c.items[key]; !found { 47 | c.items[key] = value 48 | } 49 | } 50 | 51 | func (c *ConcurrentMap) Update(key, value interface{}) bool { 52 | c.mu.Lock() 53 | defer c.mu.Unlock() 54 | if _, found := c.items[key]; found { 55 | c.items[key] = value 56 | return true 57 | } 58 | 59 | return false 60 | } 61 | 62 | func (c *ConcurrentMap) Remove(key interface{}) { 63 | c.mu.Lock() 64 | defer c.mu.Unlock() 65 | 66 | delete(c.items, key) 67 | } 68 | 69 | func (c *ConcurrentMap) Get(key interface{}) interface{} { 70 | c.mu.Lock() 71 | defer c.mu.Unlock() 72 | 73 | return c.items[key] 74 | } 75 | 76 | func (c *ConcurrentMap) Contains(key interface{}) bool { 77 | c.mu.Lock() 78 | defer c.mu.Unlock() 79 | 80 | _, found := c.items[key] 81 | return found 82 | } 83 | 84 | func (c *ConcurrentMap) Range(fn func(key, value interface{})) { 85 | c.mu.Lock() 86 | defer c.mu.Unlock() 87 | 88 | for key, value := range c.items { 89 | fn(key, value) 90 | } 91 | } 92 | 93 | func (c *ConcurrentMap) Size() int { 94 | return len(c.items) 95 | } 96 | -------------------------------------------------------------------------------- /util/local_time_origin.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package util 19 | 20 | import ( 21 | "time" 22 | ) 23 | 24 | var LocalTimeOrigin time.Time = time.Date(1970, 1, 1, 0, 0, 0, 0, time.Local) 25 | -------------------------------------------------------------------------------- /util/obversion.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package util 19 | 20 | import ( 21 | "fmt" 22 | "github.com/pkg/errors" 23 | "math" 24 | "regexp" 25 | "strconv" 26 | "strings" 27 | "sync" 28 | ) 29 | 30 | var globalObVersion float32 = 0.0 31 | var obVersionGuard sync.Mutex 32 | 33 | func ObVersion() float32 { 34 | return globalObVersion 35 | } 36 | 37 | func SetObVersion(version float32) { 38 | obVersionGuard.Lock() 39 | globalObVersion = version 40 | obVersionGuard.Unlock() 41 | } 42 | 43 | // ParseObVerionFromLogin may be used in ODP mode 44 | func ParseObVerionFromLogin(serverVersion string) (float32, error) { 45 | pattern := "" 46 | if strings.HasPrefix(serverVersion, "OceanBase_CE") { 47 | // serverVersion is like "OceanBase_CE 4.0.0.0" in CE 48 | pattern = "^OceanBase_CE\\s+(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$" 49 | } else { 50 | // serverVersion is like "OceanBase 4.0.0.0" 51 | pattern = "^OceanBase\\s+(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$" 52 | } 53 | re := regexp.MustCompile(pattern) 54 | match := re.FindStringSubmatch(serverVersion) 55 | if len(match) == 5 && match[0] == serverVersion { 56 | // transform version into 4.000 57 | subVersionStr := match[2] + match[3] + match[4] 58 | subVersion, err := strconv.Atoi(subVersionStr) 59 | if err != nil { 60 | return 0, errors.WithMessagef(err, "parse version %s failed", serverVersion) 61 | } 62 | mainVersion, err := strconv.Atoi(match[1]) 63 | if err != nil { 64 | return 0, errors.WithMessagef(err, "parse version %s failed", serverVersion) 65 | } 66 | return float32(mainVersion) + float32(subVersion)/float32(math.Pow10(len(subVersionStr))), nil 67 | } 68 | return 0, errors.New(fmt.Sprintf("parse version %s failed", serverVersion)) 69 | } 70 | -------------------------------------------------------------------------------- /util/purecrc32c_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package util 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestCalculate(t *testing.T) { 27 | s1 := "StringNeedToBeCalculatedCheckSumAndTest,Make String longer longer longer longer longer to test" 28 | assert.EqualValues(t, 1566783161, Calculate(0, []byte(s1))) 29 | s1 = "String Need To Be Calculated CheckSum And Test,Make String longer longer longer longer longer to test" 30 | assert.EqualValues(t, Calculate(0x05010927, []byte(s1)), Calculate(0x05010927, []byte(s1))) 31 | } 32 | -------------------------------------------------------------------------------- /util/security_test.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package util 19 | 20 | import ( 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | ) 25 | 26 | func TestGetPasswordScramble(t *testing.T) { 27 | for i := 0; i < 20; i++ { 28 | s := GetPasswordScramble(i) 29 | assert.EqualValues(t, i, len(s)) 30 | } 31 | } 32 | 33 | func TestScramblePassword(t *testing.T) { 34 | password := "hello" 35 | seed := "qXA4YhW5PwaWsARvj3KC" 36 | scramblePassword1 := ScramblePassword(password, seed) 37 | scramblePassword2 := ScramblePassword(password, seed) 38 | assert.EqualValues(t, 20, len(scramblePassword1)) 39 | assert.EqualValues(t, 20, len(scramblePassword2)) 40 | assert.EqualValues(t, scramblePassword1, scramblePassword2) 41 | assert.EqualValues(t, "", ScramblePassword("", seed)) 42 | } 43 | -------------------------------------------------------------------------------- /util/time_zone.go: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * OBKV Table Client Framework 4 | * %% 5 | * Copyright (C) 2021 OceanBase 6 | * %% 7 | * OBKV Table Client Framework is licensed under Mulan PSL v2. 8 | * You can use this software according to the terms and conditions of the Mulan PSL v2. 9 | * You may obtain a copy of Mulan PSL v2 at: 10 | * http://license.coscl.org.cn/MulanPSL2 11 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12 | * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13 | * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14 | * See the Mulan PSL v2 for more details. 15 | * #L% 16 | */ 17 | 18 | package util 19 | 20 | import ( 21 | "sync" 22 | "time" 23 | ) 24 | 25 | var globalTimeZone *time.Location = nil 26 | var globalTimeZoneGuard sync.Mutex 27 | 28 | func TimeZone() *time.Location { 29 | return globalTimeZone 30 | } 31 | 32 | func SetGlobalTimeZone(tz *time.Location) { 33 | obVersionGuard.Lock() 34 | globalTimeZone = tz 35 | obVersionGuard.Unlock() 36 | } 37 | --------------------------------------------------------------------------------