diff --git a/.factory/automation.yml b/.factory/automation.yml index 30fe91c844..d8bf7c820f 100644 --- a/.factory/automation.yml +++ b/.factory/automation.yml @@ -91,7 +91,7 @@ build: bazel test //rust:typedb_driver_unit_tests --test_output=streamed || exit 1 tool/test/start-core-server.sh && bazel test //rust/tests --test_output=streamed --test_arg=-- \ - --test_arg=integration::queries::core && + --test_arg=integration::queries::core && export CORE_FAILED= || export CORE_FAILED=1 tool/test/stop-core-server.sh if [[ -n "$CORE_FAILED" ]]; then exit 1; fi @@ -212,16 +212,7 @@ build: # TODO: delete --jobs=1 if we fix the issue with excess memory usage .factory/test-core.sh //java/test/behaviour/concept/... --test_output=errors .factory/test-core.sh //java/test/behaviour/driver/query/... --test_output=errors - .factory/test-core.sh //java/test/behaviour/query/language/match/... --test_output=errors - .factory/test-core.sh //java/test/behaviour/query/language/get/... --test_output=errors - .factory/test-core.sh //java/test/behaviour/query/language/fetch/... --test_output=errors - .factory/test-core.sh //java/test/behaviour/query/language/modifiers/... --test_output=errors - .factory/test-core.sh //java/test/behaviour/query/language/expression/... --test_output=errors - .factory/test-core.sh //java/test/behaviour/query/language/insert/... --test_output=errors - .factory/test-core.sh //java/test/behaviour/query/language/delete/... --test_output=errors - .factory/test-core.sh //java/test/behaviour/query/language/update/... --test_output=errors - .factory/test-core.sh //java/test/behaviour/query/language/define/... --test_output=errors - .factory/test-core.sh //java/test/behaviour/query/language/undefine/... --test_output=errors + .factory/test-core.sh //java/test/behaviour/query/language/... --test_output=errors --jobs=1 test-java-behaviour-cloud: image: vaticle-ubuntu-22.04 @@ -236,16 +227,7 @@ build: # TODO: delete --jobs=1 if we fix the issue with excess memory usage .factory/test-cloud.sh //java/test/behaviour/concept/... --test_output=errors .factory/test-cloud.sh //java/test/behaviour/driver/query/... --test_output=errors - .factory/test-cloud.sh //java/test/behaviour/query/language/match/... --test_output=errors - .factory/test-cloud.sh //java/test/behaviour/query/language/get/... --test_output=errors - .factory/test-cloud.sh //java/test/behaviour/query/language/fetch/... --test_output=errors - .factory/test-cloud.sh //java/test/behaviour/query/language/modifiers/... --test_output=errors - .factory/test-cloud.sh //java/test/behaviour/query/language/expression/... --test_output=errors - .factory/test-cloud.sh //java/test/behaviour/query/language/insert/... --test_output=errors - .factory/test-cloud.sh //java/test/behaviour/query/language/delete/... --test_output=errors - .factory/test-cloud.sh //java/test/behaviour/query/language/update/... --test_output=errors - .factory/test-cloud.sh //java/test/behaviour/query/language/define/... --test_output=errors - .factory/test-cloud.sh //java/test/behaviour/query/language/undefine/... --test_output=errors + .factory/test-cloud.sh //java/test/behaviour/query/language/... --test_output=errors --jobs=1 test-python-behaviour-core: image: vaticle-ubuntu-22.04 @@ -263,18 +245,9 @@ build: .factory/test-core.sh //python/tests/behaviour/connection/database/... --test_output=streamed --jobs=1 && .factory/test-core.sh //python/tests/behaviour/connection/session/... --test_output=streamed --jobs=1 && .factory/test-core.sh //python/tests/behaviour/connection/transaction/... --test_output=streamed --jobs=1 && - .factory/test-core.sh //python/tests/behaviour/concept/... --test_output=errors --jobs=1 && + .factory/test-core.sh //python/tests/behaviour/concept/... --test_output=errors --jobs=1 && .factory/test-core.sh //python/tests/behaviour/driver/query/... --test_output=errors && - .factory/test-core.sh //python/tests/behaviour/query/language/match/... --test_output=errors && - .factory/test-core.sh //python/tests/behaviour/query/language/get/... --test_output=errors && - .factory/test-core.sh //python/tests/behaviour/query/language/fetch/... --test_output=errors && - .factory/test-core.sh //python/tests/behaviour/query/language/modifiers/... --test_output=errors && - .factory/test-core.sh //python/tests/behaviour/query/language/expression/... --test_output=errors && - .factory/test-core.sh //python/tests/behaviour/query/language/insert/... --test_output=errors && - .factory/test-core.sh //python/tests/behaviour/query/language/delete/... --test_output=errors && - .factory/test-core.sh //python/tests/behaviour/query/language/update/... --test_output=errors && - .factory/test-core.sh //python/tests/behaviour/query/language/define/... --test_output=errors && - .factory/test-core.sh //python/tests/behaviour/query/language/undefine/... --test_output=errors && + .factory/test-core.sh //python/tests/behaviour/query/language/... --test_output=errors --jobs=1 && export TEST_SUCCESS=0 || export TEST_SUCCESS=1 tool/test/stop-core-server.sh exit $TEST_SUCCESS @@ -298,16 +271,7 @@ build: .factory/test-cloud.sh //python/tests/behaviour/connection/user/... --test_env=ROOT_CA=$ROOT_CA --test_output=streamed --jobs=1 && .factory/test-cloud.sh //python/tests/behaviour/concept/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && .factory/test-cloud.sh //python/tests/behaviour/driver/query/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //python/tests/behaviour/query/language/match/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //python/tests/behaviour/query/language/get/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //python/tests/behaviour/query/language/fetch/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //python/tests/behaviour/query/language/modifiers/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //python/tests/behaviour/query/language/expression/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //python/tests/behaviour/query/language/insert/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //python/tests/behaviour/query/language/delete/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //python/tests/behaviour/query/language/update/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //python/tests/behaviour/query/language/define/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //python/tests/behaviour/query/language/undefine/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && + .factory/test-cloud.sh //python/tests/behaviour/query/language/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && export TEST_SUCCESS=0 || export TEST_SUCCESS=1 tool/test/stop-cloud-servers.sh exit $TEST_SUCCESS @@ -363,7 +327,7 @@ build: tool/test/start-core-server.sh && node nodejs/test/integration/test-concept.js && node nodejs/test/integration/test-connection.js && - node nodejs/test/integration/test-query.js && + node nodejs/test/integration/test-query.js && export TEST_SUCCESS=0 || export TEST_SUCCESS=1 tool/test/stop-core-server.sh exit $TEST_SUCCESS @@ -381,7 +345,7 @@ build: cp -rL bazel-bin/nodejs/node_modules nodejs/. cp -rL bazel-bin/nodejs/dist nodejs/. source tool/test/start-cloud-servers.sh 3 && # use source to receive export vars - node nodejs/test/integration/test-cloud-failover.js && + node nodejs/test/integration/test-cloud-failover.js && export TEST_SUCCESS=0 || export TEST_SUCCESS=1 tool/test/stop-cloud-servers.sh exit $TEST_SUCCESS @@ -397,19 +361,10 @@ build: tool/test/start-core-server.sh && .factory/test-core.sh //nodejs/test/behaviour/connection/database/... --test_output=errors --jobs=1 && .factory/test-core.sh //nodejs/test/behaviour/connection/session/... --test_output=errors --jobs=1 && - .factory/test-core.sh //nodejs/test/behaviour/connection/transaction/... --test_output=errors --jobs=1 && + .factory/test-core.sh //nodejs/test/behaviour/connection/transaction/... --test_output=errors --jobs=1 && .factory/test-core.sh //nodejs/test/behaviour/concept/... --test_output=errors --jobs=1 && .factory/test-core.sh //nodejs/test/behaviour/driver/query/... --test_output=errors --jobs=1 && - .factory/test-core.sh //nodejs/test/behaviour/query/language/match/... --test_output=errors --jobs=1 && - .factory/test-core.sh //nodejs/test/behaviour/query/language/get/... --test_output=errors --jobs=1 && - .factory/test-core.sh //nodejs/test/behaviour/query/language/expression/... --test_output=errors --jobs=1 && - .factory/test-core.sh //nodejs/test/behaviour/query/language/fetch/... --test_output=errors --jobs=1 && - .factory/test-core.sh //nodejs/test/behaviour/query/language/modifiers/... --test_output=errors --jobs=1 && - .factory/test-core.sh //nodejs/test/behaviour/query/language/insert/... --test_output=errors --jobs=1 && - .factory/test-core.sh //nodejs/test/behaviour/query/language/delete/... --test_output=errors --jobs=1 && - .factory/test-core.sh //nodejs/test/behaviour/query/language/update/... --test_output=errors --jobs=1 && - .factory/test-core.sh //nodejs/test/behaviour/query/language/define/... --test_output=errors --jobs=1 && - .factory/test-core.sh //nodejs/test/behaviour/query/language/undefine/... --test_output=errors --jobs=1 && + .factory/test-core.sh //nodejs/test/behaviour/query/language/... --test_output=errors --jobs=1 && export TEST_SUCCESS=0 || export TEST_SUCCESS=1 tool/test/stop-core-server.sh exit $TEST_SUCCESS @@ -426,19 +381,10 @@ build: .factory/test-cloud.sh //nodejs/test/behaviour/connection/database/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && .factory/test-cloud.sh //nodejs/test/behaviour/connection/session/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && .factory/test-cloud.sh //nodejs/test/behaviour/connection/transaction/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && - .factory/test-cloud.sh //nodejs/test/behaviour/connection/user/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && + .factory/test-cloud.sh //nodejs/test/behaviour/connection/user/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && .factory/test-cloud.sh //nodejs/test/behaviour/concept/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && .factory/test-cloud.sh //nodejs/test/behaviour/driver/query/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && - .factory/test-cloud.sh //nodejs/test/behaviour/query/language/match/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && - .factory/test-cloud.sh //nodejs/test/behaviour/query/language/get/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && - .factory/test-cloud.sh //nodejs/test/behaviour/query/language/expression/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && - .factory/test-cloud.sh //nodejs/test/behaviour/query/language/fetch/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && - .factory/test-cloud.sh //nodejs/test/behaviour/query/language/modifiers/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && - .factory/test-cloud.sh //nodejs/test/behaviour/query/language/insert/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && - .factory/test-cloud.sh //nodejs/test/behaviour/query/language/delete/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && - .factory/test-cloud.sh //nodejs/test/behaviour/query/language/update/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && - .factory/test-cloud.sh //nodejs/test/behaviour/query/language/define/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && - .factory/test-cloud.sh //nodejs/test/behaviour/query/language/undefine/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && + .factory/test-cloud.sh //nodejs/test/behaviour/query/language/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && export TEST_SUCCESS=0 || export TEST_SUCCESS=1 tool/test/stop-cloud-servers.sh exit $TEST_SUCCESS @@ -477,18 +423,9 @@ build: .factory/test-core.sh //cpp/test/behaviour/connection/database/... --test_output=streamed --jobs=1 && .factory/test-core.sh //cpp/test/behaviour/connection/session/... --test_output=streamed --jobs=1 && .factory/test-core.sh //cpp/test/behaviour/connection/transaction/... --test_output=streamed --jobs=1 && - .factory/test-core.sh //cpp/test/behaviour/concept/... --test_output=errors --jobs=1 && + .factory/test-core.sh //cpp/test/behaviour/concept/... --test_output=errors --jobs=1 && .factory/test-core.sh //cpp/test/behaviour/driver/query/... --test_output=errors && - .factory/test-core.sh //cpp/test/behaviour/query/language/match/... --test_output=errors && - .factory/test-core.sh //cpp/test/behaviour/query/language/get/... --test_output=errors && - .factory/test-core.sh //cpp/test/behaviour/query/language/fetch/... --test_output=errors && - .factory/test-core.sh //cpp/test/behaviour/query/language/modifiers/... --test_output=errors && - .factory/test-core.sh //cpp/test/behaviour/query/language/expression/... --test_output=errors && - .factory/test-core.sh //cpp/test/behaviour/query/language/insert/... --test_output=errors && - .factory/test-core.sh //cpp/test/behaviour/query/language/delete/... --test_output=errors && - .factory/test-core.sh //cpp/test/behaviour/query/language/update/... --test_output=errors && - .factory/test-core.sh //cpp/test/behaviour/query/language/define/... --test_output=errors && - .factory/test-core.sh //cpp/test/behaviour/query/language/undefine/... --test_output=errors && + .factory/test-core.sh //cpp/test/behaviour/query/language/... --test_output=errors --jobs=1 && export TEST_SUCCESS=0 || export TEST_SUCCESS=1 tool/test/stop-core-server.sh exit $TEST_SUCCESS @@ -510,16 +447,70 @@ build: .factory/test-cloud.sh //cpp/test/behaviour/connection/user/... --test_env=ROOT_CA=$ROOT_CA --test_output=streamed --jobs=1 && .factory/test-cloud.sh //cpp/test/behaviour/concept/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && .factory/test-cloud.sh //cpp/test/behaviour/driver/query/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //cpp/test/behaviour/query/language/match/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //cpp/test/behaviour/query/language/get/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //cpp/test/behaviour/query/language/fetch/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //cpp/test/behaviour/query/language/modifiers/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //cpp/test/behaviour/query/language/expression/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //cpp/test/behaviour/query/language/insert/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //cpp/test/behaviour/query/language/delete/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //cpp/test/behaviour/query/language/update/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //cpp/test/behaviour/query/language/define/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && - .factory/test-cloud.sh //cpp/test/behaviour/query/language/undefine/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && + .factory/test-cloud.sh //cpp/test/behaviour/query/language/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && + export TEST_SUCCESS=0 || export TEST_SUCCESS=1 + tool/test/stop-cloud-servers.sh + exit $TEST_SUCCESS + + test-csharp-integration-core: + image: vaticle-ubuntu-22.04 + dependencies: + - build + type: foreground + command: | + sudo apt-get update + export ARTIFACT_USERNAME=$REPO_TYPEDB_USERNAME + export ARTIFACT_PASSWORD=$REPO_TYPEDB_PASSWORD + bazel run @vaticle_dependencies//tool/bazelinstall:remote_cache_setup.sh + bazel run @vaticle_dependencies//distribution/artifact:create-netrc + tool/test/start-core-server.sh && + bazel test //csharp/Test/Integration/... --test_output=streamed --jobs=1 && + export TEST_SUCCESS=0 || export TEST_SUCCESS=1 + tool/test/stop-core-server.sh + exit $TEST_SUCCESS + + test-csharp-behaviour-core: + image: vaticle-ubuntu-22.04 + dependencies: + - build + type: foreground + command: | + sudo apt-get update + export ARTIFACT_USERNAME=$REPO_TYPEDB_USERNAME + export ARTIFACT_PASSWORD=$REPO_TYPEDB_PASSWORD + bazel run @vaticle_dependencies//tool/bazelinstall:remote_cache_setup.sh + bazel run @vaticle_dependencies//distribution/artifact:create-netrc + tool/test/start-core-server.sh && + .factory/test-core.sh //csharp/Test/Behaviour/Connection/Database/... --test_output=errors --jobs=1 && + .factory/test-core.sh //csharp/Test/Behaviour/Connection/Session/... --test_output=errors --jobs=1 && + .factory/test-core.sh //csharp/Test/Behaviour/Connection/Transaction/... --test_output=errors --jobs=1 && + .factory/test-core.sh //csharp/Test/Behaviour/Concept/... --test_output=errors --jobs=1 && + .factory/test-core.sh //csharp/Test/Behaviour/Driver/Query/... --test_output=errors && + .factory/test-core.sh //csharp/Test/Behaviour/Query/Language/... --test_output=errors --jobs=1 && + .factory/test-core.sh //csharp/Test/Behaviour/Query/Reasoner/... --test_output=errors --jobs=1 && + export TEST_SUCCESS=0 || export TEST_SUCCESS=1 + tool/test/stop-core-server.sh + exit $TEST_SUCCESS + + test-csharp-behaviour-cloud: + image: vaticle-ubuntu-22.04 + dependencies: + - build + type: foreground + command: | + export ARTIFACT_USERNAME=$REPO_TYPEDB_USERNAME + export ARTIFACT_PASSWORD=$REPO_TYPEDB_PASSWORD + bazel run @vaticle_dependencies//tool/bazelinstall:remote_cache_setup.sh + bazel run @vaticle_dependencies//distribution/artifact:create-netrc + source tool/test/start-cloud-servers.sh && + .factory/test-cloud.sh //csharp/Test/Behaviour/Connection/Database/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && + .factory/test-cloud.sh //csharp/Test/Behaviour/Connection/Session/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && + .factory/test-cloud.sh //csharp/Test/Behaviour/Connection/Transaction/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && + .factory/test-cloud.sh //csharp/Test/Behaviour/Connection/User/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && + .factory/test-cloud.sh //csharp/Test/Behaviour/Concept/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && + .factory/test-cloud.sh //csharp/Test/Behaviour/Driver/Query/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors && + .factory/test-cloud.sh //csharp/Test/Behaviour/Query/Language/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && + .factory/test-cloud.sh //csharp/Test/Behaviour/Query/Reasoner/... --test_env=ROOT_CA=$ROOT_CA --test_output=errors --jobs=1 && export TEST_SUCCESS=0 || export TEST_SUCCESS=1 tool/test/stop-cloud-servers.sh exit $TEST_SUCCESS @@ -551,12 +542,15 @@ build: - test-cpp-integration-core - test-cpp-behaviour-core - test-cpp-behaviour-cloud + - test-csharp-integration-core + - test-csharp-behaviour-core + - test-csharp-behaviour-cloud command: | - sudo add-apt-repository ppa:deadsnakes/ppa - sudo apt update && sudo apt install -y python3.9 python3.9-distutils python3-pip - python3.9 -m pip install -U cffi - export SYNC_DEPENDENCIES_TOKEN=$REPO_GITHUB_TOKEN - bazel run @vaticle_dependencies//tool/sync:dependencies -- --source ${FACTORY_REPO}@${FACTORY_COMMIT} + sudo add-apt-repository -y ppa:deadsnakes/ppa + sudo apt update && sudo apt install -y python3.9 python3.9-distutils python3-pip + python3.9 -m pip install -U cffi + export SYNC_DEPENDENCIES_TOKEN=$REPO_GITHUB_TOKEN + bazel run @vaticle_dependencies//tool/sync:dependencies -- --source ${FACTORY_REPO}@${FACTORY_COMMIT} # TODO: assembly tests for all drivers to run in factory diff --git a/.gitignore b/.gitignore index 1a022df465..02cdd7e357 100644 --- a/.gitignore +++ b/.gitignore @@ -98,3 +98,7 @@ venv # Cargo files Cargo.lock Cargo.toml + +# Temporary paket files for C# +paket-files/ +paket.lock diff --git a/BUILD b/BUILD index b48925fe52..85ee49d6f4 100644 --- a/BUILD +++ b/BUILD @@ -64,6 +64,7 @@ release_validate_deps( "@vaticle_typeql", ], tags = ["manual"], # in order for bazel test //... to not fail + version_file = ":VERSION", ) # Force tools to be built during `build //...` diff --git a/WORKSPACE b/WORKSPACE index 296c96c2d0..b1386aee7c 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -64,6 +64,23 @@ rules_antlr_dependencies(antlr_version, JAVA) load("@vaticle_dependencies//builder/cpp:deps.bzl", cpp_deps = "deps") cpp_deps() +# Load //builder/csharp +load("@vaticle_dependencies//builder/csharp:deps.bzl", dotnet_deps = "deps") +dotnet_deps() +load( + "@rules_dotnet//dotnet:repositories.bzl", + "dotnet_register_toolchains", + "rules_dotnet_dependencies", +) +rules_dotnet_dependencies() +dotnet_register_toolchains("dotnet", "6.0.413") +load("@rules_dotnet//dotnet:paket.rules_dotnet_nuget_packages.bzl", "rules_dotnet_nuget_packages") +rules_dotnet_nuget_packages() +load("@rules_dotnet//dotnet:paket.paket2bazel_dependencies.bzl", "paket2bazel_dependencies") +paket2bazel_dependencies() +load("//csharp/nuget:paket.csharp_deps.bzl", csharp_deps = "csharp_deps") +csharp_deps() + # Load //builder/proto_grpc load("@vaticle_dependencies//builder/proto_grpc:deps.bzl", grpc_deps = "deps") grpc_deps() diff --git a/c/swig/typedb_driver_csharp.swg b/c/swig/typedb_driver_csharp.swg new file mode 100644 index 0000000000..4bb47d6d4d --- /dev/null +++ b/c/swig/typedb_driver_csharp.swg @@ -0,0 +1,681 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +%csconst(1); + +%typemap(cscode) SWIGTYPE %{ + public $csclassname Released() + { + var cPtr = swigCPtr.Handle; + if (swigCMemOwn) + { + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); + swigCMemOwn = false; + } + + return new $csclassname(cPtr, false); + } + + public bool IsOwned() + { + return swigCMemOwn; + } +%} + + +%typemap(csbase) Error "System.Exception"; +%typemap(csbody) Error %{ + private global::System.Runtime.InteropServices.HandleRef swigCPtr; + protected bool swigCMemOwn; + + internal Error(global::System.IntPtr cPtr, bool cMemoryOwn) + : base((typedb_driverPINVOKE.error_code(new global::System.Runtime.InteropServices.HandleRef(null, cPtr)) + " " + + typedb_driverPINVOKE.error_message(new global::System.Runtime.InteropServices.HandleRef(null, cPtr))).Trim()) + { + swigCMemOwn = cMemoryOwn; + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); + } + + internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Error obj) + { + return (obj == null) + ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) + : obj.swigCPtr; + } + + internal static global::System.Runtime.InteropServices.HandleRef swigRelease(Error obj) + { + if (obj == null) + { + return new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); + } + + if (!obj.swigCMemOwn) + { + throw new global::System.ApplicationException("Cannot release ownership as memory is not owned"); + } + + global::System.Runtime.InteropServices.HandleRef ptr = obj.swigCPtr; + obj.swigCMemOwn = false; + obj.Dispose(); + + return ptr; + } +%} + +%insert(runtime) %{ + // Code to handle throwing of C# CustomApplicationException from C/C++ code. + // The equivalent delegate to the callback, CSharpExceptionCallback_t, is NativeExceptionDelegate + // and the equivalent nativeExceptionCallback instance is nativeDelegate + typedef void (SWIGSTDCALL* CSharpExceptionCallback_t)(int*); + CSharpExceptionCallback_t nativeExceptionCallback = NULL; + + extern "C" SWIGEXPORT + void SWIGSTDCALL NativeExceptionRegisterCallback(CSharpExceptionCallback_t nativeCallback) + { + nativeExceptionCallback = nativeCallback; + } + + // Note that SWIG detects any method calls named starting with + // SWIG_CSharpSetPendingException and warns if its exception is not used where needed. + static void SWIG_CSharpSetPendingExceptionNative(int* error) + { + nativeExceptionCallback(error); + } +%} + +%pragma(csharp) imclasscode=%{ + class NativeExceptionHelper + { + // C# delegate for the C/C++ nativeExceptionCallback + public delegate void NativeExceptionDelegate(global::System.IntPtr error); + static NativeExceptionDelegate s_nativeDelegate = + new NativeExceptionDelegate(SetPendingNativeException); + + [global::System.Runtime.InteropServices.DllImport("$dllimport", EntryPoint="NativeExceptionRegisterCallback")] + public static extern void NativeExceptionRegisterCallback(NativeExceptionDelegate nativeCallback); + + static void SetPendingNativeException(global::System.IntPtr error) + { + SWIGPendingException.Set(new Error(error, true)); + } + + static NativeExceptionHelper() + { + NativeExceptionRegisterCallback(s_nativeDelegate); + } + } + + static NativeExceptionHelper exceptionHelper = new NativeExceptionHelper(); +%} + +%exception %{ + $action + + if (check_error()) + { + SWIG_CSharpSetPendingExceptionNative((int*)get_last_error()); + } +%} + +%noexception init_logging; + +/* simple getters do not throw */ +%noexception options_new; +%noexception options_get_infer; +%noexception options_get_trace_inference; +%noexception options_get_explain; +%noexception options_get_parallel; +%noexception options_get_prefetch; +%noexception options_get_prefetch_size; +%noexception options_get_session_idle_timeout_millis; +%noexception options_get_transaction_timeout_millis; +%noexception options_get_schema_lock_acquire_timeout_millis; +%noexception options_get_read_any_replica; +%noexception options_set_infer; +%noexception options_set_trace_inference; +%noexception options_set_explain; +%noexception options_set_parallel; +%noexception options_set_prefetch; +%noexception options_set_prefetch_size; +%noexception options_set_session_idle_timeout_millis; +%noexception options_set_transaction_timeout_millis; +%noexception options_set_schema_lock_acquire_timeout_millis; +%noexception options_set_read_any_replica; +%noexception options_has_infer; +%noexception options_has_trace_inference; +%noexception options_has_explain; +%noexception options_has_parallel; +%noexception options_has_prefetch; +%noexception options_has_prefetch_size; +%noexception options_has_session_idle_timeout_millis; +%noexception options_has_transaction_timeout_millis; +%noexception options_has_schema_lock_acquire_timeout_millis; +%noexception options_has_read_any_replica; + +%noexception annotation_new_key; +%noexception annotation_new_unique; +%noexception annotation_is_key; +%noexception annotation_is_unique; +%noexception annotation_to_string; +%noexception annotation_equals; + +%noexception error_code; +%noexception error_message; +%noexception schema_exception_code; +%noexception schema_exception_message; + +%noexception connection_is_open; + +%noexception session_is_open; +%noexception session_get_database_name; + +%noexception transaction_is_open; + +%noexception user_get_username; +%noexception user_get_password_expiry_seconds; + +%noexception replica_info_get_address; +%noexception replica_info_is_primary; +%noexception replica_info_is_preferred; +%noexception replica_info_get_term; + +%noexception database_get_name; +%noexception database_get_replicas_info; +%noexception database_get_primary_replica_info; +%noexception database_get_preferred_replica_info; + +%noexception concept_is_entity; +%noexception concept_is_relation; +%noexception concept_is_attribute; +%noexception concept_is_value; +%noexception concept_is_root_thing_type; +%noexception concept_is_entity_type; +%noexception concept_is_relation_type; +%noexception concept_is_attribute_type; +%noexception concept_is_role_type; +%noexception concept_as_entity; +%noexception concept_as_relation; +%noexception concept_as_attribute; +%noexception concept_as_value; +%noexception concept_as_root_thing_type; +%noexception concept_as_entity_type; +%noexception concept_as_relation_type; +%noexception concept_as_attribute_type; +%noexception concept_to_string; +%noexception concept_equals; + +%noexception concepts_get_root_entity_type; +%noexception concepts_get_root_relation_type; +%noexception concepts_get_root_attribute_type; + +%noexception attribute_type_get_value_type; + +%noexception role_type_is_root; +%noexception role_type_is_abstract; +%noexception role_type_get_scope; +%noexception role_type_get_name; + +%noexception thing_get_iid; +%noexception thing_get_is_inferred; +%noexception entity_get_type; +%noexception relation_get_type; +%noexception attribute_get_type; +%noexception attribute_get_value; + +%noexception value_get_boolean; +%noexception value_get_date_time_as_millis; +%noexception value_get_double; +%noexception value_get_long; +%noexception value_get_string; +%noexception value_is_boolean; +%noexception value_is_date_time; +%noexception value_is_double; +%noexception value_is_long; +%noexception value_is_string; +%noexception value_new_boolean; +%noexception value_new_date_time_from_millis; +%noexception value_new_double; +%noexception value_new_long; +%noexception value_new_string; + +%noexception role_player_get_role_type; +%noexception role_player_get_player; + +%noexception rule_get_label; +%noexception rule_get_when; +%noexception rule_get_then; +%noexception rule_to_string; + +%noexception concept_map_equals; +%noexception concept_map_get; +%noexception concept_map_get_explainables; +%noexception concept_map_get_values; +%noexception concept_map_get_variables; +%noexception concept_map_to_string; + +%noexception explainable_get_conjunction; +%noexception explainable_get_id; +%noexception explainables_equals; +%noexception explainables_get_attribute; +%noexception explainables_get_attributes_keys; +%noexception explainables_get_ownership; +%noexception explainables_get_ownerships_keys; +%noexception explainables_get_relation; +%noexception explainables_get_relations_keys; +%noexception explainables_to_string; + +%noexception explanation_equals; +%noexception explanation_to_string; +%noexception explanation_get_rule; +%noexception explanation_get_conclusion; +%noexception explanation_get_condition; +%noexception explanation_get_mapped_variables; +%noexception explanation_get_mapping; + +%noexception concept_map_group_get_owner; +%noexception concept_map_group_get_concept_maps; +%noexception concept_map_group_to_string; +%noexception concept_map_group_equals; + +%noexception value_group_to_string; +%noexception value_group_equals; +%noexception value_group_get_owner; +%noexception value_group_get_value; + +%noexception StringPair::_0; +%noexception StringPair::_1; + +/* director constructors do not throw */ +%noexception SessionCallbackDirector; +%noexception TransactionCallbackDirector; + +/* destructors do not throw */ +%noexception ~Annotation; +%noexception ~Concept; +%noexception ~ConceptIterator; +%noexception ~ConceptMap; +%noexception ~ConceptMapGroup; +%noexception ~ConceptMapGroupIterator; +%noexception ~ConceptMapIterator; +%noexception ~Connection; +%noexception ~Credential; +%noexception ~Database; +%noexception ~DatabaseIterator; +%noexception ~DatabaseManager; +%noexception ~DatabaseManager; +%noexception ~Error; +%noexception ~Error; +%noexception ~Explainable; +%noexception ~Explainables; +%noexception ~Explanation; +%noexception ~ExplanationIterator; +%noexception ~Options; +%noexception ~ReplicaInfo; +%noexception ~ReplicaInfoIterator; +%noexception ~RolePlayer; +%noexception ~RolePlayerIterator; +%noexception ~Rule; +%noexception ~RuleIterator; +%noexception ~SchemaException; +%noexception ~SchemaExceptionIterator; +%noexception ~Session; +%noexception ~SessionCallbackDirector; +%noexception ~StringIterator; +%noexception ~StringPair; +%noexception ~StringPairIterator; +%noexception ~Transaction; +%noexception ~TransactionCallbackDirector; +%noexception ~User; +%noexception ~UserIterator; +%noexception ~UserManager; +%noexception ~Value; +%noexception ~ValueGroup; +%noexception ~ValueGroupIterator; + +/* one-shot network requests do not throw when first constructed, only when resolved */ +%noexception concepts_get_entity_type; +%noexception concepts_get_relation_type; +%noexception concepts_get_attribute_type; +%noexception concepts_put_entity_type; +%noexception concepts_put_relation_type; +%noexception concepts_put_attribute_type; +%noexception concepts_get_entity; +%noexception concepts_get_relation; +%noexception concepts_get_attribute; +%noexception thing_delete; +%noexception thing_is_deleted; +%noexception thing_set_has; +%noexception thing_unset_has; +%noexception relation_add_role_player; +%noexception relation_remove_role_player; +%noexception thing_type_is_deleted; +%noexception thing_type_delete; +%noexception thing_type_get_label; +%noexception thing_type_set_label; +%noexception thing_type_set_abstract; +%noexception thing_type_unset_abstract; +%noexception thing_type_get_owns_overridden; +%noexception thing_type_set_owns; +%noexception thing_type_unset_owns; +%noexception thing_type_get_plays_overridden; +%noexception thing_type_set_plays; +%noexception thing_type_unset_plays; +%noexception thing_type_get_syntax; +%noexception entity_type_create; +%noexception entity_type_get_supertype; +%noexception entity_type_set_supertype; +%noexception relation_type_create; +%noexception relation_type_get_supertype; +%noexception relation_type_set_supertype; +%noexception relation_type_get_relates_for_role_label; +%noexception relation_type_get_relates_overridden; +%noexception relation_type_set_relates; +%noexception relation_type_unset_relates; +%noexception attribute_type_put; +%noexception attribute_type_get; +%noexception attribute_type_get_supertype; +%noexception attribute_type_set_supertype; +%noexception attribute_type_get_regex; +%noexception attribute_type_set_regex; +%noexception attribute_type_unset_regex; +%noexception role_type_is_deleted; +%noexception role_type_get_relation_type; +%noexception role_type_delete; +%noexception role_type_set_label; +%noexception role_type_get_supertype; +%noexception rule_set_label; +%noexception rule_delete; +%noexception rule_is_deleted; +%noexception logic_manager_put_rule; +%noexception logic_manager_get_rule; +%noexception query_define; +%noexception query_undefine; +%noexception query_delete; +%noexception query_get_aggregate; +%noexception transaction_commit; +%noexception transaction_rollback; + +%define %promise(Prefix, Type, function_prefix) +%typemap(csbody) Prefix ## Promise %{ + private global::System.Runtime.InteropServices.HandleRef swigCPtr; + protected bool swigCMemOwn; + + internal $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) + { + swigCMemOwn = cMemoryOwn; + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); + } + + internal static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) + { + return (obj == null) + ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) + : obj.swigCPtr; + } + + public Type Resolve() + { + swigCMemOwn = false; + return typedb_driver.function_prefix ## _promise_resolve(this); + } +%} + +%typemap(csdisposing, methodname="Dispose", methodmodifiers="protected", parameters="bool disposing") Prefix ## Promise %{{ + lock(this) + { + if (swigCPtr.Handle != global::System.IntPtr.Zero) + { + if (swigCMemOwn) + { + swigCMemOwn = false; + Resolve(); // An equivalent for the standard "delete_xxxPromise". + } + + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); + } + } +}%} +%enddef + +%promise(Concept, Concept, concept) +%promise(Rule, Rule, rule) +%promise(String, string, string) +%promise(Bool, bool, bool) + +/* void promises require special handling */ +%typemap(csbody) VoidPromise %{ + private global::System.Runtime.InteropServices.HandleRef swigCPtr; + protected bool swigCMemOwn; + + internal $csclassname(global::System.IntPtr cPtr, bool cMemoryOwn) + { + swigCMemOwn = cMemoryOwn; + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); + } + + internal static global::System.Runtime.InteropServices.HandleRef getCPtr($csclassname obj) + { + return (obj == null) + ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) + : obj.swigCPtr; + } + + public void Resolve() + { + swigCMemOwn = false; + typedb_driver.void_promise_resolve(this); + } +%} + +%typemap(csdisposing, methodname="Dispose", methodmodifiers="protected", parameters="bool disposing") VoidPromise %{{ + lock(this) + { + if (swigCPtr.Handle != global::System.IntPtr.Zero) + { + if (swigCMemOwn) + { + swigCMemOwn = false; + Resolve(); // An equivalent for the standard "delete_VoidPromise". + } + + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); + } + } +}%} + +%define %iterator(Type, CapitalizedType, FunctionPrefix) +%typemap(csinterfaces) CapitalizedType ## Iterator "System.Collections.Generic.IEnumerator"; +%typemap(cscode) CapitalizedType ## Iterator %{ + private bool _isFinished = false; + private Type? _current = null; + + object System.Collections.IEnumerator.Current + { + get + { + return Current; + } + } + + public Type Current + { + get + { + if (_current == null) + { + throw new System.IndexOutOfRangeException("Enumerator's Current element is out of range"); + } + + return _current; + } + } + + public bool MoveNext() + { + if (_isFinished) + { + return false; + } + + _current = typedb_driver.FunctionPrefix ## _iterator_next(this); + if (_current == null) + { + _isFinished = true; + return false; + } + + return true; + } + + public void Reset() + { + throw new System.NotSupportedException("This Enumerator does not support Reset"); + } +%} +%enddef + +%iterator(Concept, Concept, concept) +%iterator(RolePlayer, RolePlayer, role_player) +%iterator(ConceptMap, ConceptMap, concept_map) +%iterator(ConceptMapGroup, ConceptMapGroup, concept_map_group) +%iterator(ValueGroup, ValueGroup, value_group) +%iterator(Explanation, Explanation, explanation) +%iterator(string, String, string) +%iterator(StringPair, StringPair, string_pair) +%iterator(Rule, Rule, rule) +%iterator(User, User, user) +%iterator(Database, Database, database) +%iterator(ReplicaInfo, ReplicaInfo, replica_info) +%iterator(SchemaException, SchemaException, schema_exception) + + +%define %array(Type) +%typemap(ctype) Type ** "Type**" +%typemap(cstype) Type ** "Type[]" +%typemap(imtype) Type ** "global::System.IntPtr" + +%typemap( + csin, + pre="var unmanaged$csinput = Type.ArrayUnmanaged($csinput);", + post="global::System.Runtime.InteropServices.Marshal.FreeHGlobal(unmanaged$csinput);" +) Type ** "unmanaged$csinput" + +%typemap(csout) Type ** +{ + return $imcall; +} + +%typemap(in) char ** "$1 = $input;" +%typemap(freearg) char ** "" + +%typemap(cscode) Type %{ + public static global::System.IntPtr ArrayUnmanaged($csclassname[] input) + { + int arraySize = input.Length; + global::System.IntPtr unmanagedArray = System.Runtime.InteropServices.Marshal.AllocHGlobal( + (arraySize + 1) * System.Runtime.InteropServices.Marshal.SizeOf()); + + unsafe + { + global::System.IntPtr* arrayPtr = (global::System.IntPtr*)unmanagedArray.ToPointer(); + + for (int i = 0; i < arraySize; i++) + { + arrayPtr[i] = Type.getCPtr(input[i]).Handle; + } + + arrayPtr[arraySize] = global::System.IntPtr.Zero; + } + + return unmanagedArray; + } +%} +%enddef + +%array(Annotation) +%array(Concept) + + +%typemap(ctype) char ** "char**" +%typemap(cstype) char ** "string[]" +%typemap(imtype) char ** "global::System.IntPtr" + +%typemap( + csin, + pre=" + int arraySize = $csinput.Length; + global::System.IntPtr unmanaged$csinput = System.Runtime.InteropServices.Marshal.AllocHGlobal( + (arraySize + 1) * System.Runtime.InteropServices.Marshal.SizeOf()); + + unsafe + { + global::System.IntPtr* arrayPtr = (global::System.IntPtr*)unmanaged$csinput.ToPointer(); + + for (int i = 0; i < arraySize; i++) + { + arrayPtr[i] = global::System.Runtime.InteropServices.Marshal.StringToCoTaskMemAnsi($csinput[i]); + } + + arrayPtr[arraySize] = global::System.IntPtr.Zero; + }", + post=" + unsafe + { + global::System.IntPtr* arrayPtr = (global::System.IntPtr*)unmanaged$csinput.ToPointer(); + + for (int i = 0; i < arraySize; i++) + { + global::System.Runtime.InteropServices.Marshal.FreeHGlobal(arrayPtr[i]); + } + } + + global::System.Runtime.InteropServices.Marshal.FreeHGlobal(unmanaged$csinput);" +) char ** "unmanaged$csinput" + +%typemap(csout) char ** +{ + return $imcall; +} + +%typemap(in) char ** "$1 = $input;" +%typemap(freearg) char ** "" + + +%typemap(in) enum ValueType * { + if ($input >= 0) + { + $1 = (enum ValueType *)malloc(sizeof(enum ValueType)); + *$1 = (enum ValueType)$input; + } +} + +%typemap(freearg) enum ValueType * { free($1); } + +%typemap(ctype) enum ValueType * "int" +%typemap(imtype) enum ValueType * "int" +%typemap(cstype) enum ValueType * "ValueType?" + +%typemap(csin) enum ValueType * "$csinput == null ? -1 : (int)$csinput" +%typemap(csout) enum ValueType * +{ + return $imcall; +} diff --git a/c/swig/typedb_driver_java.swg b/c/swig/typedb_driver_java.swg index 96c96ba2c1..9f1a511ff4 100644 --- a/c/swig/typedb_driver_java.swg +++ b/c/swig/typedb_driver_java.swg @@ -78,8 +78,6 @@ jthrowable throwable = (jthrowable)jenv->NewObject(exceptionClass, ctor, jerror, true); jenv->Throw(throwable); - - return $null; } } @@ -316,6 +314,7 @@ %nojavaexception relation_remove_role_player; %nojavaexception thing_type_is_deleted; %nojavaexception thing_type_delete; +%nojavaexception thing_type_get_label; %nojavaexception thing_type_set_label; %nojavaexception thing_type_set_abstract; %nojavaexception thing_type_unset_abstract; @@ -393,6 +392,15 @@ } } %} +%typemap(javadestruct, methodname="delete", methodmodifiers="public synchronized") Type ## Promise %{{ + if (swigCPtr != 0) { + if (swigCMemOwn) { + swigCMemOwn = false; + get(); + } + swigCPtr = 0; + } +}%} %enddef %promise(Concept, concept) @@ -527,7 +535,6 @@ %array(Annotation) %array(Concept) -%array(ValueType) /* char** needs special handling */ %typemap(in) char ** (jint size) { diff --git a/c/typedb_driver.i b/c/typedb_driver.i index 2ed446301b..0bfcaa5c7b 100644 --- a/c/typedb_driver.i +++ b/c/typedb_driver.i @@ -37,6 +37,10 @@ extern "C" { %include "swig/typedb_driver_python.swg" #endif +#ifdef SWIGCSHARP +%include "swig/typedb_driver_csharp.swg" +#endif + %nodefaultctor; %define %dropproxy(Type, function_prefix) diff --git a/cpp/lib/common/error_message.cpp b/cpp/lib/common/error_message.cpp index 210b90ebe5..d269689b26 100644 --- a/cpp/lib/common/error_message.cpp +++ b/cpp/lib/common/error_message.cpp @@ -32,7 +32,7 @@ namespace TypeDB { namespace DriverError { -#define ERR_DRIVER(ID, MSG) ERRMSG("CCL", "Driver Error", ID, MSG) +#define ERR_DRIVER(ID, MSG) ERRMSG("CCDR", "Driver Error", ID, MSG) DECLSPEC_DLL extern const ErrorMessage DRIVER_CLOSED = ERR_DRIVER(1, "The driver has been closed and no further operation is allowed."); DECLSPEC_DLL extern const ErrorMessage SESSION_CLOSED = ERR_DRIVER(2, "The session has been closed and no further operation is allowed."); DECLSPEC_DLL extern const ErrorMessage TRANSACTION_CLOSED = ERR_DRIVER(3, "The transaction has been closed and no further operation is allowed."); @@ -48,7 +48,7 @@ DECLSPEC_DLL extern const ErrorMessage CALLBACK_EXCEPTION = ERR_DRIVER(9, "An ex namespace ConceptError { -#define ERR_CONCEPT(ID, MSG) ERRMSG("CCO", "Concept Error", ID, MSG) +#define ERR_CONCEPT(ID, MSG) ERRMSG("CCCO", "Concept Error", ID, MSG) DECLSPEC_DLL extern const ErrorMessage INVALID_CONCEPT_CASTING = ERR_CONCEPT(1, "Invalid concept conversion from '%s' to '%s'."); DECLSPEC_DLL extern const ErrorMessage MISSING_TRANSACTION = ERR_CONCEPT(2, "Transaction cannot be null."); DECLSPEC_DLL extern const ErrorMessage MISSING_IID = ERR_CONCEPT(3, "IID cannot be null or empty."); @@ -57,25 +57,25 @@ DECLSPEC_DLL extern const ErrorMessage MISSING_VARIABLE = ERR_CONCEPT(5, "Variab DECLSPEC_DLL extern const ErrorMessage MISSING_VALUE = ERR_CONCEPT(6, "Value cannot be null."); DECLSPEC_DLL extern const ErrorMessage NONEXISTENT_EXPLAINABLE_CONCEPT = ERR_CONCEPT(7, "The concept identified by '%s' is not explainable."); DECLSPEC_DLL extern const ErrorMessage NONEXISTENT_EXPLAINABLE_OWNERSHIP = ERR_CONCEPT(8, "The ownership by owner '%s' of attribute '%s' is not explainable."); -DECLSPEC_DLL extern const ErrorMessage UNRECOGNISED_ANNOTATION = ERR_CONCEPT(9, "The annotation '%s' is not recognised"); +DECLSPEC_DLL extern const ErrorMessage UNRECOGNISED_ANNOTATION = ERR_CONCEPT(9, "The annotation '%s' is not recognised."); #undef ERR_CONCEPT } // namespace ConceptError namespace QueryError { -#define ERR_QUERY(ID, MSG) ERRMSG("CQY", "Query Error", ID, MSG) +#define ERR_QUERY(ID, MSG) ERRMSG("CCQR", "Query Error", ID, MSG) DECLSPEC_DLL extern const ErrorMessage VARIABLE_DOES_NOT_EXIST = ERR_QUERY(1, "The variable '%s' does not exist."); -DECLSPEC_DLL extern const ErrorMessage MISSING_QUERY = ERR_QUERY(2, "Query cannot be null or empty"); +DECLSPEC_DLL extern const ErrorMessage MISSING_QUERY = ERR_QUERY(2, "Query cannot be null or empty."); #undef ERR_QUERY } // namespace QueryError namespace InternalError { -#define ERR_INTERNAL(ID, MSG) ERRMSG("CIN", "C++ Internal Error", ID, MSG) +#define ERR_INTERNAL(ID, MSG) ERRMSG("CCIN", "C++ Internal Error", ID, MSG) DECLSPEC_DLL extern const ErrorMessage UNEXPECTED_NATIVE_VALUE = ERR_INTERNAL(1, "Unexpected native value encountered!"); -DECLSPEC_DLL extern const ErrorMessage ILLEGAL_STATE = ERR_INTERNAL(2, "Illegal state has been reached! (%s : %d)"); +DECLSPEC_DLL extern const ErrorMessage ILLEGAL_STATE = ERR_INTERNAL(2, "Illegal state has been reached! (%s : %d)."); DECLSPEC_DLL extern const ErrorMessage ILLEGAL_CAST = ERR_INTERNAL(3, "Illegal casting operation to '%s'."); DECLSPEC_DLL extern const ErrorMessage NULL_NATIVE_VALUE = ERR_INTERNAL(4, "Unhandled null pointer to a native object encountered!"); DECLSPEC_DLL extern const ErrorMessage INVALID_NATIVE_HANDLE = ERR_INTERNAL(5, "The object does not have a valid native handle. It may have been: uninitialised, moved or disposed."); diff --git a/cpp/test/behaviour/steps/common/common_steps.cpp b/cpp/test/behaviour/steps/common/common_steps.cpp index b6ae773b81..27ce03c796 100644 --- a/cpp/test/behaviour/steps/common/common_steps.cpp +++ b/cpp/test/behaviour/steps/common/common_steps.cpp @@ -32,7 +32,7 @@ cucumber_bdd::StepCollection commonSteps = { BDD_STEP("wait (\\d+) seconds", { std::this_thread::sleep_for(std::chrono::seconds(atoi(matches[1].str().c_str()))); }), - BDD_NOOP("set time-zone is: (.*)"), + BDD_NOOP("set time-zone is: (.*)"), // TODO: Decide if we want to implement (can be changed only for POSIX). BDD_NOOP("typedb has configuration"), }; diff --git a/csharp/Api/Answer/IConceptMap.cs b/csharp/Api/Answer/IConceptMap.cs new file mode 100644 index 0000000000..80f6697e96 --- /dev/null +++ b/csharp/Api/Answer/IConceptMap.cs @@ -0,0 +1,186 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver.Api; + +namespace TypeDB.Driver.Api +{ + /** + * Contains a mapping of variables to concepts. + */ + public interface IConceptMap + { + /** + * Returns a collection of all variables in this IConceptMap. + * + *

Examples

+ *
+         * conceptMap.GetVariables();
+         * 
+ */ + IEnumerable GetVariables(); + + /** + * Returns a collection of all concepts in this IConceptMap. + * + *

Examples

+ *
+         * conceptMap.GetConcepts();
+         * 
+ */ + IEnumerable GetConcepts(); + + /** + * Returns the inner Dictionary (Map as a common TypeDB term) + * where keys are query variables, and values are concepts. + * + *

Examples

+ *
+         * conceptMap.GetMap();
+         * 
+ */ + Dictionary GetMap(); + + /** + * Retrieves a concept for a given variable name. + * + *

Examples

+ *
+         * conceptMap.Get(variable);
+         * 
+ * + * @param variable The string representation of a variable + */ + IConcept Get(string variable); + + /** + * Gets the IExplainables object for this IConceptMap, exposing + * which of the concepts in this IConceptMap are explainable. + * + *

Examples

+ *
+         * conceptMap.AllExplainables;
+         * 
+ */ + IExplainables AllExplainables { get; } + + /** + * Contains explainable objects. + */ + interface IExplainables + { + /** + * Retrieves the explainable relation with the given variable name. + * + *

Examples

+ *
+             * conceptMap.AllExplainables.Relation(variable);
+             * 
+ * + * @param variable The string representation of a variable + */ + IExplainable Relation(string variable); + + /** + * Retrieves the explainable attribute with the given variable name. + * + *

Examples

+ *
+             * conceptMap.AllExplainables.Attribute(variable);
+             * 
+ * + * @param variable The string representation of a variable + */ + IExplainable Attribute(string variable); + + /** + * Retrieves the explainable attribute ownership with the pair of (owner, attribute) variable names. + * + *

Examples

+ *
+             * conceptMap.AllExplainables.Ownership(owner, attribute);
+             * 
+ * + * @param owner The string representation of the owner variable + * @param attribute The string representation of the attribute variable + */ + IExplainable Ownership(string owner, string attribute); + + /** + * Retrieves all of this IConceptMap’s explainable relations. + * + *

Examples

+ *
+             * conceptMap.AllExplainables.GetRelations();
+             * 
+ */ + IEnumerable> GetRelations(); + + /** + * Retrieves all of this IConceptMap’s explainable attributes. + * + *

Examples

+ *
+             * conceptMap.AllExplainables.GetAttributes();
+             * 
+ */ + IEnumerable> GetAttributes(); + + /** + * Retrieves all of this IConceptMap’s explainable ownerships. + * + *

Examples

+ *
+             * conceptMap.AllExplainables.GetOwnerships();
+             * 
+ */ + IEnumerable, IExplainable>> GetOwnerships(); + } + + /** + * Contains an explainable object. + */ + interface IExplainable + { + /** + * Retrieves the subquery of the original query that is actually being explained. + * + *

Examples

+ *
+             * explainable.Conjunction;
+             * 
+ */ + string Conjunction { get; } + + /** + * Retrieves the unique ID that identifies this IExplainable. + * + *

Examples

+ *
+             * explainable.Id;
+             * 
+ */ + long Id { get; } + } + } +} diff --git a/csharp/Api/Answer/IConceptMapGroup.cs b/csharp/Api/Answer/IConceptMapGroup.cs new file mode 100644 index 0000000000..aecbb8d5f7 --- /dev/null +++ b/csharp/Api/Answer/IConceptMapGroup.cs @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver.Api; + +namespace TypeDB.Driver.Api +{ + /** + * Contains an element of the group query result. + */ + public interface IConceptMapGroup + { + /** + * Retrieves the concept that is the group owner. + * + *

Examples

+ *
+         * conceptMapGroup.Owner;
+         * 
+ */ + IConcept Owner { get; } + + /** + * Retrieves the IConceptMaps of the group. + * + *

Examples

+ *
+         * conceptMapGroup.GetConceptMaps();
+         * 
+ */ + IEnumerable GetConceptMaps(); + } +} diff --git a/csharp/Api/Answer/IValueGroup.cs b/csharp/Api/Answer/IValueGroup.cs new file mode 100644 index 0000000000..bc4a531488 --- /dev/null +++ b/csharp/Api/Answer/IValueGroup.cs @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver.Api; + +namespace TypeDB.Driver.Api +{ + /** + * Contains an element of the group aggregate query result. + */ + public interface IValueGroup + { + /** + * Retrieves the concept that is the group owner. + * + *

Examples

+ *
+         * conceptMapGroup.Owner;
+         * 
+ */ + IConcept Owner { get; } + + /** + * Retrieves the Value answer of the group. + * + *

Examples

+ *
+         * valueGroup.Value;
+         * 
+ */ + IValue? Value { get; } + } +} diff --git a/csharp/Api/BUILD b/csharp/Api/BUILD new file mode 100644 index 0000000000..bf1b339556 --- /dev/null +++ b/csharp/Api/BUILD @@ -0,0 +1,50 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +package(default_visibility = ["//visibility:public"]) + + +load("//csharp:build_opts.bzl", "nullable_context", "target_frameworks", "targeting_packs") +load("@rules_dotnet//dotnet:defs.bzl", "csharp_library") +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") + + +csharp_library( + name = "api", + srcs = glob(["*.cs", "*/*.cs", "*/*/*.cs"]), + deps = [ + "//csharp/Common:common", + "//csharp:typedb_driver_pinvoke", + "@paket.csharp_deps//newtonsoft.json", + ], + runtime_identifier = "any", + nullable = nullable_context, + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +checkstyle_test( + name = "checkstyle", + include = glob(["*", "*/*", "*/*/*"]), + license_type = "apache-header", + size = "small", +) diff --git a/csharp/Api/Concept/IConcept.cs b/csharp/Api/Concept/IConcept.cs new file mode 100644 index 0000000000..dc55d49b52 --- /dev/null +++ b/csharp/Api/Concept/IConcept.cs @@ -0,0 +1,347 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +using ConceptError = TypeDB.Driver.Common.Error.Concept; +using InternalError = TypeDB.Driver.Common.Error.Internal; + +namespace TypeDB.Driver.Api +{ + public interface IConcept + { + /** + * Checks if the concept is a IType. + * + *

Examples

+ *
+         * concept.IsType();
+         * 
+ */ + bool IsType() + { + return false; + } + + /** + * Checks if the concept is a IThingType. + * + *

Examples

+ *
+         * concept.IsThingType();
+         * 
+ */ + bool IsThingType() + { + return false; + } + + /** + * Checks if the concept is an IEntityType. + * + *

Examples

+ *
+         * concept.IsEntityType();
+         * 
+ */ + bool IsEntityType() + { + return false; + } + + /** + * Checks if the concept is an IAttributeType. + * + *

Examples

+ *
+         * concept.IsAttributeType();
+         * 
+ */ + bool IsAttributeType() + { + return false; + } + + /** + * Checks if the concept is a IRelationType. + * + *

Examples

+ *
+         * concept.IsRelationType();
+         * 
+ */ + bool IsRelationType() + { + return false; + } + + /** + * Checks if the concept is a IRoleType. + * + *

Examples

+ *
+         * concept.IsRoleType();
+         * 
+ */ + bool IsRoleType() + { + return false; + } + + /** + * Checks if the concept is a IThing. + * + *

Examples

+ *
+         * concept.IsThing();
+         * 
+ */ + bool IsThing() + { + return false; + } + + /** + * Checks if the concept is an IEntity. + * + *

Examples

+ *
+         * concept.IsEntity();
+         * 
+ */ + bool IsEntity() + { + return false; + } + + /** + * Checks if the concept is a IRelation. + * + *

Examples

+ *
+         * concept.IsRelation();
+         * 
+ */ + bool IsRelation() + { + return false; + } + + /** + * Checks if the concept is an IAttribute. + * + *

Examples

+ *
+         * concept.IsAttribute();
+         * 
+ */ + bool IsAttribute() + { + return false; + } + + /** + * Checks if the concept is a IValue. + * + *

Examples

+ *
+         * concept.IsValue();
+         * 
+ */ + bool IsValue() + { + return false; + } + + /** + * Casts the concept to IType. + * + *

Examples

+ *
+         * concept.AsType();
+         * 
+ */ + IType AsType() + { + throw new TypeDBDriverException( + ConceptError.INVALID_CONCEPT_CASTING, this.GetType().Name, typeof(IType).Name); + } + + /** + * Casts the concept to IThingType. + * + *

Examples

+ *
+         * concept.AsThingType();
+         * 
+ */ + IThingType AsThingType() + { + throw new TypeDBDriverException( + ConceptError.INVALID_CONCEPT_CASTING, this.GetType().Name, typeof(IThingType).Name); + } + + /** + * Casts the concept to IEntityType. + * + *

Examples

+ *
+         * concept.AsEntityType();
+         * 
+ */ + IEntityType AsEntityType() + { + throw new TypeDBDriverException( + ConceptError.INVALID_CONCEPT_CASTING, this.GetType().Name, typeof(IEntityType).Name); + } + + /** + * Casts the concept to IRelationType. + * + *

Examples

+ *
+         * concept.AsRelationType();
+         * 
+ */ + IRelationType AsRelationType() + { + throw new TypeDBDriverException( + ConceptError.INVALID_CONCEPT_CASTING, this.GetType().Name, typeof(IRelationType).Name); + } + + /** + * Casts the concept to IAttributeType. + * + *

Examples

+ *
+         * concept.AsAttributeType();
+         * 
+ */ + IAttributeType AsAttributeType() + { + throw new TypeDBDriverException( + ConceptError.INVALID_CONCEPT_CASTING, this.GetType().Name, typeof(IAttributeType).Name); + } + + /** + * Casts the concept to IRoleType. + * + *

Examples

+ *
+         * concept.AsRoleType();
+         * 
+ */ + IRoleType AsRoleType() + { + throw new TypeDBDriverException( + ConceptError.INVALID_CONCEPT_CASTING, this.GetType().Name, typeof(IRoleType).Name); + } + + /** + * Casts the concept to IThing. + * + *

Examples

+ *
+         * concept.AsThing();
+         * 
+ */ + IThing AsThing() + { + throw new TypeDBDriverException( + ConceptError.INVALID_CONCEPT_CASTING, this.GetType().Name, typeof(IThing).Name); + } + + /** + * Casts the concept to IEntity. + * + *

Examples

+ *
+         * concept.AsEntity();
+         * 
+ */ + IEntity AsEntity() + { + throw new TypeDBDriverException( + ConceptError.INVALID_CONCEPT_CASTING, this.GetType().Name, typeof(IEntity).Name); + } + + /** + * Casts the concept to IRelation. + * + *

Examples

+ *
+         * concept.AsRelation();
+         * 
+ */ + IRelation AsRelation() + { + throw new TypeDBDriverException( + ConceptError.INVALID_CONCEPT_CASTING, this.GetType().Name, typeof(IRelation).Name); + } + + /** + * Casts the concept to IAttribute. + * + *

Examples

+ *
+         * concept.AsAttribute();
+         * 
+ */ + IAttribute AsAttribute() + { + throw new TypeDBDriverException( + ConceptError.INVALID_CONCEPT_CASTING, this.GetType().Name, typeof(IAttribute).Name); + } + + /** + * Casts the concept to IValue. + * + *

Examples

+ *
+         * concept.AsValue();
+         * 
+ */ + IValue AsValue() + { + throw new TypeDBDriverException( + ConceptError.INVALID_CONCEPT_CASTING, this.GetType().Name, typeof(IValue).Name); + } + + /** + * This class is used for specifying whether we need explicit or transitive subtyping, instances, etc. + * + *

Examples

+ *
+         * attributeType.GetOwners(transaction, annotation, Explicit);
+         * 
+ */ + public enum Transitivity + { + Transitive = Pinvoke.Transitivity.Transitive, + Explicit = Pinvoke.Transitivity.Explicit, + } + } +} diff --git a/csharp/Api/Concept/IConceptManager.cs b/csharp/Api/Concept/IConceptManager.cs new file mode 100644 index 0000000000..1a8aee0579 --- /dev/null +++ b/csharp/Api/Concept/IConceptManager.cs @@ -0,0 +1,186 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Api +{ + /** + * Provides access for all Concept API methods. + */ + public interface IConceptManager + { + /** + * The root IEntityType, “entity”. + * + *

Examples

+ *
+         * transaction.Concepts.RootEntityType;
+         * 
+ */ + IEntityType RootEntityType { get; } + + /** + * The root IRelationType, “relation”. + * + *

Examples

+ *
+         * transaction.Concepts.RootRelationType;
+         * 
+ */ + IRelationType RootRelationType { get; } + + /** + * The root IAttributeType, “attribute”. + * + *

Examples

+ *
+         * transaction.Concepts.RootAttributeType;
+         * 
+ */ + IAttributeType RootAttributeType { get; } + + /** + * Retrieves an IEntityType by its label. + * + *

Examples

+ *
+         * transaction.Concepts.GetEntityType(label).Resolve();
+         * 
+ * + * @param label The label of the IEntityType to retrieve. + */ + Promise GetEntityType(string label); + + /** + * Retrieves a IRelationType by its label. + * + *

Examples

+ *
+         * transaction.Concepts.GetRelationType(label).Resolve();
+         * 
+ * + * @param label The label of the IRelationType to retrieve. + */ + Promise GetRelationType(string label); + + /** + * Retrieves an IAttributeType by its label. + * + *

Examples

+ *
+         * transaction.Concepts.GetAttributeType(label).Resolve();
+         * 
+ * + * @param label The label of the AttributeType to retrieve. + */ + Promise GetAttributeType(string label); + + /** + * Creates a new IEntityType if none exists with the given label, + * otherwise retrieves the existing one. + * + *

Examples

+ *
+         * transaction.Concepts.PutEntityType(label).Resolve();
+         * 
+ * + * @param label The label of the IEntityType to create or retrieve. + */ + Promise PutEntityType(string label); + + /** + * Creates a new IRelationType if none exists with the given label, + * otherwise retrieves the existing one. + * + *

Examples

+ *
+         * transaction.Concepts.PutRelationType(label).Resolve();
+         * 
+ * + * @param label The label of the IRelationType to create or retrieve. + */ + Promise PutRelationType(string label); + + /** + * Creates a new IAttributeType if none exists with the given label, + * or retrieves the existing one. + * + *

Examples

+ *
+         * await transaction.Concepts.PutAttributeType(label, valueType).Resolve();
+         * 
+ * + * @param label The label of the IAttributeType to create or retrieve. + * @param valueType The value type of the IAttributeType to create. + */ + Promise PutAttributeType(string label, IValue.ValueType valueType); + + /** + * Retrieves an IEntity by its iid. + * + *

Examples

+ *
+         * transaction.Concepts.GetEntity(iid).Resolve();
+         * 
+ * + * @param iid The iid of the Entity to retrieve. + */ + Promise GetEntity(string iid); + + /** + * Retrieves a IRelation by its iid. + * + *

Examples

+ *
+         * transaction.Concepts.GetRelation(iid).Resolve();
+         * 
+ * + * @param iid The iid of the Relation to retrieve. + */ + Promise GetRelation(string iid); + + /** + * Retrieves an IAttribute by its iid. + * + *

Examples

+ *
+         * transaction.Concepts.GetAttribute(iid).Resolve();
+         * 
+ * + * @param iid The iid of the Attribute to retrieve. + */ + Promise GetAttribute(string iid); + + /** + * A list of all schema exceptions for the current transaction. + * + *

Examples

+ *
+         * transaction.Concepts.GetSchemaExceptions();
+         * 
+ */ + IList GetSchemaExceptions(); + } +} diff --git a/csharp/Api/Concept/Thing/IAttribute.cs b/csharp/Api/Concept/Thing/IAttribute.cs new file mode 100644 index 0000000000..3a9ac50649 --- /dev/null +++ b/csharp/Api/Concept/Thing/IAttribute.cs @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver.Api; + +namespace TypeDB.Driver.Api +{ + /** + *

Attribute is an instance of the attribute type and has a value. + * This value is fixed and unique for every given instance of the attribute type.

+ *

Attributes can be uniquely addressed by their type and value.

+ */ + public interface IAttribute : IThing + { + /** + * Checks if the concept is an IAttribute. + * + *

Examples

+ *
+         * attribute.IsAttribute();
+         * 
+ */ + bool IConcept.IsAttribute() + { + return true; + } + + /** + * Casts the concept to IAttribute. + * + *

Examples

+ *
+         * attribute.AsAttribute();
+         * 
+ */ + IAttribute IConcept.AsAttribute() + { + return this; + } + + /** + * Retrieves the value which the IAttribute instance holds. + * + *

Examples

+ *
+         * attribute.Value;
+         * 
+ */ + IValue Value { get; } + + /** + * Retrieves the instances that own this IAttribute. + * + *

Examples

+ *
+         * attribute.GetOwners(transaction);
+         * 
+ * + * @param transaction The current transaction + */ + IEnumerable GetOwners(ITypeDBTransaction transaction); + + /** + * Retrieves the instances that own this IAttribute. + * + *

Examples

+ *
+         * attribute.GetOwners(transaction, ownerType);
+         * 
+ * + * @param transaction The current transaction + * @param ownerType Filter results for only owners of the given type + */ + IEnumerable GetOwners(ITypeDBTransaction transaction, IThingType ownerType); + } +} diff --git a/csharp/Api/Concept/Thing/IEntity.cs b/csharp/Api/Concept/Thing/IEntity.cs new file mode 100644 index 0000000000..0efcff8300 --- /dev/null +++ b/csharp/Api/Concept/Thing/IEntity.cs @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver.Api; + +namespace TypeDB.Driver.Api +{ + /** + * Instance of data of an entity type, representing a standalone object that exists in the data model independently. + * Entity does not have a value. It is usually addressed by its ownership over attribute instances and/or roles + * played in relation instances. + */ + public interface IEntity : IThing + { + /** + * Checks if the concept is an IEntity. + * + *

Examples

+ *
+         * entity.IsEntity();
+         * 
+ */ + bool IConcept.IsEntity() + { + return true; + } + + /** + * Casts the concept to IEntity. + * + *

Examples

+ *
+         * entity.AsEntity();
+         * 
+ */ + IEntity IConcept.AsEntity() + { + return this; + } + } +} diff --git a/csharp/Api/Concept/Thing/IRelation.cs b/csharp/Api/Concept/Thing/IRelation.cs new file mode 100644 index 0000000000..a28985bb0d --- /dev/null +++ b/csharp/Api/Concept/Thing/IRelation.cs @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Api +{ + /** + * Relation is an instance of a relation type and can be uniquely addressed + * by a combination of its type, owned attributes and role players. + */ + public interface IRelation : IThing + { + /** + * Checks if the concept is a IRelation. + * + *

Examples

+ *
+         * relation.IsRelation();
+         * 
+ */ + bool IConcept.IsRelation() + { + return true; + } + + /** + * Casts the concept to IRelation. + * + *

Examples

+ *
+         * relation.AsRelation();
+         * 
+ */ + IRelation IConcept.AsRelation() + { + return this; + } + + /** + * Adds a new role player to play the given role in this IRelation. + * + *

Examples

+ *
+         * relation.AddPlayer(transaction, roleType, player).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param roleType The role to be played by the player + * @param player The thing to play the role + */ + VoidPromise AddPlayer(ITypeDBTransaction transaction, IRoleType roleType, IThing player); + + /** + * Removes the association of the given instance that plays the given role in this IRelation. + * + *

Examples

+ *
+         * relation.RemovePlayer(transaction, roleType, player).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param roleType The role to no longer be played by the thing in this IRelation + * @param player The instance to no longer play the role in this IRelation + */ + VoidPromise RemovePlayer(ITypeDBTransaction transaction, IRoleType roleType, IThing player); + + /** + * Retrieves all role players of this IRelation, optionally filtered by given role types. + * + *

Examples

+ *
+         * relation.GetPlayersByRoleType(transaction, roleTypes);
+         * 
+ * + * @param transaction The current transaction + * @param roleTypes 0 or more role types + */ + IEnumerable GetPlayersByRoleType(ITypeDBTransaction transaction, params IRoleType[] roleTypes); + + /** + * Retrieves a mapping of all instances involved in the IRelation and the role each play. + * + *

Examples

+ *
+         * relation.GetPlayers(transaction)
+         * 
+ * + * @param transaction The current transaction + */ + Dictionary> GetPlayers(ITypeDBTransaction transaction); + + /** + * Retrieves all role types currently played in this IRelation. + * + *

Examples

+ *
+         * relation.GetRelating(transaction);
+         * 
+ * + * @param transaction The current transaction + */ + IEnumerable GetRelating(ITypeDBTransaction transaction); + } +} diff --git a/csharp/Api/Concept/Thing/IThing.cs b/csharp/Api/Concept/Thing/IThing.cs new file mode 100644 index 0000000000..72a8e10afe --- /dev/null +++ b/csharp/Api/Concept/Thing/IThing.cs @@ -0,0 +1,194 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using static TypeDB.Driver.Api.IThingType; + +namespace TypeDB.Driver.Api +{ + public interface IThing : IConcept + { + /** + * The unique id of the IThing. + * + *

Examples

+ *
+         * thing.IID;
+         * 
+ */ + string IID { get; } + + /** + * The type which this IThing belongs to. + * + *

Examples

+ *
+         * thing.Type;
+         * 
+ */ + IThingType Type { get; } + + /** + * Checks if this IThing is inferred by a [Reasoning Rule]. + * + *

Examples

+ *
+         * thing.IsInferred();
+         * 
+ */ + bool IsInferred(); + + /** + * Checks if the concept is a IThing. + * + *

Examples

+ *
+         * thing.IsThing();
+         * 
+ */ + bool IConcept.IsThing() + { + return true; + } + + /** + * Casts the concept to IThing. + * + *

Examples

+ *
+         * thing.AsThing();
+         * 
+ */ + IThing IConcept.AsThing() + { + return this; + } + + /** + * Assigns an IAttribute to be owned by this IThing. + * + *

Examples

+ *
+         * thing.SetHas(transaction, attribute).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param attribute The IAttribute to be owned by this IThing. + */ + VoidPromise SetHas(ITypeDBTransaction transaction, IAttribute attribute); + + /** + * Unassigns an IAttribute from this IThing. + * + *

Examples

+ *
+         * thing.UnsetHas(transaction, attribute).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param attribute The IAttribute to be disowned from this IThing. + */ + VoidPromise UnsetHas(ITypeDBTransaction transaction, IAttribute attribute); + + /** + * Retrieves the IAttributes that this IThing owns, + * optionally filtered by IAttributeTypes. + * + *

Examples

+ *
+         * thing.GetHas(transaction);
+         * thing.GetHas(transaction, attributeType);
+         * 
+ * + * @param transaction The current transaction + * @param attributeTypes The IAttributeTypes to filter the attributes by + */ + IEnumerable GetHas(ITypeDBTransaction transaction, params IAttributeType[] attributeTypes); + + /** + * Retrieves the IAttributes that this IThing owns, + * filtered by Annotations. + * + *

Examples

+ *
+         * thing.GetHas(transaction);
+         * thing.GetHas(transaction, new []{NewKey()});
+         * 
+ * + * @param transaction The current transaction + * @param annotations Only retrieve attributes with all given Annotations + */ + IEnumerable GetHas(ITypeDBTransaction transaction, ICollection annotations); + + /** + * Retrieves all the Relations which this IThing plays a role in, + * optionally filtered by one or more given roles. + * + *

Examples

+ *
+         * thing.GetRelations(transaction, roleTypes);
+         * 
+ * + * @param transaction The current transaction + * @param roleTypes The array of roles to filter the relations by. + */ + IEnumerable GetRelations(ITypeDBTransaction transaction, params IRoleType[] roleTypes); + + /** + * Retrieves the roles that this IThing is currently playing. + * + *

Examples

+ *
+         * thing.GetPlaying(transaction);
+         * 
+ * + * @param transaction The current transaction + */ + IEnumerable GetPlaying(ITypeDBTransaction transaction); + + /** + * Deletes this IThing. + * + *

Examples

+ *
+         * thing.Delete(transaction).Resolve();
+         * 
+ * + * @param transaction The current transaction + */ + VoidPromise Delete(ITypeDBTransaction transaction); + + /** + * Checks if this IThing is deleted. + * + *

Examples

+ *
+         * thing.IsDeleted(transaction).Resolve();
+         * 
+ * + * @param transaction The current transaction + */ + Promise IsDeleted(ITypeDBTransaction transaction); + } +} diff --git a/csharp/Api/Concept/Type/IAttributeType.cs b/csharp/Api/Concept/Type/IAttributeType.cs new file mode 100644 index 0000000000..8aab77f9fc --- /dev/null +++ b/csharp/Api/Concept/Type/IAttributeType.cs @@ -0,0 +1,453 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Api +{ + /** + * Attribute types represent properties that other types can own. + *

IAttribute types have a value type. This value type is fixed and unique for every given instance + * of the attribute type.

+ *

Other types can own an attribute type. That means that instances of these other types can own an instance + * of this attribute type. This usually means that an object in our domain has a property with the matching value.

+ *

Multiple types can own the same attribute type, and different instances of the same type or different types + * can share ownership of the same attribute instance.

+ */ + public interface IAttributeType : IThingType + { + /** + * The IValue.ValueType of this IAttributeType. + * + *

Examples

+ *
+         * attributeType.ValueType;
+         * 
+ */ + IValue.ValueType ValueType { get; } + + /** + * {@inheritDoc} + */ + bool IConcept.IsAttributeType() + { + return true; + } + + /** + * {@inheritDoc} + */ + IAttributeType IConcept.AsAttributeType() + { + return this; + } + + /** + * Adds and returns an IAttribute of this IAttributeType with the given value. + * + *

Examples

+ *
+         * attributeType.Put(transaction, value).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param value New IAttribute’s value + */ + Promise Put(ITypeDBTransaction transaction, IValue value); + + /** + * Adds and returns an IAttribute of this IAttributeType + * with the given string value. + * + *

Examples

+ *
+         * attributeType.Put(transaction, value).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param value New IAttribute’s value + */ + Promise Put(ITypeDBTransaction transaction, string value); + + /** + * Adds and returns an IAttribute of this IAttributeType + * with the given long value. + * + *

Examples

+ *
+         * attributeType.Put(transaction, value).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param value New IAttribute’s value + */ + Promise Put(ITypeDBTransaction transaction, long value); + + /** + * Adds and returns an IAttribute of this IAttributeType + * with the given double value. + * + *

Examples

+ *
+         * attributeType.Put(transaction, value).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param value New IAttribute’s value + */ + Promise Put(ITypeDBTransaction transaction, double value); + + /** + * Adds and returns an IAttribute of this IAttributeType + * with the given bool value. + * + *

Examples

+ *
+         * attributeType.Put(transaction, value).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param value New IAttribute’s value + */ + Promise Put(ITypeDBTransaction transaction, bool value); + + /** + * Adds and returns an IAttribute of this IAttributeType + * with the given DateTime value. + * The input DateTime value is treated as timezone naive, with DateTimeKind being ignored. + * + *

Examples

+ *
+         * attributeType.Put(transaction, value).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param value New IAttribute’s value + */ + Promise Put(ITypeDBTransaction transaction, System.DateTime value); + + /** + * Retrieves an IAttribute of this IAttributeType with the given value + * if such IAttribute exists. Otherwise, returns None. + * + *

Examples

+ *
+         * attributeType.Get(transaction, value).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param value IAttribute’s value + */ + Promise Get(ITypeDBTransaction transaction, IValue value); + + /** + * Retrieves an IAttribute of this IAttributeType with the given value + * if such IAttribute exists. Otherwise, returns None. + * + *

Examples

+ *
+         * attributeType.Get(transaction, value).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param value IAttribute’s value + */ + Promise Get(ITypeDBTransaction transaction, string value); + + /** + * Retrieves an IAttribute of this IAttributeType with the given value + * if such IAttribute exists. Otherwise, returns None. + * + *

Examples

+ *
+         * attributeType.Get(transaction, value).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param value IAttribute’s value + */ + Promise Get(ITypeDBTransaction transaction, long value); + + /** + * Retrieves an IAttribute of this IAttributeType with the given value + * if such IAttribute exists. Otherwise, returns None. + * + *

Examples

+ *
+         * attributeType.Get(transaction, value).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param value IAttribute’s value + */ + Promise Get(ITypeDBTransaction transaction, double value); + + /** + * Retrieves an IAttribute of this IAttributeType with the given value + * if such IAttribute exists. Otherwise, returns None. + * + *

Examples

+ *
+         * attributeType.Get(transaction, value).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param value IAttribute’s value + */ + Promise Get(ITypeDBTransaction transaction, bool value); + + /** + * Retrieves an IAttribute of this IAttributeType with the given value + * if such IAttribute exists. Otherwise, returns None. + * + *

Examples

+ *
+         * attributeType.Get(transaction, value).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param value IAttribute’s value + */ + Promise Get(ITypeDBTransaction transaction, System.DateTime value); + + /** + * Retrieves the regular expression that is defined for this IAttributeType. + * + *

Examples

+ *
+         * attributeType.GetRegex(transaction).Resolve();
+         * 
+ * + * @param transaction The current transaction + */ + Promise GetRegex(ITypeDBTransaction transaction); + + /** + * Sets a regular expression as a constraint for this IAttributeType. Values + * of all IAttributes of this type (inserted earlier or later) should match this regex. + *

Can only be applied for IAttributeTypes with a string value type.

+ * + *

Examples

+ *
+         * attributeType.SetRegex(transaction, regex).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param regex Regular expression + */ + VoidPromise SetRegex(ITypeDBTransaction transaction, string regex); + + /** + * Removes the regular expression that is defined for this IAttributeType. + * + *

Examples

+ *
+         * attributeType.UnsetRegex(transaction).Resolve();
+         * 
+ * + * @param transaction The current transaction + */ + VoidPromise UnsetRegex(ITypeDBTransaction transaction); + + /** + * Returns True if the value for attributes of this type is of type bool. + * Otherwise, returns False. + * + *

Examples

+ *
+         * attributeType.IsBool();
+         * 
+ */ + bool IsBool() + { + return ValueType == IValue.ValueType.Bool; + } + + /** + * Returns True if the value for attributes of this type is of type long. + * Otherwise, returns False. + * + *

Examples

+ *
+         * attributeType.IsLong();
+         * 
+ */ + bool IsLong() + { + return ValueType == IValue.ValueType.Long; + } + + /** + * Returns True if the value for attributes of this type is of type double. + * Otherwise, returns False. + * + *

Examples

+ *
+         * attributeType.IsDouble();
+         * 
+ */ + bool IsDouble() + { + return ValueType == IValue.ValueType.Double; + } + + /** + * Returns True if the value for attributes of this type is of type string. + * Otherwise, returns False. + * + *

Examples

+ *
+         * attributeType.IsString();
+         * 
+ */ + bool IsString() + { + return ValueType == IValue.ValueType.String; + } + + /** + * Returns True if the value for attributes of this type is of type datetime. + * Otherwise, returns False. + * + *

Examples

+ *
+         * attributeType.IsDateTime();
+         * 
+ */ + bool IsDateTime() + { + return ValueType == IValue.ValueType.DateTime; + } + + /** + * Sets the supplied IAttributeType as the supertype of the current IAttributeType. + * + *

Examples

+ *
+         * attributeType.SetSupertype(transaction, superType).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param attributeType The IAttributeType to set as the supertype of this IAttributeType + */ + VoidPromise SetSupertype(ITypeDBTransaction transaction, IAttributeType attributeType); + + /** + * Retrieves all direct and indirect subtypes of this IAttributeType + * with given IValue.ValueType. + * + *

Examples

+ *
+         * attributeType.GetSubtypes(transaction, valueType);
+         * 
+ * + * @param transaction The current transaction + * @param valueType IValue.ValueType for retrieving subtypes + */ + IEnumerable GetSubtypes(ITypeDBTransaction transaction, IValue.ValueType valueType); + + /** + * Retrieves all direct and indirect (or direct only) subtypes of this IAttributeType + * with given IValue.ValueType. + * + *

Examples

+ *
+         * attributeType.GetSubtypes(transaction, valueType, transitivity);
+         * 
+ * + * @param transaction The current transaction + * @param valueType IValue.ValueType for retrieving subtypes + * @param transitivity Transitive for direct and indirect subtypes, + * Explicit for direct subtypes only + */ + IEnumerable GetSubtypes( + ITypeDBTransaction transaction, + IValue.ValueType valueType, + IConcept.Transitivity transitivity); + + /** + * Retrieve all Things that own an attribute of this IAttributeType + * directly or through inheritance. + * + *

Examples

+ *
+         * attributeType.GetOwners(transaction);
+         * 
+ * + * @param transaction The current transaction + */ + IEnumerable GetOwners(ITypeDBTransaction transaction); + + /** + * Retrieve all Things that own an attribute of this IAttributeType, + * filtered by Annotations, directly or through inheritance. + * + *

Examples

+ *
+         * attributeType.GetOwners(transaction, annotations);
+         * 
+ * + * @param transaction The current transaction + * @param annotations Only retrieve ThingTypes that have an attribute of this + * IAttributeType with all given Annotations + */ + IEnumerable GetOwners(ITypeDBTransaction transaction, ICollection annotations); + + /** + * Retrieve all Things that own an attribute of this IAttributeType. + * + *

Examples

+ *
+         * attributeType.GetOwners(transaction, transitivity);
+         * 
+ * + * @param transaction The current transaction + * @param transitivity Transitive for direct and inherited ownership, + * Explicit for direct ownership only + */ + IEnumerable GetOwners( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity); + + /** + * Retrieve all Things that own an attribute of this IAttributeType, + * filtered by Annotations. + * + *

Examples

+ *
+         * attributeType.GetOwners(transaction, annotations, transitivity);
+         * 
+ * + * @param transaction The current transaction + * @param annotations Only retrieve ThingTypes that have an attribute of this + * IAttributeType with all given Annotations + * @param transitivity Transitive for direct and inherited ownership, + * Explicit for direct ownership only + */ + IEnumerable GetOwners( + ITypeDBTransaction transaction, + ICollection annotations, + IConcept.Transitivity transitivity); + } +} diff --git a/csharp/Api/Concept/Type/IEntityType.cs b/csharp/Api/Concept/Type/IEntityType.cs new file mode 100644 index 0000000000..3de8f33fb0 --- /dev/null +++ b/csharp/Api/Concept/Type/IEntityType.cs @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Api +{ + /** + * Entity types represent the classification of independent objects in the data model of the business domain. + */ + public interface IEntityType : IThingType + { + /** + * {@inheritDoc} + */ + bool IConcept.IsEntityType() + { + return true; + } + + /** + * {@inheritDoc} + */ + IEntityType IConcept.AsEntityType() + { + return this; + } + + /** + * Creates and returns a new instance of this IEntityType. + * + *

Examples

+ *
+         * entityType.Create(transaction).Resolve();
+         * 
+ * + * @param transaction The current transaction + */ + Promise Create(ITypeDBTransaction transaction); + + /** + * Sets the supplied IEntityType as the supertype of the current IEntityType. + * + *

Examples

+ *
+         * entityType.SetSupertype(transaction, entityType).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param superEntityType The IEntityType to set as the supertype of this IEntityType + */ + VoidPromise SetSupertype(ITypeDBTransaction transaction, IEntityType superEntityType); + } +} diff --git a/csharp/Api/Concept/Type/IRelationType.cs b/csharp/Api/Concept/Type/IRelationType.cs new file mode 100644 index 0000000000..4692823e25 --- /dev/null +++ b/csharp/Api/Concept/Type/IRelationType.cs @@ -0,0 +1,183 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Api +{ + /** + * Relation types (or subtypes of the relation root type) represent relationships between types. Relation types have roles. + * Other types can play roles in relations if it’s mentioned in their definition. + * A relation type must specify at least one role. + */ + public interface IRelationType : IThingType + { + /** + * {@inheritDoc} + */ + bool IConcept.IsRelationType() + { + return true; + } + + /** + * {@inheritDoc} + */ + IRelationType IConcept.AsRelationType() + { + return this; + } + + /** + * Creates and returns an instance of this IRelationType. + * + *

Examples

+ *
+         * relationType.Create(transaction).Resolve();
+         * 
+ * + * @param transaction The current transaction + */ + Promise Create(ITypeDBTransaction transaction); + + /** + * Retrieves roles that this IRelationType relates to directly or via inheritance. + * + * @see IRelationType#getRelates(ITypeDBTransaction, IConcept.Transitivity) + */ + IEnumerable GetRelates(ITypeDBTransaction transaction); + + /** + * Retrieves roles that this IRelationType relates to directly or via inheritance. + * + *

Examples

+ *
+         * relationType.GetRelates(transaction, transitivity);
+         * 
+ * + * @param transaction The current transaction + * @param transitivity Transitive for direct and inherited relates, + * Explicit for direct relates only + */ + IEnumerable GetRelates(ITypeDBTransaction transaction, IConcept.Transitivity transitivity); + + /** + * Retrieves roles that this IRelationType relates to directly or via inheritance. + * If role_label is given, returns a corresponding IRoleType or null. + * + *

Examples

+ *
+         * relationType.GetRelates(transaction, roleLabel).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param roleLabel Label of the role we wish to retrieve + */ + Promise GetRelates(ITypeDBTransaction transaction, string roleLabel); + + /** + * Retrieves a IRoleType that is overridden by the role with the role_label. + * + * @see IRelationType#GetRelatesOverridden(ITypeDBTransaction, string) + */ + Promise GetRelatesOverridden(ITypeDBTransaction transaction, IRoleType roleType); + + /** + * Retrieves a IRoleType that is overridden by the role with the role_label. + * + *

Examples

+ *
+         * relationType.GetRelatesOverridden(transaction, roleLabel).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param roleLabel Label of the role that overrides an inherited role + */ + Promise GetRelatesOverridden(ITypeDBTransaction transaction, string roleLabel); + + /** + * Sets the new role that this IRelationType relates to. + * + * @see IRelationType#SetRelates(ITypeDBTransaction, string, string) + */ + VoidPromise SetRelates(ITypeDBTransaction transaction, string roleLabel); + + /** + * Sets the new role that this IRelationType relates to. + * + * @see IRelationType#SetRelates(ITypeDBTransaction, string, string) + */ + VoidPromise SetRelates(ITypeDBTransaction transaction, string roleLabel, IRoleType overriddenType); + + /** + * Sets the new role that this IRelationType relates to. + * If we are setting an overriding type this way, we have to also pass the overridden type as a second argument. + * + *

Examples

+ *
+         * relationType.SetRelates(transaction, roleLabel).Resolve();
+         * relationType.SetRelates(transaction, roleLabel, overriddenLabel).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param roleLabel The new role for the IRelationType to relate to + * @param overriddenLabel The label being overridden, if applicable + */ + VoidPromise SetRelates(ITypeDBTransaction transaction, string roleLabel, string? overriddenLabel); + + /** + * Disallows this IRelationType from relating to the given role. + * + * @see IRelationType#UnsetRelates(ITypeDBTransaction, string) + */ + VoidPromise UnsetRelates(ITypeDBTransaction transaction, IRoleType roleType); + + /** + * Disallows this IRelationType from relating to the given role. + * + *

Examples

+ *
+         * relationType.UnsetRelates(transaction, roleLabel).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param roleLabel The role to not relate to the relation type. + */ + VoidPromise UnsetRelates(ITypeDBTransaction transaction, string roleLabel); + + /** + * Sets the supplied IRelationType as the supertype of the current IRelationType. + * + *

Examples

+ *
+         * relationType.SetSupertype(transaction, superRelationType).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param superRelationType The IRelationType to set as the supertype of this IRelationType + */ + VoidPromise SetSupertype(ITypeDBTransaction transaction, IRelationType superRelationType); + } +} diff --git a/csharp/Api/Concept/Type/IRoleType.cs b/csharp/Api/Concept/Type/IRoleType.cs new file mode 100644 index 0000000000..31060a74b9 --- /dev/null +++ b/csharp/Api/Concept/Type/IRoleType.cs @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Api +{ + /** + * Roles are special internal types used by relations. We can not create an instance of a role in a database. But we can set an instance of another type (role player) to play a role in a particular instance of a relation type. + * Roles allow a schema to enforce logical constraints on types of role players. + */ + public interface IRoleType : IType + { + /** + * {@inheritDoc} + */ + bool IConcept.IsRoleType() + { + return true; + } + + /** + * {@inheritDoc} + */ + IRoleType IConcept.AsRoleType() + { + return this; + } + + /** + * Retrieves RelationTypes that this role is related to (directly or indirectly). + * + *

Examples

+ *
+         * roleType.GetRelationTypes(transaction);
+         * 
+ * + * @param transaction The current transaction + */ + IEnumerable GetRelationTypes(ITypeDBTransaction transaction); + + /** + * Retrieves the ThingTypes whose instances play this role. + * Equivalent to GetPlayerTypes(transaction, Transitive). + * + * @see IRoleType#GetPlayerTypes(ITypeDBTransaction, IConcept.Transitivity) + */ + IEnumerable GetPlayerTypes(ITypeDBTransaction transaction); + + /** + * Retrieves the ThingTypes whose instances play this role. + * + *

Examples

+ *
+         * roleType.GetPlayerTypes(transaction, transitivity)
+         * 
+ * + * @param transaction The current transaction + * @param transitivity Transitive for direct and indirect playing, + * Explicit for direct playing only + */ + IEnumerable GetPlayerTypes(ITypeDBTransaction transaction, IConcept.Transitivity transitivity); + + /** + * Retrieves the Relation instances that this role is related to. + * Equivalent to GetRelationInstances(transaction, Transitive) + * + * @see IRoleType#GetRelationInstances(ITypeDBTransaction, IConcept.Transitivity) + */ + IEnumerable GetRelationInstances(ITypeDBTransaction transaction); + + /** + * Retrieves the Relation instances that this role is related to. + * + *

Examples

+ *
+         * roleType.GetRelationInstances(transaction, transitivity)
+         * 
+ * + * @param transaction The current transaction + * @param transitivity Transitive for direct and indirect relation, Explicit for direct relation only + */ + IEnumerable GetRelationInstances( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity); + + /** + * Retrieves the Thing instances that play this role. + * + * @see IRoleType#GetPlayerInstances(ITypeDBTransaction, IConcept.Transitivity) + */ + IEnumerable GetPlayerInstances(ITypeDBTransaction transaction); + + /** + * Retrieves the Thing instances that play this role. + * + *

Examples

+ *
+         * roleType.GetPlayerInstances(transaction, transitivity);
+         * 
+ * + * @param transaction The current transaction + * @param transitivity Transitive for direct and indirect playing, + * Explicit for direct playing only + */ + IEnumerable GetPlayerInstances(ITypeDBTransaction transaction, IConcept.Transitivity transitivity); + } +} diff --git a/csharp/Api/Concept/Type/IThingType.cs b/csharp/Api/Concept/Type/IThingType.cs new file mode 100644 index 0000000000..bd923f51b8 --- /dev/null +++ b/csharp/Api/Concept/Type/IThingType.cs @@ -0,0 +1,452 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using System.Collections.Generic; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Api +{ + public interface IThingType : IType + { + /** + * {@inheritDoc} + */ + bool IConcept.IsThingType() + { + return true; + } + + /** + * {@inheritDoc} + */ + IThingType IConcept.AsThingType() + { + return this; + } + + /** + * Retrieves all IThing objects that are instances of this IThingType or its subtypes. + * Equivalent to GetInstances(transaction, Transitive) + * + * @see ThingType#GetInstances(ITypeDBTransaction, IConcept.Transitivity) + */ + IEnumerable GetInstances(ITypeDBTransaction transaction); + + /** + * Retrieves IThing objects that are instances of this exact IThingType, OR + * this IThingType and any of its subtypes + * + *

Examples

+ *
+         * thingType.GetInstances(transaction);
+         * thingType.GetInstances(transaction, Explicit);
+         * 
+ * + * @param transaction The current transaction + * @param transitivity Explicit for direct instances only, Transitive to include instances of subtypes + */ + IEnumerable GetInstances(ITypeDBTransaction transaction, IConcept.Transitivity transitivity); + + /** + * Set a IThingType to be abstract, meaning it cannot have instances. + * + *

Examples

+ *
+         * thingType.SetAbstract(transaction).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @return + */ + VoidPromise SetAbstract(ITypeDBTransaction transaction); + + /** + * Set a IThingType to be non-abstract, meaning it can have instances. + * + *

Examples

+ *
+         * thingType.UnsetAbstract(transaction).Resolve();
+         * 
+ * + * @param transaction The current transaction + */ + VoidPromise UnsetAbstract(ITypeDBTransaction transaction); + + /** + * Allows the instances of this IThingType to play the given role. + * + * @see ThingType#SetPlays(ITypeDBTransaction, IRoleType, IRoleType) + */ + VoidPromise SetPlays(ITypeDBTransaction transaction, IRoleType roleType); + + /** + * Allows the instances of this IThingType to play the given role. + * + *

Examples

+ *
+         * thingType.SetPlays(transaction, roleType).Resolve();
+         * thingType.SetPlays(transaction, roleType, overriddenType).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param roleType The role to be played by the instances of this type + * @param overriddenType The role type that this role overrides, if applicable + */ + VoidPromise SetPlays(ITypeDBTransaction transaction, IRoleType roleType, IRoleType overriddenType); + + /** + * Allows the instances of this IThingType to own the given IAttributeType. + * Optionally, overriding a previously declared ownership. + * Optionally, adds annotations to the ownership. + * + *

Examples

+ *
+         * thingType.SetOwns(transaction, attributeType).Resolve();
+         * thingType.SetOwns(transaction, attributeType, overriddenType, new []{NewKey()}).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param attributeType The IAttributeType to be owned by the instances of this type. + * @param overriddenType The IAttributeType that this attribute ownership overrides, if applicable. + * @param annotations Adds annotations to the ownership. + */ + VoidPromise SetOwns( + ITypeDBTransaction transaction, + IAttributeType attributeType, + IAttributeType? overriddenType, + ICollection annotations); + + /** + * Allows the instances of this IThingType to own the given IAttributeType, + * + * @see ThingType#SetOwns(ITypeDBTransaction, IAttributeType, IAttributeType, Set) + */ + VoidPromise SetOwns( + ITypeDBTransaction transaction, IAttributeType attributeType, IAttributeType overriddenType); + + /** + * Allows the instances of this IThingType to own the given IAttributeType. + * + * @see ThingType#SetOwns(ITypeDBTransaction, IAttributeType, IAttributeType, Set) + */ + VoidPromise SetOwns(ITypeDBTransaction transaction, IAttributeType attributeType, ICollection annotations); + + /** + * Allows the instances of this IThingType to own the given IAttributeType. + * + * @see ThingType#SetOwns(ITypeDBTransaction, IAttributeType, IAttributeType, Set) + */ + VoidPromise SetOwns(ITypeDBTransaction transaction, IAttributeType attributeType); + + /** + * Retrieves all direct and inherited roles that are allowed + * to be played by the instances of this IThingType. + * + * @see ThingType#GetPlays(ITypeDBTransaction, IConcept.Transitivity) + */ + IEnumerable GetPlays(ITypeDBTransaction transaction); + + /** + * Retrieves all direct and inherited (or direct only) roles that are allowed + * to be played by the instances of this IThingType. + * + *

Examples

+ *
+         * thingType.GetPlays(transaction).Resolve();
+         * thingType.GetPlays(transaction, Explicit).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param transitivity transitivity: Transitive for direct and indirect playing, + * Explicit for direct playing only + */ + IEnumerable GetPlays(ITypeDBTransaction transaction, IConcept.Transitivity transitivity); + + /** + * Retrieves a IRoleType that is overridden by the given + * role_type for this IThingType. + * + *

Examples

+ *
+         * thingType.GetPlaysOverridden(transaction, roleType).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param roleType The IRoleType that overrides an inherited role + */ + Promise GetPlaysOverridden(ITypeDBTransaction transaction, IRoleType roleType); + + /** + * Retrieves IAttributeType that the instances of this + * IThingType are allowed to own directly or via inheritance. + * + * @see ThingType#GetOwns(ITypeDBTransaction, IValue.ValueType, ICollection<Annotation>, IConcept.Transitivity) + */ + IEnumerable GetOwns(ITypeDBTransaction transaction); + + /** + * Retrieves IAttributeType that the instances of this + * IThingType are allowed to own directly or via inheritance. + * + * @see ThingType#GetOwns(ITypeDBTransaction, IValue.ValueType, ICollection<Annotation>, IConcept.Transitivity) + */ + IEnumerable GetOwns(ITypeDBTransaction transaction, IValue.ValueType valueType); + + /** + * Retrieves IAttributeType that the instances of this + * IThingType are allowed to own directly or via inheritance. + * + * @see ThingType#GetOwns(ITypeDBTransaction, IValue.ValueType, ICollection<Annotation>, IConcept.Transitivity) + */ + IEnumerable GetOwns(ITypeDBTransaction transaction, ICollection annotations); + + /** + * Retrieves IAttributeType that the instances of this + * IThingType are allowed to own directly or via inheritance. + * + * @see ThingType#GetOwns(ITypeDBTransaction, IValue.ValueType?, ICollection<Annotation>, IConcept.Transitivity) + */ + IEnumerable GetOwns( + ITypeDBTransaction transaction, IValue.ValueType? valueType, ICollection annotations); + + /** + * Retrieves IAttributeType that the instances of this + * IThingType are allowed to own directly or via inheritance. + * + * @see ThingType#GetOwns(ITypeDBTransaction, IValue.ValueType, ICollection<Annotation>, IConcept.Transitivity) + */ + IEnumerable GetOwns(ITypeDBTransaction transaction, IConcept.Transitivity transitivity); + + /** + * Retrieves IAttributeType that the instances of this + * IThingType are allowed to own directly or via inheritance. + * + * @see ThingType#GetOwns(ITypeDBTransaction, IValue.ValueType?, ICollection<Annotation>, IConcept.Transitivity) + */ + IEnumerable GetOwns( + ITypeDBTransaction transaction, IValue.ValueType? valueType, IConcept.Transitivity transitivity); + + /** + * Retrieves IAttributeType that the instances of this + * IThingType are allowed to own directly or via inheritance. + * + * @see ThingType#GetOwns(ITypeDBTransaction, IValue.ValueType, ICollection<Annotation>, IConcept.Transitivity) + */ + IEnumerable GetOwns( + ITypeDBTransaction transaction, ICollection annotations, IConcept.Transitivity transitivity); + + /** + * Retrieves IAttributeType that the instances of this + * IThingType are allowed to own directly or via inheritance. + * + *

Examples

+ *
+         * thingType.GetOwns(transaction);
+         * thingType.GetOwns(transaction, valueType, Explicit, new []{NewKey()}));
+         * 
+ * + * @param transaction The current transaction + * @param valueType If specified, only attribute types of this ValueType will be retrieved. + * @param transitivity Transitive for direct and inherited ownership, + * Explicit for direct ownership only + * @param annotations Only retrieve attribute types owned with annotations. + */ + IEnumerable GetOwns( + ITypeDBTransaction transaction, + IValue.ValueType? valueType, + ICollection annotations, + IConcept.Transitivity transitivity); + + /** + * Retrieves an IAttributeType, ownership of which is overridden + * for this IThingType by a given IAttributeType. + * + *

Examples

+ *
+         * thingType.GetOwnsOverridden(transaction, attributeType).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param attributeType The IAttributeType that overrides requested IAttributeType + */ + Promise GetOwnsOverridden(ITypeDBTransaction transaction, IAttributeType attributeType); + + /** + * Disallows the instances of this IThingType from playing the given role. + * + *

Examples

+ *
+         * thingType.UnsetPlays(transaction, roleType).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param roleType The role to not be played by the instances of this type. + */ + VoidPromise UnsetPlays(ITypeDBTransaction transaction, IRoleType roleType); + + /** + * Disallows the instances of this IThingType from owning the given IAttributeType. + * + *

Examples

+ *
+         * thingType.UnsetOwns(transaction, attributeType).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param attributeType The IAttributeType to not be owned by the type. + */ + VoidPromise UnsetOwns(ITypeDBTransaction transaction, IAttributeType attributeType); + + /** + * Produces a pattern for creating this IThingType in a define query. + * + *

Examples

+ *
+         * thingType.GetSyntax(transaction).Resolve();
+         * 
+ * + * @param transaction The current transaction + */ + Promise GetSyntax(ITypeDBTransaction transaction); + + /** + * Annotation + */ + public class Annotation : NativeObjectWrapper + { + /** + * @hidden + */ + private readonly int _hash; + + private Annotation(Pinvoke.Annotation annotation) + : base(annotation) + { + _hash = (IsKey(), IsUnique()).GetHashCode(); + } + + /** + * Produces a @key annotation. + * + *

Examples

+ *
+             * using static TypeDB.Driver.Api.IThingType.Annotation;
+             * NewKey();
+             * 
+ */ + public static Annotation NewKey() + { + return new Annotation(Pinvoke.typedb_driver.annotation_new_key()); + } + + /** + * Produces a @unique annotation. + * + *

Examples

+ *
+             * Annotation.NewUnique();
+             * 
+ */ + public static Annotation NewUnique() + { + return new Annotation(Pinvoke.typedb_driver.annotation_new_unique()); + } + + /** + * Checks if this Annotation is a @key annotation. + * + *

Examples

+ *
+             * annotation.IsKey();
+             * 
+ */ + public bool IsKey() + { + return Pinvoke.typedb_driver.annotation_is_key(NativeObject); + } + + /** + * Checks if this Annotation is a @unique annotation. + * + *

Examples

+ *
+             * annotation.IsUnique();
+             * 
+ */ + public bool IsUnique() + { + return Pinvoke.typedb_driver.annotation_is_unique(NativeObject); + } + + /** + * Retrieves a string representation of this Annotation. + * + *

Examples

+ *
+             * annotation.ToString();
+             * 
+ */ + public override string ToString() + { + return Pinvoke.typedb_driver.annotation_to_string(NativeObject); + } + + /** + * Checks if this Annotation is equal to another object. + * + *

Examples

+ *
+             * annotation.Equals(obj);
+             * 
+ * + * @param obj Object to compare with + */ + public override bool Equals(object? obj) + { + if (Object.ReferenceEquals(this, obj)) + { + return true; + } + + if (obj == null || this.GetType() != obj.GetType()) + { + return false; + } + + Annotation that = (Annotation)obj; + + return Pinvoke.typedb_driver.annotation_equals(this.NativeObject, that.NativeObject); + } + + /** + * @hidden + */ + public override int GetHashCode() + { + return _hash; + } + } + } +} diff --git a/csharp/Api/Concept/Type/IType.cs b/csharp/Api/Concept/Type/IType.cs new file mode 100644 index 0000000000..8bea0eb206 --- /dev/null +++ b/csharp/Api/Concept/Type/IType.cs @@ -0,0 +1,162 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using System.Collections.Generic; + +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Api +{ + public interface IType : IConcept + { + /** + * The unique label of the type. + * + *

Examples

+ *
+         * type.Label;
+         * 
+ */ + Label Label { get; } + + /** + * Checks if the type is a root type. + * + *

Examples

+ *
+         * type.IsRoot();
+         * 
+ */ + bool IsRoot(); + + /** + * Checks if the type is prevented from having data instances (i.e., abstract). + * + *

Examples

+ *
+         * type.IsAbstract();
+         * 
+ */ + bool IsAbstract(); + + /** + * {@inheritDoc} + */ + bool IConcept.IsType() + { + return true; + } + + /** + * {@inheritDoc} + */ + IType IConcept.AsType() + { + return this; + } + + /** + * Renames the label of the type. The new label must remain unique. + * + *

Examples

+ *
+         * type.SetLabel(transaction, newLabel).Resolve();
+         * 
+ * + * @param transaction The current transaction + * @param label The new Label to be given to the type. + */ + VoidPromise SetLabel(ITypeDBTransaction transaction, string label); + + /** + * Retrieves the most immediate supertype of the type. + * + *

Examples

+ *
+         * type.GetSupertype(transaction).Resolve();
+         * 
+ * + * @param transaction The current transaction + */ + Promise GetSupertype(ITypeDBTransaction transaction); + + /** + * Retrieves all supertypes of the type. + * + *

Examples

+ *
+         * type.GetSupertypes(transaction);
+         * 
+ * + * @param transaction The current transaction + */ + IEnumerable GetSupertypes(ITypeDBTransaction transaction); + + /** + * Retrieves all direct and indirect subtypes of the type. + * Equivalent to GetSubtypes(transaction, Transitive) + * + * @see Type#GetSubtypes(ITypeDBTransaction, IConcept.Transitivity) + */ + IEnumerable GetSubtypes(ITypeDBTransaction transaction); + + /** + * Retrieves all direct and indirect (or direct only) subtypes of the type. + * + *

Examples

+ *
+         * type.GetSubtypes(transaction);
+         * type.GetSubtypes(transaction, Explicit);
+         * 
+ * + * @param transaction The current transaction + * @param transitivity Transitive for direct and indirect subtypes, + * Explicit for direct subtypes only + */ + IEnumerable GetSubtypes(ITypeDBTransaction transaction, IConcept.Transitivity transitivity); + + /** + * Deletes this type from the database. + * + *

Examples

+ *
+         * type.Delete(transaction).Resolve();
+         * 
+ * + * @param transaction The current transaction + */ + VoidPromise Delete(ITypeDBTransaction transaction); + + /** + * Check if the concept has been deleted. + * + *

Examples

+ *
+         * type.IsDeleted(transaction).Resolve();
+         * 
+ * + * @param transaction The current transaction + */ + Promise IsDeleted(ITypeDBTransaction transaction); + } +} diff --git a/csharp/Api/Concept/Value/IValue.cs b/csharp/Api/Concept/Value/IValue.cs new file mode 100644 index 0000000000..4174cfee9e --- /dev/null +++ b/csharp/Api/Concept/Value/IValue.cs @@ -0,0 +1,275 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using InternalError = TypeDB.Driver.Common.Error.Internal; + +namespace TypeDB.Driver.Api +{ + public interface IValue : IConcept + { + /** + * {@inheritDoc} + */ + bool IConcept.IsValue() + { + return true; + } + + /** + * {@inheritDoc} + */ + IValue IConcept.AsValue() + { + return this; + } + + /** + * Retrieves the IValue.ValueType of this value concept. + * + *

Examples

+ *
+         * value.Type;
+         * 
+ */ + ValueType Type { get; } + + /** + * Returns True if the value which this value concept holds is of type bool. + * Otherwise, returns false. + * + *

Examples

+ *
+         * value.IsBool();
+         * 
+ */ + bool IsBool(); + + /** + * Returns True if the value which this value concept holds is of type long. + * Otherwise, returns false. + * + *

Examples

+ *
+         * value.IsLong();
+         * 
+ */ + bool IsLong(); + + /** + * Returns True if the value which this value concept holds is of type double. + * Otherwise, returns false. + * + *

Examples

+ *
+         * value.IsDouble();
+         * 
+ */ + bool IsDouble(); + + /** + * Returns True if the value which this value concept holds is of type string. + * Otherwise, returns false. + * + *

Examples

+ *
+         * value.IsString();
+         * 
+ */ + bool IsString(); + + /** + * Returns True if the value which this value concept holds is of type datetime. + * Otherwise, returns false. + * + *

Examples

+ *
+         * value.IsDateTime();
+         * 
+ */ + bool IsDateTime(); + + /** + * Returns an untyped object value of this value concept. + * This is useful for value equality or printing without having to switch on the actual contained value. + * + *

Examples

+ *
+         * value.AsUntyped();
+         * 
+ */ + object AsUntyped(); + + /** + * Returns a bool value of this value concept. + * If the value has another type, raises an exception. + * + *

Examples

+ *
+         * value.AsBool();
+         * 
+ */ + bool AsBool(); + + /** + * Returns a long value of this value concept. If the value has another type, raises an exception. + * + *

Examples

+ *
+         * value.AsLong();
+         * 
+ */ + long AsLong(); + + /** + * Returns a double value of this value concept. + * If the value has another type, raises an exception. + * + *

Examples

+ *
+         * value.AsDouble();
+         * 
+ */ + double AsDouble(); + + /** + * Returns a string value of this value concept. If the value has another type, raises an exception. + * + *

Examples

+ *
+         * value.AsString();
+         * 
+ */ + string AsString(); + + /** + * Returns a datetime value of this value concept. + * This value contains raw date and time without considering your time zone (Kind = Unspecified). + * If the value has another type, raises an exception. + * + *

Examples

+ *
+         * value.AsDateTime();
+         * 
+ */ + System.DateTime AsDateTime(); + + public enum ValueType + { + Object = Pinvoke.ValueType.Object, + Bool = Pinvoke.ValueType.Boolean, + Long = Pinvoke.ValueType.Long, + Double = Pinvoke.ValueType.Double, + String = Pinvoke.ValueType.String, + DateTime = Pinvoke.ValueType.DateTime, + } + } + + public static class ValueTypeExtensions + { + /** + * Returns a System.Type equivalent of this value concept for this programming language. + * + *

Examples

+ *
+         * valueType.GetValueClass();
+         * 
+ */ + public static System.Type GetValueClass(this IValue.ValueType valueType) + { + switch (valueType) + { + case IValue.ValueType.Object: + return typeof(object); + case IValue.ValueType.Bool: + return typeof(bool); + case IValue.ValueType.Long: + return typeof(long); + case IValue.ValueType.Double: + return typeof(double); + case IValue.ValueType.String: + return typeof(string); + case IValue.ValueType.DateTime: + return typeof(System.DateTime); + default: + throw new TypeDBDriverException(InternalError.UNEXPECTED_INTERNAL_VALUE, valueType); + } + } + + /** + * Returns true if this value concept can be written to a database. + * Otherwise, returns false. + * + *

Examples

+ *
+         * valueType.IsWritable();
+         * 
+ */ + public static bool IsWritable(this IValue.ValueType valueType) + { + switch (valueType) + { + case IValue.ValueType.Object: + return false; + case IValue.ValueType.Bool: + case IValue.ValueType.Long: + case IValue.ValueType.Double: + case IValue.ValueType.String: + case IValue.ValueType.DateTime: + return true; + default: + throw new TypeDBDriverException(InternalError.UNEXPECTED_INTERNAL_VALUE, valueType); + } + } + + /** + * Returns true if this value concept can be used as a key via the @key annotation. + * Otherwise, returns false. + * + *

Examples

+ *
+         * valueType.IsKeyable();
+         * 
+ */ + public static bool IsKeyable(this ValueType valueType) + { + switch (valueType) + { + case IValue.ValueType.Object: + case IValue.ValueType.Bool: + case IValue.ValueType.Double: + return false; + case IValue.ValueType.Long: + case IValue.ValueType.String: + case IValue.ValueType.DateTime: + return true; + default: + throw new TypeDBDriverException(InternalError.UNEXPECTED_INTERNAL_VALUE, valueType); + } + } + } +} diff --git a/csharp/Api/Database/IDatabase.cs b/csharp/Api/Database/IDatabase.cs new file mode 100644 index 0000000000..6491b4b397 --- /dev/null +++ b/csharp/Api/Database/IDatabase.cs @@ -0,0 +1,138 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +namespace TypeDB.Driver.Api +{ + public interface IDatabase + { + /** + * The database name as a string. + * + *

Examples

+ *
+         * database.Name;
+         * 
+ */ + public string Name { get; } + + /** + * A full schema text as a valid TypeQL define query string. + * + *

Examples

+ *
+         * database.GetSchema();
+         * 
+ */ + public string GetSchema(); + + /** + * The types in the schema as a valid TypeQL define query string. + * + *

Examples

+ *
+         * database.GetTypeSchema();
+         * 
+ */ + public string GetTypeSchema(); + + /** + * The rules in the schema as a valid TypeQL define query string. + * + *

Examples

+ *
+         * database.GetRuleSchema();
+         * 
+ */ + public string GetRuleSchema(); + + /** + * Set of Replica instances for this database. + * Only works in TypeDB Cloud + * + *

Examples

+ *
+         * database.GetReplicas();
+         * 
+ */ + public ISet GetReplicas(); + + /** + * Returns the primary replica for this database. + * _Only works in TypeDB Cloud_ + * + *

Examples

+ *
+         * database.PrimaryReplica;
+         * 
+ */ + public IReplica? PrimaryReplica { get; } + + /** + * Returns the preferred replica for this database. Operations which can be run on any replica will prefer to use this replica. + * _Only works in TypeDB Cloud_ + * + *

Examples

+ *
+         * database.PreferredReplica;
+         * 
+ */ + public IReplica? PreferredReplica { get; } + + /** + * Deletes this database. + * + *

Examples

+ *
+         * database.Delete();
+         * 
+ */ + public void Delete(); + + /** + * The metadata and state of an individual raft replica of a database. + */ + public interface IReplica + { + /** + * Retrieves the address of the server hosting this replica. + */ + public string Address { get; } + + /** + * The raft protocol ‘term’ of this replica. + */ + public long Term { get; } + + /** + * Checks whether this is the primary replica of the raft cluster. + */ + public bool IsPrimary(); + + /** + * Checks whether this is the preferred replica of the raft cluster. + * If true, Operations which can be run on any replica will prefer to use this replica. + */ + public bool IsPreferred(); + } + } +} diff --git a/csharp/Api/Database/IDatabaseManager.cs b/csharp/Api/Database/IDatabaseManager.cs new file mode 100644 index 0000000000..a3d99d9e87 --- /dev/null +++ b/csharp/Api/Database/IDatabaseManager.cs @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver.Api; + +namespace TypeDB.Driver.Api +{ + /** + * Provides access to all database management methods. + */ + public interface IDatabaseManager + { + /** + * Retrieve the database with the given name. + * + *

Examples

+ *
+         * driver.Databases.Get(name);
+         * 
+ * + * @param name The name of the database to retrieve + */ + IDatabase Get(string name); + + /** + * Checks if a database with the given name exists. + * + *

Examples

+ *
+         * driver.Databases.Contains(name);
+         * 
+ * + * @param name The database name to be checked + */ + bool Contains(string name); + + /** + * Create a database with the given name. + * + *

Examples

+ *
+         * driver.Databases.Create(name);
+         * 
+ * + * @param name The name of the database to be created + */ + void Create(string name); + + /** + * Retrieves all databases present on the TypeDB server. + * + *

Examples

+ *
+         * driver.Databases.GetAll();
+         * 
+ */ + IList GetAll(); + } +} diff --git a/csharp/Api/ITypeDBDriver.cs b/csharp/Api/ITypeDBDriver.cs new file mode 100644 index 0000000000..b70abe69d6 --- /dev/null +++ b/csharp/Api/ITypeDBDriver.cs @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; + +using TypeDB.Driver.Api; + +namespace TypeDB.Driver.Api +{ + public interface ITypeDBDriver : IDisposable + { + /** + * Checks whether this connection is presently open. + * + *

Examples

+ *
+         * driver.IsOpen();
+         * 
+ */ + bool IsOpen(); + + /** + * The IDatabaseManager for this connection, providing access to database management methods. + * + *

Examples

+ *
+         * driver.Databases;
+         * 
+ */ + IDatabaseManager Databases { get; } + + /** + * Returns the logged-in user for the connection. Only for TypeDB Cloud. + * + *

Examples

+ *
+         * driver.GetCurrentUser();
+         * 
+ */ + IUser GetCurrentUser(); + + /** + * The UserManager instance for this connection, providing access to user management methods. + * Only for TypeDB Cloud. + * + *

Examples

+ *
+         * driver.Users;
+         * 
+ */ + IUserManager Users { get; } + + /** + * Opens a session to the given database with default options. + * + * @see TypeDBDriver#Session(string, SessionType, TypeDBOptions); + */ + ITypeDBSession Session(string database, SessionType type); + + /** + * Opens a communication tunnel (session) to the given database on the running TypeDB server. + * For more information on the methods, available with sessions, see the ITypeDBSession section. + * + *

Examples

+ *
+         * driver.Session(database, sessionType, options);
+         * 
+ * + * @param database The name of the database with which the session connects + * @param type The type of session to be created (Data or Schema) + * @param options TypeDBOptions for the session + */ + ITypeDBSession Session(string database, SessionType type, TypeDBOptions options); + + /** + * Closes the driver. Before instantiating a new driver, the driver that’s currently open should first be closed. + * + *

Examples

+ *
+         * driver.Close();
+         * 
+ */ + void Close(); + } +} diff --git a/csharp/Api/ITypeDBSession.cs b/csharp/Api/ITypeDBSession.cs new file mode 100644 index 0000000000..b9714aa3a6 --- /dev/null +++ b/csharp/Api/ITypeDBSession.cs @@ -0,0 +1,145 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using System.Collections.Generic; + +using TypeDB.Driver; +using TypeDB.Driver.Common; + +using InternalError = TypeDB.Driver.Common.Error.Internal; + +namespace TypeDB.Driver.Api +{ + public interface ITypeDBSession : IDisposable + { + + /** + * Checks whether this session is open. + * + *

Examples

+ *
+         * session.IsOpen();
+         * 
+ */ + bool IsOpen(); + + /** + * The current session’s type (Schema or Data). + * + *

Examples

+ *
+         * session.Type;
+         * 
+ */ + SessionType Type { get; } + + /** + * Returns the name of the database of the session. + * + *

Examples

+ *
+         * session.DatabaseName;
+         * 
+ */ + string DatabaseName { get; } + + /** + * Gets the options for the session. + * + *

Examples

+ *
+         * session.Options;
+         * 
+ */ + TypeDBOptions Options { get; } + + /** + * Opens a transaction on the database connected to the session with default options. + * + * @see ITypeDBSession#Transaction(TransactionType, TypeDBOptions) + */ + ITypeDBTransaction Transaction(TransactionType type); + + /** + * Opens a transaction to perform read or write queries on the database connected to the session. + * + *

Examples

+ *
+         * session.Transaction(transactionType, options);
+         * 
+ * + * @param type The type of transaction to be created (Read or Write) + * @param options Options for the session + */ + ITypeDBTransaction Transaction(TransactionType type, TypeDBOptions options); + + /** + * Registers a callback function which will be executed when this session is closed. + * + *

Examples

+ *
+         * session.OnClose(function);
+         * 
+ * + * @param function The callback function. + */ + void OnClose(Action function); + + /** + * Registers a callback function which will be executed when this session is reopened. + * A session may be closed if it times out, or loses the connection to the database. + * In such situations, the session is reopened automatically when opening a new transaction. + * + *

Examples

+ *
+         * session.OnReopen(function);
+         * 
+ * + * @param function The callback function. + */ + void OnReopen(Action function); + + /** + * Closes the session. Before opening a new session, the session currently open should first be closed. + * + *

Examples

+ *
+         * session.Close();
+         * 
+ */ + void Close(); + } + + /** + * Used to specify the type of the session. + * + *

Examples

+ *
+     * driver.Session(database, SessionType.Schema);
+     * 
+ */ + public enum SessionType + { + Data = Pinvoke.SessionType.Data, + Schema = Pinvoke.SessionType.Schema, + } +} diff --git a/csharp/Api/ITypeDBTransaction.cs b/csharp/Api/ITypeDBTransaction.cs new file mode 100644 index 0000000000..56ce82e001 --- /dev/null +++ b/csharp/Api/ITypeDBTransaction.cs @@ -0,0 +1,150 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using System.Collections.Generic; + +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using InternalError = TypeDB.Driver.Common.Error.Internal; + +namespace TypeDB.Driver.Api +{ + public interface ITypeDBTransaction : IDisposable + { + /** + * The transaction’s type (Read or Write). + * + *

Examples

+ *
+         * transaction.Type;
+         * 
+ */ + TransactionType Type { get; } + + /** + * The options for the transaction. + * + *

Examples

+ *
+         * transaction.Options;
+         * 
+ */ + TypeDBOptions Options { get; } + + /** + * The ConceptManager for this transaction, providing access to all Concept API methods. + * + *

Examples

+ *
+         * transaction.Concepts;
+         * 
+ */ + IConceptManager Concepts { get; } + + /** + * The LogicManager for this Transaction, providing access to all Concept API - Logic methods. + * + *

Examples

+ *
+         * transaction.Logic;
+         * 
+ */ + ILogicManager Logic { get; } + + /** + * TheQueryManager for this Transaction, from which any TypeQL query can be executed. + * + *

Examples

+ *
+         * transaction.Query;
+         * 
+ */ + IQueryManager Query { get; } + + /** + * Checks whether this transaction is open. + * + *

Examples

+ *
+         * transaction.IsOpen();
+         * 
+ */ + bool IsOpen(); + + /** + * Registers a callback function which will be executed when this transaction is closed. + * + *

Examples

+ *
+         * transaction.OnClose(function);
+         * 
+ * + * @param function The callback function. + */ + void OnClose(Action function); + + /** + * Commits the changes made via this transaction to the TypeDB database. + * Whether or not the transaction is committed successfully, it gets closed after the commit call. + * + *

Examples

+ *
+         * transaction.Commit();
+         * 
+ */ + void Commit(); + + /** + * Rolls back the uncommitted changes made via this transaction. + * + *

Examples

+ *
+         * transaction.Rollback();
+         * 
+ */ + void Rollback(); + + /** + * Closes the transaction. + * + *

Examples

+ *
+         * transaction.Close();
+         * 
+ */ + void Close(); + } + + /** + * Used to specify the type of transaction. + * + *

Examples

+ *
+     * session.Transaction(TransactionType.Read);
+     * 
+ */ + public enum TransactionType + { + Read = Pinvoke.TransactionType.Read, + Write = Pinvoke.TransactionType.Write, + } +} diff --git a/csharp/Api/Logic/IExplanation.cs b/csharp/Api/Logic/IExplanation.cs new file mode 100644 index 0000000000..83b8a8c1c5 --- /dev/null +++ b/csharp/Api/Logic/IExplanation.cs @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver.Api; + +namespace TypeDB.Driver.Api +{ + /** + * An explanation of which rule was used for inferring the explained concept, the condition of the rule, + * the conclusion of the rule, and the mapping of variables between the query and the rule’s conclusion. + */ + public interface IExplanation + { + + /** + * Retrieves the Rule for this Explanation. + * + *

Examples

+ *
+         * explanation.Rule;
+         * 
+ */ + IRule Rule { get; } + + /** + * Retrieves the Conclusion for this Explanation. + * + *

Examples

+ *
+         * explanation.Conclusion
+         * 
+ */ + IConceptMap Conclusion { get; } + + /** + * Retrieves the Condition for this Explanation. + * + *

Examples

+ *
+         * explanation.Condition
+         * 
+ */ + IConceptMap Condition { get; } + + /** + * Retrieves the query variables for this Explanation. + * + *

Examples

+ *
+         * explanation.GetQueryVariables()
+         * 
+ */ + ISet GetQueryVariables(); + + /** + * Retrieves the rule variables corresponding to the query variable var for this Explanation. + * + *

Examples

+ *
+         * explanation.VariableMapping(variable)
+         * 
+ * + * @param variable The query variable to map to rule variables. + */ + ISet QueryVariableMapping(string variable); + } +} diff --git a/csharp/Api/Logic/ILogicManager.cs b/csharp/Api/Logic/ILogicManager.cs new file mode 100644 index 0000000000..2431e7a6d9 --- /dev/null +++ b/csharp/Api/Logic/ILogicManager.cs @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Api +{ + /** + * Provides methods for manipulating rules in the database. + */ + public interface ILogicManager + { + /** + * Retrieves all rules. + * + *

Examples

+ *
+         * transaction.Logic.GetRules();
+         * 
+ */ + IEnumerable GetRules(); + + /** + * Retrieves the Rule that has the given label. + * + *

Examples

+ *
+         * transaction.Logic.GetRule(label).Resolve()
+         * 
+ * + * @param label The label of the Rule to create or retrieve + */ + Promise GetRule(string label); + + /** + * Creates a new Rule if none exists with the given label, or replaces the existing one. + * + *

Examples

+ *
+         * transaction.Logic.PutRule(label, when, then).Resolve()
+         * 
+ * + * @param label The label of the IRule to create or replace + * @param when The when body of the rule to create + * @param then The then body of the rule to create + */ + Promise PutRule(string label, string when, string then); + } +} diff --git a/csharp/Api/Logic/IRule.cs b/csharp/Api/Logic/IRule.cs new file mode 100644 index 0000000000..e7cdef5523 --- /dev/null +++ b/csharp/Api/Logic/IRule.cs @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Api +{ + /** + * Rules are a part of schema and define embedded logic. + * The reasoning engine uses rules as a set of logic to infer new data. + * A rule consists of a condition and a conclusion, and is uniquely identified by a label. + */ + public interface IRule + { + /** + * Retrieves the unique label of the rule. + */ + string Label { get; } + + /** + * The statements that constitute the ‘when’ of the rule. + */ + string When { get; } + + /** + * The single statement that constitutes the ‘then’ of the rule. + */ + string Then { get; } + + /** + * Renames the label of the rule. The new label must remain unique. + * + *

Examples

+ *
+         * rule.SetLabel(transaction, newLabel).Resolve();
+         * 
+ * + * @param transaction The current Transaction + * @param label The new label to be given to the rule + */ + VoidPromise SetLabel(ITypeDBTransaction transaction, string label); + + /** + * Deletes this rule. + * + *

Examples

+ *
+         * rule.Delete(transaction).Resolve();
+         * 
+ * + * @param transaction The current Transaction + */ + VoidPromise Delete(ITypeDBTransaction transaction); + + /** + * Check if this rule has been deleted. + * + *

Examples

+ *
+         * rule.IsDeleted(transaction).Resolve();
+         * 
+ * + * @param transaction The current Transaction + */ + Promise IsDeleted(ITypeDBTransaction transaction); + } +} diff --git a/csharp/Api/Query/IQueryManager.cs b/csharp/Api/Query/IQueryManager.cs new file mode 100644 index 0000000000..30e650b4f7 --- /dev/null +++ b/csharp/Api/Query/IQueryManager.cs @@ -0,0 +1,255 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using Newtonsoft.Json.Linq; +using System.Collections.Generic; + +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Api +{ + /** + * Provides methods for executing TypeQL queries in the transaction. + */ + public interface IQueryManager + { + /** + * Performs a TypeQL Get (Get) with default options. + * + * @see IQueryManager#Get(string, TypeDBOptions) + */ + IEnumerable Get(string query); + + /** + * Performs a TypeQL Get (Get) query in the transaction. + * + *

Examples

+ *
+         * transaction.Query.Get(query, options);
+         * 
+ * + * @param query The TypeQL Get (Get) query to be executed + * @param options Specify query options + */ + IEnumerable Get(string query, TypeDBOptions options); + + /** + * Performs a TypeQL Get Aggregate query with default options. + * + * @see IQueryManager#GetAggregate(string, TypeDBOptions) + */ + Promise GetAggregate(string query); + + /** + * Performs a TypeQL Get Aggregate query in the transaction. + * + *

Examples

+ *
+         * transaction.Query.GetAggregate(query, options).Resolve()
+         * 
+ * + * @param query The TypeQL Get Aggregate query to be executed + * @param options Specify query options + */ + Promise GetAggregate(string query, TypeDBOptions options); + + /** + * Performs a TypeQL Get Group query with default options. + * + * @see IQueryManager#GetGroup(string, TypeDBOptions) + */ + IEnumerable GetGroup(string query); + + /** + * Performs a TypeQL Get Group query in the transaction. + * + *

Examples

+ *
+         * transaction.Query.GetGroup(query, options)
+         * 
+ * + * @param query The TypeQL Get Group query to be executed + * @param options Specify query options + */ + IEnumerable GetGroup(string query, TypeDBOptions options); + + /** + * Performs a TypeQL Get Group Aggregate query with default options. + * + * @see IQueryManager#GetGroupAggregate(string, TypeDBOptions) + */ + IEnumerable GetGroupAggregate(string query); + + /** + * Performs a TypeQL Get Group Aggregate query in the transaction. + * + *

Examples

+ *
+         * transaction.Query.GetGroupAggregate(query, options)
+         * 
+ * + * @param query The TypeQL Get Group Aggregate query to be executed + * @param options Specify query options + */ + IEnumerable GetGroupAggregate(string query, TypeDBOptions options); + + /** + * Performs a TypeQL Fetch (Fetch) with default options. + * + * @see IQueryManager#Fetch(string, TypeDBOptions) + */ + IEnumerable Fetch(string query); + + /** + * Performs a TypeQL Fetch (Fetch) query in the transaction. + * + *

Examples

+ *
+         * transaction.Query.Fetch(query, options)
+         * 
+ * + * @param query The TypeQL Fetch (Fetch) query to be executed + * @param options Specify query options + */ + IEnumerable Fetch(string query, TypeDBOptions options); + + /** + * Performs a TypeQL Insert query with default options. + * + * @see IQueryManager#Insert(string, TypeDBOptions) + */ + IEnumerable Insert(string query); + + /** + * Performs a TypeQL Insert query in the transaction. + * + *

Examples

+ *
+         * transaction.Query.Insert(query, options)
+         * 
+ * + * @param query The TypeQL Insert query to be executed + * @param options Specify query options + */ + IEnumerable Insert(string query, TypeDBOptions options); + + /** + * Performs a TypeQL Delete query with default options. + * + * @see IQueryManager#Delete(string, TypeDBOptions) + */ + VoidPromise Delete(string query); + + /** + * Performs a TypeQL Delete query in the transaction. + * + *

Examples

+ *
+         * transaction.Query.Delete(query, options).Resolve()
+         * 
+ * + * @param query The TypeQL Delete query to be executed + * @param options Specify query options + */ + VoidPromise Delete(string query, TypeDBOptions options); + + /** + * Performs a TypeQL Update query with default options. + * + * @see IQueryManager#Update(string, TypeDBOptions) + */ + IEnumerable Update(string query); + + /** + * Performs a TypeQL Update query in the transaction. + * + *

Examples

+ *
+         * transaction.Query.Update(query, options)
+         * 
+ * + * @param query The TypeQL Update query to be executed + * @param options Specify query options + */ + IEnumerable Update(string query, TypeDBOptions options); + + /** + * Performs a TypeQL Define query with default options. + * + * @see IQueryManager#Define(string, TypeDBOptions) + */ + VoidPromise Define(string query); + + /** + * Performs a TypeQL Define query in the transaction. + * + *

Examples

+ *
+         * transaction.Query.Define(query, options).Resolve()
+         * 
+ * + * @param query The TypeQL Define query to be executed + * @param options Specify query options + */ + VoidPromise Define(string query, TypeDBOptions options); + + /** + * Performs a TypeQL Undefine query with default options. + * + * @see IQueryManager#Undefine(string, TypeDBOptions) + */ + VoidPromise Undefine(string query); + + /** + * Performs a TypeQL Undefine query in the transaction. + * + *

Examples

+ *
+         * transaction.Query.Undefine(query, options).Resolve()
+         * 
+ * + * @param query The TypeQL Undefine query to be executed + * @param options Specify query options + */ + VoidPromise Undefine(string query, TypeDBOptions options); + + /** + * Performs a TypeQL Explain query with default options. + * + * @see IQueryManager#Explain(IConceptMap.IExplainable, TypeDBOptions) + */ + IEnumerable Explain(IConceptMap.IExplainable explainable); + + /** + * Performs a TypeQL Explain query in the transaction. + * + *

Examples

+ *
+         * transaction.Query.Explain(explainable, options)
+         * 
+ * + * @param explainable The IExplainable to be explained + * @param options Specify query options + */ + IEnumerable Explain(IConceptMap.IExplainable explainable, TypeDBOptions options); + } +} \ No newline at end of file diff --git a/csharp/Api/TypeDBCredential.cs b/csharp/Api/TypeDBCredential.cs new file mode 100644 index 0000000000..592c42a75b --- /dev/null +++ b/csharp/Api/TypeDBCredential.cs @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Diagnostics; +using System.IO; + +using TypeDB.Driver; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Api +{ + /** + * User credentials and TLS encryption settings for connecting to TypeDB Cloud. + * + *

Examples

+ *
+     * // Creates a credential as above, but the connection will be made over TLS.
+     * TypeDBCredential credential = new TypeDBCredential(username, password, true);
+     *
+     * // Creates a credential as above, but TLS will use the specified CA to authenticate server certificates.
+     * TypeDBCredential credential = new TypeDBCredential(username, password, Path.of("path/to/ca-certificate.pem"));
+     * 
+ */ + public class TypeDBCredential : NativeObjectWrapper + { + /** + * + * @param username The name of the user to connect as + * @param password The password for the user + * @param tlsEnabled Specify whether the connection to TypeDB Cloud must be done over TLS + */ + public TypeDBCredential(string username, string password, bool tlsEnabled) + : this(username, password, null, tlsEnabled) + {} + + /** + * + * @param username The name of the user to connect as + * @param password The password for the user + * @param tlsRootCAPath Path to the CA certificate to use for authenticating server certificates + */ + public TypeDBCredential(string username, string password, string? tlsRootCAPath) + : this(username, password, tlsRootCAPath, true) + {} + + private TypeDBCredential(string username, string password, string? tlsRootCAPath, bool tlsEnabled) + : base(NativeCredential(username, password, tlsRootCAPath, tlsEnabled)) + {} + + private static Pinvoke.Credential NativeCredential( + string username, string password, string? tlsRootCAPath, bool tlsEnabled) + { + Debug.Assert(tlsEnabled || tlsRootCAPath == null); + try + { + return Pinvoke.typedb_driver.credential_new(username, password, tlsRootCAPath, tlsEnabled); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + } +} diff --git a/csharp/Api/TypeDBOptions.cs b/csharp/Api/TypeDBOptions.cs new file mode 100644 index 0000000000..c734521bf7 --- /dev/null +++ b/csharp/Api/TypeDBOptions.cs @@ -0,0 +1,428 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using TypeDB.Driver; +using TypeDB.Driver.Common; +using TypeDB.Driver.Common.Validation; + +using DriverError = TypeDB.Driver.Common.Error.Driver; + +namespace TypeDB.Driver.Api +{ + /** + * TypeDB session and transaction options. TypeDBOptions object can be used to override + * the default server behaviour. + */ + public class TypeDBOptions : NativeObjectWrapper + { + /** + * Produces a new TypeDBOptions object. + * + *

Examples

+ *
+         * TypeDBOptions options = TypeDBOptions();
+         * 
+ */ + public TypeDBOptions() + : base(Pinvoke.typedb_driver.options_new()) + {} + + /** + * Returns the value set for the inference in this TypeDBOptions object. + * + *

Examples

+ *
+         * options.Infer();
+         * 
+ */ + public bool? Infer() + { + if (Pinvoke.typedb_driver.options_has_infer(NativeObject)) + { + return Pinvoke.typedb_driver.options_get_infer(NativeObject); + } + return null; + } + + /** + * Explicitly enables or disables inference. + * Only settable at transaction level and above. Only affects read transactions. + * + *

Examples

+ *
+         * options.Infer(infer);
+         * 
+ * + * @param infer Explicitly enable or disable inference + */ + public TypeDBOptions Infer(bool infer) + { + Pinvoke.typedb_driver.options_set_infer(NativeObject, infer); + return this; + } + + /** + * Returns the value set for reasoning tracing in this TypeDBOptions object. + * If set to true, reasoning tracing graphs are output in the logging directory. + * + *

Examples

+ *
+         * options.TraceInference();
+         * 
+ */ + public bool? TraceInference() + { + if (Pinvoke.typedb_driver.options_has_trace_inference(NativeObject)) + { + return Pinvoke.typedb_driver.options_get_trace_inference(NativeObject); + } + return null; + } + + /** + * Explicitly enables or disables reasoning tracing. + * If set to true, reasoning tracing graphs are output in the logging directory. + * Should be used with parallel = False. + * + *

Examples

+ *
+         * options.TraceInference(traceInference);
+         * 
+ * + * @param traceInference Explicitly enable or disable reasoning tracing + */ + public TypeDBOptions TraceInference(bool traceInference) + { + Pinvoke.typedb_driver.options_set_trace_inference(NativeObject, traceInference); + return this; + } + + /** + * Returns the value set for the explanation in this TypeDBOptions object. + * If set to true, explanations for queries are enabled. + * + *

Examples

+ *
+         * options.Explain();
+         * 
+ */ + public bool? Explain() + { + if (Pinvoke.typedb_driver.options_has_explain(NativeObject)) + { + return Pinvoke.typedb_driver.options_get_explain(NativeObject); + } + return null; + } + + /** + * Explicitly enables or disables explanations. + * If set to true, enables explanations for queries. Only affects read transactions. + * + *

Examples

+ *
+         * options.Explain(explain);
+         * 
+ * + * @param explain Explicitly enable or disable explanations + */ + public TypeDBOptions Explain(bool explain) + { + Pinvoke.typedb_driver.options_set_explain(NativeObject, explain); + return this; + } + + /** + * Returns the value set for the parallel execution in this TypeDBOptions object. + * If set to true, the server uses parallel instead of single-threaded execution. + * + *

Examples

+ *
+         * options.Parallel();
+         * 
+ */ + public bool? Parallel() + { + if (Pinvoke.typedb_driver.options_has_parallel(NativeObject)) + { + return Pinvoke.typedb_driver.options_get_parallel(NativeObject); + } + return null; + } + + /** + * Explicitly enables or disables parallel execution. + * If set to true, the server uses parallel instead of single-threaded execution. + * + *

Examples

+ *
+         * options.Parallel(parallel);
+         * 
+ * + * @param parallel Explicitly enable or disable parallel execution + */ + public TypeDBOptions Parallel(bool parallel) + { + Pinvoke.typedb_driver.options_set_parallel(NativeObject, parallel); + return this; + } + + /** + * Returns the value set for the prefetching in this TypeDBOptions object. + * If set to true, the first batch of answers is streamed to the driver even without + * an explicit request for it. + * + *

Examples

+ *
+         * options.Prefetch();
+         * 
+ */ + public bool? Prefetch() + { + if (Pinvoke.typedb_driver.options_has_prefetch(NativeObject)) + { + return Pinvoke.typedb_driver.options_get_prefetch(NativeObject); + } + return null; + } + + /** + * Explicitly enables or disables prefetching. + * If set to true, the first batch of answers is streamed to the driver even without + * an explicit request for it. + * + *

Examples

+ *
+         * options.Prefetch(prefetch);
+         * 
+ * + * @param prefetch Explicitly enable or disable prefetching + */ + public TypeDBOptions Prefetch(bool prefetch) + { + Pinvoke.typedb_driver.options_set_prefetch(NativeObject, prefetch); + return this; + } + + /** + * Returns the value set for the prefetch size in this TypeDBOptions object. + * If set, specifies a guideline number of answers that the server should send before the driver + * issues a fresh request. + * + *

Examples

+ *
+         * options.PrefetchSize();
+         * 
+ */ + public int? PrefetchSize() + { + if (Pinvoke.typedb_driver.options_has_prefetch_size(NativeObject)) + { + return Pinvoke.typedb_driver.options_get_prefetch_size(NativeObject); + } + return null; + } + + /** + * Explicitly sets a prefetch size. + * If set, specifies a guideline number of answers that the server should send before the driver + * issues a fresh request. + * + *

Examples

+ *
+         * options.PrefetchSize(prefetchSize);
+         * 
+ * + * @param prefetchSize Number of answers that the server should send before the driver issues a fresh request + */ + public TypeDBOptions PrefetchSize(int prefetchSize) + { + Validator.ThrowIfTrue(() => prefetchSize < 1, DriverError.POSITIVE_VALUE_REQUIRED, prefetchSize); + + Pinvoke.typedb_driver.options_set_prefetch_size(NativeObject, prefetchSize); + return this; + } + + /** + * Returns the value set for the session idle timeout in this TypeDBOptions object. + * If set, specifies a timeout that allows the server to close sessions if the driver terminates + * or becomes unresponsive. + * + *

Examples

+ *
+         * options.SessionIdleTimeoutMillis();
+         * 
+ */ + public int? SessionIdleTimeoutMillis() + { + if (Pinvoke.typedb_driver.options_has_session_idle_timeout_millis(NativeObject)) + { + return (int)Pinvoke.typedb_driver.options_get_session_idle_timeout_millis(NativeObject); + } + return null; + } + + /** + * Explicitly sets a session idle timeout. + * If set, specifies a timeout that allows the server to close sessions if the driver terminates + * or becomes unresponsive. + * + *

Examples

+ *
+         * options.SessionIdleTimeoutMillis(sessionIdleTimeoutMillis);
+         * 
+ * + * @param sessionIdleTimeoutMillis timeout that allows the server to close sessions if the driver terminates + * or becomes unresponsive. + */ + public TypeDBOptions SessionIdleTimeoutMillis(int sessionIdleTimeoutMillis) + { + Validator.ThrowIfTrue( + () => sessionIdleTimeoutMillis < 1, + DriverError.POSITIVE_VALUE_REQUIRED, + sessionIdleTimeoutMillis); + + Pinvoke.typedb_driver.options_set_session_idle_timeout_millis(NativeObject, sessionIdleTimeoutMillis); + return this; + } + + /** + * Returns the value set for the transaction timeout in this TypeDBOptions object. + * If set, specifies a timeout for killing transactions automatically, preventing memory leaks + * in unclosed transactions. + * + *

Examples

+ *
+         * options.TransactionTimeoutMillis();
+         * 
+ */ + public int? TransactionTimeoutMillis() + { + if (Pinvoke.typedb_driver.options_has_transaction_timeout_millis(NativeObject)) + { + return (int)Pinvoke.typedb_driver.options_get_transaction_timeout_millis(NativeObject); + } + return null; + } + + /** + * Explicitly set a transaction timeout. + * If set, specifies a timeout for killing transactions automatically, preventing memory leaks + * in unclosed transactions. + * + *

Examples

+ *
+         * options.TransactionTimeoutMillis(transactionTimeoutMillis);
+         * 
+ * + * @param transactionTimeoutMillis Timeout for killing transactions automatically. + */ + public TypeDBOptions TransactionTimeoutMillis(int transactionTimeoutMillis) + { + Validator.ThrowIfTrue( + () => transactionTimeoutMillis < 1, + DriverError.POSITIVE_VALUE_REQUIRED, + transactionTimeoutMillis); + + Pinvoke.typedb_driver.options_set_transaction_timeout_millis(NativeObject, transactionTimeoutMillis); + return this; + } + + /** + * Returns the value set for the schema lock acquire timeout in this TypeDBOptions object. + * If set, specifies how long the driver should wait if opening a session or transaction is blocked + * by a schema write lock. + * + *

Examples

+ *
+         * options.SchemaLockAcquireTimeoutMillis();
+         * 
+ */ + public int? SchemaLockAcquireTimeoutMillis() + { + if (Pinvoke.typedb_driver.options_has_schema_lock_acquire_timeout_millis(NativeObject)) + { + return (int)Pinvoke.typedb_driver.options_get_schema_lock_acquire_timeout_millis(NativeObject); + } + return null; + } + + /** + * Explicitly sets schema lock acquire timeout. + * If set, specifies how long the driver should wait if opening a session or transaction is blocked + * by a schema write lock. + * + *

Examples

+ *
+         * options.SchemaLockAcquireTimeoutMillis(schemaLockAcquireTimeoutMillis);
+         * 
+ * + * @param schemaLockAcquireTimeoutMillis How long the driver should wait if opening a session + * or transaction is blocked by a schema write lock. + */ + public TypeDBOptions SchemaLockAcquireTimeoutMillis(int schemaLockAcquireTimeoutMillis) + { + Validator.ThrowIfTrue( + () => schemaLockAcquireTimeoutMillis < 1, + DriverError.POSITIVE_VALUE_REQUIRED, + schemaLockAcquireTimeoutMillis); + + Pinvoke.typedb_driver.options_set_schema_lock_acquire_timeout_millis(NativeObject, schemaLockAcquireTimeoutMillis); + return this; + } + + /** + * Returns the value set for reading data from any replica in this TypeDBOptions object. + * If set to True, enables reading data from any replica, potentially boosting read throughput. + * + *

Examples

+ *
+         * options.ReadAnyReplica();
+         * 
+ */ + public bool? ReadAnyReplica() + { + if (Pinvoke.typedb_driver.options_has_read_any_replica(NativeObject)) + { + return Pinvoke.typedb_driver.options_get_read_any_replica(NativeObject); + } + return null; + } + + /** + * Explicitly enables or disables reading data from any replica. + * If set to True, enables reading data from any replica, potentially boosting read throughput. + * Only settable in TypeDB Cloud. + * + *

Examples

+ *
+         * options.ReadAnyReplica(readAnyReplica);
+         * 
+ * + * @param readAnyReplica Explicitly enable or disable reading data from any replica + */ + public TypeDBOptions ReadAnyReplica(bool readAnyReplica) + { + Pinvoke.typedb_driver.options_set_read_any_replica(NativeObject, readAnyReplica); + return this; + } + } +} diff --git a/csharp/Api/User/IUser.cs b/csharp/Api/User/IUser.cs new file mode 100644 index 0000000000..8a9609b2fb --- /dev/null +++ b/csharp/Api/User/IUser.cs @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +namespace TypeDB.Driver.Api +{ + /** + * TypeDB user information + */ + public interface IUser + { + /** + * Returns the name of this user. + */ + string Username { get; } + + /** + * Returns the number of seconds remaining till this user’s current password expires. + */ + long? PasswordExpirySeconds { get; } + + /** + * Updates the password for this user. + * + * @param passwordOld The current password of this user + * @param passwordNew The new password + */ + void UpdatePassword(string passwordOld, string passwordNew); + } +} diff --git a/csharp/Api/User/IUserManager.cs b/csharp/Api/User/IUserManager.cs new file mode 100644 index 0000000000..1eeb0345f1 --- /dev/null +++ b/csharp/Api/User/IUserManager.cs @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver.Api; + +namespace TypeDB.Driver.Api +{ + /** + * Provides access to all user management methods. + */ + public interface IUserManager + { + /** + * Checks if a user with the given name exists. + * + *

Examples

+ *
+         * driver.Users.Contains(username);
+         * 
+ * + * @param username The user name to be checked + */ + bool Contains(string username); + + /** + * Creates a user with the given name & password. + * + *

Examples

+ *
+         * driver.Users.Create(username, password);
+         * 
+ * + * @param username The name of the user to be created + * @param password The password of the user to be created + */ + void Create(string username, string password); + + /** + * Deletes a user with the given name. + * + *

Examples

+ *
+         * driver.Users.Delete(username);
+         * 
+ * + * @param username The name of the user to be deleted + */ + void Delete(string username); + + /** + * Retrieves a user with the given name. + * + *

Examples

+ *
+         * driver.Users.Get(username);
+         * 
+ * + * @param username The name of the user to retrieve + */ + IUser? Get(string username); + + /** + * Retrieves all users which exist on the TypeDB server. + * + *

Examples

+ *
+         * driver.Users.GetAll();
+         * 
+ */ + ISet GetAll(); + + /** + * Sets a new password for a user. This operation can only be performed by administrators. + * + *

Examples

+ *
+         * driver.Users.SetPassword(username, password);
+         * 
+ * + * @param username The name of the user to set the password of + * @param password The new password + */ + void SetPassword(string username, string password); + } +} diff --git a/csharp/BUILD b/csharp/BUILD new file mode 100644 index 0000000000..9c0dc10b95 --- /dev/null +++ b/csharp/BUILD @@ -0,0 +1,73 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +load("@rules_dotnet//dotnet:defs.bzl", "csharp_binary", "csharp_library") +load(":build_opts.bzl", "target_frameworks", "targeting_packs", "nullable_context") +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") +load(":rules.bzl", "swig_native_csharp_library") + + +swig_native_csharp_library( + name = "typedb_driver_pinvoke", + lib = "//c:typedb_driver_clib_headers", + namespace = "TypeDB.Driver.Pinvoke", + interface = "//c:typedb_driver.i", + includes = ["//c:swig/typedb_driver_csharp.swg"], + enable_cxx = True, + nullable_context = nullable_context, + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, + visibility = ["//visibility:public"], +# platforms = { # TODO: We'll need to build for different platforms? +# "@vaticle_bazel_distribution//platform:is_linux_arm64": "linux-arm64", +# "@vaticle_bazel_distribution//platform:is_linux_x86_64": "linux-x86_64", +# "@vaticle_bazel_distribution//platform:is_mac_arm64": "macosx-arm64", +# "@vaticle_bazel_distribution//platform:is_mac_x86_64": "macosx-x86_64", +# "@vaticle_bazel_distribution//platform:is_windows_x86_64": "windows-x86_64", +# }, +) + + +csharp_library( + name = "driver-csharp", + srcs = glob(["*.cs"]), + resources = ["//:LICENSE"], + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp/Connection:connection", + "//csharp:typedb_driver_pinvoke", + ], + visibility = ["//visibility:public"], + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +checkstyle_test( + name = "checkstyle", + size = "small", + include = glob(["*"]), + exclude = glob([ + "README.md", + "docs/**/*.adoc", + ]), + license_type = "apache-header", +) diff --git a/csharp/Common/BUILD b/csharp/Common/BUILD new file mode 100644 index 0000000000..1976bb7be2 --- /dev/null +++ b/csharp/Common/BUILD @@ -0,0 +1,45 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +package(default_visibility = ["//visibility:public"]) + +load("//csharp:build_opts.bzl", "nullable_context", "target_frameworks", "targeting_packs") +load("@rules_dotnet//dotnet:defs.bzl", "csharp_library") +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") + + +csharp_library( + name = "common", + srcs = glob(["*.cs", "*/*.cs"]), + deps = ["//csharp:typedb_driver_pinvoke"], + runtime_identifier = "any", + nullable = nullable_context, + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +checkstyle_test( + name = "checkstyle", + size = "small", + include = glob(["*", "*/*"]), + license_type = "apache-header", +) diff --git a/csharp/Common/Exception/ErrorMessage.cs b/csharp/Common/Exception/ErrorMessage.cs new file mode 100644 index 0000000000..36da4ab9d8 --- /dev/null +++ b/csharp/Common/Exception/ErrorMessage.cs @@ -0,0 +1,147 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; + +namespace TypeDB.Driver.Common +{ + public abstract class ErrorMessage + { + private readonly string _codePrefix; + private readonly string _codeNumber; + private readonly string _messagePrefix; + private readonly string _messageBody; + + public ErrorMessage( + string codePrefix, int codeNumber, string messagePrefix, string messageBody) + { + _codePrefix = codePrefix; + _codeNumber = codeNumber.ToString("D2"); + _messagePrefix = messagePrefix; + _messageBody = messageBody; + } + + public string ToString(params object?[] errorParams) + { + var formattedBody = String.Format(_messageBody, errorParams); + return $"[{_codePrefix}{_codeNumber}] {_messagePrefix}: {formattedBody}"; + } + } + + namespace Error + { + public class Driver : ErrorMessage + { + private const string CODE_PREFIX = "CSDR"; + private const string MESSAGE_PREFIX = "Driver Error"; + + public Driver(int codeNumber, string message) + : base(CODE_PREFIX, codeNumber, MESSAGE_PREFIX, message) + { + } + + public static readonly Driver DRIVER_CLOSED = + new Driver(1, "The driver has been closed and no further operation is allowed."); + public static readonly Driver SESSION_CLOSED = + new Driver(2, "The session has been closed and no further operation is allowed."); + public static readonly Driver TRANSACTION_CLOSED = + new Driver(3, "The transaction has been closed and no further operation is allowed."); + public static readonly Driver TRANSACTION_CLOSED_WITH_ERRORS = + new Driver(4, "The transaction has been closed with error(s): \n{0}."); + public static readonly Driver DATABASE_DELETED = + new Driver(5, "The database has been deleted and no further operation is allowed."); + public static readonly Driver POSITIVE_VALUE_REQUIRED = + new Driver(6, "Value cannot be less than 1, was: {0}."); + public static readonly Driver MISSING_DB_NAME = + new Driver(7, "Database name cannot be null."); + } + + public class Concept : ErrorMessage + { + private const string CODE_PREFIX = "CSCO"; + private const string MESSAGE_PREFIX = "Concept Error"; + + public Concept(int codeNumber, string message) + : base(CODE_PREFIX, codeNumber, MESSAGE_PREFIX, message) + { + } + + public static readonly Concept INVALID_CONCEPT_CASTING = + new Concept(1, "Invalid concept conversion from {0} to {1}."); + public static readonly Concept MISSING_TRANSACTION = + new Concept(2, "Transaction cannot be null."); + public static readonly Concept MISSING_IID = + new Concept(3, "IID cannot be null or empty."); + public static readonly Concept MISSING_LABEL = + new Concept(4, "Label cannot be null or empty."); + public static readonly Concept MISSING_VARIABLE = + new Concept(5, "Variable name cannot be null or empty."); + public static readonly Concept MISSING_VALUE = + new Concept(6, "Value cannot be null."); + public static readonly Concept NONEXISTENT_EXPLAINABLE_CONCEPT = + new Concept(7, "The concept identified by {0} is not explainable."); + public static readonly Concept NONEXISTENT_EXPLAINABLE_OWNERSHIP = + new Concept(8, "The ownership by owner {0} of attribute {1} is not explainable."); + public static readonly Concept UNRECOGNISED_ANNOTATION = + new Concept(9, "The annotation {0} is not recognised."); + } + + public class Query : ErrorMessage + { + private const string CODE_PREFIX = "CSQR"; + private const string MESSAGE_PREFIX = "Query Error"; + + public Query(int codeNumber, string message) + : base(CODE_PREFIX, codeNumber, MESSAGE_PREFIX, message) + { + } + + public static readonly Query VARIABLE_DOES_NOT_EXIST = + new Query(1, "The variable {0} does not exist."); + public static readonly Query MISSING_QUERY = + new Query(2, "Query cannot be null or empty."); + } + + public class Internal : ErrorMessage + { + private const string CODE_PREFIX = "CSIN"; + private const string MESSAGE_PREFIX = "C# Internal Error"; + + public Internal(int codeNumber, string message) + : base(CODE_PREFIX, codeNumber, MESSAGE_PREFIX, message) + { + } + + public static readonly Internal UNEXPECTED_NATIVE_VALUE = + new Internal(1, "Unexpected native value encountered!"); + public static readonly Internal ILLEGAL_STATE = + new Internal(2, "Illegal state has been reached! ({0} : {1})."); + public static readonly Internal ILLEGAL_CAST = + new Internal(3, "Illegal casting operation to {0}."); + public static readonly Internal NULL_NATIVE_VALUE = + new Internal(4, "Unhandled null pointer to a native object encountered!"); + public static readonly Internal ENUMERATOR_EXCESSIVE_ACCESS = + new Internal(5, "Such Enumerables support Enumerator's getting only once."); + public static readonly Internal UNEXPECTED_INTERNAL_VALUE = + new Internal(6, "Unexpected internal value {0} encountered!"); + } + } +} diff --git a/csharp/Common/Exception/TypeDBDriverException.cs b/csharp/Common/Exception/TypeDBDriverException.cs new file mode 100644 index 0000000000..8b899fc450 --- /dev/null +++ b/csharp/Common/Exception/TypeDBDriverException.cs @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; + +using TypeDB.Driver; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Common +{ + public class TypeDBDriverException : System.Exception + { + /** + * @hidden + */ + public TypeDBDriverException(ErrorMessage error, params object?[] errorParams) + : base(error.ToString(errorParams)) + { + } + + /** + * @hidden + */ + public TypeDBDriverException(string message) + : base(message) + { + } + + /** + * @hidden + */ + public TypeDBDriverException(System.Exception error) + : base(error.Message) + { + } + + /** + * @hidden + */ + public TypeDBDriverException(Pinvoke.Error nativeError) + : base(nativeError.Message) + { + } + + /** + * Checks whether a substring is a part of this exception's message. + * + *

Examples

+ *
+         * try
+         * {
+         *     ...
+         * }
+         * catch (TypeDBDriverException e)
+         * {
+         *     if (e.Contains("CSCO01"))
+         *     {
+         *         ...
+         *     }
+         *     else
+         *     {
+         *         ...
+         *     }
+         * }
+         * 
+ */ + public bool Contains(string subString) + { + return Message.Contains(subString); + } + } +} diff --git a/csharp/Common/Exception/TypeDBException.cs b/csharp/Common/Exception/TypeDBException.cs new file mode 100644 index 0000000000..4a0e573cae --- /dev/null +++ b/csharp/Common/Exception/TypeDBException.cs @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; + +namespace TypeDB.Driver.Common +{ + public class TypeDBException : Exception + { + public TypeDBException(string code, string message) + : base(message) + { + Code = code; + } + + public readonly string Code; + } +} diff --git a/csharp/Common/Label.cs b/csharp/Common/Label.cs new file mode 100644 index 0000000000..1757154045 --- /dev/null +++ b/csharp/Common/Label.cs @@ -0,0 +1,153 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; + +namespace TypeDB.Driver.Common +{ + /** + * A Label holds the uniquely identifying name of a type. + *

It consists of an optional scope, and a name, represented scope:name. + * The scope is used only used to distinguish between role-types of the same name declared in different + * relation types.

+ */ + public struct Label + { + /** + * Returns the scope of this Label. + * + *

Examples

+ *
+         * label.Scope;
+         * 
+ */ + public readonly string? Scope; + + /** + * Returns the name of this Label. + * + *

Examples

+ *
+         * label.Name;
+         * 
+ */ + public readonly string Name; + + /** + * @hidden + */ + private readonly int _hash; + + /** + * Creates a Label from a specified scope and name. + * + *

Examples

+ *
+         * new Label("relation", "role");
+         * 
+ * + * @param scope Label scope + * @param name Label name + */ + public Label(string? scope, string name) + { + Scope = scope; + Name = name; + _hash = (Name, Scope).GetHashCode(); + } + + /** + * Creates a Label from a specified name. + * + *

Examples

+ *
+         * new Label("entity");
+         * 
+ * + * @param name Label name + */ + public Label(string name) + : this(null, name) + { + } + + /** + * Returns the string representation of the scoped name. + * + *

Examples

+ *
+         * label.ScopedName;
+         * 
+ */ + public string ScopedName + { + get => Scope == null ? Name : Scope + ":" + Name; + } + + /** + * Returns the string representation of the scoped name. + * + *

Examples

+ *
+         * label.ToString();
+         * 
+ */ + public override string ToString() + { + return ScopedName; + } + + /** + * Checks if this Label is equal to another object. + * + *

Examples

+ *
+         * label.Equals(obj);
+         * 
+ * + * @param obj Object to compare with + */ + public override bool Equals(object? obj) + { + if (Object.ReferenceEquals(this, obj)) + { + return true; + } + + if (obj == null || this.GetType() != obj.GetType()) + { + return false; + } + + Label that = (Label)obj; + + return this.Name == that.Name && this.Scope == that.Scope; + } + + /** + * @hidden + */ + public override int GetHashCode() + { + return _hash; + } + } +} diff --git a/csharp/Common/NativeEnumerable.cs b/csharp/Common/NativeEnumerable.cs new file mode 100644 index 0000000000..56f82ee316 --- /dev/null +++ b/csharp/Common/NativeEnumerable.cs @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections; +using System.Collections.Generic; + +using TypeDB.Driver.Common; +using TypeDB.Driver.Common.Validation; + +using InternalError = TypeDB.Driver.Common.Error.Internal; + +namespace TypeDB.Driver.Common +{ + public class NativeEnumerable : IEnumerable + { + private readonly NativeEnumerator _enumerator; + private bool _enumeratorUsed; + + public NativeEnumerable(IEnumerator enumerator) + { + _enumerator = new NativeEnumerator(enumerator); + _enumeratorUsed = false; + } + + public IEnumerator GetEnumerator() + { + Validator.ThrowIfTrue(() => _enumeratorUsed, InternalError.ENUMERATOR_EXCESSIVE_ACCESS); + + _enumeratorUsed = true; + return _enumerator; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return this.GetEnumerator(); + } + } + + internal class NativeEnumerator : IEnumerator + { + private IEnumerator _innerEnumerator; + + public NativeEnumerator(IEnumerator enumerator) + { + _innerEnumerator = enumerator; + } + + object IEnumerator.Current + { + get { return Current!; } + } + + public T Current + { + get { return _innerEnumerator.Current; } + } + + public bool MoveNext() + { + try + { + return _innerEnumerator.MoveNext(); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public void Reset() + { + _innerEnumerator.Reset(); + } + + public void Dispose() + { + } + } +} diff --git a/java/common/collection/Bytes.java b/csharp/Common/NativeObjectWrapper.cs similarity index 57% rename from java/common/collection/Bytes.java rename to csharp/Common/NativeObjectWrapper.cs index 6b2af79796..69931febda 100644 --- a/java/common/collection/Bytes.java +++ b/csharp/Common/NativeObjectWrapper.cs @@ -19,23 +19,27 @@ * under the License. */ -package com.vaticle.typedb.driver.common.collection; +using System; -import java.nio.ByteBuffer; -import java.util.UUID; +using TypeDB.Driver; +using TypeDB.Driver.Common; -public class Bytes { - public static byte[] uuidToBytes(UUID uuid) { - ByteBuffer buffer = ByteBuffer.wrap(new byte[16]); - buffer.putLong(uuid.getMostSignificantBits()); - buffer.putLong(uuid.getLeastSignificantBits()); - return buffer.array(); - } +using InternalError = TypeDB.Driver.Common.Error.Internal; + +namespace TypeDB.Driver.Common +{ + public abstract class NativeObjectWrapper + { + public readonly T NativeObject; + + static NativeObjectWrapper() + { + Pinvoke.typedb_driver.init_logging(); + } - public static UUID bytesToUUID(byte[] bytes) { - ByteBuffer buffer = ByteBuffer.wrap(bytes); - long firstLong = buffer.getLong(); - long secondLong = buffer.getLong(); - return new UUID(firstLong, secondLong); + protected NativeObjectWrapper(T? nativeObject) + { + NativeObject = nativeObject ?? throw new TypeDBDriverException(InternalError.NULL_NATIVE_VALUE); + } } } diff --git a/csharp/Common/Promise/Promise.cs b/csharp/Common/Promise/Promise.cs new file mode 100644 index 0000000000..c7ea5a29af --- /dev/null +++ b/csharp/Common/Promise/Promise.cs @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; + +using TypeDB.Driver; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Common +{ + /** + * A Promise represents an asynchronous network operation. + *

The request it represents is performed immediately. The response is only retrieved + * once the Promise is Resolved.

. + */ + public class Promise + { + private readonly Func _resolver; + + /** + * Promise constructor + * + *

Examples

+ *
+         * new Promise(supplier);
+         * 
+ * + * @param promise The function to wrap into the promise + */ + public Promise(Func resolver) + { + _resolver = resolver; + } + + /** + * Retrieves the result of the Promise. + * + *

Examples

+ *
+         * promise.Resolve();
+         * 
+ */ + public T? Resolve() + { + try + { + return _resolver(); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + /** + * Helper function to map promises. + * + *

Examples

+ *
+         * Promise<TFrom>.Map<TTo, T>(supplier, selector);
+         * 
+ * + * @param promise The function to wrap into the promise + * @param fn The mapping function + */ + public static Promise Map(Func resolver, Func selector) + { + return new Promise(() => + { + TFrom? res = resolver(); + if (res != null) + { + return selector(res!); + } + + return default; + }); + } + } +} diff --git a/csharp/Common/Promise/VoidPromise.cs b/csharp/Common/Promise/VoidPromise.cs new file mode 100644 index 0000000000..567a1998a6 --- /dev/null +++ b/csharp/Common/Promise/VoidPromise.cs @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; + +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Common +{ + /** + * A VoidPromise represents a Promise without an operation's result. + * @see Promise + */ + public class VoidPromise + { + private readonly Action _resolver; + /** + * Promise constructor + * + *

Examples

+ *
+         * new Promise(action);
+         * 
+ * + * @param promise The function to wrap into the promise + */ + public VoidPromise(Action resolver) + { + _resolver = resolver; + } + + /** + * Retrieves the result of the Promise. + * + *

Examples

+ *
+         * promise.Resolve();
+         * 
+ */ + public void Resolve() + { + try + { + _resolver(); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + } +} diff --git a/csharp/Common/Validation/Validator.cs b/csharp/Common/Validation/Validator.cs new file mode 100644 index 0000000000..5c41e5dddb --- /dev/null +++ b/csharp/Common/Validation/Validator.cs @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; + +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Common.Validation +{ + public static class Validator + { + public static void ThrowIfFalse(Func checker, ErrorMessage errorMessage, params object?[] exceptionArgs) + { + ThrowIf(false, checker, errorMessage, exceptionArgs); + } + + public static void ThrowIfTrue(Func checker, ErrorMessage errorMessage, params object?[] exceptionArgs) + { + ThrowIf(true, checker, errorMessage, exceptionArgs); + } + + public static void NonEmptyString(string input, ErrorMessage errorMessage, params object?[] exceptionArgs) + { + ThrowIfTrue(() => string.IsNullOrEmpty(input), errorMessage, exceptionArgs); + } + + private static void ThrowIf( + bool expectedResult, + Func checker, + ErrorMessage errorMessage, + params object?[] exceptionArgs) + { + if (checker() == expectedResult) + { + throw new TypeDBDriverException(errorMessage, exceptionArgs); + } + } + } +} \ No newline at end of file diff --git a/csharp/Concept/Answer/ConceptMap.cs b/csharp/Concept/Answer/ConceptMap.cs new file mode 100644 index 0000000000..376fbc73e2 --- /dev/null +++ b/csharp/Concept/Answer/ConceptMap.cs @@ -0,0 +1,308 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Concept; +using TypeDB.Driver.Common.Validation; +using static TypeDB.Driver.Concept.Concept; + +using ConceptError = TypeDB.Driver.Common.Error.Concept; +using QueryError = TypeDB.Driver.Common.Error.Query; + +namespace TypeDB.Driver.Concept +{ + public class ConceptMap : NativeObjectWrapper, IConceptMap + { + private Dictionary? _cachedMap; + private IConceptMap.IExplainables? _allExplainables; + private int _hash = 0; + + public ConceptMap(Pinvoke.ConceptMap nativeConceptMap) + : base(nativeConceptMap) + { + } + + public IEnumerable GetVariables() + { + return new NativeEnumerable( + Pinvoke.typedb_driver.concept_map_get_variables(NativeObject)); + } + + public IEnumerable GetConcepts() + { + return new NativeEnumerable( + Pinvoke.typedb_driver.concept_map_get_values(NativeObject)) + .Select(obj => ConceptOf(obj)); + } + + public Dictionary GetMap() + { + return _cachedMap ?? (_cachedMap = GetVariables().ToDictionary(v => v, v => Get(v))); + } + + public IConcept Get(string variable) + { + Validator.NonEmptyString(variable, ConceptError.MISSING_VARIABLE); + + Pinvoke.Concept concept = Pinvoke.typedb_driver.concept_map_get(NativeObject, variable); + if (concept == null) + { + throw new TypeDBDriverException(QueryError.VARIABLE_DOES_NOT_EXIST, variable); + } + + return ConceptOf(concept); + } + + public IConceptMap.IExplainables AllExplainables + { + get + { + return _allExplainables ?? (_allExplainables = + new Explainables(Pinvoke.typedb_driver.concept_map_get_explainables(NativeObject))); + } + } + + public override string ToString() + { + return Pinvoke.typedb_driver.concept_map_to_string(NativeObject); + } + + public override bool Equals(object? obj) + { + if (Object.ReferenceEquals(this, obj)) + { + return true; + } + + if (obj == null || this.GetType() != obj.GetType()) + { + return false; + } + + ConceptMap that = (ConceptMap)obj; + + return Pinvoke.typedb_driver.concept_map_equals( + this.NativeObject, that.NativeObject); + } + + public override int GetHashCode() + { + if (_hash == 0) + { + _hash = ComputeHash(); + } + + return _hash; + } + + private int ComputeHash() + { + return GetMap().GetHashCode(); + } + + public class Explainables : NativeObjectWrapper, IConceptMap.IExplainables + { + private int _hash = 0; + + public Explainables(Pinvoke.Explainables nativeExplainables) + : base(nativeExplainables) + { + } + + public IConceptMap.IExplainable Relation(string variable) + { + Validator.NonEmptyString(variable, ConceptError.MISSING_VARIABLE); + + Pinvoke.Explainable explainable = + Pinvoke.typedb_driver.explainables_get_relation(NativeObject, variable); + if (explainable == null) + { + throw new TypeDBDriverException(ConceptError.NONEXISTENT_EXPLAINABLE_CONCEPT, variable); + } + + return new Explainable(explainable); + } + + public IConceptMap.IExplainable Attribute(string variable) + { + Validator.NonEmptyString(variable, ConceptError.MISSING_VARIABLE); + + Pinvoke.Explainable explainable = + Pinvoke.typedb_driver.explainables_get_attribute(NativeObject, variable); + if (explainable == null) + { + throw new TypeDBDriverException(ConceptError.NONEXISTENT_EXPLAINABLE_CONCEPT, variable); + } + + return new Explainable(explainable); + } + + public IConceptMap.IExplainable Ownership(string owner, string attribute) + { + Validator.NonEmptyString(owner, ConceptError.MISSING_VARIABLE); + Validator.NonEmptyString(attribute, ConceptError.MISSING_VARIABLE); + + Pinvoke.Explainable explainable = + Pinvoke.typedb_driver.explainables_get_ownership(NativeObject, owner, attribute); + if (explainable == null) + { + throw new TypeDBDriverException(ConceptError.NONEXISTENT_EXPLAINABLE_OWNERSHIP, owner, attribute); + } + + return new Explainable(explainable); + } + + public IEnumerable> GetRelations() + { + return new NativeEnumerable( + Pinvoke.typedb_driver.explainables_get_relations_keys(NativeObject)) + .Select(key => new KeyValuePair(key, Relation(key))); + } + + public IEnumerable> GetAttributes() + { + return new NativeEnumerable( + Pinvoke.typedb_driver.explainables_get_attributes_keys(NativeObject)) + .Select(key => new KeyValuePair(key, Attribute(key))); + } + + public IEnumerable, IConceptMap.IExplainable>> GetOwnerships() + { + return new NativeEnumerable( + Pinvoke.typedb_driver.explainables_get_ownerships_keys(NativeObject)) + .Select(pair => + { + string owner = pair._0; + string attribute = pair._1; + return new KeyValuePair, IConceptMap.IExplainable>( + new KeyValuePair(owner, attribute), + Ownership(owner, attribute)); + }); + } + + public override string ToString() + { + return Pinvoke.typedb_driver.explainables_to_string(NativeObject); + } + + public override bool Equals(object? obj) + { + if (Object.ReferenceEquals(this, obj)) + { + return true; + } + + if (obj == null || this.GetType() != obj.GetType()) + { + return false; + } + + Explainables that = (Explainables)obj; + + return Pinvoke.typedb_driver.explainables_equals( + this.NativeObject, that.NativeObject); + } + + public override int GetHashCode() + { + if (_hash == 0) + { + _hash = ComputeHash(); + } + + return _hash; + } + + private int ComputeHash() + { + return (GetRelations().ToList(), + GetAttributes().ToList(), + GetOwnerships().ToList()).GetHashCode(); + } + } + + public class Explainable : NativeObjectWrapper, IConceptMap.IExplainable + { + private string? _conjunction; + private long? _id; + + public Explainable(Pinvoke.Explainable nativeExplainable) + : base(nativeExplainable) + { + } + + public string Conjunction + { + get + { + return _conjunction ?? (_conjunction = + Pinvoke.typedb_driver.explainable_get_conjunction(NativeObject)); + } + } + + public long Id + { + get + { + if (!_id.HasValue) + { + _id = Pinvoke.typedb_driver.explainable_get_id(NativeObject); + } + + return _id.Value; + } + } + + public override string ToString() + { + return "Explainable { id: " + Id + ", conjunction: " + Conjunction + " }"; + } + + public override bool Equals(object? obj) + { + if (Object.ReferenceEquals(this, obj)) + { + return true; + } + + if (obj == null || this.GetType() != obj.GetType()) + { + return false; + } + + Explainable that = (Explainable)obj; + + return this.Id == that.Id; + } + + public override int GetHashCode() + { + return (int)Id; + } + } + } +} diff --git a/csharp/Concept/Answer/ConceptMapGroup.cs b/csharp/Concept/Answer/ConceptMapGroup.cs new file mode 100644 index 0000000000..2414e2fea3 --- /dev/null +++ b/csharp/Concept/Answer/ConceptMapGroup.cs @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +using static TypeDB.Driver.Concept.Concept; + +namespace TypeDB.Driver.Concept +{ + public class ConceptMapGroup : NativeObjectWrapper, IConceptMapGroup + { + private IConcept? _owner; + private int _hash = 0; + + public ConceptMapGroup(Pinvoke.ConceptMapGroup nativeConceptMapGroup) + : base(nativeConceptMapGroup) + { + } + + public IConcept Owner + { + get + { + return _owner ?? (_owner = + ConceptOf(Pinvoke.typedb_driver.concept_map_group_get_owner(NativeObject))); + } + } + + public IEnumerable GetConceptMaps() + { + return new NativeEnumerable( + Pinvoke.typedb_driver.concept_map_group_get_concept_maps(NativeObject)) + .Select(obj => new ConceptMap(obj)); + } + + public override string ToString() + { + return Pinvoke.typedb_driver.concept_map_group_to_string(NativeObject); + } + + public override bool Equals(object? obj) + { + if (Object.ReferenceEquals(this, obj)) + { + return true; + } + + if (obj == null || this.GetType() != obj.GetType()) + { + return false; + } + + ConceptMapGroup that = (ConceptMapGroup)obj; + + return Pinvoke.typedb_driver.concept_map_group_equals( + this.NativeObject, that.NativeObject); + } + + public override int GetHashCode() + { + if (_hash == 0) + { + _hash = ComputeHash(); + } + + return _hash; + } + + private int ComputeHash() + { + return (Owner, GetConceptMaps().ToList()).GetHashCode(); + } + } +} diff --git a/csharp/Concept/Answer/ValueGroup.cs b/csharp/Concept/Answer/ValueGroup.cs new file mode 100644 index 0000000000..504752fb0e --- /dev/null +++ b/csharp/Concept/Answer/ValueGroup.cs @@ -0,0 +1,113 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Concept; +using TypeDB.Driver.Common.Validation; +using static TypeDB.Driver.Concept.Concept; + +using ConceptError = TypeDB.Driver.Common.Error.Concept; +using QueryError = TypeDB.Driver.Common.Error.Query; + +namespace TypeDB.Driver.Concept +{ + public class ValueGroup : NativeObjectWrapper, IValueGroup + { + private IConcept? _owner; + private IValue? _value; + private bool _valueFetched = false; + private int _hash = 0; + + public ValueGroup(Pinvoke.ValueGroup nativeValueGroup) + : base(nativeValueGroup) + { + } + + public IConcept Owner + { + get { return _owner ?? (_owner = ConceptOf(Pinvoke.typedb_driver.value_group_get_owner(NativeObject))); } + } + + public IValue? Value + { + get + { + if (_valueFetched) + { + return _value; + } + + Pinvoke.Concept concept = Pinvoke.typedb_driver.value_group_get_value(NativeObject); + _valueFetched = true; + + if (concept == null) + { + return null; + } + + return (_value = new Value(concept)); + } + } + + public override string ToString() + { + return Pinvoke.typedb_driver.value_group_to_string(NativeObject); + } + + public override bool Equals(object? obj) + { + if (Object.ReferenceEquals(this, obj)) + { + return true; + } + + if (obj == null || this.GetType() != obj.GetType()) + { + return false; + } + + ValueGroup that = (ValueGroup)obj; + + return Pinvoke.typedb_driver.value_group_equals(this.NativeObject, that.NativeObject); + } + + public override int GetHashCode() + { + if (_hash == 0) + { + _hash = ComputeHash(); + } + + return _hash; + } + + private int ComputeHash() + { + return (Owner, Value).GetHashCode(); + } + } +} diff --git a/csharp/Concept/BUILD b/csharp/Concept/BUILD new file mode 100644 index 0000000000..205c3fd966 --- /dev/null +++ b/csharp/Concept/BUILD @@ -0,0 +1,47 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +package(default_visibility = ["//visibility:public"]) + +load("@rules_dotnet//dotnet:defs.bzl", "csharp_library") +load("//csharp:build_opts.bzl", "target_frameworks", "targeting_packs", "nullable_context") +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") + + +csharp_library( + name = "concept", + srcs = glob(["*.cs", "*/*.cs"]), + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp:typedb_driver_pinvoke", + ], + nullable = nullable_context, + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +checkstyle_test( + name = "checkstyle", + include = glob(["*", "*/*"]), + license_type = "apache-header", +) diff --git a/csharp/Concept/Concept.cs b/csharp/Concept/Concept.cs new file mode 100644 index 0000000000..0ccfbf52a5 --- /dev/null +++ b/csharp/Concept/Concept.cs @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; + +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Common.Validation; +using TypeDB.Driver.Concept; + +using DriverError = TypeDB.Driver.Common.Error.Driver; +using InternalError = TypeDB.Driver.Common.Error.Internal; + +namespace TypeDB.Driver.Concept +{ + public abstract class Concept : NativeObjectWrapper, IConcept + { + protected Concept(Pinvoke.Concept nativeConcept) + : base(nativeConcept) + { + } + + public static IConcept ConceptOf(Pinvoke.Concept nativeConcept) + { + if (Pinvoke.typedb_driver.concept_is_entity_type(nativeConcept)) + return new EntityType(nativeConcept); + if (Pinvoke.typedb_driver.concept_is_relation_type(nativeConcept)) + return new RelationType(nativeConcept); + if (Pinvoke.typedb_driver.concept_is_attribute_type(nativeConcept)) + return new AttributeType(nativeConcept); + if (Pinvoke.typedb_driver.concept_is_root_thing_type(nativeConcept)) + return new ThingType.Root(nativeConcept); + if (Pinvoke.typedb_driver.concept_is_entity(nativeConcept)) + return new Entity(nativeConcept); + if (Pinvoke.typedb_driver.concept_is_relation(nativeConcept)) + return new Relation(nativeConcept); + if (Pinvoke.typedb_driver.concept_is_attribute(nativeConcept)) + return new Attribute(nativeConcept); + if (Pinvoke.typedb_driver.concept_is_value(nativeConcept)) + return new Value(nativeConcept); + if (Pinvoke.typedb_driver.concept_is_role_type(nativeConcept)) + return new RoleType(nativeConcept); + + throw new TypeDBDriverException(InternalError.UNEXPECTED_NATIVE_VALUE); + } + + protected static Pinvoke.Transaction NativeTransaction(ITypeDBTransaction transaction) + { + Pinvoke.Transaction nativeTransaction = ((ConceptManager)transaction.Concepts).NativeTransaction; + Validator.ThrowIfFalse(nativeTransaction.IsOwned, DriverError.TRANSACTION_CLOSED); + + return nativeTransaction; + } + + public override string ToString() + { + return Pinvoke.typedb_driver.concept_to_string(NativeObject); + } + + public override bool Equals(object? obj) + { + if (Object.ReferenceEquals(this, obj)) + { + return true; + } + + if (obj == null || this.GetType() != obj.GetType()) + { + return false; + } + + Concept that = (Concept)obj; + return Pinvoke.typedb_driver.concept_equals(this.NativeObject, that.NativeObject); + } + + public abstract override int GetHashCode(); + } +} diff --git a/csharp/Concept/ConceptManager.cs b/csharp/Concept/ConceptManager.cs new file mode 100644 index 0000000000..d07d6c581f --- /dev/null +++ b/csharp/Concept/ConceptManager.cs @@ -0,0 +1,187 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Concept; +using TypeDB.Driver.Common.Validation; + +using DriverError = TypeDB.Driver.Common.Error.Driver; +using ConceptError = TypeDB.Driver.Common.Error.Concept; + +namespace TypeDB.Driver.Concept +{ + public class ConceptManager : IConceptManager + { + public readonly Pinvoke.Transaction NativeTransaction; + + private IEntityType? _rootEntityType; + private IRelationType? _rootRelationType; + private IAttributeType? _rootAttributeType; + + public ConceptManager(Pinvoke.Transaction nativeTransaction) + { + NativeTransaction = nativeTransaction; + } + + public IEntityType RootEntityType + { + get + { + return _rootEntityType ?? (_rootEntityType = + new EntityType(Pinvoke.typedb_driver.concepts_get_root_entity_type())); + } + } + + public IRelationType RootRelationType + { + get + { + return _rootRelationType ?? (_rootRelationType = + new RelationType(Pinvoke.typedb_driver.concepts_get_root_relation_type())); + } + } + + public IAttributeType RootAttributeType + { + get + { + return _rootAttributeType ?? (_rootAttributeType = + new AttributeType(Pinvoke.typedb_driver.concepts_get_root_attribute_type())); + } + } + + public Promise GetEntityType(string label) + { + Validator.NonEmptyString(label, ConceptError.MISSING_LABEL); + Validator.ThrowIfFalse(NativeTransaction.IsOwned, DriverError.TRANSACTION_CLOSED); + + return Promise.Map( + Pinvoke.typedb_driver.concepts_get_entity_type(NativeTransaction, label).Resolve, + obj => new EntityType(obj)); + } + + public Promise GetRelationType(string label) + { + Validator.NonEmptyString(label, ConceptError.MISSING_LABEL); + Validator.ThrowIfFalse(NativeTransaction.IsOwned, DriverError.TRANSACTION_CLOSED); + + return Promise.Map( + Pinvoke.typedb_driver.concepts_get_relation_type(NativeTransaction, label).Resolve, + obj => new RelationType(obj)); + } + + public Promise GetAttributeType(string label) + { + Validator.NonEmptyString(label, ConceptError.MISSING_LABEL); + Validator.ThrowIfFalse(NativeTransaction.IsOwned, DriverError.TRANSACTION_CLOSED); + + return Promise.Map( + Pinvoke.typedb_driver.concepts_get_attribute_type(NativeTransaction, label).Resolve, + obj => new AttributeType(obj)); + } + + public Promise PutEntityType(string label) + { + Validator.NonEmptyString(label, ConceptError.MISSING_LABEL); + Validator.ThrowIfFalse(NativeTransaction.IsOwned, DriverError.TRANSACTION_CLOSED); + + return Promise.Map( + Pinvoke.typedb_driver.concepts_put_entity_type(NativeTransaction, label).Resolve, + obj => new EntityType(obj)); + } + + public Promise PutRelationType(string label) + { + Validator.NonEmptyString(label, ConceptError.MISSING_LABEL); + Validator.ThrowIfFalse(NativeTransaction.IsOwned, DriverError.TRANSACTION_CLOSED); + + return Promise.Map( + Pinvoke.typedb_driver.concepts_put_relation_type(NativeTransaction, label).Resolve, + obj => new RelationType(obj)); + } + + public Promise PutAttributeType(string label, IValue.ValueType valueType) + { + Validator.NonEmptyString(label, ConceptError.MISSING_LABEL); + Validator.ThrowIfFalse(NativeTransaction.IsOwned, DriverError.TRANSACTION_CLOSED); + + return Promise.Map( + Pinvoke.typedb_driver.concepts_put_attribute_type( + NativeTransaction, label, (Pinvoke.ValueType)valueType).Resolve, + obj => new AttributeType(obj)); + } + + public Promise GetEntity(string iid) + { + Validator.NonEmptyString(iid, ConceptError.MISSING_IID); + Validator.ThrowIfFalse(NativeTransaction.IsOwned, DriverError.TRANSACTION_CLOSED); + + return Promise.Map( + Pinvoke.typedb_driver.concepts_get_entity(NativeTransaction, iid).Resolve, + obj => new Entity(obj)); + } + + public Promise GetRelation(string iid) + { + Validator.NonEmptyString(iid, ConceptError.MISSING_IID); + Validator.ThrowIfFalse(NativeTransaction.IsOwned, DriverError.TRANSACTION_CLOSED); + + return Promise.Map( + Pinvoke.typedb_driver.concepts_get_relation(NativeTransaction, iid).Resolve, + obj => new Relation(obj)); + } + + public Promise GetAttribute(string iid) + { + Validator.NonEmptyString(iid, ConceptError.MISSING_IID); + Validator.ThrowIfFalse(NativeTransaction.IsOwned, DriverError.TRANSACTION_CLOSED); + + return Promise.Map( + Pinvoke.typedb_driver.concepts_get_attribute(NativeTransaction, iid).Resolve, + obj => new Attribute(obj)); + } + + public IList GetSchemaExceptions() + { + + Validator.ThrowIfFalse(NativeTransaction.IsOwned, DriverError.TRANSACTION_CLOSED); + + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.concepts_get_schema_exceptions(NativeTransaction)) + .Select(e => new TypeDBException( + Pinvoke.typedb_driver.schema_exception_code(e), + Pinvoke.typedb_driver.schema_exception_message(e))) + .ToList(); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + } +} diff --git a/csharp/Concept/Thing/Attribute.cs b/csharp/Concept/Thing/Attribute.cs new file mode 100644 index 0000000000..1b69b2094b --- /dev/null +++ b/csharp/Concept/Thing/Attribute.cs @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Concept; +using static TypeDB.Driver.Concept.Thing; + +namespace TypeDB.Driver.Concept +{ + public class Attribute : Thing, IAttribute + { + public Attribute(Pinvoke.Concept nativeConcept) + : base(nativeConcept) + { + } + + public override IAttributeType Type + { + get { return new AttributeType(Pinvoke.typedb_driver.attribute_get_type(NativeObject)); } + } + + public IValue Value + { + get { return new Value(Pinvoke.typedb_driver.attribute_get_value(NativeObject)); } + } + + public IEnumerable GetOwners(ITypeDBTransaction transaction) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.attribute_get_owners( + NativeTransaction(transaction), NativeObject, null)) + .Select(obj => ThingOf(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public IEnumerable GetOwners(ITypeDBTransaction transaction, IThingType ownerType) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.attribute_get_owners( + NativeTransaction(transaction), + NativeObject, + ((ThingType)ownerType).NativeObject)) + .Select(obj => ThingOf(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + } +} diff --git a/csharp/Concept/Thing/Entity.cs b/csharp/Concept/Thing/Entity.cs new file mode 100644 index 0000000000..ddde4e3d18 --- /dev/null +++ b/csharp/Concept/Thing/Entity.cs @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using TypeDB.Driver.Api; +using TypeDB.Driver.Concept; + +namespace TypeDB.Driver.Concept +{ + public class Entity : Thing, IEntity + { + public Entity(Pinvoke.Concept nativeConcept) + : base(nativeConcept) + { + } + + public override IEntityType Type + { + get { return new EntityType(Pinvoke.typedb_driver.entity_get_type(NativeObject)); } + } + + public IEntity AsEntity() + { + return this; + } + } +} \ No newline at end of file diff --git a/csharp/Concept/Thing/Relation.cs b/csharp/Concept/Thing/Relation.cs new file mode 100644 index 0000000000..ca9756941d --- /dev/null +++ b/csharp/Concept/Thing/Relation.cs @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Concept; +using static TypeDB.Driver.Concept.Thing; + +namespace TypeDB.Driver.Concept +{ + public class Relation : Thing, IRelation + { + private IRelationType? _type; + + public Relation(Pinvoke.Concept nativeConcept) + : base(nativeConcept) + { + } + + public override IRelationType Type + { + get { return _type ?? (_type = new RelationType(Pinvoke.typedb_driver.relation_get_type(NativeObject))); } + } + + public VoidPromise AddPlayer( + ITypeDBTransaction transaction, IRoleType roleType, IThing player) + { + return new VoidPromise(Pinvoke.typedb_driver.relation_add_role_player( + NativeTransaction(transaction), + NativeObject, + ((RoleType)roleType).NativeObject, + ((Thing)player).NativeObject).Resolve); + } + + public VoidPromise RemovePlayer( + ITypeDBTransaction transaction, IRoleType roleType, IThing player) + { + return new VoidPromise(Pinvoke.typedb_driver.relation_remove_role_player( + NativeTransaction(transaction), + NativeObject, + ((RoleType)roleType).NativeObject, + ((Thing)player).NativeObject).Resolve); + } + + public IEnumerable GetPlayersByRoleType( + ITypeDBTransaction transaction, params IRoleType[] roleTypes) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.relation_get_players_by_role_type( + NativeTransaction(transaction), + NativeObject, + roleTypes.Select(obj => (Pinvoke.Concept)((RoleType)obj).NativeObject).ToArray())) + .Select(obj => ThingOf(obj)); + + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public Dictionary> GetPlayers(ITypeDBTransaction transaction) + { + var rolePlayers = new Dictionary>(); + + try + { + var nativeRolePlayers = new NativeEnumerable( + Pinvoke.typedb_driver.relation_get_role_players( + NativeTransaction(transaction), NativeObject)); + + foreach (var rolePlayer in nativeRolePlayers) + { + RoleType role = new RoleType(Pinvoke.typedb_driver.role_player_get_role_type(rolePlayer)); + IThing player = ThingOf(Pinvoke.typedb_driver.role_player_get_player(rolePlayer)); + + if (!rolePlayers.ContainsKey(role)) + { + rolePlayers[role] = new List(); + } + + rolePlayers[role].Add(player); + } + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + + return rolePlayers; + } + + public IEnumerable GetRelating(ITypeDBTransaction transaction) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.relation_get_relating( + NativeTransaction(transaction), NativeObject)) + .Select(obj => new RoleType(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + } +} diff --git a/csharp/Concept/Thing/Thing.cs b/csharp/Concept/Thing/Thing.cs new file mode 100644 index 0000000000..2ff25a7cbe --- /dev/null +++ b/csharp/Concept/Thing/Thing.cs @@ -0,0 +1,196 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Concept; +using static TypeDB.Driver.Api.IThingType; + +using InternalError = TypeDB.Driver.Common.Error.Internal; + +namespace TypeDB.Driver.Concept +{ + public abstract class Thing : Concept, IThing + { + private string? _iid; + private int _hash = 0; + + internal Thing(Pinvoke.Concept nativeConcept) + : base(nativeConcept) + { + } + + public static IThing ThingOf(Pinvoke.Concept nativeConcept) + { + if (Pinvoke.typedb_driver.concept_is_entity(nativeConcept)) + return new Entity(nativeConcept); + if (Pinvoke.typedb_driver.concept_is_relation(nativeConcept)) + return new Relation(nativeConcept); + if (Pinvoke.typedb_driver.concept_is_attribute(nativeConcept)) + return new Attribute(nativeConcept); + + throw new TypeDBDriverException(InternalError.UNEXPECTED_NATIVE_VALUE); + } + + public string IID + { + get { return _iid ?? (_iid = Pinvoke.typedb_driver.thing_get_iid(NativeObject)); } + } + + public abstract IThingType Type { get; } + + public bool IsInferred() + { + return Pinvoke.typedb_driver.thing_get_is_inferred(NativeObject); + } + + public IThing AsThing() + { + return this; + } + + public IEnumerable GetHas(ITypeDBTransaction transaction, params IAttributeType[] attributeTypes) + { + Pinvoke.Concept[] attributeTypesArray = attributeTypes + .Select(obj => ((AttributeType)obj).NativeObject) + .ToArray(); + + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.thing_get_has( + NativeTransaction(transaction), + NativeObject, + attributeTypesArray, + new Pinvoke.Annotation[0])) + .Select(obj => new Attribute(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public IEnumerable GetHas( + ITypeDBTransaction transaction, ICollection annotations) + { + Pinvoke.Annotation[] annotationsArray = annotations + .Select(obj => obj.NativeObject) + .ToArray(); + + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.thing_get_has( + NativeTransaction(transaction), + NativeObject, + new Pinvoke.Concept[0], + annotationsArray)) + .Select(obj => new Attribute(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public IEnumerable GetRelations( + ITypeDBTransaction transaction, params IRoleType[] roleTypes) + { + Pinvoke.Concept[] roleTypesArray = roleTypes + .Select(obj => ((RoleType)obj).NativeObject) + .ToArray(); + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.thing_get_relations( + NativeTransaction(transaction), NativeObject, roleTypesArray)) + .Select(obj => new Relation(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public IEnumerable GetPlaying(ITypeDBTransaction transaction) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.thing_get_playing( + NativeTransaction(transaction), NativeObject)) + .Select(obj => new RoleType(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public VoidPromise SetHas(ITypeDBTransaction transaction, IAttribute attribute) + { + return new VoidPromise(Pinvoke.typedb_driver.thing_set_has( + NativeTransaction(transaction), + NativeObject, + ((Attribute)attribute).NativeObject).Resolve); + } + + public VoidPromise UnsetHas(ITypeDBTransaction transaction, IAttribute attribute) + { + return new VoidPromise(Pinvoke.typedb_driver.thing_unset_has( + NativeTransaction(transaction), + NativeObject, + ((Attribute)attribute).NativeObject).Resolve); + } + + public VoidPromise Delete(ITypeDBTransaction transaction) + { + return new VoidPromise(Pinvoke.typedb_driver.thing_delete( + NativeTransaction(transaction), NativeObject).Resolve); + } + + public Promise IsDeleted(ITypeDBTransaction transaction) + { + return new Promise(Pinvoke.typedb_driver.thing_is_deleted( + NativeTransaction(transaction), NativeObject).Resolve); + } + + public override int GetHashCode() + { + if (_hash == 0) + { + _hash = ComputeHash(); + } + + return _hash; + } + + private int ComputeHash() + { + return IID.GetHashCode(); + } + } +} \ No newline at end of file diff --git a/csharp/Concept/Type/AttributeType.cs b/csharp/Concept/Type/AttributeType.cs new file mode 100644 index 0000000000..ae865dc55e --- /dev/null +++ b/csharp/Concept/Type/AttributeType.cs @@ -0,0 +1,284 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Concept; +using static TypeDB.Driver.Api.IConcept.Transitivity; +using static TypeDB.Driver.Api.IThingType; +using static TypeDB.Driver.Api.IValue.ValueType; +using static TypeDB.Driver.Concept.ThingType; + +namespace TypeDB.Driver.Concept +{ + public class AttributeType : ThingType, IAttributeType + { + public AttributeType(Pinvoke.Concept nativeConcept) + : base(nativeConcept) + { + } + + public IValue.ValueType ValueType + { + get + { + return (IValue.ValueType)Pinvoke.typedb_driver.attribute_type_get_value_type(NativeObject); + } + } + + public VoidPromise SetSupertype(ITypeDBTransaction transaction, IAttributeType attributeType) + { + return new VoidPromise(Pinvoke.typedb_driver.attribute_type_set_supertype( + NativeTransaction(transaction), + NativeObject, + ((AttributeType)attributeType).NativeObject).Resolve); + } + + public override Promise GetSupertype(ITypeDBTransaction transaction) + { + return Promise.Map( + Pinvoke.typedb_driver.attribute_type_get_supertype( + NativeTransaction(transaction), NativeObject).Resolve, + obj => new AttributeType(obj)); + } + + public override IEnumerable GetSupertypes(ITypeDBTransaction transaction) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.attribute_type_get_supertypes( + NativeTransaction(transaction), NativeObject)) + .Select(obj => new AttributeType(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public override IEnumerable GetSubtypes(ITypeDBTransaction transaction) + { + return GetSubtypes(transaction, Transitive); + } + + public IEnumerable GetSubtypes( + ITypeDBTransaction transaction, IValue.ValueType valueType) + { + return GetSubtypes(transaction, valueType, Transitive); + } + + public override IEnumerable GetSubtypes( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.attribute_type_get_subtypes( + NativeTransaction(transaction), + NativeObject, + (Pinvoke.Transitivity)transitivity)) + .Select(obj => new AttributeType(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public IEnumerable GetSubtypes( + ITypeDBTransaction transaction, + IValue.ValueType valueType, + IConcept.Transitivity transitivity) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.attribute_type_get_subtypes_with_value_type( + NativeTransaction(transaction), + NativeObject, + (Pinvoke.ValueType)valueType, + (Pinvoke.Transitivity)transitivity)) + .Select(obj => new AttributeType(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public override IEnumerable GetInstances(ITypeDBTransaction transaction) + { + return GetInstances(transaction, Transitive); + } + + public override IEnumerable GetInstances( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.attribute_type_get_instances( + NativeTransaction(transaction), + NativeObject, + (Pinvoke.Transitivity)transitivity)) + .Select(obj => new Attribute(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public IEnumerable GetOwners(ITypeDBTransaction transaction) + { + return GetOwners(transaction, new Annotation[0]); + } + + public IEnumerable GetOwners( + ITypeDBTransaction transaction, ICollection annotations) + { + return GetOwners(transaction, annotations, Transitive); + } + + public IEnumerable GetOwners( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity) + { + return GetOwners(transaction, new Annotation[0], transitivity); + } + + public IEnumerable GetOwners( + ITypeDBTransaction transaction, + ICollection annotations, + IConcept.Transitivity transitivity) + { + Pinvoke.Annotation[] annotationsArray = + annotations.Select(obj => obj.NativeObject).ToArray(); + + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.attribute_type_get_owners( + NativeTransaction(transaction), + NativeObject, + (Pinvoke.Transitivity)transitivity, + annotationsArray)) + .Select(obj => ThingTypeOf(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public Promise Put(ITypeDBTransaction transaction, string value) + { + return Put(transaction, new Value(value)); + } + + public Promise Put(ITypeDBTransaction transaction, long value) + { + return Put(transaction, new Value(value)); + } + + public Promise Put(ITypeDBTransaction transaction, double value) + { + return Put(transaction, new Value(value)); + } + + public Promise Put(ITypeDBTransaction transaction, bool value) + { + return Put(transaction, new Value(value)); + } + + public Promise Put(ITypeDBTransaction transaction, System.DateTime value) + { + return Put(transaction, new Value(value)); + } + + public Promise Put(ITypeDBTransaction transaction, IValue value) + { + return Promise.Map( + Pinvoke.typedb_driver.attribute_type_put( + NativeTransaction(transaction), + NativeObject, + ((Value)value).NativeObject).Resolve, + obj => new Attribute(obj)); + } + + public Promise Get(ITypeDBTransaction transaction, string value) + { + return Get(transaction, new Value(value)); + } + + public Promise Get(ITypeDBTransaction transaction, long value) + { + return Get(transaction, new Value(value)); + } + + public Promise Get(ITypeDBTransaction transaction, double value) + { + return Get(transaction, new Value(value)); + } + + public Promise Get(ITypeDBTransaction transaction, bool value) + { + return Get(transaction, new Value(value)); + } + + public Promise Get(ITypeDBTransaction transaction, System.DateTime value) + { + return Get(transaction, new Value(value)); + } + + public Promise Get(ITypeDBTransaction transaction, IValue value) + { + return Promise.Map( + Pinvoke.typedb_driver.attribute_type_get( + NativeTransaction(transaction), + NativeObject, + ((Value)value).NativeObject).Resolve, + obj => new Attribute(obj)); + } + + public Promise GetRegex(ITypeDBTransaction transaction) + { + return new Promise(Pinvoke.typedb_driver.attribute_type_get_regex( + NativeTransaction(transaction), NativeObject).Resolve); + } + + public VoidPromise SetRegex(ITypeDBTransaction transaction, string regex) + { + return new VoidPromise(Pinvoke.typedb_driver.attribute_type_set_regex( + NativeTransaction(transaction), NativeObject, regex).Resolve); + } + + public VoidPromise UnsetRegex(ITypeDBTransaction transaction) + { + return new VoidPromise(Pinvoke.typedb_driver.attribute_type_unset_regex( + NativeTransaction(transaction), NativeObject).Resolve); + } + } +} diff --git a/csharp/Concept/Type/EntityType.cs b/csharp/Concept/Type/EntityType.cs new file mode 100644 index 0000000000..ddce395cd5 --- /dev/null +++ b/csharp/Concept/Type/EntityType.cs @@ -0,0 +1,119 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Concept; +using static TypeDB.Driver.Api.IConcept.Transitivity; + +namespace TypeDB.Driver.Concept +{ + public class EntityType : ThingType, IEntityType + { + public EntityType(Pinvoke.Concept nativeConcept) + : base(nativeConcept) + { + } + + public Promise Create(ITypeDBTransaction transaction) + { + return Promise.Map( + Pinvoke.typedb_driver.entity_type_create( + NativeTransaction(transaction), NativeObject).Resolve, + obj => new Entity(obj)); + } + + public VoidPromise SetSupertype(ITypeDBTransaction transaction, IEntityType entityType) + { + return new VoidPromise(Pinvoke.typedb_driver.entity_type_set_supertype( + NativeTransaction(transaction), NativeObject, ((EntityType)entityType).NativeObject).Resolve); + } + + public override Promise GetSupertype(ITypeDBTransaction transaction) + { + return Promise.Map( + Pinvoke.typedb_driver.entity_type_get_supertype( + NativeTransaction(transaction), NativeObject).Resolve, + obj => new EntityType(obj)); + } + + public override IEnumerable GetSupertypes(ITypeDBTransaction transaction) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.entity_type_get_supertypes( + NativeTransaction(transaction), NativeObject)) + .Select(obj => new EntityType(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public override IEnumerable GetSubtypes(ITypeDBTransaction transaction) + { + return GetSubtypes(transaction, Transitive); + } + + public override IEnumerable GetSubtypes( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.entity_type_get_subtypes( + NativeTransaction(transaction), NativeObject, (Pinvoke.Transitivity)transitivity)) + .Select(obj => new EntityType(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public override IEnumerable GetInstances(ITypeDBTransaction transaction) + { + return GetInstances(transaction, Transitive); + } + + public override IEnumerable GetInstances( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.entity_type_get_instances( + NativeTransaction(transaction), NativeObject, (Pinvoke.Transitivity)transitivity)) + .Select(obj => new Entity(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + } +} diff --git a/csharp/Concept/Type/RelationType.cs b/csharp/Concept/Type/RelationType.cs new file mode 100644 index 0000000000..f308081bfa --- /dev/null +++ b/csharp/Concept/Type/RelationType.cs @@ -0,0 +1,193 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Concept; +using static TypeDB.Driver.Api.IConcept.Transitivity; + +namespace TypeDB.Driver.Concept +{ + public class RelationType : ThingType, IRelationType + { + public RelationType(Pinvoke.Concept nativeConcept) + : base(nativeConcept) + { + } + + public Promise Create(ITypeDBTransaction transaction) + { + return Promise.Map( + Pinvoke.typedb_driver.relation_type_create( + NativeTransaction(transaction), NativeObject).Resolve, + obj => new Relation(obj)); + } + + public VoidPromise SetSupertype(ITypeDBTransaction transaction, IRelationType relationType) + { + return new VoidPromise(Pinvoke.typedb_driver.relation_type_set_supertype( + NativeTransaction(transaction), + NativeObject, + ((RelationType)relationType).NativeObject).Resolve); + } + + public IEnumerable GetRelates(ITypeDBTransaction transaction) + { + return GetRelates(transaction, Transitive); + } + + public IEnumerable GetRelates( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity) + { + try + { + return new NativeEnumerable(Pinvoke.typedb_driver.relation_type_get_relates( + NativeTransaction(transaction), NativeObject, (Pinvoke.Transitivity)transitivity)) + .Select(obj => new RoleType(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public Promise GetRelates(ITypeDBTransaction transaction, string roleLabel) + { + return Promise.Map( + Pinvoke.typedb_driver.relation_type_get_relates_for_role_label( + NativeTransaction(transaction), NativeObject, roleLabel).Resolve, + obj => new RoleType(obj)); + } + + public Promise GetRelatesOverridden(ITypeDBTransaction transaction, IRoleType roleType) + { + return GetRelatesOverridden(transaction, roleType.Label.Name); + } + + public Promise GetRelatesOverridden(ITypeDBTransaction transaction, string roleLabel) + { + return Promise.Map( + Pinvoke.typedb_driver.relation_type_get_relates_overridden( + NativeTransaction(transaction), NativeObject, roleLabel).Resolve, + obj => new RoleType(obj)); + } + + public VoidPromise SetRelates(ITypeDBTransaction transaction, string roleLabel) + { + return SetRelates(transaction, roleLabel, (string?)null); + } + + public VoidPromise SetRelates( + ITypeDBTransaction transaction, string roleLabel, IRoleType overriddenType) + { + return SetRelates(transaction, roleLabel, overriddenType.Label.Name); + } + + public VoidPromise SetRelates( + ITypeDBTransaction transaction, string roleLabel, string? overriddenLabel) + { + return new VoidPromise(Pinvoke.typedb_driver.relation_type_set_relates( + NativeTransaction(transaction), NativeObject, roleLabel, overriddenLabel).Resolve); + } + + public VoidPromise UnsetRelates(ITypeDBTransaction transaction, IRoleType roleType) + { + return new VoidPromise(Pinvoke.typedb_driver.relation_type_unset_relates( + NativeTransaction(transaction), NativeObject, roleType.Label.Name).Resolve); + } + + public VoidPromise UnsetRelates(ITypeDBTransaction transaction, string roleLabel) + { + return new VoidPromise(Pinvoke.typedb_driver.relation_type_unset_relates( + NativeTransaction(transaction), NativeObject, roleLabel).Resolve); + } + + public override Promise GetSupertype(ITypeDBTransaction transaction) + { + return Promise.Map( + Pinvoke.typedb_driver.relation_type_get_supertype( + NativeTransaction(transaction), NativeObject).Resolve, + obj => new RelationType(obj)); + } + + public override IEnumerable GetSupertypes(ITypeDBTransaction transaction) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.relation_type_get_supertypes( + NativeTransaction(transaction), NativeObject)) + .Select(obj => new RelationType(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public override IEnumerable GetSubtypes(ITypeDBTransaction transaction) + { + return GetSubtypes(transaction, Transitive); + } + + public override IEnumerable GetSubtypes( + ITypeDBTransaction transaction, + IConcept.Transitivity transitivity) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.relation_type_get_subtypes( + NativeTransaction(transaction), NativeObject, (Pinvoke.Transitivity)transitivity)) + .Select(obj => new RelationType(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public override IEnumerable GetInstances(ITypeDBTransaction transaction) + { + return GetInstances(transaction, Transitive); + } + + public override IEnumerable GetInstances( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.relation_type_get_instances( + NativeTransaction(transaction), NativeObject, (Pinvoke.Transitivity)transitivity)) + .Select(obj => new Relation(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + } +} diff --git a/csharp/Concept/Type/RoleType.cs b/csharp/Concept/Type/RoleType.cs new file mode 100644 index 0000000000..f3cfaeed66 --- /dev/null +++ b/csharp/Concept/Type/RoleType.cs @@ -0,0 +1,217 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Concept; +using static TypeDB.Driver.Api.IConcept.Transitivity; +using static TypeDB.Driver.Concept.Thing; +using static TypeDB.Driver.Concept.ThingType; + +namespace TypeDB.Driver.Concept +{ + public class RoleType : Type, IRoleType + { + private Label? _label; + + public RoleType(Pinvoke.Concept nativeConcept) + : base(nativeConcept) + { + } + + public override bool IsRoot() + { + return Pinvoke.typedb_driver.role_type_is_root(NativeObject); + } + + public override bool IsAbstract() + { + return Pinvoke.typedb_driver.role_type_is_abstract(NativeObject); + } + + public override Label Label + { + get + { + if (!_label.HasValue) + { + _label = new Label( + Pinvoke.typedb_driver.role_type_get_scope(NativeObject), + Pinvoke.typedb_driver.role_type_get_name(NativeObject)); + } + + return _label.Value; + } + } + + public override VoidPromise Delete(ITypeDBTransaction transaction) + { + return new VoidPromise(Pinvoke.typedb_driver.role_type_delete( + NativeTransaction(transaction), NativeObject).Resolve); + } + + public override Promise IsDeleted(ITypeDBTransaction transaction) + { + return new Promise(Pinvoke.typedb_driver.role_type_is_deleted( + NativeTransaction(transaction), NativeObject).Resolve); + } + + public override VoidPromise SetLabel(ITypeDBTransaction transaction, string label) + { + return new VoidPromise(Pinvoke.typedb_driver.role_type_set_label( + NativeTransaction(transaction), NativeObject, label).Resolve); + } + + public override Promise GetSupertype(ITypeDBTransaction transaction) + { + return Promise.Map( + Pinvoke.typedb_driver.role_type_get_supertype( + NativeTransaction(transaction), NativeObject).Resolve, + obj => new RoleType(obj)); + } + + public override IEnumerable GetSupertypes(ITypeDBTransaction transaction) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.role_type_get_supertypes( + NativeTransaction(transaction), NativeObject)) + .Select(obj => new RoleType(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public override IEnumerable GetSubtypes(ITypeDBTransaction transaction) + { + return GetSubtypes(transaction, Transitive); + } + + public override IEnumerable GetSubtypes( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.role_type_get_subtypes( + NativeTransaction(transaction), NativeObject, (Pinvoke.Transitivity)transitivity)) + .Select(obj => new RoleType(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public Promise GetRelationType(ITypeDBTransaction transaction) + { + return Promise.Map( + Pinvoke.typedb_driver.role_type_get_relation_type( + NativeTransaction(transaction), NativeObject).Resolve, + obj => new RelationType(obj)); + } + + public IEnumerable GetRelationTypes(ITypeDBTransaction transaction) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.role_type_get_relation_types( + NativeTransaction(transaction), NativeObject)) + .Select(obj => new RelationType(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public IEnumerable GetPlayerTypes(ITypeDBTransaction transaction) + { + return GetPlayerTypes(transaction, Transitive); + } + + public IEnumerable GetPlayerTypes( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.role_type_get_player_types( + NativeTransaction(transaction), NativeObject, (Pinvoke.Transitivity)transitivity)) + .Select(obj => ThingTypeOf(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public IEnumerable GetRelationInstances(ITypeDBTransaction transaction) + { + return GetRelationInstances(transaction, Transitive); + } + + public IEnumerable GetRelationInstances( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.role_type_get_relation_instances( + NativeTransaction(transaction), NativeObject, (Pinvoke.Transitivity)transitivity)) + .Select(obj => new Relation(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public IEnumerable GetPlayerInstances(ITypeDBTransaction transaction) + { + return GetPlayerInstances(transaction, Transitive); + } + + public IEnumerable GetPlayerInstances( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.role_type_get_player_instances( + NativeTransaction(transaction), NativeObject, (Pinvoke.Transitivity)transitivity)) + .Select(obj => ThingOf(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + } +} diff --git a/csharp/Concept/Type/ThingType.cs b/csharp/Concept/Type/ThingType.cs new file mode 100644 index 0000000000..c19c927a8f --- /dev/null +++ b/csharp/Concept/Type/ThingType.cs @@ -0,0 +1,381 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Concept; +using static TypeDB.Driver.Api.IConcept.Transitivity; +using static TypeDB.Driver.Api.IThingType; + +using InternalError = TypeDB.Driver.Common.Error.Internal; + +namespace TypeDB.Driver.Concept +{ + public abstract class ThingType : Type, IThingType + { + private Label? _label; + + internal ThingType(Pinvoke.Concept nativeConcept) + : base(nativeConcept) + { + } + + public static IThingType ThingTypeOf(Pinvoke.Concept nativeConcept) + { + if (Pinvoke.typedb_driver.concept_is_entity_type(nativeConcept)) + return new EntityType(nativeConcept); + if (Pinvoke.typedb_driver.concept_is_relation_type(nativeConcept)) + return new RelationType(nativeConcept); + if (Pinvoke.typedb_driver.concept_is_attribute_type(nativeConcept)) + return new AttributeType(nativeConcept); + if (Pinvoke.typedb_driver.concept_is_root_thing_type(nativeConcept)) + return new Root(nativeConcept); + + throw new TypeDBDriverException(InternalError.UNEXPECTED_NATIVE_VALUE); + } + + public abstract IEnumerable GetInstances(ITypeDBTransaction transaction); + + public abstract IEnumerable GetInstances( + ITypeDBTransaction transaction, + IConcept.Transitivity transitivity); + + public override bool IsRoot() + { + try + { + return Pinvoke.typedb_driver.thing_type_is_root(NativeObject); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public override bool IsAbstract() + { + try + { + return Pinvoke.typedb_driver.thing_type_is_abstract(NativeObject); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public override Label Label + { + get + { + if (!_label.HasValue) + { + _label = new Label(Pinvoke.typedb_driver.thing_type_get_label(NativeObject)); + } + + return _label.Value; + } + } + + public override VoidPromise Delete(ITypeDBTransaction transaction) + { + return new VoidPromise(Pinvoke.typedb_driver.thing_type_delete( + NativeTransaction(transaction), NativeObject).Resolve); + } + + public override Promise IsDeleted(ITypeDBTransaction transaction) + { + return new Promise(Pinvoke.typedb_driver.thing_type_is_deleted( + NativeTransaction(transaction), NativeObject).Resolve); + } + + public override VoidPromise SetLabel(ITypeDBTransaction transaction, string label) + { + return new VoidPromise(Pinvoke.typedb_driver.thing_type_set_label( + NativeTransaction(transaction), NativeObject, label).Resolve); + } + + public VoidPromise SetAbstract(ITypeDBTransaction transaction) + { + return new VoidPromise(Pinvoke.typedb_driver.thing_type_set_abstract( + NativeTransaction(transaction), NativeObject).Resolve); + } + + public VoidPromise UnsetAbstract(ITypeDBTransaction transaction) + { + return new VoidPromise(Pinvoke.typedb_driver.thing_type_unset_abstract( + NativeTransaction(transaction), NativeObject).Resolve); + } + + public VoidPromise SetPlays(ITypeDBTransaction transaction, IRoleType roleType) + { + return new VoidPromise(Pinvoke.typedb_driver.thing_type_set_plays( + NativeTransaction(transaction), NativeObject, ((RoleType)roleType).NativeObject, null).Resolve); + } + + public VoidPromise SetPlays( + ITypeDBTransaction transaction, IRoleType roleType, IRoleType overriddenRoleType) + { + return new VoidPromise(Pinvoke.typedb_driver.thing_type_set_plays( + NativeTransaction(transaction), + NativeObject, + ((RoleType)roleType).NativeObject, + ((RoleType)overriddenRoleType).NativeObject).Resolve); + } + + public VoidPromise SetOwns(ITypeDBTransaction transaction, IAttributeType attributeType) + { + return SetOwns(transaction, attributeType, null, new Annotation[0]); + } + + public VoidPromise SetOwns( + ITypeDBTransaction transaction, + IAttributeType attributeType, + ICollection annotations) + { + return SetOwns(transaction, attributeType, null, annotations); + } + + public VoidPromise SetOwns( + ITypeDBTransaction transaction, IAttributeType attributeType, IAttributeType overriddenType) + { + return SetOwns(transaction, attributeType, overriddenType, new Annotation[0]); + } + + public VoidPromise SetOwns( + ITypeDBTransaction transaction, + IAttributeType attributeType, + IAttributeType? overriddenType, + ICollection annotations) + { + Pinvoke.Concept? overriddenTypeNative = overriddenType != null + ? ((AttributeType)overriddenType).NativeObject + : null; + + Pinvoke.Annotation[] annotationsArray = annotations + .Select(obj => obj.NativeObject) + .ToArray(); + + return new VoidPromise(Pinvoke.typedb_driver.thing_type_set_owns( + NativeTransaction(transaction), + NativeObject, + ((AttributeType)attributeType).NativeObject, + overriddenTypeNative, + annotationsArray).Resolve); + } + + public IEnumerable GetPlays(ITypeDBTransaction transaction) + { + return GetPlays(transaction, Transitive); + } + + public IEnumerable GetPlays( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity) + { + try + { + return new NativeEnumerable(Pinvoke.typedb_driver.thing_type_get_plays( + NativeTransaction(transaction), NativeObject, (Pinvoke.Transitivity)transitivity)) + .Select(obj => new RoleType(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public Promise GetPlaysOverridden(ITypeDBTransaction transaction, IRoleType roleType) + { + return Promise.Map( + Pinvoke.typedb_driver.thing_type_get_plays_overridden( + NativeTransaction(transaction), NativeObject, ((RoleType)roleType).NativeObject).Resolve, + obj => new RoleType(obj)); + } + + public IEnumerable GetOwns(ITypeDBTransaction transaction) + { + return GetOwns(transaction, Transitive, new Annotation[0]); + } + + public IEnumerable GetOwns(ITypeDBTransaction transaction, IValue.ValueType valueType) + { + return GetOwns( + transaction, valueType, Transitive, new Annotation[0]); + } + + public IEnumerable GetOwns( + ITypeDBTransaction transaction, ICollection annotations) + { + return GetOwns(transaction, Transitive, annotations); + } + + public IEnumerable GetOwns( + ITypeDBTransaction transaction, IValue.ValueType? valueType, ICollection annotations) + { + return GetOwns(transaction, valueType, Transitive, annotations); + } + + public IEnumerable GetOwns( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity) + { + return GetOwns(transaction, transitivity, new Annotation[0]); + } + + public IEnumerable GetOwns( + ITypeDBTransaction transaction, IValue.ValueType? valueType, IConcept.Transitivity transitivity) + { + return GetOwns(transaction, valueType, transitivity, new Annotation[0]); + } + + public IEnumerable GetOwns( + ITypeDBTransaction transaction, + ICollection annotations, + IConcept.Transitivity transitivity) + { + return GetOwns(transaction, transitivity, annotations); + } + + public IEnumerable GetOwns( + ITypeDBTransaction transaction, + IValue.ValueType? valueType, + ICollection annotations, + IConcept.Transitivity transitivity) + { + return GetOwns(transaction, valueType, transitivity, annotations); + } + + private IEnumerable GetOwns( + ITypeDBTransaction transaction, + IConcept.Transitivity transitivity, + ICollection annotations) + { + return GetOwns(transaction, null, transitivity, annotations); + } + + private IEnumerable GetOwns( + ITypeDBTransaction transaction, + IValue.ValueType? valueType, + IConcept.Transitivity transitivity, + ICollection annotations) + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.thing_type_get_owns( + NativeTransaction(transaction), + NativeObject, + valueType != null ? (Pinvoke.ValueType)valueType : null, + (Pinvoke.Transitivity)transitivity, + annotations.Select(obj => obj.NativeObject).ToArray())) + .Select(obj => new AttributeType(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public Promise GetOwnsOverridden( + ITypeDBTransaction transaction, IAttributeType attributeType) + { + return Promise.Map( + Pinvoke.typedb_driver.thing_type_get_owns_overridden( + NativeTransaction(transaction), + NativeObject, + ((AttributeType)attributeType).NativeObject).Resolve, + obj => new AttributeType(obj)); + } + + public VoidPromise UnsetOwns(ITypeDBTransaction transaction, IAttributeType attributeType) + { + return new VoidPromise(Pinvoke.typedb_driver.thing_type_unset_owns( + NativeTransaction(transaction), + NativeObject, + ((AttributeType)attributeType).NativeObject).Resolve); + } + + public VoidPromise UnsetPlays(ITypeDBTransaction transaction, IRoleType roleType) + { + return new VoidPromise(Pinvoke.typedb_driver.thing_type_unset_plays( + NativeTransaction(transaction), NativeObject, ((RoleType)roleType).NativeObject).Resolve); + } + + public Promise GetSyntax(ITypeDBTransaction transaction) + { + return new Promise(Pinvoke.typedb_driver.thing_type_get_syntax( + NativeTransaction(transaction), NativeObject).Resolve); + } + + public class Root : ThingType + { + public Root(Pinvoke.Concept nativeConcept) + : base(nativeConcept) + { + } + + public override Promise GetSupertype(ITypeDBTransaction transaction) + { + return new Promise(() => null); + } + + public override IEnumerable GetSupertypes(ITypeDBTransaction transaction) + { + return new List{this}; + } + + public override IEnumerable GetSubtypes(ITypeDBTransaction transaction) + { + return new List(){this} + .Concat(transaction.Concepts.RootEntityType.GetSubtypes(transaction)) + .Concat(transaction.Concepts.RootRelationType.GetSubtypes(transaction)) + .Concat(transaction.Concepts.RootAttributeType.GetSubtypes(transaction)); + } + + public override IEnumerable GetSubtypes( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity) + { + return new List() + { + transaction.Concepts.RootEntityType, + transaction.Concepts.RootRelationType, + transaction.Concepts.RootAttributeType + }; + } + + public override IEnumerable GetInstances(ITypeDBTransaction transaction) + { + return transaction.Concepts.RootEntityType.GetInstances(transaction) + .Concat(transaction.Concepts.RootRelationType.GetInstances(transaction)) + .Concat(transaction.Concepts.RootAttributeType.GetInstances(transaction)) + .Cast(); + } + + public override IEnumerable GetInstances(ITypeDBTransaction transaction, IConcept.Transitivity transitivity) + { + return new List(){}; + } + } + } +} diff --git a/csharp/Concept/Type/Type.cs b/csharp/Concept/Type/Type.cs new file mode 100644 index 0000000000..e9d2aaa266 --- /dev/null +++ b/csharp/Concept/Type/Type.cs @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; + +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Concept; + +namespace TypeDB.Driver.Concept +{ + public abstract class Type : Concept, IType + { + private int _hash = 0; + + internal Type(Pinvoke.Concept nativeConcept) + : base(nativeConcept) + { + } + + public abstract Label Label { get; } + + public abstract bool IsRoot(); + + public abstract bool IsAbstract(); + + public abstract VoidPromise SetLabel(ITypeDBTransaction transaction, string label); + + public abstract VoidPromise Delete(ITypeDBTransaction transaction); + + public abstract Promise IsDeleted(ITypeDBTransaction transaction); + + public abstract Promise GetSupertype(ITypeDBTransaction transaction); + + public abstract IEnumerable GetSupertypes(ITypeDBTransaction transaction); + + public abstract IEnumerable GetSubtypes(ITypeDBTransaction transaction); + + public abstract IEnumerable GetSubtypes( + ITypeDBTransaction transaction, IConcept.Transitivity transitivity); + + public override int GetHashCode() + { + if (_hash == 0) + { + _hash = ComputeHash(); + } + + return _hash; + } + + private int ComputeHash() + { + return Label.GetHashCode(); + } + } +} \ No newline at end of file diff --git a/csharp/Concept/Value/Value.cs b/csharp/Concept/Value/Value.cs new file mode 100644 index 0000000000..9f7636cfbc --- /dev/null +++ b/csharp/Concept/Value/Value.cs @@ -0,0 +1,202 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; + +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Common.Validation; +using TypeDB.Driver.Concept; + +using ConceptError = TypeDB.Driver.Common.Error.Concept; +using InternalError = TypeDB.Driver.Common.Error.Internal; + +namespace TypeDB.Driver.Concept +{ + public class Value : Concept, IValue + { + private int _hash = 0; + + public Value(Pinvoke.Concept nativeConcept) + : base(nativeConcept) + { + } + + public Value(bool value) + : this(Pinvoke.typedb_driver.value_new_boolean(value)) + { + } + + public Value(long value) + : this(Pinvoke.typedb_driver.value_new_long(value)) + { + } + + public Value(double value) + : this(Pinvoke.typedb_driver.value_new_double(value)) + { + } + + public Value(string value) + : this(Pinvoke.typedb_driver.value_new_string(value)) + { + } + + public Value(System.DateTime value) + : this(Pinvoke.typedb_driver.value_new_date_time_from_millis( + new System.DateTimeOffset( + System.DateTime.SpecifyKind(value, DateTimeKind.Unspecified)).ToUnixTimeMilliseconds())) + { + } + + public IValue.ValueType Type + { + get + { + if (IsBool()) return IValue.ValueType.Bool; + if (IsLong()) return IValue.ValueType.Long; + if (IsDouble()) return IValue.ValueType.Double; + if (IsString()) return IValue.ValueType.String; + if (IsDateTime()) return IValue.ValueType.DateTime; + + throw new TypeDBDriverException(InternalError.ILLEGAL_STATE); + } + } + + public bool IsBool() + { + return Pinvoke.typedb_driver.value_is_boolean(NativeObject); + } + + public bool IsLong() + { + return Pinvoke.typedb_driver.value_is_long(NativeObject); + } + + public bool IsDouble() + { + return Pinvoke.typedb_driver.value_is_double(NativeObject); + } + + public bool IsString() + { + return Pinvoke.typedb_driver.value_is_string(NativeObject); + } + + public bool IsDateTime() + { + return Pinvoke.typedb_driver.value_is_date_time(NativeObject); + } + + public object AsUntyped() + { + if (IsBool()) return AsBool(); + if (IsLong()) return AsLong(); + if (IsDouble()) return AsDouble(); + if (IsString()) return AsString(); + if (IsDateTime()) return AsDateTime(); + + throw new TypeDBDriverException(InternalError.UNEXPECTED_NATIVE_VALUE); + } + + public bool AsBool() + { + Validator.ThrowIfFalse(IsBool, InternalError.ILLEGAL_CAST, "bool"); + + return Pinvoke.typedb_driver.value_get_boolean(NativeObject); + } + + public long AsLong() + { + Validator.ThrowIfFalse(IsLong, InternalError.ILLEGAL_CAST, "long"); + + return Pinvoke.typedb_driver.value_get_long(NativeObject); + } + + public double AsDouble() + { + Validator.ThrowIfFalse(IsDouble, InternalError.ILLEGAL_CAST, "double"); + + return Pinvoke.typedb_driver.value_get_double(NativeObject); + } + + public string AsString() + { + Validator.ThrowIfFalse(IsString, InternalError.ILLEGAL_CAST, "string"); + + return Pinvoke.typedb_driver.value_get_string(NativeObject); + } + + public System.DateTime AsDateTime() + { + Validator.ThrowIfFalse(IsDateTime, InternalError.ILLEGAL_CAST, "DateTime"); + + return System.DateTimeOffset.FromUnixTimeMilliseconds( + Pinvoke.typedb_driver.value_get_date_time_as_millis(NativeObject)).DateTime; + } + + public override string ToString() + { + if (IsBool()) + { + var str = AsBool().ToString(); + return str[0].ToString().ToLower() + str.Substring(1); + } + + if (IsLong()) + { + return AsLong().ToString(); + } + + if (IsDouble()) + { + return AsDouble().ToString("0.0#####"); + } + + if (IsString()) + { + return AsString(); + } + + if (IsDateTime()) + { + return AsDateTime().ToString(); + } + + throw new TypeDBDriverException(InternalError.UNEXPECTED_NATIVE_VALUE); + } + + public override int GetHashCode() + { + if (_hash == 0) + { + _hash = ComputeHash(); + } + + return _hash; + } + + private int ComputeHash() + { + return AsUntyped().GetHashCode(); + } + } +} diff --git a/csharp/Connection/BUILD b/csharp/Connection/BUILD new file mode 100644 index 0000000000..4ae44675e2 --- /dev/null +++ b/csharp/Connection/BUILD @@ -0,0 +1,56 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +package(default_visibility = ["//visibility:public"]) + +load("@rules_dotnet//dotnet:defs.bzl", "csharp_library") +load("//csharp:build_opts.bzl", "nullable_context", "target_frameworks", "targeting_packs") +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") + + +csharp_library( + name = "connection", + srcs = glob(["*.cs", "*/*.cs"], + ), + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp/Concept:concept", + "//csharp/Logic:logic", + "//csharp/Query:query", + "//csharp/User:user", + "//csharp:typedb_driver_pinvoke", + ], + nullable = nullable_context, + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +checkstyle_test( + name = "checkstyle", + size = "small", + include = glob([ + "*", + "*/*", + ]), + license_type = "apache-header", +) diff --git a/csharp/Connection/TypeDBDatabase.cs b/csharp/Connection/TypeDBDatabase.cs new file mode 100644 index 0000000000..a77598cdb6 --- /dev/null +++ b/csharp/Connection/TypeDBDatabase.cs @@ -0,0 +1,210 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Common.Validation; + +using DriverError = TypeDB.Driver.Common.Error.Driver; + +namespace TypeDB.Driver.Connection +{ + public class TypeDBDatabase : NativeObjectWrapper, IDatabase + { + private string? _name; + + private IDatabase.IReplica? _primaryReplica; + private bool _primaryReplicaFetched = false; + + private IDatabase.IReplica? _preferredReplica; + private bool _preferredReplicaFetched = false; + + public TypeDBDatabase(Pinvoke.Database database) + : base(database) + {} + + public string Name + { + get + { + Validator.ThrowIfFalse(NativeObject.IsOwned, DriverError.DATABASE_DELETED); + return _name ?? (_name = Pinvoke.typedb_driver.database_get_name(NativeObject)); + } + } + + public string GetSchema() + { + Validator.ThrowIfFalse(NativeObject.IsOwned, DriverError.DATABASE_DELETED); + + try + { + return Pinvoke.typedb_driver.database_schema(NativeObject); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public string GetTypeSchema() + { + Validator.ThrowIfFalse(NativeObject.IsOwned, DriverError.DATABASE_DELETED); + + try + { + return Pinvoke.typedb_driver.database_type_schema(NativeObject); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public string GetRuleSchema() + { + Validator.ThrowIfFalse(NativeObject.IsOwned, DriverError.DATABASE_DELETED); + + try + { + return Pinvoke.typedb_driver.database_rule_schema(NativeObject); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public ISet GetReplicas() + { + Validator.ThrowIfFalse(NativeObject.IsOwned, DriverError.DATABASE_DELETED); + + return new NativeEnumerable( + Pinvoke.typedb_driver.database_get_replicas_info(NativeObject)) + .Select(obj => new Replica(obj)) + .ToHashSet(); + } + + public IDatabase.IReplica? PrimaryReplica + { + get + { + Validator.ThrowIfFalse(NativeObject.IsOwned, DriverError.DATABASE_DELETED); + if (_primaryReplicaFetched) + { + return _primaryReplica; + } + + Pinvoke.ReplicaInfo replicaInfo = Pinvoke.typedb_driver.database_get_primary_replica_info(NativeObject); + _primaryReplicaFetched = true; + + if (replicaInfo == null) + { + return null; + } + + return (_primaryReplica = new Replica(replicaInfo)); + } + } + + public IDatabase.IReplica? PreferredReplica + { + get + { + Validator.ThrowIfFalse(NativeObject.IsOwned, DriverError.DATABASE_DELETED); + if (_preferredReplicaFetched) + { + return _preferredReplica; + } + + Pinvoke.ReplicaInfo replicaInfo = Pinvoke.typedb_driver.database_get_preferred_replica_info(NativeObject); + _preferredReplicaFetched = true; + + if (replicaInfo == null) + { + return null; + } + + return (_preferredReplica = new Replica(replicaInfo)); + } + } + + public void Delete() + { + Validator.ThrowIfFalse(NativeObject.IsOwned, DriverError.DATABASE_DELETED); + + try + { + Pinvoke.typedb_driver.database_delete(NativeObject?.Released()); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public override string ToString() + { + return Name; + } + + public class Replica : NativeObjectWrapper, IDatabase.IReplica + { + private string? _address; + private long? _term; + + public Replica(Pinvoke.ReplicaInfo replicaInfo) + : base(replicaInfo) + {} + + public bool IsPrimary() + { + return Pinvoke.typedb_driver.replica_info_is_primary(NativeObject); + } + + public bool IsPreferred() + { + return Pinvoke.typedb_driver.replica_info_is_preferred(NativeObject); + } + + public string Address + { + get { return _address ?? (_address = Pinvoke.typedb_driver.replica_info_get_address(NativeObject)); } + } + + public long Term + { + get + { + if (!_term.HasValue) + { + _term = Pinvoke.typedb_driver.replica_info_get_term(NativeObject); + } + + return _term.Value; + } + } + } + } +} diff --git a/csharp/Connection/TypeDBDatabaseManager.cs b/csharp/Connection/TypeDBDatabaseManager.cs new file mode 100644 index 0000000000..162fd6834d --- /dev/null +++ b/csharp/Connection/TypeDBDatabaseManager.cs @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Common.Validation; + +using DriverError = TypeDB.Driver.Common.Error.Driver; + +namespace TypeDB.Driver.Connection +{ + public class TypeDBDatabaseManager : NativeObjectWrapper, IDatabaseManager + { + public TypeDBDatabaseManager(Pinvoke.Connection nativeConnection) + : base(NewNative(nativeConnection)) + {} + + private static Pinvoke.DatabaseManager NewNative(Pinvoke.Connection nativeConnection) + { + try + { + return Pinvoke.typedb_driver.database_manager_new(nativeConnection); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public IDatabase Get(string name) + { + Validator.NonEmptyString(name, DriverError.MISSING_DB_NAME); + + try + { + return new TypeDBDatabase(Pinvoke.typedb_driver.databases_get(NativeObject, name)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public bool Contains(string name) + { + Validator.NonEmptyString(name, DriverError.MISSING_DB_NAME); + + try + { + return Pinvoke.typedb_driver.databases_contains(NativeObject, name); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public void Create(string name) + { + Validator.NonEmptyString(name, DriverError.MISSING_DB_NAME); + + try + { + Pinvoke.typedb_driver.databases_create(NativeObject, name); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public IList GetAll() + { + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.databases_all(NativeObject)) + .Select(obj => new TypeDBDatabase(obj)) + .ToList(); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + } +} diff --git a/csharp/Connection/TypeDBDriver.cs b/csharp/Connection/TypeDBDriver.cs new file mode 100644 index 0000000000..0200a674a8 --- /dev/null +++ b/csharp/Connection/TypeDBDriver.cs @@ -0,0 +1,130 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Connection; +using TypeDB.Driver.User; + +namespace TypeDB.Driver.Connection +{ + public class TypeDBDriver : NativeObjectWrapper, ITypeDBDriver + { + private readonly IDatabaseManager _databaseManager; + private readonly UserManager _userManager; + + public TypeDBDriver(string address) + : this(OpenCore(address)) + {} + + public TypeDBDriver(ICollection initAddresses, TypeDBCredential credential) + : this(OpenCloud(initAddresses, credential)) + {} + + private TypeDBDriver(Pinvoke.Connection connection) + : base(connection) + { + _databaseManager = new TypeDBDatabaseManager(this.NativeObject); + _userManager = new UserManager(this.NativeObject); + } + + private static Pinvoke.Connection OpenCore(string address) + { + try + { + return Pinvoke.typedb_driver.connection_open_core(address); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + private static Pinvoke.Connection OpenCloud(ICollection initAddresses, TypeDBCredential credential) + { + try + { + return Pinvoke.typedb_driver.connection_open_cloud(initAddresses.ToArray(), credential.NativeObject); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public bool IsOpen() + { + return Pinvoke.typedb_driver.connection_is_open(NativeObject); + } + + public IDatabaseManager Databases + { + get { return _databaseManager; } + } + + public IUser GetCurrentUser() + { + return _userManager.GetCurrentUser(); + } + + public IUserManager Users + { + get { return _userManager; } + } + + public ITypeDBSession Session(string database, SessionType type) + { + return Session(database, type, new TypeDBOptions()); + } + + public ITypeDBSession Session( + string database, SessionType type, TypeDBOptions options) + { + return new TypeDBSession(Databases, database, type, options); + } + + public void Close() + { + if (!IsOpen()) + { + return; + } + + try + { + Pinvoke.typedb_driver.connection_force_close(NativeObject); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public void Dispose() + { + Close(); + } + } +} diff --git a/csharp/Connection/TypeDBSession.cs b/csharp/Connection/TypeDBSession.cs new file mode 100644 index 0000000000..89e62abbc5 --- /dev/null +++ b/csharp/Connection/TypeDBSession.cs @@ -0,0 +1,153 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using System.Collections.Generic; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Connection +{ + public class TypeDBSession : NativeObjectWrapper, ITypeDBSession + { + private string? _databaseName; + private readonly List _callbacks; + + internal TypeDBSession(IDatabaseManager databaseManager, string database, SessionType type, TypeDBOptions options) + : base(NewNative(databaseManager, database, type, options)) + { + Type = type; + Options = options; + _callbacks = new List(); + } + + private static Pinvoke.Session NewNative( + IDatabaseManager databaseManager, string database, SessionType type, TypeDBOptions options) + { + try + { + return Pinvoke.typedb_driver.session_new( + ((TypeDBDatabaseManager)databaseManager).NativeObject, + database, + (Pinvoke.SessionType)type, + options.NativeObject); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public bool IsOpen() + { + return Pinvoke.typedb_driver.session_is_open(NativeObject); + } + + public SessionType Type { get; } + + public TypeDBOptions Options { get; } + + public string DatabaseName + { + get + { + return _databaseName ?? (_databaseName = + Pinvoke.typedb_driver.session_get_database_name(NativeObject)); + } + } + + public ITypeDBTransaction Transaction(TransactionType type) + { + return Transaction(type, new TypeDBOptions()); + } + + public ITypeDBTransaction Transaction(TransactionType type, TypeDBOptions options) + { + return new TypeDBTransaction(this, type, options); + } + + public void OnClose(Action function) + { + try + { + SessionCallback callback = new SessionCallback(function); + _callbacks.Add(callback); + Pinvoke.typedb_driver.session_on_close(NativeObject, callback.Released()); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public void OnReopen(Action function) + { + try + { + SessionCallback callback = new SessionCallback(function); + _callbacks.Add(callback); + Pinvoke.typedb_driver.session_on_reopen(NativeObject, callback.Released()); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public void Close() + { + try + { + Pinvoke.typedb_driver.session_force_close(NativeObject); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + finally + { + _callbacks.Clear(); + } + } + + public void Dispose() + { + Close(); + } + + private class SessionCallback : Pinvoke.SessionCallbackDirector + { + private readonly Action _function; + + public SessionCallback(Action function) + { + _function = function; + } + + public override void callback() + { + _function(); + } + } + } +} diff --git a/csharp/Connection/TypeDBTransaction.cs b/csharp/Connection/TypeDBTransaction.cs new file mode 100644 index 0000000000..04cbe27765 --- /dev/null +++ b/csharp/Connection/TypeDBTransaction.cs @@ -0,0 +1,170 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using System.Collections.Generic; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Concept; +using TypeDB.Driver.Common; +using TypeDB.Driver.Common.Validation; +using TypeDB.Driver.Logic; +using TypeDB.Driver.Query; + +using DriverError = TypeDB.Driver.Common.Error.Driver; + +namespace TypeDB.Driver.Connection +{ + public class TypeDBTransaction : NativeObjectWrapper, ITypeDBTransaction + { + private readonly List _callbacks; + + internal TypeDBTransaction(TypeDBSession session, TransactionType type, TypeDBOptions options) + : base(NewNative(session, type, options)) + { + Type = type; + Options = options; + + Concepts = new ConceptManager(NativeObject); + Logic = new LogicManager(NativeObject); + Query = new QueryManager(NativeObject); + + _callbacks = new List(); + } + + private static Pinvoke.Transaction NewNative( + TypeDBSession session, TransactionType type, TypeDBOptions options) + { + try + { + return Pinvoke.typedb_driver.transaction_new( + session.NativeObject, (Pinvoke.TransactionType)type, options.NativeObject); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public TransactionType Type { get; } + + public TypeDBOptions Options { get; } + + public IConceptManager Concepts { get; } + + public ILogicManager Logic { get; } + + public IQueryManager Query { get; } + + public bool IsOpen() + { + return NativeObject.IsOwned() + ? Pinvoke.typedb_driver.transaction_is_open(NativeObject) + : false; + } + + public void OnClose(Action function) + { + Validator.ThrowIfFalse(NativeObject.IsOwned, DriverError.TRANSACTION_CLOSED); + + try + { + TransactionOnClose callback = new TransactionOnClose(function); + _callbacks.Add(callback); + Pinvoke.typedb_driver.transaction_on_close(NativeObject, callback.Released()); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public void Commit() + { + Validator.ThrowIfFalse(NativeObject.IsOwned, DriverError.TRANSACTION_CLOSED); + + try + { + Pinvoke.typedb_driver.transaction_commit(NativeObject.Released()).Resolve(); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public void Rollback() + { + Validator.ThrowIfFalse(NativeObject.IsOwned, DriverError.TRANSACTION_CLOSED); + + try + { + Pinvoke.typedb_driver.transaction_rollback(NativeObject).Resolve(); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public void Close() + { + if (!NativeObject.IsOwned()) + { + return; + } + + try + { + Pinvoke.typedb_driver.transaction_force_close(NativeObject); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + finally + { + _callbacks.Clear(); + } + } + + public void Dispose() + { + Close(); + } + + private class TransactionOnClose : Pinvoke.TransactionCallbackDirector + { + private readonly Action _function; + + public TransactionOnClose(Action function) + { + _function = function; + } + + public override void callback(Pinvoke.Error e) + { + _function(e); + } + } + } +} diff --git a/csharp/Logic/BUILD b/csharp/Logic/BUILD new file mode 100644 index 0000000000..4a2ee5fe87 --- /dev/null +++ b/csharp/Logic/BUILD @@ -0,0 +1,48 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +package(default_visibility = ["//visibility:public"]) + +load("@rules_dotnet//dotnet:defs.bzl", "csharp_library") +load("//csharp:build_opts.bzl", "target_frameworks", "targeting_packs", "nullable_context") +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") + + +csharp_library( + name = "logic", + srcs = glob(["*.cs"]), + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp/Concept:concept", + "//csharp:typedb_driver_pinvoke", + ], + nullable = nullable_context, + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +checkstyle_test( + name = "checkstyle", + include = glob(["*"]), + license_type = "apache-header", +) diff --git a/csharp/Logic/Explanation.cs b/csharp/Logic/Explanation.cs new file mode 100644 index 0000000000..be998486f4 --- /dev/null +++ b/csharp/Logic/Explanation.cs @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Concept; +using TypeDB.Driver.Common.Validation; + +using ConceptError = TypeDB.Driver.Common.Error.Concept; + +namespace TypeDB.Driver.Logic +{ + public class Explanation : NativeObjectWrapper, IExplanation + { + private IRule? _rule; + private IConceptMap? _conclusion; + private IConceptMap? _condition; + + private int _hash = 0; + + public Explanation(Pinvoke.Explanation nativeExplanation) + : base(nativeExplanation) + { + } + + public IRule Rule + { + get { return _rule ?? (_rule = new Rule(Pinvoke.typedb_driver.explanation_get_rule(NativeObject))); } + } + + public IConceptMap Conclusion + { + get + { + return _conclusion ?? (_conclusion = + new ConceptMap(Pinvoke.typedb_driver.explanation_get_conclusion(NativeObject))); + } + } + + public IConceptMap Condition + { + get + { + return _condition ?? (_condition = + new ConceptMap(Pinvoke.typedb_driver.explanation_get_condition(NativeObject))); + } + } + + public ISet GetQueryVariables() + { + return new NativeEnumerable( + Pinvoke.typedb_driver.explanation_get_mapped_variables(NativeObject)) + .ToHashSet(); + } + + public ISet QueryVariableMapping(string variable) + { + Validator.NonEmptyString(variable, ConceptError.MISSING_VARIABLE); + + return new NativeEnumerable( + Pinvoke.typedb_driver.explanation_get_mapping(NativeObject, variable)) + .ToHashSet(); + } + + public override bool Equals(object? obj) + { + if (Object.ReferenceEquals(this, obj)) + { + return true; + } + + if (obj == null || this.GetType() != obj.GetType()) + { + return false; + } + + Explanation that = (Explanation)obj; + + return Pinvoke.typedb_driver.explanation_equals(this.NativeObject, that.NativeObject); + } + + public override string ToString() + { + return Pinvoke.typedb_driver.explanation_to_string(NativeObject); + } + + public override int GetHashCode() + { + if (_hash == 0) + { + _hash = ComputeHash(); + } + + return _hash; + } + + private int ComputeHash() + { + return (Rule, Conclusion, Condition).GetHashCode(); + } + } +} diff --git a/csharp/Logic/LogicManager.cs b/csharp/Logic/LogicManager.cs new file mode 100644 index 0000000000..8cf26013e2 --- /dev/null +++ b/csharp/Logic/LogicManager.cs @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Common.Validation; + +using DriverError = TypeDB.Driver.Common.Error.Driver; +using ConceptError = TypeDB.Driver.Common.Error.Concept; + +namespace TypeDB.Driver.Logic +{ + public class LogicManager : ILogicManager + { + public readonly Pinvoke.Transaction NativeTransaction; + + public LogicManager(Pinvoke.Transaction nativeTransaction) + { + NativeTransaction = nativeTransaction; + } + + public IEnumerable GetRules() + { + Validator.ThrowIfFalse(NativeTransaction.IsOwned, DriverError.TRANSACTION_CLOSED); + + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.logic_manager_get_rules(NativeTransaction)) + .Select(obj => new Rule(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public Promise GetRule(string label) + { + Validator.NonEmptyString(label, ConceptError.MISSING_LABEL); + Validator.ThrowIfFalse(NativeTransaction.IsOwned, DriverError.TRANSACTION_CLOSED); + + return Promise.Map( + Pinvoke.typedb_driver.logic_manager_get_rule(NativeTransaction, label).Resolve, + obj => new Rule(obj)); + } + + public Promise PutRule(string label, string when, string then) + { + Validator.NonEmptyString(label, ConceptError.MISSING_LABEL); + Validator.ThrowIfFalse(NativeTransaction.IsOwned, DriverError.TRANSACTION_CLOSED); + + Pinvoke.RulePromise promise = + Pinvoke.typedb_driver.logic_manager_put_rule(NativeTransaction, label, when, then); + return new Promise(() => new Rule(promise.Resolve())); + } + } +} diff --git a/csharp/Logic/Rule.cs b/csharp/Logic/Rule.cs new file mode 100644 index 0000000000..774f17576a --- /dev/null +++ b/csharp/Logic/Rule.cs @@ -0,0 +1,115 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Common.Validation; + +using DriverError = TypeDB.Driver.Common.Error.Driver; +using ConceptError = TypeDB.Driver.Common.Error.Concept; + +namespace TypeDB.Driver.Logic +{ + public class Rule : NativeObjectWrapper, IRule + { + private string? _label; + private int _hash = 0; + + internal Rule(Pinvoke.Rule nativeRule) + : base(nativeRule) + { + When = Pinvoke.typedb_driver.rule_get_when(NativeObject); + Then = Pinvoke.typedb_driver.rule_get_then(NativeObject); + } + + public string Label + { + get { return _label ?? (_label = Pinvoke.typedb_driver.rule_get_label(NativeObject)); } + } + + public string When { get; } + + public string Then { get; } + + public VoidPromise SetLabel(ITypeDBTransaction transaction, string label) + { + Validator.NonEmptyString(label, ConceptError.MISSING_LABEL); + + return new VoidPromise(Pinvoke.typedb_driver.rule_set_label( + NativeTransaction(transaction), NativeObject, label).Resolve); + } + + public VoidPromise Delete(ITypeDBTransaction transaction) + { + return new VoidPromise(Pinvoke.typedb_driver.rule_delete( + NativeTransaction(transaction), NativeObject).Resolve); + } + + public Promise IsDeleted(ITypeDBTransaction transaction) + { + return new Promise(Pinvoke.typedb_driver.rule_is_deleted( + NativeTransaction(transaction), NativeObject).Resolve); + } + + private static Pinvoke.Transaction NativeTransaction(ITypeDBTransaction transaction) + { + Pinvoke.Transaction nativeTransaction = ((LogicManager)transaction.Logic).NativeTransaction; + Validator.ThrowIfFalse(nativeTransaction.IsOwned, DriverError.TRANSACTION_CLOSED); + + return nativeTransaction; + } + + public override string ToString() + { + return Pinvoke.typedb_driver.rule_to_string(NativeObject); + } + + public override bool Equals(object? obj) + { + if (Object.ReferenceEquals(this, obj)) + { + return true; + } + + if (obj == null || this.GetType() != obj.GetType()) + { + return false; + } + + Rule that = (Rule)obj; + + return Label.Equals(that.Label); + } + + public override int GetHashCode() + { + if (_hash == 0) + { + _hash = Label.GetHashCode(); + } + + return _hash; + } + } +} diff --git a/csharp/Query/BUILD b/csharp/Query/BUILD new file mode 100644 index 0000000000..026f072df9 --- /dev/null +++ b/csharp/Query/BUILD @@ -0,0 +1,50 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +package(default_visibility = ["//visibility:public"]) + +load("@rules_dotnet//dotnet:defs.bzl", "csharp_library") +load("//csharp:build_opts.bzl", "target_frameworks", "targeting_packs", "nullable_context") +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") + + +csharp_library( + name = "query", + srcs = glob(["*.cs"]), + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp/Concept:concept", + "//csharp/Logic:logic", + "//csharp:typedb_driver_pinvoke", + "@paket.csharp_deps//newtonsoft.json", + ], + nullable = nullable_context, + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +checkstyle_test( + name = "checkstyle", + include = glob(["*"]), + license_type = "apache-header", +) diff --git a/csharp/Query/QueryManager.cs b/csharp/Query/QueryManager.cs new file mode 100644 index 0000000000..32b1a71aa0 --- /dev/null +++ b/csharp/Query/QueryManager.cs @@ -0,0 +1,275 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using Newtonsoft.Json.Linq; +using System.Collections.Generic; +using System.Linq; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using TypeDB.Driver.Concept; +using TypeDB.Driver.Logic; +using TypeDB.Driver.Common.Validation; + +using DriverError = TypeDB.Driver.Common.Error.Driver; +using QueryError = TypeDB.Driver.Common.Error.Query; + +namespace TypeDB.Driver.Query +{ + public class QueryManager : IQueryManager + { + private readonly Pinvoke.Transaction _nativeTransaction; + + public QueryManager(Pinvoke.Transaction nativeTransaction) + { + _nativeTransaction = nativeTransaction; + } + + public IEnumerable Get(string query) + { + return Get(query, new TypeDBOptions()); + } + + public IEnumerable Get(string query, TypeDBOptions options) + { + CheckQueryAndTransaction(query); + + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.query_get(_nativeTransaction, query, options.NativeObject)) + .Select(obj => new ConceptMap(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public Promise GetAggregate(string query) + { + return GetAggregate(query, new TypeDBOptions()); + } + + public Promise GetAggregate(string query, TypeDBOptions options) + { + CheckQueryAndTransaction(query); + + Pinvoke.ConceptPromise promise = Pinvoke.typedb_driver.query_get_aggregate( + _nativeTransaction, query, options.NativeObject); + + return new Promise(() => + { + var res = promise.Resolve(); + if (res == null) + { + return null; + } + + return new Value(res); + }); + } + + public IEnumerable GetGroup(string query) + { + return GetGroup(query, new TypeDBOptions()); + } + + public IEnumerable GetGroup(string query, TypeDBOptions options) + { + CheckQueryAndTransaction(query); + + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.query_get_group(_nativeTransaction, query, options.NativeObject)) + .Select(obj => new ConceptMapGroup(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public IEnumerable GetGroupAggregate(string query) + { + return GetGroupAggregate(query, new TypeDBOptions()); + } + + public IEnumerable GetGroupAggregate(string query, TypeDBOptions options) + { + CheckQueryAndTransaction(query); + + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.query_get_group_aggregate(_nativeTransaction, query, options.NativeObject)) + .Select(obj => new ValueGroup(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public IEnumerable Fetch(string query) + { + return Fetch(query, new TypeDBOptions()); + } + + public IEnumerable Fetch(string query, TypeDBOptions options) + { + CheckQueryAndTransaction(query); + + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.query_fetch(_nativeTransaction, query, options.NativeObject)) + .Select(obj => JObject.Parse(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public IEnumerable Insert(string query) + { + return Insert(query, new TypeDBOptions()); + } + + public IEnumerable Insert(string query, TypeDBOptions options) + { + CheckQueryAndTransaction(query); + + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.query_insert(_nativeTransaction, query, options.NativeObject)) + .Select(obj => new ConceptMap(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public VoidPromise Delete(string query) + { + return Delete(query, new TypeDBOptions()); + } + + public VoidPromise Delete(string query, TypeDBOptions options) + { + CheckQueryAndTransaction(query); + + return new VoidPromise(Pinvoke.typedb_driver.query_delete( + _nativeTransaction, query, options.NativeObject).Resolve); + } + + public IEnumerable Update(string query) + { + return Update(query, new TypeDBOptions()); + } + + public IEnumerable Update(string query, TypeDBOptions options) + { + CheckQueryAndTransaction(query); + + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.query_update(_nativeTransaction, query, options.NativeObject)) + .Select(obj => new ConceptMap(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + public VoidPromise Define(string query) + { + return Define(query, new TypeDBOptions()); + } + + public VoidPromise Define(string query, TypeDBOptions options) + { + CheckQueryAndTransaction(query); + + return new VoidPromise(Pinvoke.typedb_driver.query_define( + _nativeTransaction, query, options.NativeObject).Resolve); + } + + public VoidPromise Undefine(string query) + { + return Undefine(query, new TypeDBOptions()); + } + + public VoidPromise Undefine(string query, TypeDBOptions options) + { + CheckQueryAndTransaction(query); + + return new VoidPromise(Pinvoke.typedb_driver.query_undefine( + _nativeTransaction, query, options.NativeObject).Resolve); + } + + public IEnumerable Explain(IConceptMap.IExplainable explainable) + { + return Explain(explainable, new TypeDBOptions()); + } + + public IEnumerable Explain( + IConceptMap.IExplainable explainable, TypeDBOptions options) + { + CheckTransaction(); + + try + { + return new NativeEnumerable( + Pinvoke.typedb_driver.query_explain( + _nativeTransaction, + ((ConceptMap.Explainable)explainable).NativeObject, + options.NativeObject)) + .Select(obj => new Explanation(obj)); + } + catch (Pinvoke.Error e) + { + throw new TypeDBDriverException(e); + } + } + + private void CheckTransaction() + { + if (!_nativeTransaction.IsOwned()) + { + throw new TypeDBDriverException(DriverError.TRANSACTION_CLOSED); + } + } + + private void CheckQueryAndTransaction(string query) + { + CheckTransaction(); + Validator.NonEmptyString(query, QueryError.MISSING_QUERY); + } + } +} diff --git a/csharp/README.md b/csharp/README.md new file mode 100644 index 0000000000..f38dfda466 --- /dev/null +++ b/csharp/README.md @@ -0,0 +1,16 @@ +# TypeDB C# Driver +The C# driver. .NET 6.0 version. + +## Usage +TODO + +## API Reference +TODO +## Driver Architecture +TODO + +## Build TypeDB Driver for C# from Source +TODO + +### TypeDB Cloud +TODO \ No newline at end of file diff --git a/csharp/Test/BUILD b/csharp/Test/BUILD new file mode 100644 index 0000000000..5dbef594fa --- /dev/null +++ b/csharp/Test/BUILD @@ -0,0 +1,29 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") + + +checkstyle_test( + name = "checkstyle", + include = glob(["*"]), + license_type = "apache-header", +) diff --git a/csharp/Test/Behaviour/BUILD b/csharp/Test/Behaviour/BUILD new file mode 100644 index 0000000000..5dbef594fa --- /dev/null +++ b/csharp/Test/Behaviour/BUILD @@ -0,0 +1,29 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") + + +checkstyle_test( + name = "checkstyle", + include = glob(["*"]), + license_type = "apache-header", +) diff --git a/csharp/Test/Behaviour/Concept/BUILD b/csharp/Test/Behaviour/Concept/BUILD new file mode 100644 index 0000000000..5dbef594fa --- /dev/null +++ b/csharp/Test/Behaviour/Concept/BUILD @@ -0,0 +1,29 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") + + +checkstyle_test( + name = "checkstyle", + include = glob(["*"]), + license_type = "apache-header", +) diff --git a/csharp/Test/Behaviour/Concept/Thing/Attribute/AttributeSteps.cs b/csharp/Test/Behaviour/Concept/Thing/Attribute/AttributeSteps.cs new file mode 100644 index 0000000000..1136d1cdb2 --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Thing/Attribute/AttributeSteps.cs @@ -0,0 +1,239 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using Xunit; +using Xunit.Gherkin.Quick; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Test.Behaviour +{ + public partial class BehaviourSteps + { + [When(@"attribute\(([a-zA-Z0-9-_]+)\) get instances contain: \$([a-zA-Z0-9]+)")] + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) get instances contain: \$([a-zA-Z0-9]+)")] + public void AttributeTypeGetInstancesContain(string typeLabel, string var) + { + var instances = Tx.Concepts + .GetAttributeType(typeLabel).Resolve()! + .GetInstances(Tx); + + Assert.True(instances.Where(i => i.Equals(Get(var)!)).Any()); + } + + [Then(@"attribute \$([a-zA-Z0-9]+) get owners contain: \$([a-zA-Z0-9]+)")] + public void AttributeGetOwnersContain(string var1, string var2) + { + Assert.True(Get(var1)!.AsAttribute().GetOwners(Tx).Where(o => o.Equals(Get(var2)!)).Any()); + } + + [Then(@"attribute \$([a-zA-Z0-9]+) get owners do not contain: \$([a-zA-Z0-9]+)")] + public void AttributeGetOwnersDoNotContain(string var1, string var2) + { + Assert.False( + Get(var1)!.AsAttribute().GetOwners(Tx).Where(o => o.Equals(Get(var2)!)).Any()); + } + + [Then(@"attribute \$([a-zA-Z0-9]+) has value type: {}")] + public void AttributeHasValueType(string var, string valueTypeData) + { + IValue.ValueType valueType = GetValueType(valueTypeData); + Assert.Equal(valueType, Get(var)!.Type.AsAttributeType().ValueType); + } + + [When(@"\$([a-zA-Z0-9]+) = attribute\(([a-zA-Z0-9-_]+)\) as\(boolean\) put: (true|false)")] + public void AttributeTypeAsBooleanPut(string var, string typeLabel, bool value) + { + var attributeType = Tx.Concepts + .GetAttributeType(typeLabel).Resolve()! + .Put(Tx, value).Resolve()!; + + Put(var, attributeType); + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) as\(boolean\) put: (true|false); throws exception")] + public void AttributeTypeAsBooleanPutThrowsException(string typeLabel, bool value) + { + Assert.Throws(() => Tx.Concepts + .GetAttributeType(typeLabel).Resolve()! + .Put(Tx, value).Resolve()!); + } + + [When(@"\$([a-zA-Z0-9]+) = attribute\(([a-zA-Z0-9-_]+)\) as\(long\) put: {int}")] + public void AttributeTypeAsLongPut(string var, string typeLabel, long value) + { + var attributeType = Tx.Concepts + .GetAttributeType(typeLabel).Resolve()! + .Put(Tx, value).Resolve()!; + + Put(var, attributeType); + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) as\(long\) put: {int}; throws exception")] + public void AttributeTypeAsLongPutThrowsException(string typeLabel, long value) + { + Assert.Throws(() => Tx.Concepts + .GetAttributeType(typeLabel).Resolve()! + .Put(Tx, value).Resolve()!); + } + + [When(@"\$([a-zA-Z0-9]+) = attribute\(([a-zA-Z0-9-_]+)\) as\(double\) put: {float}")] + public void AttributeTypeAsDoublePut(string var, string typeLabel, double value) + { + var attributeType = Tx.Concepts + .GetAttributeType(typeLabel).Resolve()! + .Put(Tx, value).Resolve()!; + + Put(var, attributeType); + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) as\(double\) put: {float}; throws exception")] + public void AttributeTypeAsDoublePutThrowsException(string typeLabel, double value) + { + Assert.Throws(() => Tx.Concepts + .GetAttributeType(typeLabel).Resolve()! + .Put(Tx, value).Resolve()!); + } + + [When(@"\$([a-zA-Z0-9]+) = attribute\(([a-zA-Z0-9-_]+)\) as\(string\) put: {}")] + public void AttributeTypeAsStringPut(string var, string typeLabel, string value) + { + var attributeType = Tx.Concepts + .GetAttributeType(typeLabel).Resolve()! + .Put(Tx, value).Resolve()!; + + Put(var, attributeType); + } + + [When(@"attribute\(([a-zA-Z0-9-_]+)\) as\(string\) put: {}; throws exception")] + public void AttributeTypeAsStringPutThrowsException(string typeLabel, string value) + { + Assert.Throws(() => Tx.Concepts + .GetAttributeType(typeLabel).Resolve()! + .Put(Tx, value).Resolve()!); + } + + [When(@"\$([a-zA-Z0-9]+) = attribute\(([a-zA-Z0-9-_]+)\) as\(datetime\) put: (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})")] + public void AttributeTypeAsDatetimePut(string var, string typeLabel, DateTime value) + { + var attributeType = Tx.Concepts + .GetAttributeType(typeLabel).Resolve()! + .Put(Tx, value).Resolve()!; + + Put(var, attributeType); + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) as\(datetime\) put: (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}); throws exception")] + public void AttributeTypeAsDatetimePutThrowsException(string typeLabel, DateTime value) + { + var exception = Assert.Throws(() => Tx.Concepts.GetAttributeType(typeLabel).Resolve()! + .Put(Tx, value)); + } + + [When(@"\$([a-zA-Z0-9]+) = attribute\(([a-zA-Z0-9-_]+)\) as\(boolean\) get: (true|false)")] + public void AttributeTypeAsBooleanGet(string var, string typeLabel, bool value) + { + var attributeType = Tx.Concepts + .GetAttributeType(typeLabel).Resolve()! + .Get(Tx, value).Resolve()!; + + Put(var, attributeType); + } + + [When(@"\$([a-zA-Z0-9]+) = attribute\(([a-zA-Z0-9-_]+)\) as\(long\) get: {int}")] + public void AttributeTypeAsLongGet(string var, string typeLabel, long value) + { + var attributeType = Tx.Concepts + .GetAttributeType(typeLabel).Resolve()! + .Get(Tx, value).Resolve()!; + + Put(var, attributeType); + } + + [When(@"\$([a-zA-Z0-9]+) = attribute\(([a-zA-Z0-9-_]+)\) as\(double\) get: {float}")] + public void AttributeTypeAsDoubleGet(string var, string typeLabel, double value) + { + var attributeType = Tx.Concepts + .GetAttributeType(typeLabel).Resolve()! + .Get(Tx, value).Resolve()!; + + Put(var, attributeType); + } + + [When(@"\$([a-zA-Z0-9]+) = attribute\(([a-zA-Z0-9-_]+)\) as\(string\) get: {}")] + public void AttributeTypeAsStringGet(string var, string typeLabel, string value) + { + var attributeType = Tx.Concepts + .GetAttributeType(typeLabel).Resolve()! + .Get(Tx, value).Resolve()!; + + Put(var, attributeType); + } + + [When(@"\$([a-zA-Z0-9]+) = attribute\(([a-zA-Z0-9-_]+)\) as\(datetime\) get: (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})")] + public void AttributeTypeAsDatetimeGet(string var, string typeLabel, DateTime value) + { + var attributeType = Tx.Concepts + .GetAttributeType(typeLabel).Resolve()! + .Get(Tx, value).Resolve()!; + + Put(var, attributeType); + } + + [Then(@"attribute \$([a-zA-Z0-9]+) has boolean value: (true|false)")] + public void AttributeHasBooleanValue(string var, bool value) + { + Assert.Equal(value, Get(var)!.AsAttribute().Value.AsBool()); + } + + [Then(@"attribute \$([a-zA-Z0-9]+) has long value: {int}")] + public void AttributeHasLongValue(string var, long value) + { + Assert.Equal(value, Get(var)!.AsAttribute().Value.AsLong()); + } + + [Then(@"attribute \$([a-zA-Z0-9]+) has double value: {float}")] + public void AttributeHasDoubleValue(string var, double value) + { + Assert.Equal(value, Get(var)!.AsAttribute().Value.AsDouble(), 0.0001); + } + + [Then(@"attribute \$([a-zA-Z0-9]+) has string value: {}")] + public void AttributeHasStringValue(string var, string value) + { + Assert.Equal(value, Get(var)!.AsAttribute().Value.AsString()); + } + + [Then(@"attribute \$([a-zA-Z0-9]+) has datetime value: (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})")] + public void AttributeHasDatetimeValue(string var, DateTime value) + { + var resultDateTime = Get(var)!.AsAttribute().Value.AsDateTime(); + + Assert.Equal(DateTimeKind.Unspecified, resultDateTime.Kind); + Assert.Equal(value, Get(var)!.AsAttribute().Value.AsDateTime()); + } + } +} diff --git a/csharp/Test/Behaviour/Concept/Thing/Attribute/AttributeTest.cs b/csharp/Test/Behaviour/Concept/Thing/Attribute/AttributeTest.cs new file mode 100644 index 0000000000..bc366f5aff --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Thing/Attribute/AttributeTest.cs @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using Xunit.Gherkin.Quick; + +namespace TypeDB.Driver.Test.Behaviour +{ + [FeatureFile("external/vaticle_typedb_behaviour/concept/thing/attribute.feature")] + public partial class BehaviourSteps + { + } +} diff --git a/csharp/Test/Behaviour/Concept/Thing/Attribute/BUILD b/csharp/Test/Behaviour/Concept/Thing/Attribute/BUILD new file mode 100644 index 0000000000..d12dee1e8b --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Thing/Attribute/BUILD @@ -0,0 +1,94 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +package(default_visibility = ["//csharp/Test/Behaviour:__subpackages__"]) + +load("//csharp:build_opts.bzl", "nullable_context", "target_frameworks", "targeting_packs") +load("//csharp/Test:build_opts.bzl", "behaviour_tests_deps") +load("//csharp/Test:rules.bzl", "csharp_behaviour_test") +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") + + +filegroup( + name = "steps", + srcs = ["AttributeSteps.cs"], + visibility = ["//csharp/Test/Behaviour:__subpackages__"], +) + + +csharp_behaviour_test( + name = "test-core", + test_files = ["AttributeTest.cs"], + steps_files = [ + ":steps", + "//csharp/Test/Behaviour/Util:steps", + "//csharp/Test/Behaviour/Concept/Thing:steps", + "//csharp/Test/Behaviour/Concept/Type/AttributeType:steps", + "//csharp/Test/Behaviour/Concept/Type/ThingType:steps", + "//csharp/Test/Behaviour/Connection/Transaction:steps", + "//csharp/Test/Behaviour/Connection/Session:steps", + "//csharp/Test/Behaviour/Connection/Database:steps", + "//csharp/Test/Behaviour/Connection:steps-core", + ], + features = ["@vaticle_typedb_behaviour//concept/thing:attribute.feature"], + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp:driver-csharp", + "//csharp/Test/Behaviour/Util:util", + ], + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +csharp_behaviour_test( + name = "test-cloud", + test_files = ["AttributeTest.cs"], + steps_files = [ + ":steps", + "//csharp/Test/Behaviour/Util:steps", + "//csharp/Test/Behaviour/Concept/Thing:steps", + "//csharp/Test/Behaviour/Concept/Type/AttributeType:steps", + "//csharp/Test/Behaviour/Concept/Type/ThingType:steps", + "//csharp/Test/Behaviour/Connection/Transaction:steps", + "//csharp/Test/Behaviour/Connection/Session:steps", + "//csharp/Test/Behaviour/Connection/Database:steps", + "//csharp/Test/Behaviour/Connection:steps-cloud", + ], + features = ["@vaticle_typedb_behaviour//concept/thing:attribute.feature"], + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp:driver-csharp", + "//csharp/Test/Behaviour/Util:util", + ], + add_certificates = True, + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +checkstyle_test( + name = "checkstyle", + include = glob(["*"]), + license_type = "apache-header", +) diff --git a/csharp/Test/Behaviour/Concept/Thing/BUILD b/csharp/Test/Behaviour/Concept/Thing/BUILD new file mode 100644 index 0000000000..3d70e7ae23 --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Thing/BUILD @@ -0,0 +1,39 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +package(default_visibility = ["//csharp/Test/Behaviour:__subpackages__"]) + +load("//csharp/Test:rules.bzl", "csharp_behaviour_test") +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") + + +filegroup( + name = "steps", + srcs = ["ThingSteps.cs"], + visibility = ["//csharp/Test/Behaviour:__subpackages__"], +) + + +checkstyle_test( + name = "checkstyle", + include = glob(["*"]), + license_type = "apache-header", +) diff --git a/csharp/Test/Behaviour/Concept/Thing/Entity/BUILD b/csharp/Test/Behaviour/Concept/Thing/Entity/BUILD new file mode 100644 index 0000000000..2de34204e2 --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Thing/Entity/BUILD @@ -0,0 +1,96 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +package(default_visibility = ["//csharp/Test/Behaviour:__subpackages__"]) + +load("//csharp:build_opts.bzl", "nullable_context", "target_frameworks", "targeting_packs") +load("//csharp/Test:build_opts.bzl", "behaviour_tests_deps") +load("//csharp/Test:rules.bzl", "csharp_behaviour_test") +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") + + +filegroup( + name = "steps", + srcs = ["EntitySteps.cs"], + visibility = ["//csharp/Test/Behaviour:__subpackages__"], +) + + +csharp_behaviour_test( + name = "test-core", + test_files = ["EntityTest.cs"], + steps_files = [ + ":steps", + "//csharp/Test/Behaviour/Util:steps", + "//csharp/Test/Behaviour/Concept/Thing/Attribute:steps", + "//csharp/Test/Behaviour/Concept/Thing:steps", + "//csharp/Test/Behaviour/Concept/Type/AttributeType:steps", + "//csharp/Test/Behaviour/Concept/Type/ThingType:steps", + "//csharp/Test/Behaviour/Connection/Transaction:steps", + "//csharp/Test/Behaviour/Connection/Session:steps", + "//csharp/Test/Behaviour/Connection/Database:steps", + "//csharp/Test/Behaviour/Connection:steps-core", + ], + features = ["@vaticle_typedb_behaviour//concept/thing:entity.feature"], + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp:driver-csharp", + "//csharp/Test/Behaviour/Util:util", + ], + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +csharp_behaviour_test( + name = "test-cloud", + test_files = ["EntityTest.cs"], + steps_files = [ + ":steps", + "//csharp/Test/Behaviour/Util:steps", + "//csharp/Test/Behaviour/Concept/Thing/Attribute:steps", + "//csharp/Test/Behaviour/Concept/Thing:steps", + "//csharp/Test/Behaviour/Concept/Type/AttributeType:steps", + "//csharp/Test/Behaviour/Concept/Type/ThingType:steps", + "//csharp/Test/Behaviour/Connection/Transaction:steps", + "//csharp/Test/Behaviour/Connection/Session:steps", + "//csharp/Test/Behaviour/Connection/Database:steps", + "//csharp/Test/Behaviour/Connection:steps-cloud", + ], + features = ["@vaticle_typedb_behaviour//concept/thing:entity.feature"], + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp:driver-csharp", + "//csharp/Test/Behaviour/Util:util", + ], + add_certificates = True, + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +checkstyle_test( + name = "checkstyle", + include = glob(["*"]), + license_type = "apache-header", +) diff --git a/csharp/Test/Behaviour/Concept/Thing/Entity/EntitySteps.cs b/csharp/Test/Behaviour/Concept/Thing/Entity/EntitySteps.cs new file mode 100644 index 0000000000..d5788edde9 --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Thing/Entity/EntitySteps.cs @@ -0,0 +1,164 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using Xunit; +using Xunit.Gherkin.Quick; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Test.Behaviour +{ + public partial class BehaviourSteps + { + [When(@"\$([a-zA-Z0-9]+) = entity\(([a-zA-Z0-9-_]+)\) create new instance")] + public void EntityTypeCreateNewInstance(string var, string typeLabel) + { + var entityType = Tx.Concepts + .GetEntityType(typeLabel).Resolve()! + .Create(Tx).Resolve()!; + + Put(var, entityType); + } + + [When(@"entity\(([a-zA-Z0-9-_]+)\) create new instance; throws exception")] + [Then(@"entity\(([a-zA-Z0-9-_]+)\) create new instance; throws exception")] + public void EntityTypeCreateNewInstanceThrowsException(string typeLabel) + { + Assert.Throws(() => Tx.Concepts + .GetEntityType(typeLabel).Resolve()! + .Create(Tx).Resolve()!); + } + + [When(@"\$([a-zA-Z0-9]+) = entity\(([a-zA-Z0-9-_]+)\) create new instance with key\(([a-zA-Z0-9-_]+)\): {int}")] + public void EntityTypeCreateNewInstanceWithKey(string var, string type, string keyType, int keyValue) + { + IAttribute key = Tx.Concepts + .GetAttributeType(keyType).Resolve()! + .Put(Tx, keyValue).Resolve()!; + + IEntity entity = Tx.Concepts + .GetEntityType(type).Resolve()! + .Create(Tx).Resolve()!; + + entity.SetHas(Tx, key).Resolve(); + + Put(var, entity); + } + + [When(@"\$([a-zA-Z0-9]+) = entity\(([a-zA-Z0-9-_]+)\) create new instance with key\(([a-zA-Z0-9-_]+)\): {word}")] + public void EntityTypeCreateNewInstanceWithKey(string var, string type, string keyType, string keyValue) + { + IAttribute key = Tx.Concepts + .GetAttributeType(keyType).Resolve()! + .Put(Tx, keyValue).Resolve()!; + + IEntity entity = Tx.Concepts + .GetEntityType(type).Resolve()! + .Create(Tx).Resolve()!; + + entity.SetHas(Tx, key).Resolve(); + + Put(var, entity); + } + + [When(@"\$([a-zA-Z0-9]+) = entity\(([a-zA-Z0-9-_]+)\) create new instance with key\(([a-zA-Z0-9-_]+)\): (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})")] + public void EntityTypeCreateNewInstanceWithKey( + string var, string type, string keyType, DateTime keyValue) + { + IAttribute key = Tx.Concepts + .GetAttributeType(keyType).Resolve()! + .Put(Tx, keyValue).Resolve()!; + + IEntity entity = Tx.Concepts + .GetEntityType(type).Resolve()! + .Create(Tx).Resolve()!; + + entity.SetHas(Tx, key).Resolve(); + + Put(var, entity); + } + + [When(@"\$([a-zA-Z0-9]+) = entity\(([a-zA-Z0-9-_]+)\) get instance with key\(([a-zA-Z0-9-_]+)\): {int}")] + public void EntityTypeGetInstanceWithKey(string var, string type, string keyType, long keyValue) + { + var entityType = Tx.Concepts + .GetAttributeType(keyType).Resolve()! + .Get(Tx, keyValue).Resolve()! + .GetOwners(Tx) + .Where(owner => owner.Type.Label.Equals(new Label(type))) + .FirstOrDefault(); + + Put(var, entityType); + } + + [When(@"\$([a-zA-Z0-9]+) = entity\(([a-zA-Z0-9-_]+)\) get instance with key\(([a-zA-Z0-9-_]+)\): {word}")] + public void EntityTypeGetInstanceWithKey(string var, string type, string keyType, string keyValue) + { + var entityType = Tx.Concepts + .GetAttributeType(keyType).Resolve()! + .Get(Tx, keyValue).Resolve()! + .GetOwners(Tx) + .Where(owner => owner.Type.Label.Equals(new Label(type))) + .FirstOrDefault(); + + Put(var, entityType); + } + + [When(@"\$([a-zA-Z0-9]+) = entity\(([a-zA-Z0-9-_]+)\) get instance with key\(([a-zA-Z0-9-_]+)\): (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})")] + public void EntityTypeGetInstanceWithKey( + string var, string type, string keyType, DateTime keyValue) + { + var entityType = Tx.Concepts + .GetAttributeType(keyType).Resolve()! + .Get(Tx, keyValue).Resolve()! + .GetOwners(Tx) + .Where(owner => owner.Type.Label.Equals(new Label(type))) + .FirstOrDefault(); + + Put(var, entityType); + } + + [Then(@"entity\(([a-zA-Z0-9-_]+)\) get instances contain: \$([a-zA-Z0-9]+)")] + public void EntityTypeGetInstancesContain(string typeLabel, string var) + { + Assert.True(Tx.Concepts + .GetEntityType(typeLabel).Resolve()! + .GetInstances(Tx) + .Where(i => i.Equals(Get(var))) + .Any()); + } + + [Then(@"entity\(([a-zA-Z0-9-_]+)\) get instances is empty")] + public void EntityTypeGetInstancesIsEmpty(string typeLabel) + { + var instances = Tx.Concepts + .GetEntityType(typeLabel).Resolve()! + .GetInstances(Tx); + + Assert.Equal(0, instances.Count()); + } + } +} diff --git a/csharp/Test/Behaviour/Concept/Thing/Entity/EntityTest.cs b/csharp/Test/Behaviour/Concept/Thing/Entity/EntityTest.cs new file mode 100644 index 0000000000..7cb10c77fa --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Thing/Entity/EntityTest.cs @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using Xunit.Gherkin.Quick; + +namespace TypeDB.Driver.Test.Behaviour +{ + [FeatureFile("external/vaticle_typedb_behaviour/concept/thing/entity.feature")] + public partial class BehaviourSteps + { + } +} diff --git a/csharp/Test/Behaviour/Concept/Thing/Relation/BUILD b/csharp/Test/Behaviour/Concept/Thing/Relation/BUILD new file mode 100644 index 0000000000..8e63a1a4db --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Thing/Relation/BUILD @@ -0,0 +1,100 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +package(default_visibility = ["//csharp/Test/Behaviour:__subpackages__"]) + +load("//csharp:build_opts.bzl", "nullable_context", "target_frameworks", "targeting_packs") +load("//csharp/Test:build_opts.bzl", "behaviour_tests_deps") +load("//csharp/Test:rules.bzl", "csharp_behaviour_test") +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") + + +filegroup( + name = "steps", + srcs = ["RelationSteps.cs"], + visibility = ["//csharp/Test/Behaviour:__subpackages__"], +) + + +csharp_behaviour_test( + name = "test-core", + test_files = ["RelationTest.cs"], + steps_files = [ + ":steps", + "//csharp/Test/Behaviour/Util:steps", + "//csharp/Test/Behaviour/Concept/Thing/Attribute:steps", + "//csharp/Test/Behaviour/Concept/Thing/Entity:steps", + "//csharp/Test/Behaviour/Concept/Thing:steps", + "//csharp/Test/Behaviour/Concept/Type/AttributeType:steps", + "//csharp/Test/Behaviour/Concept/Type/RelationType:steps", + "//csharp/Test/Behaviour/Concept/Type/ThingType:steps", + "//csharp/Test/Behaviour/Connection/Transaction:steps", + "//csharp/Test/Behaviour/Connection/Session:steps", + "//csharp/Test/Behaviour/Connection/Database:steps", + "//csharp/Test/Behaviour/Connection:steps-core", + ], + features = ["@vaticle_typedb_behaviour//concept/thing:relation.feature"], + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp:driver-csharp", + "//csharp/Test/Behaviour/Util:util", + ], + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +csharp_behaviour_test( + name = "test-cloud", + test_files = ["RelationTest.cs"], + steps_files = [ + ":steps", + "//csharp/Test/Behaviour/Util:steps", + "//csharp/Test/Behaviour/Concept/Thing/Attribute:steps", + "//csharp/Test/Behaviour/Concept/Thing/Entity:steps", + "//csharp/Test/Behaviour/Concept/Thing:steps", + "//csharp/Test/Behaviour/Concept/Type/AttributeType:steps", + "//csharp/Test/Behaviour/Concept/Type/RelationType:steps", + "//csharp/Test/Behaviour/Concept/Type/ThingType:steps", + "//csharp/Test/Behaviour/Connection/Transaction:steps", + "//csharp/Test/Behaviour/Connection/Session:steps", + "//csharp/Test/Behaviour/Connection/Database:steps", + "//csharp/Test/Behaviour/Connection:steps-cloud", + ], + features = ["@vaticle_typedb_behaviour//concept/thing:relation.feature"], + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp:driver-csharp", + "//csharp/Test/Behaviour/Util:util", + ], + add_certificates = True, + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +checkstyle_test( + name = "checkstyle", + include = glob(["*"]), + license_type = "apache-header", +) diff --git a/csharp/Test/Behaviour/Concept/Thing/Relation/RelationSteps.cs b/csharp/Test/Behaviour/Concept/Thing/Relation/RelationSteps.cs new file mode 100644 index 0000000000..e4bca9faef --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Thing/Relation/RelationSteps.cs @@ -0,0 +1,292 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using DataTable = Gherkin.Ast.DataTable; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Xunit; +using Xunit.Gherkin.Quick; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; + +namespace TypeDB.Driver.Test.Behaviour +{ + public partial class BehaviourSteps + { + [When(@"\$([a-zA-Z0-9]+) = relation\(([a-zA-Z0-9-_]+)\) create new instance")] + [Then(@"\$([a-zA-Z0-9]+) = relation\(([a-zA-Z0-9-_]+)\) create new instance")] + public void RelationTypeCreateNewInstance(string var, string typeLabel) + { + Put( + var, + Tx.Concepts.GetRelationType(typeLabel).Resolve()!.Create(Tx).Resolve()!); + } + + [Then(@"relation\(([a-zA-Z0-9-_]+)\) create new instance; throws exception")] + public void RelationTypeCreateNewInstanceThrowsException(string typeLabel) + { + Assert.Throws(() => + Tx.Concepts.GetRelationType(typeLabel).Resolve()!.Create(Tx).Resolve()!); + } + + [When(@"\$([a-zA-Z0-9]+) = relation\(([a-zA-Z0-9-_]+)\) create new instance with key\(([a-zA-Z0-9-_]+)\): {int}")] + public void RelationTypeCreateNewInstanceWithKey(string var, string type, string keyType, int keyValue) + { + IAttribute key = Tx.Concepts + .GetAttributeType(keyType).Resolve()! + .Put(Tx, keyValue).Resolve()!; + + IRelation relation = Tx.Concepts + .GetRelationType(type).Resolve()! + .Create(Tx).Resolve()!; + + relation.SetHas(Tx, key).Resolve(); + Put(var, relation); + } + + [When(@"\$([a-zA-Z0-9]+) = relation\(([a-zA-Z0-9-_]+)\) create new instance with key\(([a-zA-Z0-9-_]+)\): {word}")] + public void RelationTypeCreateNewInstanceWithKey( + string var, string type, string keyType, string keyValue) + { + IAttribute key = Tx.Concepts + .GetAttributeType(keyType).Resolve()! + .Put(Tx, keyValue).Resolve()!; + + IRelation relation = Tx.Concepts + .GetRelationType(type).Resolve()! + .Create(Tx).Resolve()!; + + relation.SetHas(Tx, key).Resolve(); + Put(var, relation); + } + + [When(@"\$([a-zA-Z0-9]+) = relation\(([a-zA-Z0-9-_]+)\) create new instance with key\(([a-zA-Z0-9-_]+)\): (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})")] + public void RelationTypeCreateNewInstanceWithKey( + string var, string type, string keyType, DateTime keyValue) + { + IAttribute key = Tx.Concepts + .GetAttributeType(keyType).Resolve()! + .Put(Tx, keyValue).Resolve()!; + + IRelation relation = Tx.Concepts + .GetRelationType(type).Resolve()! + .Create(Tx).Resolve()!; + + relation.SetHas(Tx, key).Resolve(); + Put(var, relation); + } + + [When(@"\$([a-zA-Z0-9]+) = relation\(([a-zA-Z0-9-_]+)\) get instance with key\(([a-zA-Z0-9-_]+)\): {int}")] + public void RelationTypeGetInstanceWithKey(string var1, string type, string keyType, long keyValue) + { + var owner = Tx.Concepts + .GetAttributeType(keyType).Resolve()! + .Get(Tx, keyValue).Resolve()! + .GetOwners(Tx) + .Where(owner => owner.Type.Label.Equals(new Label(type))) + .FirstOrDefault(); + + Put(var1, owner); + } + + [When(@"\$([a-zA-Z0-9]+) = relation\(([a-zA-Z0-9-_]+)\) get instance with key\(([a-zA-Z0-9-_]+)\): {word}")] + public void RelationTypeGetInstanceWithKey(string var1, string type, string keyType, string keyValue) + { + var owner = Tx.Concepts + .GetAttributeType(keyType).Resolve()! + .Get(Tx, keyValue).Resolve()! + .GetOwners(Tx) + .Where(owner => owner.Type.Label.Equals(new Label(type))) + .FirstOrDefault(); + + Put(var1, owner); + } + + [When(@"\$([a-zA-Z0-9]+) = relation\(([a-zA-Z0-9-_]+)\) get instance with key\(([a-zA-Z0-9-_]+)\): (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})")] + public void RelationTypeGetInstanceWithKey( + string var1, string type, string keyType, DateTime keyValue) + { + var owner = Tx.Concepts + .GetAttributeType(keyType).Resolve()! + .Get(Tx, keyValue).Resolve()! + .GetOwners(Tx) + .Where(owner => owner.Type.Label.Equals(new Label(type))) + .FirstOrDefault(); + + Put(var1, owner); + } + + [Then(@"relation\(([a-zA-Z0-9-_]+)\) get instances contain: \$([a-zA-Z0-9]+)")] + public void RelationTypeGetInstancesContain(string typeLabel, string var) + { + var instances = Tx.Concepts + .GetRelationType(typeLabel).Resolve()! + .GetInstances(Tx); + + Assert.True(instances.Where(i => i.Equals(Get(var)!)).Any()); + } + + [Then(@"relation\(([a-zA-Z0-9-_]+)\) get instances do not contain: \$([a-zA-Z0-9]+)")] + public void RelationTypeGetInstancesDoNotContain(string typeLabel, string var) + { + var instances = Tx.Concepts + .GetRelationType(typeLabel).Resolve()! + .GetInstances(Tx); + + Assert.False(instances.Where(i => i.Equals(Get(var)!)).Any()); + } + + [Then(@"relation\(([a-zA-Z0-9-_]+)\) get instances is empty")] + public void RelationTypeGetInstancesIsEmpty(string typeLabel) + { + var instances = Tx.Concepts + .GetRelationType(typeLabel).Resolve()! + .GetInstances(Tx); + + Assert.Equal(0, instances.Count()); + } + + [When(@"relation \$([a-zA-Z0-9]+) add player for role\(([a-zA-Z0-9-_]+)\): \$([a-zA-Z0-9]+)")] + public void RelationAddPlayerForRole(string var1, string roleTypeLabel, string var2) + { + var relates = Get(var1)! + .AsRelation() + .Type.AsRelationType() + .GetRelates(Tx, roleTypeLabel).Resolve()!; + + Get(var1)! + .AsRelation() + .AddPlayer(Tx, relates, Get(var2)!).Resolve(); + } + + [When(@"relation \$([a-zA-Z0-9]+) add player for role\(([a-zA-Z0-9-_]+)\): \$([a-zA-Z0-9]+); throws exception")] + public void RelationAddPlayerForRoleThrowsException(string var1, string roleTypeLabel, string var2) + { + var relates = Get(var1)! + .AsRelation() + .Type.AsRelationType() + .GetRelates(Tx, roleTypeLabel).Resolve()!; + + Assert.Throws(() => Get(var1)! + .AsRelation() + .AddPlayer(Tx, relates, Get(var2)!).Resolve()); + } + + [When(@"relation \$([a-zA-Z0-9]+) remove player for role\(([a-zA-Z0-9-_]+)\): \$([a-zA-Z0-9]+)")] + public void RelationRemovePlayerForRole(string var1, string roleTypeLabel, string var2) + { + var relates = Get(var1)! + .AsRelation() + .Type.AsRelationType() + .GetRelates(Tx, roleTypeLabel).Resolve()!; + + Get(var1)! + .AsRelation() + .RemovePlayer(Tx, relates, Get(var2)!).Resolve(); + } + + [Then(@"relation \$([a-zA-Z0-9]+) get players contain:")] + public void RelationGetPlayersContain(string var, DataTable playersData) + { + Dictionary players = Util.ParseDataTableToDictionary(playersData); + IRelation relation = Get(var)!.AsRelation(); + + foreach (var (rt, var2) in players) + { + var relationPlayers = relation + .GetPlayers(Tx)[relation.Type.AsRelationType().GetRelates(Tx, rt).Resolve()!]; + + Assert.True(relationPlayers.Contains(Get(var2.Substring(1))!)); + } + } + + [Then(@"relation \$([a-zA-Z0-9]+) get players do not contain:")] + public void RelationGetPlayersDoNotContain(string var, DataTable playersData) + { + Dictionary expectedPlayers = Util.ParseDataTableToDictionary(playersData); + + IRelation relation = Get(var)!.AsRelation(); + + foreach (var (rt, var2) in expectedPlayers) + { + var players = relation.GetPlayers(Tx); + var relates = relation.Type.AsRelationType().GetRelates(Tx, rt).Resolve()!; + + if (players.ContainsKey(relates)) + { + var relatesPlayers = players[relates]; + Assert.False(relatesPlayers.Contains(Get(var2.Substring(1))!)); + } + } + } + + [Then(@"relation \$([a-zA-Z0-9]+) get players contain: \$([a-zA-Z0-9]+)")] + public void RelationGetPlayersContain(string var1, string var2) + { + var players = Get(var1)!.AsRelation().GetPlayersByRoleType(Tx); + Assert.True(players.Where(p => p.Equals(Get(var2)!)).Any()); + } + + [Then(@"relation \$([a-zA-Z0-9]+) get players do not contain: \$([a-zA-Z0-9]+)")] + public void RelationGetPlayersDoNotContain(string var1, string var2) + { + var players = Get(var1)!.AsRelation().GetPlayersByRoleType(Tx); + + Assert.False(players.Where(p => p.Equals(Get(var2)!)).Any()); + } + + [Then(@"relation \$([a-zA-Z0-9]+) get players for role\(([a-zA-Z0-9-_]+)\) contain: \$([a-zA-Z0-9]+)")] + public void RelationGetPlayersForRoleContain(string var1, string roleTypeLabel, string var2) + { + var relates = Get(var1)! + .AsRelation() + .Type.AsRelationType() + .GetRelates(Tx, roleTypeLabel).Resolve()!; + + var players = Get(var1)! + .AsRelation() + .GetPlayersByRoleType(Tx, relates); + + Assert.True(players.Where(p => p.Equals(Get(var2)!)).Any()); + } + + [Then(@"relation \$([a-zA-Z0-9]+) get players for role\(([a-zA-Z0-9-_]+)\) do not contain: \$([a-zA-Z0-9]+)")] + public void RelationGetPlayersForRoleDoNotContain(string var1, string roleTypeLabel, string var2) + { + var relates = Get(var1)! + .AsRelation() + .Type.AsRelationType() + .GetRelates(Tx, roleTypeLabel).Resolve()!; + + var players = Get(var1)! + .AsRelation() + .GetPlayersByRoleType(Tx, relates); + + Assert.False(players.Where(p => p.Equals(Get(var2)!)).Any()); + } + } +} diff --git a/csharp/Test/Behaviour/Concept/Thing/Relation/RelationTest.cs b/csharp/Test/Behaviour/Concept/Thing/Relation/RelationTest.cs new file mode 100644 index 0000000000..176725a4c2 --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Thing/Relation/RelationTest.cs @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using Xunit.Gherkin.Quick; + +namespace TypeDB.Driver.Test.Behaviour +{ + [FeatureFile("external/vaticle_typedb_behaviour/concept/thing/relation.feature")] + public partial class BehaviourSteps + { + } +} diff --git a/csharp/Test/Behaviour/Concept/Thing/ThingSteps.cs b/csharp/Test/Behaviour/Concept/Thing/ThingSteps.cs new file mode 100644 index 0000000000..f6fd8c5628 --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Thing/ThingSteps.cs @@ -0,0 +1,268 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using Xunit; +using Xunit.Gherkin.Quick; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using static TypeDB.Driver.Api.IThingType.Annotation; + +namespace TypeDB.Driver.Test.Behaviour +{ + public partial class BehaviourSteps + { + private static Dictionary _things = new Dictionary(); + + public static IThing? Get(string variable) + { + return _things[variable]; + } + + public static void Put(string variable, IThing? thing) + { + _things[variable] = thing; + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) is null: (true|false)")] + public void ThingIsNull(string rootLabel, string var, bool isNull) + { + Assert.Equal(isNull, Get(var) == null); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) is deleted: (true|false)")] + public void ThingIsDeleted(string rootLabel, string var, bool isDeleted) + { + Assert.Equal(isDeleted, Get(var)!.IsDeleted(Tx).Resolve()!); + } + + [Then(@"(entity|attribute|relation|thing) \$([a-zA-Z0-9]+) has type: ([a-zA-Z0-9-_]+)")] + public void ThingHasType(string rootLabel, string var, string typeLabel) + { + IThingType type = GetThingType(rootLabel, typeLabel); + Assert.Equal(type, Get(var)!.Type); + } + + [When(@"delete (entity|attribute|relation): \$([a-zA-Z0-9]+)")] + public void DeleteThings(string rootLabel, string var) + { + Get(var)!.Delete(Tx).Resolve(); + } + + [When(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) set has: \$([a-zA-Z0-9]+)")] + public void ThingSetHas(string rootLabel, string var1, string var2) + { + Get(var1)!.SetHas(Tx, Get(var2)!.AsAttribute()).Resolve(); + } + + [When(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) set has: \$([a-zA-Z0-9]+); throws exception")] + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) set has: \$([a-zA-Z0-9]+); throws exception")] + public void ThingSetHasThrowsException(string rootLabel, string var1, string var2) + { + Assert.Throws( + () => Get(var1)!.SetHas(Tx, Get(var2)!.AsAttribute()).Resolve()); + } + + [When(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) unset has: \$([a-zA-Z0-9]+)")] + public void ThingUnsetHas(string rootLabel, string var1, string var2) + { + Get(var1)!.UnsetHas(Tx, Get(var2)!.AsAttribute()).Resolve(); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get keys contain: \$([a-zA-Z0-9]+)")] + public void ThingGetKeysContain(string rootLabel, string var1, string var2) + { + Assert.True(Get(var1)! + .GetHas(Tx, new []{NewKey()}) + .Where(k => k.Equals(Get(var2)!)) + .Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get keys do not contain: \$([a-zA-Z0-9]+)")] + public void ThingGetKeysDoNotContain(string rootLabel, string var1, string var2) + { + Assert.False(Get(var1)! + .GetHas(Tx, new []{NewKey()}) + .Where(k => k.Equals(Get(var2)!)) + .Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get attributes contain: \$([a-zA-Z0-9]+)")] + public void ThingGetAttributesContain(string rootLabel, string var1, string var2) + { + Assert.True(Get(var1)!.GetHas(Tx).Where(k => k.Equals(Get(var2)!)).Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get attributes\(([a-zA-Z0-9-_]+)\) contain: \$([a-zA-Z0-9]+)")] + public void ThingGetAttributesContain(string rootLabel, string var1, string typeLabel, string var2) + { + Assert.True(Get(var1)! + .GetHas(Tx, Tx.Concepts.GetAttributeType(typeLabel).Resolve()!) + .Where(k => k.Equals(Get(var2)!)) + .Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get attributes\(([a-zA-Z0-9-_]+)\) as\(boolean\) contain: \$([a-zA-Z0-9]+)")] + public void ThingGetAttributesAsBooleanContain(string rootLabel, string var1, string typeLabel, string var2) + { + Assert.True(Get(var1)! + .GetHas(Tx, Tx.Concepts.GetAttributeType(typeLabel).Resolve()!) + .Where(k => k.Equals(Get(var2)!)) + .Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get attributes\(([a-zA-Z0-9-_]+)\) as\(long\) contain: \$([a-zA-Z0-9]+)")] + public void ThingGetAttributesAsLongContain(string rootLabel, string var1, string typeLabel, string var2) + { + Assert.True(Get(var1)! + .GetHas(Tx, Tx.Concepts.GetAttributeType(typeLabel).Resolve()!) + .Where(k => k.Equals(Get(var2)!)) + .Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get attributes\(([a-zA-Z0-9-_]+)\) as\(double\) contain: \$([a-zA-Z0-9]+)")] + public void ThingGetAttributesAsDoubleContain(string rootLabel, string var1, string typeLabel, string var2) + { + Assert.True(Get(var1)! + .GetHas(Tx, Tx.Concepts.GetAttributeType(typeLabel).Resolve()!) + .Where(k => k.Equals(Get(var2)!)) + .Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get attributes\(([a-zA-Z0-9-_]+)\) as\(string\) contain: \$([a-zA-Z0-9]+)")] + public void ThingGetAttributesAsStringContain(string rootLabel, string var1, string typeLabel, string var2) + { + Assert.True(Get(var1)! + .GetHas(Tx, Tx.Concepts.GetAttributeType(typeLabel).Resolve()!) + .Where(k => k.Equals(Get(var2)!)) + .Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get attributes\(([a-zA-Z0-9-_]+)\) as\(datetime\) contain: \$([a-zA-Z0-9]+)")] + public void ThingGetAttributesAsDatetimeContain(string rootLabel, string var1, string typeLabel, string var2) + { + Assert.True(Get(var1)! + .GetHas(Tx, Tx.Concepts.GetAttributeType(typeLabel).Resolve()!) + .Where(k => k.Equals(Get(var2)!)) + .Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get attributes do not contain: \$([a-zA-Z0-9]+)")] + public void ThingGetAttributesDoNotContain(string rootLabel, string var1, string var2) + { + Assert.False(Get(var1)!.GetHas(Tx).Where(k => k.Equals(Get(var2)!)).Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get attributes\(([a-zA-Z0-9-_]+)\) do not contain: \$([a-zA-Z0-9]+)")] + public void ThingGetAttributesDoNotContain(string rootLabel, string var1, string typeLabel, string var2) + { + Assert.False(Get(var1)! + .GetHas(Tx, Tx.Concepts.GetAttributeType(typeLabel).Resolve()!) + .Where(k => k.Equals(Get(var2)!)) + .Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get attributes\(([a-zA-Z0-9-_]+)\) as\(boolean\) do not contain: \$([a-zA-Z0-9]+)")] + public void ThingGetAttributesAsBooleanDoNotContain(string rootLabel, string var1, string typeLabel, string var2) + { + Assert.False(Get(var1)! + .GetHas(Tx, Tx.Concepts.GetAttributeType(typeLabel).Resolve()!) + .Where(k => k.Equals(Get(var2)!)) + .Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get attributes\(([a-zA-Z0-9-_]+)\) as\(long\) do not contain: \$([a-zA-Z0-9]+)")] + public void ThingGetAttributesAsLongDoNotContain(string rootLabel, string var1, string typeLabel, string var2) + { + Assert.False(Get(var1)! + .GetHas(Tx, Tx.Concepts.GetAttributeType(typeLabel).Resolve()!) + .Where(k => k.Equals(Get(var2)!)) + .Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get attributes\(([a-zA-Z0-9-_]+)\) as\(double\) do not contain: \$([a-zA-Z0-9]+)")] + public void ThingGetAttributesAsDoubleDoNotContain(string rootLabel, string var1, string typeLabel, string var2) + { + Assert.False(Get(var1)! + .GetHas(Tx, Tx.Concepts.GetAttributeType(typeLabel).Resolve()!) + .Where(k => k.Equals(Get(var2)!)) + .Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get attributes\(([a-zA-Z0-9-_]+)\) as\(string\) do not contain: \$([a-zA-Z0-9]+)")] + public void ThingGetAttributesAsStringDoNotContain(string rootLabel, string var1, string typeLabel, string var2) + { + Assert.False(Get(var1)! + .GetHas(Tx, Tx.Concepts.GetAttributeType(typeLabel).Resolve()!) + .Where(k => k.Equals(Get(var2)!)) + .Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get attributes\(([a-zA-Z0-9-_]+)\) as\(datetime\) do not contain: \$([a-zA-Z0-9]+)")] + public void ThingGetAttributesAsDatetimeDoNotContain(string rootLabel, string var1, string typeLabel, string var2) + { + Assert.False(Get(var1)! + .GetHas(Tx, Tx.Concepts.GetAttributeType(typeLabel).Resolve()!) + .Where(k => k.Equals(Get(var2)!)) + .Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get relations\(([a-zA-Z0-9-_]+:[a-zA-Z0-9-_]+)\) contain: \$([a-zA-Z0-9]+)")] + public void ThingGetRelationsContain(string rootLabel, string var1, string scopedLabelData, string var2) + { + Label scopedLabel = GetScopedLabel(scopedLabelData); + + var relates = Tx.Concepts + .GetRelationType(scopedLabel.Scope!).Resolve()! + .GetRelates(Tx, scopedLabel.Name).Resolve()!; + + Assert.True(Get(var1)!.GetRelations(Tx, relates).Where(k => k.Equals(Get(var2)!)).Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get relations contain: \$([a-zA-Z0-9]+)")] + public void ThingGetRelationsContain(string rootLabel, string var1, string var2) + { + Assert.True(Get(var1)!.GetRelations(Tx).Where(k => k.Equals(Get(var2)!)).Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get relations\(([a-zA-Z0-9-_]+:[a-zA-Z0-9-_]+)\) do not contain: \$([a-zA-Z0-9]+)")] + public void ThingGetRelationsDoNotContain(string rootLabel, string var1, string scopedLabelData, string var2) + { + Label scopedLabel = GetScopedLabel(scopedLabelData); + + var relates = Tx.Concepts + .GetRelationType(scopedLabel.Scope!).Resolve()! + .GetRelates(Tx, scopedLabel.Name).Resolve()!; + + Assert.False(Get(var1)!.GetRelations(Tx, relates).Where(k => k.Equals(Get(var2)!)).Any()); + } + + [Then(@"(entity|attribute|relation) \$([a-zA-Z0-9]+) get relations do not contain: \$([a-zA-Z0-9]+)")] + public void ThingGetRelationsDoNotContain(string rootLabel, string var1, string var2) + { + Assert.False(Get(var1)!.GetRelations(Tx).Where(k => k.Equals(Get(var2)!)).Any()); + } + } +} diff --git a/csharp/Test/Behaviour/Concept/Type/AttributeType/AttributeTypeSteps.cs b/csharp/Test/Behaviour/Concept/Type/AttributeType/AttributeTypeSteps.cs new file mode 100644 index 0000000000..91af954702 --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Type/AttributeType/AttributeTypeSteps.cs @@ -0,0 +1,296 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using DataTable = Gherkin.Ast.DataTable; +using System; +using System.Collections.Generic; +using System.Linq; +using Xunit; +using Xunit.Gherkin.Quick; +using static TypeDB.Driver.Api.IConcept.Transitivity; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using static TypeDB.Driver.Api.IThingType; + +namespace TypeDB.Driver.Test.Behaviour +{ + public partial class BehaviourSteps + { + public IValue.ValueType GetValueType(string type) + { + switch (type) + { + case "long": + return IValue.ValueType.Long; + case "double": + return IValue.ValueType.Double; + case "string": + return IValue.ValueType.String; + case "boolean": + return IValue.ValueType.Bool; + case "datetime": + return IValue.ValueType.DateTime; + default: + throw new BehaviourTestException($"Unexpected value type {type}"); + } + } + + [Given(@"put attribute type: ([a-zA-Z0-9-_]+), with value type: {}")] + [When(@"put attribute type: ([a-zA-Z0-9-_]+), with value type: {}")] + public void PutAttributeTypeWithValueType(string typeLabel, string valueTypeData) + { + IValue.ValueType valueType = GetValueType(valueTypeData); + Tx.Concepts.PutAttributeType(typeLabel, valueType).Resolve(); + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) get value type: {}")] + public void AttributeTypeGetValueType(string typeLabel, string valueTypeData) + { + IValue.ValueType valueType = GetValueType(valueTypeData); + Assert.Equal( + valueType, + Tx.Concepts.GetAttributeType(typeLabel).Resolve()!.ValueType); + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) get supertype value type: {}")] + public void AttributeTypeGetSupertypeValueType(string typeLabel, string valueTypeData) + { + IValue.ValueType valueType = GetValueType(valueTypeData); + IAttributeType supertype = Tx.Concepts + .GetAttributeType(typeLabel).Resolve()! + .GetSupertype(Tx).Resolve()! + .AsAttributeType(); + + Assert.Equal(valueType, supertype.ValueType); + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) as\({}\) get subtypes contain:")] + public void AttributeTypeAsValueTypeGetSubtypesContain( + string typeLabel, string valueTypeData, DataTable subLabelsData) + { + IValue.ValueType valueType = GetValueType(valueTypeData); + var subLabels = Util.ParseDataTableToTypeList(subLabelsData, val => val.ToString()); + + IAttributeType attributeType = Tx.Concepts.GetAttributeType(typeLabel).Resolve()!; + HashSet actuals = attributeType + .GetSubtypes(Tx, valueType) + .Select(t => t.Label.Name) + .ToHashSet(); + + Assert.False(subLabels.Except(actuals).Any()); + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) as\({}\) get subtypes do not contain:")] + public void AttributeTypeAsValueTypeGetSubtypesDoNotContain( + string typeLabel, string valueTypeData, DataTable subLabelsData) + { + IValue.ValueType valueType = GetValueType(valueTypeData); + var subLabels = Util.ParseDataTableToTypeList(subLabelsData, val => val.ToString()); + + IAttributeType attributeType = Tx.Concepts.GetAttributeType(typeLabel).Resolve()!; + HashSet actuals = attributeType + .GetSubtypes(Tx, valueType) + .Select(t => t.Label.Name) + .ToHashSet(); + + foreach (string subLabel in subLabels) + { + Assert.False(actuals.Contains(subLabel)); + } + } + + [Given(@"attribute\(([a-zA-Z0-9-_]+)\) as\({}\) set regex: {}")] + [When(@"attribute\(([a-zA-Z0-9-_]+)\) as\({}\) set regex: {}")] + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) as\({}\) set regex: {}")] + public void AttributeTypeAsValueTypeSetRegex(string typeLabel, string valueTypeData, string regex) + { + IValue.ValueType valueType = GetValueType(valueTypeData); + Assert.True(valueType.Equals(IValue.ValueType.String)); + + IAttributeType attributeType = Tx.Concepts.GetAttributeType(typeLabel).Resolve()!; + attributeType.SetRegex(Tx, regex).Resolve(); + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) as\({}\) unset regex")] + public void AttributeTypeAsValueTypeUnsetRegex(string typeLabel, string valueTypeData) + { + IValue.ValueType valueType = GetValueType(valueTypeData); + Assert.True(valueType.Equals(IValue.ValueType.String)); + + IAttributeType attributeType = Tx.Concepts.GetAttributeType(typeLabel).Resolve()!; + attributeType.UnsetRegex(Tx).Resolve(); + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) as\({}\) get regex: {}")] + public void AttributeTypeAsValueTypeGetRegex(string typeLabel, string valueTypeData, string? regex) + { + IValue.ValueType valueType = GetValueType(valueTypeData); + Assert.True(valueType.Equals(IValue.ValueType.String)); + + IAttributeType attributeType = Tx.Concepts.GetAttributeType(typeLabel).Resolve()!; + Assert.Equal(regex, attributeType.GetRegex(Tx).Resolve()); + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) as\({}\) does not have any regex")] + public void AttributeTypeAsValueTypeDoesNotHaveAnyRegex(string typeLabel, string valueTypeData) + { + AttributeTypeAsValueTypeGetRegex(typeLabel, valueTypeData, null); + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) get owners, with annotations: (\s*([\w\-_]+,\s*)*[\w\-_]*\s*); contain:")] + public void AttributeTypeGetOwnersWithAnnotationsContain( + string typeLabel, string annotationsData, DataTable ownerLabelsData) + { + List annotations = GetAnnotations(Util.ParseEnumerationToList(annotationsData)); + + var ownerLabels = Util.ParseDataTableToTypeList(ownerLabelsData, val => val.ToString()); + + IAttributeType attributeType = Tx.Concepts.GetAttributeType(typeLabel).Resolve()!; + HashSet actuals = attributeType + .GetOwners(Tx, annotations) + .Select(t => t.Label.Name) + .ToHashSet(); + + Assert.False(ownerLabels.Except(actuals).Any()); + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) get owners, with annotations: (\s*([\w\-_]+,\s*)*[\w\-_]*\s*); do not contain:")] + public void AttributeTypeGetOwnersWithAnnotationsDoNotContain( + string typeLabel, string annotationsData, DataTable ownerLabelsData) + { + List annotations = GetAnnotations(Util.ParseEnumerationToList(annotationsData)); + + var ownerLabels = Util.ParseDataTableToTypeList(ownerLabelsData, val => val.ToString()); + + IAttributeType attributeType = Tx.Concepts.GetAttributeType(typeLabel).Resolve()!; + HashSet actuals = attributeType + .GetOwners(Tx, annotations) + .Select(t => t.Label.Name) + .ToHashSet(); + + foreach (string ownerLabel in ownerLabels) + { + Assert.False(actuals.Contains(ownerLabel)); + } + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) get owners explicit, with annotations: (\s*([\w\-_]+,\s*)*[\w\-_]*\s*); contain:")] + public void AttributeTypeGetOwnersExplicitWithAnnotationsContain( + string typeLabel, string annotationsData, DataTable ownerLabelsData) + { + List annotations = GetAnnotations(Util.ParseEnumerationToList(annotationsData)); + + var ownerLabels = Util.ParseDataTableToTypeList(ownerLabelsData, val => val.ToString()); + + IAttributeType attributeType = Tx.Concepts.GetAttributeType(typeLabel).Resolve()!; + HashSet actuals = attributeType + .GetOwners(Tx, annotations, Explicit) + .Select(t => t.Label.Name) + .ToHashSet(); + + Assert.False(ownerLabels.Except(actuals).Any()); + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) get owners explicit, with annotations: (\s*([\w\-_]+,\s*)*[\w\-_]*\s*); do not contain:")] + public void AttributeTypeGetOwnersExplicitWithAnnotationsDoNotContain( + string typeLabel, string annotationsData, DataTable ownerLabelsData) + { + List annotations = GetAnnotations(Util.ParseEnumerationToList(annotationsData)); + + var ownerLabels = Util.ParseDataTableToTypeList(ownerLabelsData, val => val.ToString()); + + IAttributeType attributeType = Tx.Concepts.GetAttributeType(typeLabel).Resolve()!; + HashSet actuals = attributeType + .GetOwners(Tx, annotations, Explicit) + .Select(t => t.Label.Name) + .ToHashSet(); + + foreach (string ownerLabel in ownerLabels) + { + Assert.False(actuals.Contains(ownerLabel)); + } + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) get owners contain:")] + public void AttributeTypeGetOwnersContain(string typeLabel, DataTable ownerLabelsData) + { + var ownerLabels = Util.ParseDataTableToTypeList(ownerLabelsData, val => val.ToString()); + + IAttributeType attributeType = Tx.Concepts.GetAttributeType(typeLabel).Resolve()!; + HashSet actuals = attributeType + .GetOwners(Tx, new Annotation[0]) + .Select(t => t.Label.Name) + .ToHashSet(); + + Assert.False(ownerLabels.Except(actuals).Any()); + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) get owners do not contain:")] + public void AttributeTypeGetOwnersDoNotContain(string typeLabel, DataTable ownerLabelsData) + { + var ownerLabels = Util.ParseDataTableToTypeList(ownerLabelsData, val => val.ToString()); + + IAttributeType attributeType = Tx.Concepts.GetAttributeType(typeLabel).Resolve()!; + HashSet actuals = attributeType + .GetOwners(Tx, new Annotation[0]) + .Select(t => t.Label.Name) + .ToHashSet(); + + foreach (string ownerLabel in ownerLabels) + { + Assert.False(actuals.Contains(ownerLabel)); + } + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) get owners explicit contain:")] + public void AttributeTypeGetOwnersExplicitContain(string typeLabel, DataTable ownerLabelsData) + { + var ownerLabels = Util.ParseDataTableToTypeList(ownerLabelsData, val => val.ToString()); + + IAttributeType attributeType = Tx.Concepts.GetAttributeType(typeLabel).Resolve()!; + HashSet actuals = attributeType + .GetOwners(Tx, new Annotation[0], Explicit) + .Select(t => t.Label.Name) + .ToHashSet(); + + Assert.False(ownerLabels.Except(actuals).Any()); + } + + [Then(@"attribute\(([a-zA-Z0-9-_]+)\) get owners explicit do not contain:")] + public void AttributeTypeGetOwnersExplicitDoNotContain(string typeLabel, DataTable ownerLabelsData) + { + var ownerLabels = Util.ParseDataTableToTypeList(ownerLabelsData, val => val.ToString()); + + IAttributeType attributeType = Tx.Concepts.GetAttributeType(typeLabel).Resolve()!; + HashSet actuals = attributeType + .GetOwners(Tx, new Annotation[0], Explicit) + .Select(t => t.Label.Name) + .ToHashSet(); + + foreach (string ownerLabel in ownerLabels) + { + Assert.False(actuals.Contains(ownerLabel)); + } + } + } +} diff --git a/csharp/Test/Behaviour/Concept/Type/AttributeType/AttributeTypeTest.cs b/csharp/Test/Behaviour/Concept/Type/AttributeType/AttributeTypeTest.cs new file mode 100644 index 0000000000..4e758690d2 --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Type/AttributeType/AttributeTypeTest.cs @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using Xunit.Gherkin.Quick; + +namespace TypeDB.Driver.Test.Behaviour +{ + [FeatureFile("external/vaticle_typedb_behaviour/concept/type/attributetype.feature")] + public partial class BehaviourSteps + { + } +} diff --git a/csharp/Test/Behaviour/Concept/Type/AttributeType/BUILD b/csharp/Test/Behaviour/Concept/Type/AttributeType/BUILD new file mode 100644 index 0000000000..42c5ed3385 --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Type/AttributeType/BUILD @@ -0,0 +1,94 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +package(default_visibility = ["//csharp/Test/Behaviour:__subpackages__"]) + +load("//csharp:build_opts.bzl", "nullable_context", "target_frameworks", "targeting_packs") +load("//csharp/Test:build_opts.bzl", "behaviour_tests_deps") +load("//csharp/Test:rules.bzl", "csharp_behaviour_test") +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") + + +filegroup( + name = "steps", + srcs = ["AttributeTypeSteps.cs"], + visibility = ["//csharp/Test/Behaviour:__subpackages__"], +) + + +csharp_behaviour_test( + name = "test-core", + test_files = ["AttributeTypeTest.cs"], + steps_files = [ + ":steps", + "//csharp/Test/Behaviour/Util:steps", + "//csharp/Test/Behaviour/Concept/Thing/Attribute:steps", + "//csharp/Test/Behaviour/Concept/Thing:steps", + "//csharp/Test/Behaviour/Concept/Type/ThingType:steps", + "//csharp/Test/Behaviour/Connection/Transaction:steps", + "//csharp/Test/Behaviour/Connection/Session:steps", + "//csharp/Test/Behaviour/Connection/Database:steps", + "//csharp/Test/Behaviour/Connection:steps-core", + ], + features = ["@vaticle_typedb_behaviour//concept/type:attributetype.feature"], + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp:driver-csharp", + "//csharp/Test/Behaviour/Util:util", + ], + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +csharp_behaviour_test( + name = "test-cloud", + test_files = ["AttributeTypeTest.cs"], + steps_files = [ + ":steps", + "//csharp/Test/Behaviour/Util:steps", + "//csharp/Test/Behaviour/Concept/Thing/Attribute:steps", + "//csharp/Test/Behaviour/Concept/Thing:steps", + "//csharp/Test/Behaviour/Concept/Type/ThingType:steps", + "//csharp/Test/Behaviour/Connection/Transaction:steps", + "//csharp/Test/Behaviour/Connection/Session:steps", + "//csharp/Test/Behaviour/Connection/Database:steps", + "//csharp/Test/Behaviour/Connection:steps-cloud", + ], + features = ["@vaticle_typedb_behaviour//concept/type:attributetype.feature"], + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp:driver-csharp", + "//csharp/Test/Behaviour/Util:util", + ], + add_certificates = True, + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +checkstyle_test( + name = "checkstyle", + include = glob(["*"]), + license_type = "apache-header", +) diff --git a/csharp/Test/Behaviour/Concept/Type/EntityType/BUILD b/csharp/Test/Behaviour/Concept/Type/EntityType/BUILD new file mode 100644 index 0000000000..d84177c6be --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Type/EntityType/BUILD @@ -0,0 +1,93 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +package(default_visibility = ["//csharp/Test/Behaviour:__subpackages__"]) + +load("//csharp:build_opts.bzl", "nullable_context", "target_frameworks", "targeting_packs") +load("//csharp/Test:build_opts.bzl", "behaviour_tests_deps") +load("//csharp/Test:rules.bzl", "csharp_behaviour_test") +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") + + +csharp_behaviour_test( + name = "test-core", + test_files = ["EntityTypeTest.cs"], + steps_files = [ + "//csharp/Test/Behaviour/Util:steps", + "//csharp/Test/Behaviour/Concept/Thing/Attribute:steps", + "//csharp/Test/Behaviour/Concept/Thing/Entity:steps", + "//csharp/Test/Behaviour/Concept/Thing/Relation:steps", + "//csharp/Test/Behaviour/Concept/Thing:steps", + "//csharp/Test/Behaviour/Concept/Type/AttributeType:steps", + "//csharp/Test/Behaviour/Concept/Type/RelationType:steps", + "//csharp/Test/Behaviour/Concept/Type/ThingType:steps", + "//csharp/Test/Behaviour/Connection/Transaction:steps", + "//csharp/Test/Behaviour/Connection/Session:steps", + "//csharp/Test/Behaviour/Connection/Database:steps", + "//csharp/Test/Behaviour/Connection:steps-core", + ], + features = ["@vaticle_typedb_behaviour//concept/type:entitytype.feature"], + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp:driver-csharp", + "//csharp/Test/Behaviour/Util:util", + ], + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +csharp_behaviour_test( + name = "test-cloud", + test_files = ["EntityTypeTest.cs"], + steps_files = [ + "//csharp/Test/Behaviour/Util:steps", + "//csharp/Test/Behaviour/Concept/Thing/Attribute:steps", + "//csharp/Test/Behaviour/Concept/Thing/Entity:steps", + "//csharp/Test/Behaviour/Concept/Thing/Relation:steps", + "//csharp/Test/Behaviour/Concept/Thing:steps", + "//csharp/Test/Behaviour/Concept/Type/AttributeType:steps", + "//csharp/Test/Behaviour/Concept/Type/RelationType:steps", + "//csharp/Test/Behaviour/Concept/Type/ThingType:steps", + "//csharp/Test/Behaviour/Connection/Transaction:steps", + "//csharp/Test/Behaviour/Connection/Session:steps", + "//csharp/Test/Behaviour/Connection/Database:steps", + "//csharp/Test/Behaviour/Connection:steps-cloud", + ], + features = ["@vaticle_typedb_behaviour//concept/type:entitytype.feature"], + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp:driver-csharp", + "//csharp/Test/Behaviour/Util:util", + ], + add_certificates = True, + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +checkstyle_test( + name = "checkstyle", + include = glob(["*"]), + license_type = "apache-header", +) diff --git a/csharp/Test/Behaviour/Concept/Type/EntityType/EntityTypeTest.cs b/csharp/Test/Behaviour/Concept/Type/EntityType/EntityTypeTest.cs new file mode 100644 index 0000000000..a31e211ee5 --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Type/EntityType/EntityTypeTest.cs @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using Xunit.Gherkin.Quick; + +namespace TypeDB.Driver.Test.Behaviour +{ + [FeatureFile("external/vaticle_typedb_behaviour/concept/type/entitytype.feature")] + public partial class BehaviourSteps + { + } +} diff --git a/csharp/Test/Behaviour/Concept/Type/RelationType/BUILD b/csharp/Test/Behaviour/Concept/Type/RelationType/BUILD new file mode 100644 index 0000000000..cbbc8c5bf4 --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Type/RelationType/BUILD @@ -0,0 +1,98 @@ +# +# Copyright (C) 2022 Vaticle +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +package(default_visibility = ["//csharp/Test/Behaviour:__subpackages__"]) + +load("//csharp:build_opts.bzl", "nullable_context", "target_frameworks", "targeting_packs") +load("//csharp/Test:build_opts.bzl", "behaviour_tests_deps") +load("//csharp/Test:rules.bzl", "csharp_behaviour_test") +load("@vaticle_dependencies//tool/checkstyle:rules.bzl", "checkstyle_test") + + +filegroup( + name = "steps", + srcs = ["RelationTypeSteps.cs"], + visibility = ["//csharp/Test/Behaviour:__subpackages__"], +) + + +csharp_behaviour_test( + name = "test-core", + test_files = ["RelationTypeTest.cs"], + steps_files = [ + ":steps", + "//csharp/Test/Behaviour/Util:steps", + "//csharp/Test/Behaviour/Concept/Thing/Entity:steps", + "//csharp/Test/Behaviour/Concept/Thing/Relation:steps", + "//csharp/Test/Behaviour/Concept/Thing:steps", + "//csharp/Test/Behaviour/Concept/Type/AttributeType:steps", + "//csharp/Test/Behaviour/Concept/Type/ThingType:steps", + "//csharp/Test/Behaviour/Connection/Transaction:steps", + "//csharp/Test/Behaviour/Connection/Session:steps", + "//csharp/Test/Behaviour/Connection/Database:steps", + "//csharp/Test/Behaviour/Connection:steps-core", + ], + features = ["@vaticle_typedb_behaviour//concept/type:relationtype.feature"], + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp:driver-csharp", + "//csharp/Test/Behaviour/Util:util", + ], + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +csharp_behaviour_test( + name = "test-cloud", + test_files = ["RelationTypeTest.cs"], + steps_files = [ + ":steps", + "//csharp/Test/Behaviour/Util:steps", + "//csharp/Test/Behaviour/Concept/Thing/Entity:steps", + "//csharp/Test/Behaviour/Concept/Thing/Relation:steps", + "//csharp/Test/Behaviour/Concept/Thing:steps", + "//csharp/Test/Behaviour/Concept/Type/AttributeType:steps", + "//csharp/Test/Behaviour/Concept/Type/ThingType:steps", + "//csharp/Test/Behaviour/Connection/Transaction:steps", + "//csharp/Test/Behaviour/Connection/Session:steps", + "//csharp/Test/Behaviour/Connection/Database:steps", + "//csharp/Test/Behaviour/Connection:steps-cloud", + ], + features = ["@vaticle_typedb_behaviour//concept/type:relationtype.feature"], + deps = [ + "//csharp/Api:api", + "//csharp/Common:common", + "//csharp:driver-csharp", + "//csharp/Test/Behaviour/Util:util", + ], + add_certificates = True, + target_frameworks = target_frameworks, + targeting_packs = targeting_packs, +) + + +checkstyle_test( + name = "checkstyle", + include = glob(["*"]), + license_type = "apache-header", +) diff --git a/csharp/Test/Behaviour/Concept/Type/RelationType/RelationTypeSteps.cs b/csharp/Test/Behaviour/Concept/Type/RelationType/RelationTypeSteps.cs new file mode 100644 index 0000000000..79cc7a4e98 --- /dev/null +++ b/csharp/Test/Behaviour/Concept/Type/RelationType/RelationTypeSteps.cs @@ -0,0 +1,341 @@ +/* + * Copyright (C) 2022 Vaticle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +using DataTable = Gherkin.Ast.DataTable; +using System; +using System.Collections.Generic; +using System.Linq; +using Xunit; +using Xunit.Gherkin.Quick; + +using TypeDB.Driver; +using TypeDB.Driver.Api; +using TypeDB.Driver.Common; +using static TypeDB.Driver.Api.IConcept.Transitivity; + +namespace TypeDB.Driver.Test.Behaviour +{ + public partial class BehaviourSteps + { + [Given(@"relation\(([a-zA-Z0-9-_]+)\) set relates role: ([a-zA-Z0-9-_]+)")] + [When(@"relation\(([a-zA-Z0-9-_]+)\) set relates role: ([a-zA-Z0-9-_]+)")] + public void RelationTypeSetRelatesRoleType(string relationLabel, string roleLabel) + { + Tx.Concepts + .GetRelationType(relationLabel).Resolve()! + .SetRelates(Tx, roleLabel).Resolve(); + } + + [Then(@"relation\(([a-zA-Z0-9-_]+)\) set relates role: ([a-zA-Z0-9-_]+); throws exception")] + public void RelationTypeSetRelatesRoleTypeThrowsException(string relationLabel, string roleLabel) + { + Assert.Throws(() => RelationTypeSetRelatesRoleType(relationLabel, roleLabel)); + } + + [When(@"relation\(([a-zA-Z0-9-_]+)\) unset related role: ([a-zA-Z0-9-_]+)")] + [Then(@"relation\(([a-zA-Z0-9-_]+)\) unset related role: ([a-zA-Z0-9-_]+)")] + public void RelationTypeUnsetRelatedRoleType(string relationLabel, string roleLabel) + { + Tx.Concepts + .GetRelationType(relationLabel).Resolve()! + .UnsetRelates(Tx, roleLabel).Resolve(); + } + + [Then(@"relation\(([a-zA-Z0-9-_]+)\) unset related role: ([a-zA-Z0-9-_]+); throws exception")] + public void RelationTypeUnsetRelatedRoleTypeThrowsException(string relationLabel, string roleLabel) + { + Assert.Throws(() => RelationTypeUnsetRelatedRoleType(relationLabel, roleLabel)); + } + + [When(@"relation\(([a-zA-Z0-9-_]+)\) set relates role: ([a-zA-Z0-9-_]+) as ([a-zA-Z0-9-_]+)")] + public void RelationTypeSetRelatesRoleTypeAs(string relationLabel, string roleLabel, string superRole) + { + Tx.Concepts + .GetRelationType(relationLabel).Resolve()! + .SetRelates(Tx, roleLabel, superRole).Resolve(); + } + + [Then(@"relation\(([a-zA-Z0-9-_]+)\) set relates role: ([a-zA-Z0-9-_]+) as ([a-zA-Z0-9-_]+); throws exception")] + public void RelationTypeSetRelatesRoleTypeAsThrowsException( + string relationLabel, string roleLabel, string superRole) + { + Assert.Throws(() => + RelationTypeSetRelatesRoleTypeAs(relationLabel, roleLabel, superRole)); + } + + [When(@"relation\(([a-zA-Z0-9-_]+)\) remove related role: ([a-zA-Z0-9-_]+)")] + public void RelationTypeRemoveRelatedRole(string relationLabel, string roleLabel) + { + Tx.Concepts + .GetRelationType(relationLabel).Resolve()! + .GetRelates(Tx, roleLabel).Resolve()! + .Delete(Tx).Resolve(); + } + + [Then(@"relation\(([a-zA-Z0-9-_]+)\) get role\(([a-zA-Z0-9-_]+)\) is null: (true|false)")] + public void RelationTypeGetRoleTypeIsNull(string relationLabel, string roleLabel, bool isNull) + { + var roleType = Tx.Concepts + .GetRelationType(relationLabel).Resolve()! + .GetRelates(Tx, roleLabel).Resolve()!; + + Assert.Equal(isNull, roleType == null); + } + + [Then(@"relation\(([a-zA-Z0-9-_]+)\) get overridden role\(([a-zA-Z0-9-_]+)\) is null: (true|false)")] + public void RelationTypeGetOverriddenRoleTypeIsNull( + string relationLabel, string roleLabel, bool isNull) + { + var overridenType = Tx.Concepts + .GetRelationType(relationLabel).Resolve()! + .GetRelatesOverridden(Tx, roleLabel).Resolve()!; + + Assert.Equal(isNull, overridenType == null); + } + + [When(@"relation\(([a-zA-Z0-9-_]+)\) get role\(([a-zA-Z0-9-_]+)\) set label: ([a-zA-Z0-9-_]+)")] + public void RelationTypeGetRoleTypeSetLabel(string relationLabel, string roleLabel, string newLabel) + { + Tx.Concepts + .GetRelationType(relationLabel).Resolve()! + .GetRelates(Tx, roleLabel).Resolve()! + .SetLabel(Tx, newLabel).Resolve(); + } + + [Then(@"relation\(([a-zA-Z0-9-_]+)\) get role\(([a-zA-Z0-9-_]+)\) get label: ([a-zA-Z0-9-_]+)")] + public void RelationTypeGetRoleTypeGetLabel(string relationLabel, string roleLabel, string getLabel) + { + var relates = Tx.Concepts + .GetRelationType(relationLabel).Resolve()! + .GetRelates(Tx, roleLabel).Resolve()!; + + Assert.Equal(getLabel, relates.Label.Name); + } + + [Then(@"relation\(([a-zA-Z0-9-_]+)\) get overridden role\(([a-zA-Z0-9-_]+)\) get label: ([a-zA-Z0-9-_]+)")] + public void RelationTypeGetOverriddenRoleTypeGetLabel( + string relationLabel, string roleLabel, string getLabel) + { + var relates = Tx.Concepts + .GetRelationType(relationLabel).Resolve()! + .GetRelatesOverridden(Tx, roleLabel).Resolve()!; + + Assert.Equal(getLabel, relates.Label.Name); + } + + [Then(@"relation\(([a-zA-Z0-9-_]+)\) get role\(([a-zA-Z0-9-_]+)\) is abstract: (true|false)")] + public void RelationTypeGetRoleTypeIsAbstract(string relationLabel, string roleLabel, bool isAbstract) + { + var isRelatesAbstract = Tx.Concepts + .GetRelationType(relationLabel).Resolve()! + .GetRelates(Tx, roleLabel).Resolve()! + .IsAbstract(); + + Assert.Equal(isAbstract, isRelatesAbstract); + } + + private HashSet