├── ballerina ├── icon.png ├── .gitignore ├── init.bal ├── Package.md ├── error.bal ├── external_functions.bal ├── iterator.bal ├── Ballerina.toml ├── Module.md ├── build.gradle ├── Dependencies.toml └── constants.bal ├── docs └── images │ ├── cred.png │ ├── connector.gif │ └── multi-model.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitattributes ├── native ├── src │ └── main │ │ ├── resources │ │ └── META-INF │ │ │ └── native-image │ │ │ └── org.ballerinax │ │ │ └── azure-cosmosdb-native │ │ │ └── resource-config.json │ │ └── java │ │ ├── module-info.java │ │ └── io │ │ └── ballerinax │ │ └── cosmosdb │ │ ├── BallerinaErrorGenerator.java │ │ ├── ModuleUtils.java │ │ ├── RecordIteratorUtils.java │ │ └── Constants.java └── build.gradle ├── .github ├── CODEOWNERS └── workflows │ ├── trivy-scan.yml │ ├── pull-request.yml │ ├── build-with-bal-test-native.yml │ ├── daily-build.yml │ ├── release.yml │ ├── dev-stg-release.yml │ ├── ci.yml │ └── weekly-build.yml ├── gradle.properties ├── .gitignore ├── issue_template.md ├── spotbugs-exclude.xml ├── pull_request_template.md ├── examples ├── admin-operations │ ├── database │ │ ├── create_database.bal │ │ ├── get_a_database.bal │ │ ├── delete_database.bal │ │ ├── list_databases.bal │ │ └── database_operations.bal │ ├── users-permissions │ │ ├── user │ │ │ ├── create_user.bal │ │ │ ├── get_user.bal │ │ │ ├── delete_user.bal │ │ │ ├── replace_user_id.bal │ │ │ └── list_users.bal │ │ ├── permission │ │ │ ├── delete_permission.bal │ │ │ ├── get_permission.bal │ │ │ ├── list_permissions.bal │ │ │ ├── create_permission.bal │ │ │ └── replace_permission.bal │ │ └── users_access_control.bal │ ├── container │ │ ├── get_container.bal │ │ ├── delete_container.bal │ │ ├── list_containers.bal │ │ ├── create_container.bal │ │ └── container_operations.bal │ ├── triggers │ │ ├── delete_trigger.bal │ │ ├── list_trigger.bal │ │ ├── create_trigger.bal │ │ ├── replace_trigger.bal │ │ └── trigger_operations.bal │ ├── user-defined-functions │ │ ├── delete_udf.bal │ │ ├── list_udf.bal │ │ ├── create_udf.bal │ │ ├── replace_udf.bal │ │ └── user_defined_functions.bal │ └── offers │ │ └── offer_operations.bal ├── data-operations │ ├── stored-procedure │ │ ├── delete_stored_procedure.bal │ │ ├── list_stored_procedure.bal │ │ ├── execute_stored_procedure.bal │ │ ├── create_stored_procedure.bal │ │ └── stored_procedure_operations.bal │ └── documents │ │ ├── list_documents.bal │ │ ├── delete_document.bal │ │ ├── get_document.bal │ │ ├── query_document.bal │ │ ├── create_document.bal │ │ ├── replace_document.bal │ │ └── document_operations.bal └── build.gradle ├── settings.gradle ├── gradlew.bat ├── README.md └── gradlew /ballerina/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ballerina-platform/module-ballerinax-azure-cosmosdb/HEAD/ballerina/icon.png -------------------------------------------------------------------------------- /docs/images/cred.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ballerina-platform/module-ballerinax-azure-cosmosdb/HEAD/docs/images/cred.png -------------------------------------------------------------------------------- /docs/images/connector.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ballerina-platform/module-ballerinax-azure-cosmosdb/HEAD/docs/images/connector.gif -------------------------------------------------------------------------------- /docs/images/multi-model.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ballerina-platform/module-ballerinax-azure-cosmosdb/HEAD/docs/images/multi-model.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ballerina-platform/module-ballerinax-azure-cosmosdb/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # 2 | # https://help.github.com/articles/dealing-with-line-endings/ 3 | # 4 | # These are explicitly windows files and should use crlf 5 | *.bat text eol=crlf 6 | 7 | -------------------------------------------------------------------------------- /native/src/main/resources/META-INF/native-image/org.ballerinax/azure-cosmosdb-native/resource-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "resources": { 3 | "includes": [ 4 | { 5 | "pattern": "\\Qazure-cosmos.properties\\E" 6 | } 7 | ] 8 | } 9 | } -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Lines starting with '#' are comments. 2 | # Each line is a file pattern followed by one or more owners. 3 | 4 | # See: https://help.github.com/articles/about-codeowners/ 5 | 6 | # These owners will be the default owners for everything in the repo. 7 | * @NipunaRanasinghe @shafreenAnfar 8 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.caching=true 2 | group=org.ballerinalang.azure_cosmosdb 3 | version=4.2.0 4 | ballerinaLangVersion=2201.8.0 5 | 6 | checkstylePluginVersion=10.12.1 7 | spotbugsPluginVersion=5.0.14 8 | shadowJarPluginVersion=8.1.1 9 | downloadPluginVersion=5.4.0 10 | releasePluginVersion=2.8.0 11 | ballerinaGradlePluginVersion=2.2.0 12 | 13 | # Azure CosmosDB dependencies 14 | azureCosmosVersion=4.52.0 15 | nettyVersion=4.1.100.Final 16 | reactorNettyVersion=1.1.13 17 | micrometerVersion=1.12.0 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | !gradle/wrapper/gradle-wrapper.jar 15 | *.jar 16 | *.war 17 | *.nar 18 | *.ear 19 | *.zip 20 | *.tar.gz 21 | *.rar 22 | 23 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 24 | hs_err_pid* 25 | 26 | # Java related ignores 27 | build/ 28 | target/ 29 | .gradle/ 30 | 31 | # IDE-related files 32 | .idea 33 | .code 34 | .project 35 | .settings 36 | .vscode 37 | 38 | # Ballerina related ignores 39 | Ballerina.lock 40 | 41 | # Gradle plugin related ignores 42 | docker.env 43 | -------------------------------------------------------------------------------- /ballerina/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | # Ballerina configuartion file 26 | /tests/Config.toml 27 | 28 | # Target folder of ballerina project 29 | /target 30 | 31 | # json files created inside resources folder 32 | /modules 33 | 34 | # resource folder in tests folder 35 | /tests/resources 36 | 37 | # resources folder 38 | /resources/*.json 39 | 40 | # idea files 41 | *.idea 42 | 43 | # .ballerina files 44 | *.ballerina -------------------------------------------------------------------------------- /issue_template.md: -------------------------------------------------------------------------------- 1 | **Description:** 2 | 3 | 4 | **Suggested Labels:** 5 | 6 | 7 | **Suggested Assignees:** 8 | 9 | 10 | **Affected Product Version:** 11 | 12 | **OS, DB, other environment details and versions:** 13 | 14 | **Steps to reproduce:** 15 | 16 | 17 | **Related Issues:** 18 | -------------------------------------------------------------------------------- /ballerina/init.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/jballerina.java; 18 | 19 | function init() { 20 | setModule(); 21 | } 22 | 23 | function setModule() = @java:Method { 24 | 'class: "io.ballerinax.cosmosdb.ModuleUtils" 25 | } external; 26 | -------------------------------------------------------------------------------- /native/src/main/java/module-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) 3 | * 4 | * WSO2 LLC. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | module io.ballerinax.cosmosdb { 20 | requires io.ballerina.runtime; 21 | requires com.azure.cosmos; 22 | requires io.ballerina.lang.value; 23 | 24 | exports io.ballerinax.cosmosdb; 25 | } 26 | -------------------------------------------------------------------------------- /ballerina/Package.md: -------------------------------------------------------------------------------- 1 | Connects to [Azure Cosmos DB(SQL) API](https://docs.microsoft.com/en-us/rest/api/cosmos-db/) from Ballerina. 2 | 3 | ## Package overview 4 | The `azure_cosmosdb` is a [Ballerina](https://ballerina.io/) connector for Azure Cosmos DB. 5 | 6 | ### Compatibility 7 | | | Version | 8 | |----------------------|-------------------------------| 9 | | Ballerina Language | Ballerina Swan Lake 2201.7.0 | 10 | | Cosmos DB (SQL)API | 2018-12-31 | 11 | 12 | ## Report issues 13 | To report bugs, request new features, start new discussions, view project boards, etc., go to the [Ballerina Extended Library repository](https://github.com/ballerina-platform/ballerina-extended-library) 14 | 15 | ## Useful links 16 | - Discuss code changes of the Ballerina project via [ballerina-dev@googlegroups.com](mailto:ballerina-dev@googlegroups.com). 17 | - Chat live with us via our [Discord server](https://discord.gg/ballerinalang). 18 | - Post all technical questions on Stack Overflow with the [#ballerina](https://stackoverflow.com/questions/tagged/ballerina) tag 19 | -------------------------------------------------------------------------------- /.github/workflows/trivy-scan.yml: -------------------------------------------------------------------------------- 1 | name: Trivy 2 | 3 | on: 4 | workflow_dispatch: 5 | schedule: 6 | - cron: '30 20 * * *' 7 | 8 | jobs: 9 | ubuntu-build: 10 | name: Build on Ubuntu 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v3 14 | 15 | - name: Set up JDK 17 16 | uses: actions/setup-java@v3 17 | with: 18 | distribution: 'temurin' 19 | java-version: 17.0.7 20 | 21 | - name: Set Up Ballerina 22 | uses: ballerina-platform/setup-ballerina@v1.1.0 23 | with: 24 | version: latest 25 | 26 | - name: Build with Gradle 27 | env: 28 | packageUser: ${{ github.actor }} 29 | packagePAT: ${{ secrets.GITHUB_TOKEN }} 30 | run: ./gradlew build -x check -x test -x :azure-cosmosdb-examples:build 31 | 32 | - name: Run Trivy vulnerability scanner 33 | uses: aquasecurity/trivy-action@master 34 | with: 35 | scan-type: 'rootfs' 36 | scan-ref: '.' 37 | skip-dirs: 'gradle/' 38 | format: 'table' 39 | timeout: '10m0s' 40 | exit-code: '1' 41 | -------------------------------------------------------------------------------- /spotbugs-exclude.xml: -------------------------------------------------------------------------------- 1 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /.github/workflows/pull-request.yml: -------------------------------------------------------------------------------- 1 | name: Pull Request 2 | 3 | on: [ pull_request ] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/checkout@v3 11 | 12 | # Set up Java Environment 13 | - name: Set up JDK 17 14 | uses: actions/setup-java@v3 15 | with: 16 | distribution: 'temurin' 17 | java-version: 17.0.7 18 | 19 | # Setup Ballerina Environment 20 | - name: Set Up Ballerina 21 | uses: ballerina-platform/setup-ballerina@v1.1.0 22 | with: 23 | version: latest 24 | 25 | # Grant execute permission to the gradlew script 26 | - name: Grant execute permission for gradlew 27 | run: chmod +x gradlew 28 | 29 | # Build the project with Gradle 30 | - name: Build with Gradle 31 | env: 32 | packageUser: ${{ github.actor }} 33 | packagePAT: ${{ secrets.GITHUB_TOKEN }} 34 | JAVA_OPTS: -DBALLERINA_DEV_COMPILE_BALLERINA_ORG=true 35 | run: | 36 | ./gradlew build -x test 37 | 38 | # Build Ballerina Project 39 | - name: Ballerina Build 40 | run: bal pack ./ballerina 41 | env: 42 | JAVA_HOME: /usr/lib/jvm/default-jvm 43 | -------------------------------------------------------------------------------- /native/src/main/java/io/ballerinax/cosmosdb/BallerinaErrorGenerator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package io.ballerinax.cosmosdb; 20 | 21 | import io.ballerina.runtime.api.creators.ErrorCreator; 22 | import io.ballerina.runtime.api.utils.StringUtils; 23 | import io.ballerina.runtime.api.values.BError; 24 | 25 | /** 26 | * The class holds the utility methods to generate errors. 27 | */ 28 | public class BallerinaErrorGenerator { 29 | 30 | public static BError createBallerinaDatabaseError(Exception e) { 31 | return ErrorCreator.createError(StringUtils.fromString(e.getMessage())); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /native/src/main/java/io/ballerinax/cosmosdb/ModuleUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package io.ballerinax.cosmosdb; 20 | 21 | import io.ballerina.runtime.api.Environment; 22 | import io.ballerina.runtime.api.Module; 23 | 24 | /** 25 | * This class will hold module related utility functions. 26 | */ 27 | public class ModuleUtils { 28 | 29 | private static Module cosmosdbdbModule = null; 30 | 31 | private ModuleUtils() { 32 | } 33 | 34 | public static void setModule(Environment env) { 35 | cosmosdbdbModule = env.getCurrentModule(); 36 | } 37 | 38 | public static Module getModule() { 39 | return cosmosdbdbModule; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /ballerina/error.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | # Extra HTTP status code detail of an error. 18 | # 19 | # + status - The HTTP status code of the error 20 | public type HttpDetail record { 21 | int status; 22 | }; 23 | 24 | # The errors which will come from the Azure API call itself. 25 | public type PayloadValidationError distinct error; 26 | 27 | # The payload access errors where the error detail contains the HTTP status. 28 | public type DbOperationError error; 29 | 30 | # The errors which occur when providing an invalid value. 31 | public type InputValidationError distinct error; 32 | 33 | # The union of all types of errors in the connector. 34 | public type Error PayloadValidationError|DbOperationError|InputValidationError|error; 35 | -------------------------------------------------------------------------------- /pull_request_template.md: -------------------------------------------------------------------------------- 1 | # Description 2 | 3 | Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. 4 | 5 | Fixes # (issue) 6 | 7 | Related Pull Requests (remove if not relevant) 8 | - Pull request 1 9 | - Pull request 2 10 | 11 | One line release note: 12 | - One line describing the feature/improvement/fix made by this PR 13 | 14 | ## Type of change 15 | 16 | Please delete options that are not relevant. 17 | 18 | - [ ] Bug fix (non-breaking change which fixes an issue) 19 | - [ ] New feature (non-breaking change which adds functionality) 20 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) 21 | - [ ] This change requires a documentation update 22 | 23 | # How Has This Been Tested? 24 | 25 | Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration 26 | 27 | - [ ] Test A 28 | - [ ] Test B 29 | 30 | **Test Configuration**: 31 | * Ballerina Version: 32 | * Operating System: 33 | * Java SDK: 34 | 35 | # Checklist: 36 | 37 | ### Security checks 38 | - [ ] Followed secure coding standards in http://wso2.com/technical-reports/wso2-secure-engineering-guidelines? 39 | - [ ] Confirmed that this PR doesn't commit any keys, passwords, tokens, usernames, or other secrets? 40 | -------------------------------------------------------------------------------- /examples/admin-operations/database/create_database.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | 31 | log:printInfo("Creating database"); 32 | cosmosdb:Database|error result = managementClient->createDatabase(databaseId); 33 | 34 | if (result is cosmosdb:Database) { 35 | log:printInfo(result.toString()); 36 | log:printInfo("Success!"); 37 | } else { 38 | log:printError(result.message()); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /examples/admin-operations/database/get_a_database.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | 31 | log:printInfo("Reading database by id"); 32 | cosmosdb:Database|error result = managementClient->getDatabase(databaseId); 33 | 34 | if (result is cosmosdb:Database) { 35 | log:printInfo(result.toString()); 36 | log:printInfo("Success!"); 37 | } else { 38 | log:printError(result.message()); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /examples/admin-operations/database/delete_database.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | 31 | log:printInfo("Deleting database"); 32 | cosmosdb:DeleteResponse|error result = managementClient->deleteDatabase(databaseId); 33 | 34 | if (result is cosmosdb:DeleteResponse) { 35 | log:printInfo(result.toString()); 36 | log:printInfo("Success!"); 37 | } else { 38 | log:printError(result.message()); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /examples/admin-operations/users-permissions/user/create_user.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string userId = "my_user"; 31 | 32 | log:printInfo("Creating user"); 33 | cosmosdb:User|error result = managementClient->createUser(databaseId, userId); 34 | 35 | if (result is cosmosdb:User) { 36 | log:printInfo(result.toString()); 37 | log:printInfo("Success!"); 38 | } else { 39 | log:printError(result.message()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /examples/admin-operations/users-permissions/user/get_user.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string userId = "my_user"; 31 | 32 | log:printInfo("Get user information"); 33 | cosmosdb:User|error result = managementClient->getUser(databaseId, userId); 34 | 35 | if (result is cosmosdb:User) { 36 | log:printInfo(result.toString()); 37 | log:printInfo("Success!"); 38 | } else { 39 | log:printError(result.message()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /examples/admin-operations/container/get_container.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | 32 | log:printInfo("Reading container info"); 33 | cosmosdb:Container|error result = managementClient->getContainer(databaseId, containerId); 34 | 35 | if (result is cosmosdb:Container) { 36 | log:printInfo(result.toString()); 37 | log:printInfo("Success!"); 38 | } else { 39 | log:printError(result.message()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /examples/admin-operations/users-permissions/user/delete_user.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string userId = "my_new_user"; 31 | 32 | log:printInfo("Delete user"); 33 | cosmosdb:DeleteResponse|error result = managementClient->deleteUser(databaseId, userId); 34 | 35 | if (result is cosmosdb:DeleteResponse) { 36 | log:printInfo(result.toString()); 37 | log:printInfo("Success!"); 38 | } else { 39 | log:printError(result.message()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /examples/admin-operations/container/delete_container.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | 32 | log:printInfo("Deleting the container"); 33 | cosmosdb:DeleteResponse|error result = managementClient->deleteContainer(databaseId, containerId); 34 | 35 | if (result is cosmosdb:DeleteResponse) { 36 | log:printInfo(result.toString()); 37 | log:printInfo("Success!"); 38 | } else { 39 | log:printError(result.message()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /examples/data-operations/stored-procedure/delete_stored_procedure.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ConnectionConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:DataPlaneClient azureCosmosClient = check new (config); 27 | 28 | public function main() returns error? { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | string storedProcedureId = "my_stored_procedure"; 32 | 33 | log:printInfo("Deleting stored procedure"); 34 | cosmosdb:StoredProcedureResponse result = check azureCosmosClient->deleteStoredProcedure(databaseId, containerId, 35 | storedProcedureId); 36 | 37 | log:printInfo(result.toString()); 38 | log:printInfo("Success!"); 39 | 40 | } 41 | -------------------------------------------------------------------------------- /examples/admin-operations/database/list_databases.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | log:printInfo("Getting list of databases"); 30 | stream|error result = managementClient->listDatabases(); 31 | 32 | if (result is stream) { 33 | error? e = result.forEach(function (cosmosdb:Database database) { 34 | log:printInfo(database.toString()); 35 | }); 36 | log:printInfo("Success!"); 37 | 38 | } else { 39 | log:printError(result.message()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /examples/admin-operations/users-permissions/user/replace_user_id.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string oldUserId = "my_user"; 31 | string newUserId = "my_new_user"; 32 | 33 | log:printInfo("Replace user id"); 34 | cosmosdb:User|error result = managementClient->replaceUserId(databaseId, oldUserId, newUserId); 35 | 36 | if (result is cosmosdb:User) { 37 | log:printInfo(result.toString()); 38 | log:printInfo("Success!"); 39 | } else { 40 | log:printError(result.message()); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /examples/data-operations/documents/list_documents.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ConnectionConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:DataPlaneClient azureCosmosClient = check new (config); 27 | 28 | public function main() returns error? { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | int partitionKeyValue = 0; 32 | 33 | log:printInfo("Getting list of documents"); 34 | stream result = check azureCosmosClient->getDocumentList(databaseId, containerId, 35 | partitionKeyValue); 36 | 37 | check result.forEach(function (record {} document) { 38 | log:printInfo(document.toString()); 39 | }); 40 | log:printInfo("Success!"); 41 | 42 | } 43 | -------------------------------------------------------------------------------- /examples/admin-operations/users-permissions/user/list_users.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | 31 | log:printInfo("List users"); 32 | stream|error result = managementClient->listUsers(databaseId); 33 | if (result is stream) { 34 | error? e = result.forEach(function (cosmosdb:User storedPrcedure) { 35 | log:printInfo(storedPrcedure.toString()); 36 | }); 37 | log:printInfo("Success!"); 38 | } else { 39 | log:printError(result.message()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /examples/admin-operations/triggers/delete_trigger.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | string triggerId = "my_trigger"; 32 | 33 | log:printInfo("Deleting trigger"); 34 | 35 | cosmosdb:DeleteResponse|error result = managementClient->deleteTrigger(databaseId, containerId, triggerId); 36 | 37 | if (result is cosmosdb:DeleteResponse) { 38 | log:printInfo(result.toString()); 39 | log:printInfo("Success!"); 40 | } else { 41 | log:printError(result.message()); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /ballerina/external_functions.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/jballerina.java; 18 | 19 | isolated function ofEpochSecond(int epochSeconds, int nanoAdjustments) returns handle = @java:Method { 20 | 'class: "java.time.Instant", 21 | name: "ofEpochSecond" 22 | } external; 23 | 24 | isolated function getZoneId(handle zoneId) returns handle = @java:Method { 25 | 'class: "java.time.ZoneId", 26 | name: "of" 27 | } external; 28 | 29 | isolated function atZone(handle receiver, handle zoneId) returns handle = @java:Method { 30 | 'class: "java.time.Instant", 31 | name: "atZone" 32 | } external; 33 | 34 | isolated function ofPattern(handle pattern) returns handle = @java:Method { 35 | 'class: "java.time.format.DateTimeFormatter", 36 | name: "ofPattern" 37 | } external; 38 | 39 | isolated function format(handle receiver, handle dateTimeFormatter) returns handle = @java:Method { 40 | 'class: "java.time.ZonedDateTime", 41 | name: "format" 42 | } external; 43 | -------------------------------------------------------------------------------- /examples/admin-operations/users-permissions/permission/delete_permission.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | public function main() { 28 | string databaseId = "my_database"; 29 | string userId = "my_user"; 30 | string permissionId = "my_permission"; 31 | 32 | log:printInfo("Delete permission"); 33 | cosmosdb:DeleteResponse|error result = managementClient->deletePermission(databaseId, userId, permissionId); 34 | 35 | if (result is cosmosdb:DeleteResponse) { 36 | log:printInfo(result.toString()); 37 | log:printInfo("Success!"); 38 | } else { 39 | log:printError(result.message()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /examples/admin-operations/user-defined-functions/delete_udf.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | string udfId = "my_udf"; 32 | 33 | log:printInfo("Delete user defined function"); 34 | cosmosdb:DeleteResponse|error result = managementClient->deleteUserDefinedFunction(databaseId, containerId, udfId); 35 | 36 | if (result is cosmosdb:DeleteResponse) { 37 | log:printInfo(result.toString()); 38 | log:printInfo("Success!"); 39 | } else { 40 | log:printError(result.message()); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /examples/admin-operations/users-permissions/permission/get_permission.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string userId = "my_user"; 31 | string permissionId = "my_permission"; 32 | 33 | log:printInfo("Get intormation about one permission"); 34 | cosmosdb:Permission|error result = managementClient->getPermission(databaseId, userId, permissionId); 35 | 36 | if (result is cosmosdb:Permission) { 37 | log:printInfo(result.toString()); 38 | log:printInfo("Success!"); 39 | } else { 40 | log:printError(result.message()); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /examples/admin-operations/container/list_containers.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | 31 | log:printInfo("Getting list of containers"); 32 | stream|error result = managementClient->listContainers(databaseId); 33 | 34 | if (result is stream) { 35 | error? e = result.forEach(function (cosmosdb:Container container) { 36 | log:printInfo(container.toString()); 37 | }); 38 | log:printInfo("Success!"); 39 | } else { 40 | log:printError(result.message()); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /examples/data-operations/documents/delete_document.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ConnectionConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:DataPlaneClient azureCosmosClient = check new (config); 27 | 28 | public function main() returns error? { 29 | string databaseId = "my_database"; 30 | // Assume partition key of this container is set as /gender which is an int of 0 or 1 31 | string containerId = "my_container"; 32 | string documentId = "my_document"; 33 | int partitionKeyValue = 0; 34 | 35 | log:printInfo("Deleting the document"); 36 | cosmosdb:DocumentResponse documentResponse = check azureCosmosClient->deleteDocument(databaseId, containerId, 37 | documentId, partitionKeyValue); 38 | log:printInfo(documentResponse.toString()); 39 | } 40 | -------------------------------------------------------------------------------- /examples/data-operations/documents/get_document.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ConnectionConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:DataPlaneClient azureCosmosClient = check new (config); 27 | 28 | public function main() returns error? { 29 | string databaseId = "my_database"; 30 | // Assume partition key of this container is set as /gender which is an int of 0 or 1 31 | string containerId = "my_container"; 32 | string documentId = "my_document"; 33 | int partitionKeyValue = 0; 34 | 35 | log:printInfo("Read the document by id"); 36 | cosmosdb:Document result = check azureCosmosClient->getDocument(databaseId, containerId, documentId, 37 | partitionKeyValue); 38 | 39 | log:printInfo(result.toString()); 40 | log:printInfo("Success!"); 41 | 42 | } 43 | -------------------------------------------------------------------------------- /examples/admin-operations/triggers/list_trigger.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | 32 | log:printInfo("List available triggers"); 33 | stream|error result = managementClient->listTriggers(databaseId, containerId); 34 | 35 | if (result is stream) { 36 | error? e = result.forEach(function (cosmosdb:Trigger trigger) { 37 | log:printInfo(trigger.toString()); 38 | }); 39 | log:printInfo("Success!"); 40 | } else { 41 | log:printError(result.message()); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /.github/workflows/build-with-bal-test-native.yml: -------------------------------------------------------------------------------- 1 | name: GraalVM Check 2 | 3 | on: 4 | schedule: 5 | - cron: '30 18 * * *' 6 | workflow_dispatch: 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v3 13 | 14 | - name: Set up JDK 17 15 | uses: actions/setup-java@v3 16 | with: 17 | distribution: 'temurin' 18 | java-version: 17.0.7 19 | 20 | - name: Set Up Ballerina 21 | uses: ballerina-platform/setup-ballerina@v1.1.0 22 | with: 23 | version: latest 24 | 25 | - name: Grant execute permission for gradlew 26 | run: chmod +x gradlew 27 | 28 | - name: Build with Gradle 29 | env: 30 | packageUser: ${{ secrets.BALLERINA_BOT_USERNAME }} 31 | packagePAT: ${{ secrets.BALLERINA_BOT_TOKEN }} 32 | JAVA_OPTS: -DBALLERINA_DEV_COMPILE_BALLERINA_ORG=true 33 | run: | 34 | ./gradlew build -x test 35 | 36 | - name: Set up GraalVM 37 | uses: graalvm/setup-graalvm@v1 38 | with: 39 | java-version: '17' 40 | distribution: 'graalvm-community' 41 | github-token: ${{ secrets.GITHUB_TOKEN }} 42 | set-java-home: 'false' 43 | 44 | - name: Check GraalVM installation 45 | run: | 46 | echo "GRAALVM_HOME: ${{ env.GRAALVM_HOME }}" 47 | echo "JAVA_HOME: ${{ env.JAVA_HOME }}" 48 | native-image --version 49 | 50 | - name: Run Ballerina tests using the native executable 51 | run: bal test --graalvm ./ballerina 52 | env: 53 | BASE_URL: ${{ secrets.BASE_URL }} 54 | MASTER_OR_RESOURCE_TOKEN: ${{ secrets.MASTER_OR_RESOURCE_TOKEN }} 55 | -------------------------------------------------------------------------------- /examples/admin-operations/container/create_container.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | 32 | log:printInfo("Creating container"); 33 | cosmosdb:PartitionKey partitionKey = { 34 | paths: ["/gender"], 35 | keyVersion: 2 36 | }; 37 | 38 | cosmosdb:Container|error result = managementClient->createContainer(databaseId, containerId, partitionKey); 39 | 40 | if (result is cosmosdb:Container) { 41 | log:printInfo(result.toString()); 42 | log:printInfo("Success!"); 43 | } else { 44 | log:printError(result.message()); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /examples/admin-operations/users-permissions/permission/list_permissions.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string userId = "my_user"; 31 | 32 | log:printInfo("List permissions"); 33 | stream|error result = managementClient->listPermissions(databaseId, userId); 34 | 35 | if (result is stream) { 36 | error? e = result.forEach(function (cosmosdb:Permission storedPrcedure) { 37 | log:printInfo(storedPrcedure.toString()); 38 | }); 39 | log:printInfo("Success!"); 40 | } else { 41 | log:printError(result.message()); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /examples/data-operations/stored-procedure/list_stored_procedure.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ConnectionConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:DataPlaneClient azureCosmosClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | 32 | log:printInfo("List stored procedure"); 33 | stream|error result = azureCosmosClient->listStoredProcedures(databaseId, containerId); 34 | if (result is stream) { 35 | error? e = result.forEach(function (cosmosdb:StoredProcedure storedPrcedure) { 36 | log:printInfo(storedPrcedure.toString()); 37 | }); 38 | log:printInfo("Success!"); 39 | } else { 40 | log:printError(result.message()); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /examples/admin-operations/user-defined-functions/list_udf.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | 32 | log:printInfo("List user defined functions"); 33 | stream|error result = managementClient->listUserDefinedFunctions(databaseId, containerId); 34 | 35 | if (result is stream) { 36 | error? e = result.forEach(function (cosmosdb:UserDefinedFunction udf) { 37 | log:printInfo(udf.toString()); 38 | }); 39 | log:printInfo("Success!"); 40 | } else { 41 | log:printError(result.message()); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /examples/data-operations/stored-procedure/execute_stored_procedure.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ConnectionConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:DataPlaneClient azureCosmosClient = check new (config); 27 | 28 | public function main() returns error? { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | string partitionKey = "key"; 32 | string storedProcedureId = "my_stored_procedure"; 33 | 34 | log:printInfo("Executing stored procedure"); 35 | cosmosdb:StoredProcedureExecuteOptions options = { 36 | parameters: ["Sachi"] 37 | }; 38 | 39 | cosmosdb:StoredProcedureResponse result = check azureCosmosClient->executeStoredProcedure(databaseId, containerId, 40 | storedProcedureId, partitionKey, options); 41 | 42 | log:printInfo(result.toString()); 43 | log:printInfo("Success!"); 44 | 45 | } 46 | -------------------------------------------------------------------------------- /examples/data-operations/documents/query_document.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ConnectionConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:DataPlaneClient azureCosmosClient = check new (config); 27 | 28 | public function main() returns error? { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | 32 | log:printInfo("Query1 - Select all from the container where gender 0"); 33 | string selectAllQuery = string `SELECT * FROM ${containerId.toString()} f WHERE f.gender = ${0}`; 34 | 35 | cosmosdb:QueryOptions options = {partitionKey : 0}; 36 | stream result = check azureCosmosClient->queryDocuments(databaseId, containerId, 37 | selectAllQuery, options); 38 | 39 | check result.forEach(function (record {} queryResult) { 40 | log:printInfo(queryResult.toString()); 41 | }); 42 | log:printInfo("Success!"); 43 | 44 | } 45 | -------------------------------------------------------------------------------- /examples/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) 3 | * 4 | * WSO2 LLC. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | apply plugin: 'java-library' 20 | 21 | description = 'Ballerina - Azure Cosmosdb Examples' 22 | 23 | def filePath = project.fileTree("${project.projectDir}") 24 | def examples = filePath.matching { 25 | include("**/*.bal") 26 | exclude("**/deprecated/**/*.bal") 27 | } 28 | 29 | task testExamples { 30 | dependsOn ":${project.packageName}-ballerina:build" 31 | 32 | doLast { 33 | examples.each { example -> executeBalCommand ("run ${example}", "${project.rootDir}") } 34 | } 35 | } 36 | 37 | task buildExamples { 38 | dependsOn ":${project.packageName}-ballerina:build" 39 | 40 | gradle.taskGraph.whenReady { graph -> 41 | if (graph.hasTask(":${project.packageName}-examples:test")) { 42 | buildExamples.enabled = false 43 | } else { 44 | testExamples.enabled = false 45 | } 46 | } 47 | doLast { 48 | // TODO: Enabled --offline due to a bug in pulling incorrect versions from the central repository. 49 | examples.each { example -> executeBalCommand ("build --offline ${example}", "${project.rootDir}") } 50 | } 51 | } 52 | 53 | test.dependsOn testExamples 54 | build.dependsOn buildExamples 55 | -------------------------------------------------------------------------------- /.github/workflows/daily-build.yml: -------------------------------------------------------------------------------- 1 | name: Daily Build without Tests 2 | 3 | on: 4 | schedule: 5 | - cron: '30 2 * * *' 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v3 12 | 13 | # Set up Java Environment 14 | - name: Set up JDK 17 15 | uses: actions/setup-java@v3 16 | with: 17 | distribution: 'temurin' 18 | java-version: 17.0.7 19 | 20 | # Setup Ballerina Environment 21 | - name: Set Up Ballerina 22 | uses: ballerina-platform/setup-ballerina@v1.1.0 23 | with: 24 | version: latest 25 | 26 | # Grant execute permission to the gradlew script 27 | - name: Grant execute permission for gradlew 28 | run: chmod +x gradlew 29 | 30 | # Build the project with Gradle 31 | - name: Build with Gradle 32 | env: 33 | packageUser: ${{ secrets.BALLERINA_BOT_USERNAME }} 34 | packagePAT: ${{ secrets.BALLERINA_BOT_TOKEN }} 35 | JAVA_OPTS: -DBALLERINA_DEV_COMPILE_BALLERINA_ORG=true 36 | run: | 37 | ./gradlew build -x test 38 | 39 | # Build Ballerina Project 40 | - name: Ballerina Build 41 | run: bal pack ./ballerina 42 | env: 43 | JAVA_HOME: /usr/lib/jvm/default-jvm 44 | 45 | # Send notification when build fails 46 | - name: Notify failure 47 | if: ${{ failure() }} 48 | run: | 49 | curl -X POST \ 50 | 'https://api.github.com/repos/ballerina-platform/ballerina-release/dispatches' \ 51 | -H 'Accept: application/vnd.github.v3+json' \ 52 | -H 'Authorization: Bearer ${{ secrets.BALLERINA_BOT_TOKEN }}' \ 53 | --data "{ 54 | \"event_type\": \"notify-build-failure\", 55 | \"client_payload\": { 56 | \"repoName\": \"module-ballerinax-azure-cosmosdb\" 57 | } 58 | }" 59 | -------------------------------------------------------------------------------- /examples/admin-operations/users-permissions/permission/create_permission.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | string userId = "my_user"; 32 | 33 | string permissionId = "my_permission"; 34 | cosmosdb:PermisssionMode permissionMode = "All"; 35 | string permissionResource = string `dbs/${databaseId}/colls/${containerId}`; 36 | 37 | log:printInfo("Create permission for a user"); 38 | cosmosdb:Permission|error result = managementClient->createPermission(databaseId, userId, permissionId, 39 | permissionMode, permissionResource); 40 | 41 | if (result is cosmosdb:Permission) { 42 | log:printInfo(result.toString()); 43 | log:printInfo("Success!"); 44 | } else { 45 | log:printError(result.message()); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /examples/admin-operations/users-permissions/permission/replace_permission.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | string userId = "my_user"; 32 | string permissionId = "my_permission"; 33 | 34 | cosmosdb:PermisssionMode permissionModeReplace = "Read"; 35 | string permissionResourceReplace = string `dbs/${databaseId}/colls/${containerId}`; 36 | 37 | log:printInfo("Replace permission"); 38 | cosmosdb:Permission|error result = managementClient->replacePermission(databaseId, userId, permissionId, 39 | permissionModeReplace, permissionResourceReplace); 40 | 41 | if (result is cosmosdb:Permission) { 42 | log:printInfo(result.toString()); 43 | log:printInfo("Success!"); 44 | } else { 45 | log:printError(result.message()); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Deployment 2 | 3 | on: 4 | release: 5 | types: [ published ] 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - uses: actions/checkout@v3 13 | 14 | # Set up Java Environment 15 | - name: Set up JDK 17 16 | uses: actions/setup-java@v3 17 | with: 18 | distribution: 'temurin' 19 | java-version: 17.0.7 20 | 21 | # Setup Ballerina Environment 22 | - name: Set Up Ballerina 23 | uses: ballerina-platform/setup-ballerina@v1.1.0 24 | with: 25 | version: 2201.7.0 26 | 27 | # Grant execute permission to the gradlew script 28 | - name: Grant execute permission for gradlew 29 | run: chmod +x gradlew 30 | 31 | # Build the project with Gradle 32 | - name: Build with Gradle 33 | env: 34 | packageUser: ${{ secrets.BALLERINA_BOT_USERNAME }} 35 | packagePAT: ${{ secrets.BALLERINA_BOT_TOKEN }} 36 | JAVA_OPTS: -DBALLERINA_DEV_COMPILE_BALLERINA_ORG=true 37 | run: | 38 | ./gradlew build -x test -x :azure-cosmosdb-examples:build 39 | 40 | # Perform Trivy scan 41 | - name: Run Trivy vulnerability scanner 42 | uses: aquasecurity/trivy-action@master 43 | with: 44 | scan-type: 'rootfs' 45 | scan-ref: '.' 46 | skip-dirs: 'gradle/' 47 | format: 'table' 48 | timeout: '10m0s' 49 | exit-code: '1' 50 | 51 | # Build Ballerina Project 52 | - name: Ballerina Build 53 | run: bal pack ./ballerina 54 | env: 55 | JAVA_HOME: /usr/lib/jvm/default-jvm 56 | 57 | # Push to Ballerina Central 58 | - name: Ballerina Push 59 | run: bal push 60 | working-directory: ./ballerina 61 | env: 62 | BALLERINA_CENTRAL_ACCESS_TOKEN: ${{ secrets.BALLERINA_CENTRAL_ACCESS_TOKEN }} 63 | JAVA_HOME: /usr/lib/jvm/default-jvm 64 | -------------------------------------------------------------------------------- /ballerina/iterator.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/jballerina.java; 18 | 19 | # Represents ResultIterator. 20 | public class ResultIterator { 21 | 22 | private Error? err; 23 | 24 | public isolated function init(Error? err = ()) { 25 | self.err = err; 26 | } 27 | 28 | public isolated function next() returns record {|record {} value;|}|Error? { 29 | record {}|Error? result; 30 | result = nextResult(self); 31 | if result is record {} { 32 | record {| 33 | record {} value; 34 | |} streamRecord = {value: result}; 35 | return streamRecord; 36 | } else if result is Error { 37 | self.err = result; 38 | return self.err; 39 | } else { 40 | return result; 41 | } 42 | } 43 | } 44 | 45 | isolated function nextResult(ResultIterator iterator) returns record {}|Error? = @java:Method { 46 | 'class: "io.ballerinax.cosmosdb.RecordIteratorUtils" 47 | } external; 48 | 49 | # Represents CosmosResultIterator. 50 | public class CosmosResultIterator { 51 | public isolated function nextResult(ResultIterator iterator) returns record {}|Error? = @java:Method { 52 | 'class: "io.ballerinax.cosmosdb.RecordIteratorUtils" 53 | } external; 54 | } 55 | -------------------------------------------------------------------------------- /examples/data-operations/stored-procedure/create_stored_procedure.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ConnectionConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:DataPlaneClient azureCosmosClient = check new (config); 27 | 28 | public function main() returns error? { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | string storedProcedureId = "my_stored_procedure"; 32 | 33 | log:printInfo("Creating stored procedure"); 34 | string storedProcedureBody = string `function (){ 35 | var context = getContext(); 36 | var response = context.getResponse(); 37 | response.setBody("Hello, World"); 38 | }`; 39 | 40 | cosmosdb:StoredProcedureResponse result = check azureCosmosClient->createStoredProcedure(databaseId, containerId, 41 | storedProcedureId, storedProcedureBody); 42 | 43 | log:printInfo(result.toString()); 44 | log:printInfo("Success!"); 45 | 46 | } 47 | -------------------------------------------------------------------------------- /examples/data-operations/documents/create_document.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ConnectionConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:DataPlaneClient azureCosmosClient = check new (config); 27 | 28 | public function main() returns error? { 29 | string databaseId = "my_database"; 30 | // Assume partition key of this container is set as /gender which is an int of 0 or 1 31 | string containerId = "my_container"; 32 | string documentId = "my_document"; 33 | 34 | log:printInfo("Create a new document"); 35 | map documentBody = { 36 | "FirstName": "Alan", 37 | "FamilyName": "Turing", 38 | "Parents": [{ 39 | "FamilyName": "Turing", 40 | "FirstName": "Julius" 41 | }, { 42 | "FamilyName": "Stoney", 43 | "FirstName": "Ethel" 44 | }], 45 | "gender": 0 46 | }; 47 | int partitionKeyValue = 0; 48 | 49 | cosmosdb:DocumentResponse documentResponse = check azureCosmosClient->createDocument(databaseId, containerId, 50 | documentId, documentBody, partitionKeyValue); 51 | log:printInfo(documentResponse.toString()); 52 | } 53 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | pluginManagement { 19 | plugins { 20 | id "com.github.spotbugs-base" version "${spotbugsPluginVersion}" 21 | id "com.github.johnrengelman.shadow" version "${shadowJarPluginVersion}" 22 | id "de.undercouch.download" version "${downloadPluginVersion}" 23 | id "net.researchgate.release" version "${releasePluginVersion}" 24 | id "io.ballerina.plugin" version "${ballerinaGradlePluginVersion}" 25 | } 26 | 27 | repositories { 28 | gradlePluginPortal() 29 | maven { 30 | url = 'https://maven.pkg.github.com/ballerina-platform/*' 31 | credentials { 32 | username System.getenv("packageUser") 33 | password System.getenv("packagePAT") 34 | } 35 | } 36 | } 37 | } 38 | 39 | plugins { 40 | id "com.gradle.enterprise" version "3.13.2" 41 | } 42 | 43 | def projectName = 'azure-cosmosdb' 44 | rootProject.name = "ballerinax-${projectName}" 45 | 46 | include ":checkstyle" 47 | include ":${projectName}-native" 48 | include ":${projectName}-ballerina" 49 | 50 | project(':checkstyle').projectDir = file("build-config${File.separator}checkstyle") 51 | project(":${projectName}-native").projectDir = file('native') 52 | project(":${projectName}-ballerina").projectDir = file('ballerina') 53 | 54 | gradleEnterprise { 55 | buildScan { 56 | termsOfServiceUrl = 'https://gradle.com/terms-of-service' 57 | termsOfServiceAgree = 'yes' 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /examples/data-operations/documents/replace_document.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ConnectionConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:DataPlaneClient azureCosmosClient = check new (config); 27 | 28 | public function main() returns error? { 29 | string databaseId = "my_database"; 30 | // Assume partition key of this container is set as /gender which is an int of 0 or 1 31 | string containerId = "my_container"; 32 | string documentId = "my_document"; 33 | //We have to give the currently existing partition key of this document we can't replace that 34 | int partitionKeyValue = 0; 35 | 36 | log:printInfo("Replacing document"); 37 | map documentBody = { 38 | "FirstName": "Alan", 39 | "FamilyName": "Turing", 40 | "Parents": [{ 41 | "FamilyName": "Turing", 42 | "FirstName": "Julius" 43 | }, { 44 | "FamilyName": "Turing", 45 | "FirstName": "Ethel" 46 | }], 47 | "gender": 0 48 | }; 49 | 50 | cosmosdb:DocumentResponse documentResponse = check azureCosmosClient->replaceDocument(databaseId, containerId, 51 | documentId, documentBody, partitionKeyValue); 52 | log:printInfo(documentResponse.toString()); 53 | log:printInfo("Success!"); 54 | 55 | } 56 | -------------------------------------------------------------------------------- /examples/admin-operations/user-defined-functions/create_udf.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | string udfId = "my_udf"; 32 | 33 | log:printInfo("Creating a user defined function"); 34 | string userDefinedFunctionBody = string `function tax(income){ 35 | if (income == undefined) 36 | throw 'no input'; 37 | 38 | if (income < 1000) 39 | return income * 0.1; 40 | else if (income < 10000) 41 | return income * 0.2; 42 | else 43 | return income * 0.4; 44 | }`; 45 | 46 | cosmosdb:UserDefinedFunction|error result = managementClient->createUserDefinedFunction(databaseId, containerId, 47 | udfId, userDefinedFunctionBody); 48 | 49 | if (result is cosmosdb:UserDefinedFunction) { 50 | log:printInfo(result.toString()); 51 | log:printInfo("Success!"); 52 | } else { 53 | log:printError(result.message()); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /examples/admin-operations/user-defined-functions/replace_udf.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | string udfId = "my_udf"; 32 | 33 | log:printInfo("Replacing a user defined function"); 34 | string newUserDefinedFuncBody = string `function taxIncome(income){ 35 | if (income == undefined) 36 | throw 'no input'; 37 | if (income < 1000) 38 | return income * 0.1; 39 | else if (income < 10000) 40 | return income * 0.2; 41 | else 42 | return income * 0.4; 43 | }`; 44 | 45 | cosmosdb:UserDefinedFunction|error result = managementClient->replaceUserDefinedFunction(databaseId, containerId, 46 | udfId, newUserDefinedFuncBody); 47 | 48 | if (result is cosmosdb:UserDefinedFunction) { 49 | log:printInfo(result.toString()); 50 | log:printInfo("Success!"); 51 | } else { 52 | log:printError(result.message()); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /ballerina/Ballerina.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | distribution = "2201.8.0" 3 | org= "ballerinax" 4 | name= "azure_cosmosdb" 5 | version = "4.2.0" 6 | authors = ["Ballerina"] 7 | keywords = ["IT Operations/Databases", "Cost/Paid", "Vendor/Microsoft"] 8 | icon = "icon.png" 9 | repository = "https://github.com/ballerina-platform/module-ballerinax-azure-cosmosdb" 10 | license = ["Apache-2.0"] 11 | 12 | [build-options] 13 | observabilityIncluded=true 14 | 15 | [platform.java17] 16 | graalvmCompatible = true 17 | 18 | [[platform.java17.dependency]] 19 | groupId = "io.ballerinax" 20 | artifactId = "cosmosdb" 21 | version = "4.2.0" 22 | path = "../native/build/libs/azure-cosmosdb-native-4.2.0.jar" 23 | 24 | [[platform.java17.dependency]] 25 | groupId = "com.azure" 26 | artifactId = "azure-cosmos" 27 | version = "4.52.0" 28 | path = "./lib/azure-cosmos-4.52.0.jar" 29 | 30 | [[platform.java17.dependency]] 31 | groupId = "io.netty" 32 | artifactId = "netty-resolver-dns" 33 | version = "4.1.100.Final" 34 | path = "./lib/netty-resolver-dns-4.1.100.Final.jar" 35 | 36 | [[platform.java17.dependency]] 37 | groupId = "io.netty" 38 | artifactId = "netty-handler" 39 | version = "4.1.100.Final" 40 | path = "./lib/netty-handler-4.1.100.Final.jar" 41 | 42 | [[platform.java17.dependency]] 43 | groupId = "io.netty" 44 | artifactId = "netty-transport-native-unix-common" 45 | version = "4.1.100.Final" 46 | path = "./lib/netty-transport-native-unix-common-4.1.100.Final.jar" 47 | 48 | [[platform.java17.dependency]] 49 | groupId = "io.projectreactor.netty" 50 | artifactId = "reactor-netty-core" 51 | version = "1.1.13" 52 | path = "./lib/reactor-netty-core-1.1.13.jar" 53 | 54 | [[platform.java17.dependency]] 55 | groupId = "io.projectreactor.netty" 56 | artifactId = "reactor-netty" 57 | version = "1.1.13" 58 | path = "./lib/reactor-netty-1.1.13.jar" 59 | 60 | [[platform.java17.dependency]] 61 | groupId = "io.projectreactor.netty" 62 | artifactId = "reactor-netty-http" 63 | version = "1.1.13" 64 | path = "./lib/reactor-netty-http-1.1.13.jar" 65 | 66 | [[platform.java17.dependency]] 67 | groupId = "io.micrometer" 68 | artifactId = "micrometer-observation" 69 | version = "1.12.0" 70 | path = "./lib/micrometer-observation-1.12.0.jar" 71 | 72 | [[platform.java17.dependency]] 73 | groupId = "io.micrometer" 74 | artifactId = "micrometer-core" 75 | version = "1.12.0" 76 | path = "./lib/micrometer-core-1.12.0.jar" 77 | 78 | [[platform.java17.dependency]] 79 | groupId = "io.micrometer" 80 | artifactId = "micrometer-commons" 81 | version = "1.12.0" 82 | path = "./lib/micrometer-commons-1.12.0.jar" 83 | 84 | -------------------------------------------------------------------------------- /.github/workflows/dev-stg-release.yml: -------------------------------------------------------------------------------- 1 | name: Dev/Staging BCentral Release 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | bal_central_environment: 7 | description: Ballerina Central Environment 8 | type: choice 9 | options: 10 | - STAGE 11 | - DEV 12 | required: true 13 | 14 | jobs: 15 | release: 16 | runs-on: ubuntu-latest 17 | env: 18 | BALLERINA_${{ github.event.inputs.bal_central_environment }}_CENTRAL: true 19 | 20 | steps: 21 | - uses: actions/checkout@v3 22 | 23 | # Set up Java Environment 24 | - name: Set up JDK 17 25 | uses: actions/setup-java@v3 26 | with: 27 | distribution: 'temurin' 28 | java-version: 17.0.7 29 | 30 | # Setup Ballerina Environment 31 | - name: Set Up Ballerina 32 | uses: ballerina-platform/setup-ballerina@v1.1.0 33 | with: 34 | version: 2201.7.0 35 | 36 | # Grant execute permission to the gradlew script 37 | - name: Grant execute permission for gradlew 38 | run: chmod +x gradlew 39 | 40 | # Build the project with Gradle 41 | - name: Build with Gradle 42 | env: 43 | packageUser: ${{ secrets.BALLERINA_BOT_USERNAME }} 44 | packagePAT: ${{ secrets.BALLERINA_BOT_TOKEN }} 45 | JAVA_OPTS: -DBALLERINA_DEV_COMPILE_BALLERINA_ORG=true 46 | run: | 47 | ./gradlew build -x test -x :azure-cosmosdb-examples:build 48 | 49 | # Perform Trivy scan 50 | - name: Run Trivy vulnerability scanner 51 | uses: aquasecurity/trivy-action@master 52 | with: 53 | scan-type: 'rootfs' 54 | scan-ref: '.' 55 | skip-dirs: 'gradle/' 56 | format: 'table' 57 | timeout: '10m0s' 58 | exit-code: '1' 59 | 60 | # Push to Ballerina Staging Central 61 | - name: Push to Staging 62 | if: github.event.inputs.bal_central_environment == 'STAGE' 63 | run: bal push 64 | working-directory: ./ballerina 65 | env: 66 | BALLERINA_CENTRAL_ACCESS_TOKEN: ${{ secrets.BALLERINA_CENTRAL_STAGE_ACCESS_TOKEN }} 67 | JAVA_HOME: /usr/lib/jvm/default-jvm 68 | 69 | # Push to Ballerina Dev Central 70 | - name: Push to Dev 71 | if: github.event.inputs.bal_central_environment == 'DEV' 72 | run: bal push 73 | working-directory: ./ballerina 74 | env: 75 | BALLERINA_CENTRAL_ACCESS_TOKEN: ${{ secrets.BALLERINA_CENTRAL_DEV_ACCESS_TOKEN }} 76 | JAVA_HOME: /usr/lib/jvm/default-jvm 77 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | push: 4 | branches: 5 | - main 6 | - 2201.[0-9]+.x 7 | repository_dispatch: 8 | types: 9 | check_connector_for_breaking_changes 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v3 17 | 18 | # Set up Java Environment 19 | - name: Set up JDK 17 20 | uses: actions/setup-java@v3 21 | with: 22 | distribution: 'temurin' 23 | java-version: 17.0.7 24 | 25 | # Setup Ballerina Environment 26 | - name: Set Up Ballerina 27 | uses: ballerina-platform/setup-ballerina@v1.1.0 28 | with: 29 | version: latest 30 | 31 | # Grant execute permission to the gradlew script 32 | - name: Grant execute permission for gradlew 33 | run: chmod +x gradlew 34 | 35 | # Build the project with Gradle 36 | - name: Build with Gradle 37 | env: 38 | packageUser: ${{ secrets.BALLERINA_BOT_USERNAME }} 39 | packagePAT: ${{ secrets.BALLERINA_BOT_TOKEN }} 40 | JAVA_OPTS: -DBALLERINA_DEV_COMPILE_BALLERINA_ORG=true 41 | run: | 42 | ./gradlew build -x test 43 | 44 | # Build Ballerina Project 45 | - name: Ballerina Build 46 | run: bal pack ./ballerina 47 | env: 48 | JAVA_HOME: /usr/lib/jvm/default-jvm 49 | 50 | # Test Ballerina Project 51 | - name: Ballerina Test 52 | if: github.event_name == 'push' 53 | run: bal test --test-report --code-coverage --coverage-format=xml 54 | env: 55 | BASE_URL: ${{ secrets.BASE_URL }} 56 | MASTER_OR_RESOURCE_TOKEN: ${{ secrets.MASTER_OR_RESOURCE_TOKEN }} 57 | JAVA_HOME: /usr/lib/jvm/default-jvm 58 | 59 | - name: Upload coverage reports to Codecov 60 | uses: codecov/codecov-action@v3 61 | 62 | - name: Alert notifier on failure 63 | if: failure() && (github.event.action == 'check_connector_for_breaking_changes') 64 | run: | 65 | curl -X POST \ 66 | 'https://api.github.com/repos/ballerina-platform/ballerina-release/dispatches' \ 67 | --header 'Accept: application/vnd.github.v3+json' \ 68 | --header 'Authorization: Bearer ${{ secrets.BALLERINA_BOT_TOKEN }}' \ 69 | --data-raw '{ 70 | "event_type": "notify-ballerinax-connector-build-failure", 71 | "client_payload": { 72 | "repoName": "module-ballerinax-azure-cosmosdb", 73 | "workflow": "CI" 74 | } 75 | }' 76 | -------------------------------------------------------------------------------- /native/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) 3 | * 4 | * WSO2 LLC. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | plugins { 20 | id 'java-library' 21 | id 'checkstyle' 22 | id 'com.github.spotbugs' 23 | } 24 | 25 | description = 'Ballerina - Azure Cosmosdb Native' 26 | 27 | dependencies { 28 | checkstyle project(':checkstyle') 29 | checkstyle "com.puppycrawl.tools:checkstyle:${checkstylePluginVersion}" 30 | 31 | implementation group: 'org.ballerinalang', name: 'ballerina-lang', version: "${ballerinaLangVersion}" 32 | implementation group: 'org.ballerinalang', name: 'value', version: "${ballerinaLangVersion}" 33 | implementation group: 'org.ballerinalang', name: 'ballerina-runtime', version: "${ballerinaLangVersion}" 34 | implementation group: 'com.azure', name: 'azure-cosmos', version: "${azureCosmosVersion}" 35 | } 36 | 37 | def excludePattern = '**/module-info.java' 38 | tasks.withType(Checkstyle) { 39 | exclude excludePattern 40 | } 41 | 42 | checkstyle { 43 | toolVersion "${project.checkstylePluginVersion}" 44 | configFile rootProject.file("build-config/checkstyle/build/checkstyle.xml") 45 | configProperties = ["suppressionFile" : file("${rootDir}/build-config/checkstyle/build/suppressions.xml")] 46 | } 47 | 48 | checkstyleMain.dependsOn(":checkstyle:downloadCheckstyleRuleFiles") 49 | 50 | spotbugsMain { 51 | effort "max" 52 | reportLevel "low" 53 | reportsDir = file("$project.buildDir/reports/spotbugs") 54 | reports { 55 | html.enabled true 56 | text.enabled = true 57 | } 58 | def excludeFile = file("${rootDir}/spotbugs-exclude.xml") 59 | if(excludeFile.exists()) { 60 | excludeFilter = excludeFile 61 | } 62 | } 63 | 64 | spotbugsTest { 65 | enabled = false 66 | } 67 | 68 | compileJava { 69 | doFirst { 70 | options.compilerArgs = [ 71 | '--module-path', classpath.asPath, 72 | ] 73 | classpath = files() 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /.github/workflows/weekly-build.yml: -------------------------------------------------------------------------------- 1 | name: Weekly build 2 | 3 | on: 4 | schedule: 5 | - cron: '15 2 * * 1' 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - uses: actions/checkout@v3 13 | 14 | # Set up Java Environment 15 | - name: Set up JDK 17 16 | uses: actions/setup-java@v3 17 | with: 18 | distribution: 'temurin' 19 | java-version: 17.0.7 20 | 21 | # Setup Ballerina Environment 22 | - name: Set Up Ballerina 23 | uses: ballerina-platform/setup-ballerina@v1.1.0 24 | with: 25 | version: latest 26 | 27 | # Grant execute permission to the gradlew script 28 | - name: Grant execute permission for gradlew 29 | run: chmod +x gradlew 30 | 31 | # Build the project with Gradle 32 | - name: Build with Gradle 33 | env: 34 | packageUser: ${{ secrets.BALLERINA_BOT_USERNAME }} 35 | packagePAT: ${{ secrets.BALLERINA_BOT_TOKEN }} 36 | JAVA_OPTS: -DBALLERINA_DEV_COMPILE_BALLERINA_ORG=true 37 | run: | 38 | ./gradlew build -x test 39 | 40 | # Build Ballerina Project 41 | - name: Ballerina Build 42 | run: bal pack ./ballerina 43 | env: 44 | JAVA_HOME: /usr/lib/jvm/default-jvm 45 | 46 | # Test Ballerina Project 47 | - name: Ballerina Test 48 | run: bal test --test-report --code-coverage --coverage-format=xml ./ballerina 49 | env: 50 | BASE_URL: ${{ secrets.BASE_URL }} 51 | MASTER_OR_RESOURCE_TOKEN: ${{ secrets.MASTER_OR_RESOURCE_TOKEN }} 52 | JAVA_HOME: /usr/lib/jvm/default-jvm 53 | 54 | - name: Upload coverage reports to Codecov 55 | uses: codecov/codecov-action@v3 56 | 57 | # Send notification when build fails 58 | - name: Notify failure 59 | if: ${{ failure() }} 60 | run: | 61 | curl \ 62 | -X POST 'https://chat.googleapis.com/v1/spaces/${{secrets.BALLERINA_CHAT_ID}}/messages?key=${{secrets.BALLERINA_CHAT_KEY}}&token=${{secrets.BALLERINA_CHAT_TOKEN}}' \ 63 | --header 'Content-Type: application/json' \ 64 | -d '{"text": "*module-ballerinax-azure-cosmosdb* build failure \nPlease visit for more information"}' 65 | curl \ 66 | -X POST 'https://chat.googleapis.com/v1/spaces/${{secrets.CONNECTOR_CHAT_ID}}/messages?key=${{secrets.CONNECTOR_CHAT_KEY}}&token=${{secrets.CONNECTOR_CHAT_TOKEN}}' \ 67 | --header 'Content-Type: application/json' \ 68 | -d '{"text": "*module-ballerinax-azure-cosmosdb* build failure \nPlease visit for more information"}' 69 | 70 | -------------------------------------------------------------------------------- /examples/admin-operations/triggers/create_trigger.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | string triggerId = "my_trigger"; 32 | 33 | log:printInfo("Creating a trigger"); 34 | string createTriggerBody = 35 | string `function updateMetadata() { 36 | var context = getContext(); 37 | var collection = context.getCollection(); 38 | var response = context.getResponse(); 39 | var createdDocument = response.getBody(); 40 | 41 | // query for metadata document 42 | var filterQuery = 'SELECT * FROM root r WHERE r.id = "_metadata"'; 43 | var accept = collection.queryDocuments(collection.getSelfLink(), filterQuery, updateMetadataCallback); 44 | if(!accept) throw "Unable to update metadata, abort"; 45 | } 46 | 47 | function updateMetadataCallback(err, documents, responseOptions) { 48 | if(err) throw new Error("Error" + err.message); 49 | if(documents.length != 1) throw "Unable to find metadata document"; 50 | var metadataDocument = documents[0]; 51 | // update metadata 52 | metadataDocument.createdDocuments += 1; 53 | metadataDocument.createdNames += " " + createdDocument.id; 54 | var accept = collection.replaceDocument(metadataDocument._self, metadataDocument, function(err, docReplaced) { 55 | if(err) throw "Unable to update metadata, abort"; 56 | }); 57 | 58 | if(!accept) throw "Unable to update metadata, abort"; 59 | return; 60 | }`; 61 | cosmosdb:TriggerOperation createTriggerOperationType = "All"; 62 | cosmosdb:TriggerType createTriggerType = "Post"; 63 | 64 | cosmosdb:Trigger|error result = managementClient->createTrigger(databaseId, containerId, triggerId, 65 | createTriggerBody, createTriggerOperationType, createTriggerType); 66 | 67 | if (result is cosmosdb:Trigger) { 68 | log:printInfo(result.toString()); 69 | log:printInfo("Success!"); 70 | } else { 71 | log:printError(result.message()); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /examples/admin-operations/triggers/replace_trigger.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/log; 18 | import ballerina/os; 19 | import ballerinax/azure_cosmosdb as cosmosdb; 20 | 21 | cosmosdb:ManagementClientConfig config = { 22 | baseUrl: os:getEnv("BASE_URL"), 23 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 24 | }; 25 | 26 | cosmosdb:ManagementClient managementClient = check new (config); 27 | 28 | public function main() { 29 | string databaseId = "my_database"; 30 | string containerId = "my_container"; 31 | string existingTriggerId = "my_trigger"; 32 | 33 | log:printInfo("Replacing a trigger"); 34 | string replaceTriggerBody = 35 | string `function replaceFunction() { 36 | var context = getContext(); 37 | var collection = context.getCollection(); 38 | var response = context.getResponse(); 39 | var createdDocument = response.getBody(); 40 | 41 | // query for metadata document 42 | var filterQuery = 'SELECT * FROM root r WHERE r.id = "_metadata"'; 43 | var accept = collection.queryDocuments(collection.getSelfLink(), filterQuery, updateMetadataCallback); 44 | if(!accept) throw "Unable to update metadata, abort"; 45 | } 46 | 47 | function updateMetadataCallback(err, documents, responseOptions) { 48 | if(err) throw new Error("Error" + err.message); 49 | if(documents.length != 1) throw "Unable to find metadata document"; 50 | var metadataDocument = documents[0]; 51 | // update metadata 52 | metadataDocument.createdDocuments += 1; 53 | metadataDocument.createdNames += " " + createdDocument.id; 54 | var accept = collection.replaceDocument(metadataDocument._self, metadataDocument, function(err, docReplaced) { 55 | if(err) throw "Unable to update metadata, abort"; 56 | }); 57 | 58 | if(!accept) throw "Unable to update metadata, abort"; 59 | return; 60 | }`; 61 | cosmosdb:TriggerOperation replaceTriggerOperation = "All"; 62 | cosmosdb:TriggerType replaceTriggerType = "Post"; 63 | 64 | cosmosdb:Trigger|error result = managementClient->replaceTrigger(databaseId, containerId, existingTriggerId, 65 | replaceTriggerBody, replaceTriggerOperation, replaceTriggerType); 66 | 67 | if (result is cosmosdb:Trigger) { 68 | log:printInfo(result.toString()); 69 | log:printInfo("Success!"); 70 | } else { 71 | log:printError(result.message()); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /ballerina/Module.md: -------------------------------------------------------------------------------- 1 | ## Overview 2 | It provides the capability to connect to Azure Cosmos DB and execute CRUD (Create, Read, Update, and Delete) operations 3 | for databases and containers, to execute SQL queries to query containers, etc. In addition, it allows the special 4 | features provided by Cosmos DB such as operations on JavaScript language-integrated queries, management of users and 5 | permissions, etc. 6 | 7 | This module supports [Azure Cosmos DB(SQL) API](https://docs.microsoft.com/en-us/rest/api/cosmos-db/) version `2018-12-31`. 8 | ## Prerequisites 9 | Before using this connector in your Ballerina application, complete the following: 10 | 11 | * [Create a Microsoft Account with Azure Subscription](https://docs.microsoft.com/en-us/learn/modules/create-an-azure-account/) 12 | * [Create an Azure Cosmos DB account](https://docs.microsoft.com/en-us/azure/cosmos-db/how-to-manage-database-account/) 13 | * Obtain tokens 14 | 1. Go to your Azure Cosmos DB account and click **Keys**. 15 | 2. Copy the URI and PRIMARY KEY in the **Read-write Keys** tab. 16 | 17 | ## Quickstart 18 | To use the Azure Cosmos DB connector in your Ballerina application, update the .bal file as follows: 19 | 20 | ### Step 1 - Import connector 21 | Import the `ballerinax/azure_cosmosdb` module into the Ballerina project. 22 | ```ballerina 23 | import ballerinax/azure_cosmosdb as cosmosdb; 24 | ``` 25 | ### Step 2 - Create a new connector instance 26 | You can now add the connection configuration with the `Master-Token` or `Resource-Token`, and the resource URI to the 27 | Cosmos DB Account. 28 | ```ballerina 29 | cosmosdb:ConnectionConfig configuration = { 30 | baseUrl: , 31 | primaryKeyOrResourceToken: 32 | }; 33 | cosmosdb:DataPlaneClient azureCosmosClient = check new (configuration); 34 | 35 | ``` 36 | ### Step 3 - Invoke connector operation 37 | 1. Create a document
38 | Once you follow the above steps. you can create a new document inside the Cosmos container as shown below. Cosmos DB is designed to store and query JSON-like documents. Therefore, the document you create must be of the `JSON` type. In this example, the document ID is `my_document` 39 | 40 | ```ballerina 41 | map document = { 42 | "FirstName": "Alan", 43 | "FamilyName": "Turing", 44 | "Parents": [{ 45 | "FamilyName": "Turing", 46 | "FirstName": "Julius" 47 | }, { 48 | "FamilyName": "Stoney", 49 | "FirstName": "Ethel" 50 | }], 51 | "gender": 0 52 | }; 53 | int valueOfPartitionKey = 0; 54 | string id = "my_document"; 55 | 56 | cosmosdb:DocumentResponse response = check azureCosmosClient-> createDocument("my_database", "my_container", id, document, valueOfPartitionKey); 57 | ``` 58 | **Note:**
59 | - This document is created inside an already existing container with ID **my_container** and the container was created inside a database with ID **my_database**. 60 | - As this container have selected path **/gender** as the partition key path. The document you create should include that path with a valid value. 61 | - The document is represented as `map` 62 | 63 | 2. Use `bal run` command to compile and run the Ballerina program 64 | 65 | **[You can find a list of samples here](https://github.com/ballerina-platform/module-ballerinax-azure-cosmosdb/tree/main/examples)** 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Ballerina Azure Cosmos DB Connector 2 | =================== 3 | [![Build Status](https://github.com/ballerina-platform/module-ballerinax-azure-cosmosdb/workflows/CI/badge.svg)](https://github.com/ballerina-platform/module-ballerinax-azure-cosmosdb/actions?query=workflow%3ACI) 4 | [![codecov](https://codecov.io/gh/ballerina-platform/module-ballerinax-azure-cosmosdb/branch/main/graph/badge.svg)](https://codecov.io/gh/ballerina-platform/module-ballerinax-azure-cosmosdb) 5 | [![Trivy](https://github.com/ballerina-platform/module-ballerinax-azure-cosmosdb/actions/workflows/trivy-scan.yml/badge.svg)](https://github.com/ballerina-platform/module-ballerinax-azure-cosmosdb/actions/workflows/trivy-scan.yml) 6 | [![GitHub Last Commit](https://img.shields.io/github/last-commit/ballerina-platform/module-ballerinax-azure-cosmosdb.svg)](https://github.com/ballerina-platform/module-ballerinax-azure-cosmosdb/commits/master) 7 | [![GraalVM Check](https://github.com/ballerina-platform/module-ballerinax-azure-cosmosdb/actions/workflows/build-with-bal-test-native.yml/badge.svg)](https://github.com/ballerina-platform/module-ballerinax-azure-cosmosdb/actions/workflows/build-with-bal-test-native.yml) 8 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 9 | 10 | The Cosmos DB SQL(Core) API supports all database-related operations that are carried out extensively by the existing 11 | developer community. 12 | 13 | The Ballerina connector for Azure Cosmos DB provides the capability to connect to Azure Cosmos DB and to execute basic 14 | CRUD (Create, Read, Update and Delete) operations on databases and containers, executing SQL queries to query 15 | containers, etc. In addition, it allows the special features provided by Cosmos DB such as operations via JavaScript 16 | language-integrated queries and management of users and permissions. 17 | 18 | For more information, see module(s). 19 | - [azure_cosmosdb](cosmosdb/Module.md) 20 | 21 | ## Building from the source 22 | ### Setting up the prerequisites 23 | 1. Download and install Java SE Development Kit (JDK) version 17. You can install either [OpenJDK](https://adoptopenjdk.net/) or [Oracle JDK](https://www.oracle.com/java/technologies/downloads/). 24 | > **Note:** Set the JAVA_HOME environment variable to the path name of the directory into which you installed 25 | JDK. 26 | 27 | 2. Download and install [Ballerina Swan Lake](https://ballerina.io/) 28 | 29 | ### Building the source 30 | 31 | Execute the following commands to build from the source: 32 | 33 | - To build the package: 34 | ``` 35 | bal build ./ballerina 36 | ``` 37 | - To run tests after build: 38 | ``` 39 | bal test ./ballerina 40 | ``` 41 | ## Contributing to ballerina 42 | 43 | As an open source project, Ballerina welcomes contributions from the community. 44 | 45 | For more information, see [contribution guidelines](https://github.com/ballerina-platform/ballerina-lang/blob/master/CONTRIBUTING.md). 46 | 47 | ## Code of conduct 48 | 49 | All contributors are encouraged to read the [Ballerina Code of Conduct](https://ballerina.io/code-of-conduct). 50 | 51 | ## Useful links 52 | 53 | * Discuss code changes of the Ballerina project via [ballerina-dev@googlegroups.com](mailto:ballerina-dev@googlegroups.com). 54 | * Chat live with us via our [Discord server](https://discord.gg/ballerinalang). 55 | * Post all technical questions on Stack Overflow with the [#ballerina](https://stackoverflow.com/questions/tagged/ballerina) tag. 56 | -------------------------------------------------------------------------------- /examples/data-operations/stored-procedure/stored_procedure_operations.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/jballerina.java; 18 | import ballerina/log; 19 | import ballerina/os; 20 | import ballerina/regex; 21 | import ballerinax/azure_cosmosdb as cosmosdb; 22 | 23 | cosmosdb:ConnectionConfig config = { 24 | baseUrl: os:getEnv("BASE_URL"), 25 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 26 | }; 27 | 28 | cosmosdb:DataPlaneClient azureCosmosClient = check new (config); 29 | 30 | public function main() returns error? { 31 | string databaseId = "my_database"; 32 | string containerId = "my_container"; 33 | string primaryKey = "key"; 34 | var uuid = createRandomUUIDWithoutHyphens(); 35 | 36 | log:printInfo("Creating stored procedure"); 37 | string storedProcedureId = string `sproc_${uuid.toString()}`; 38 | string storedProcedureBody = string `function (){ 39 | var context = getContext(); 40 | var response = context.getResponse(); 41 | response.setBody("Hello, World"); 42 | }`; 43 | 44 | cosmosdb:StoredProcedureResponse storedProcedureCreateResult = check azureCosmosClient->createStoredProcedure( 45 | databaseId, containerId, storedProcedureId, storedProcedureBody); 46 | 47 | log:printInfo(storedProcedureCreateResult.toString()); 48 | 49 | log:printInfo("List stored procedures"); 50 | stream spList = check azureCosmosClient->listStoredProcedures(databaseId, 51 | containerId); 52 | error? e = spList.forEach(function(cosmosdb:StoredProcedure storedPrcedure) { 53 | log:printInfo(storedPrcedure.toString()); 54 | }); 55 | log:printInfo("Success!"); 56 | 57 | log:printInfo("Executing stored procedure"); 58 | cosmosdb:StoredProcedureExecuteOptions options = { 59 | parameters: ["Sachi"] 60 | }; 61 | 62 | cosmosdb:StoredProcedureResponse result = check azureCosmosClient->executeStoredProcedure(databaseId, containerId, 63 | storedProcedureId, primaryKey, options); 64 | 65 | log:printInfo(result.toString()); 66 | 67 | log:printInfo("Deleting stored procedure"); 68 | cosmosdb:StoredProcedureResponse deletionResult = check azureCosmosClient->deleteStoredProcedure(databaseId, 69 | containerId, storedProcedureId); 70 | 71 | log:printInfo(deletionResult.toString()); 72 | 73 | log:printInfo("End!"); 74 | } 75 | 76 | function createRandomUUIDWithoutHyphens() returns string { 77 | string? stringUUID = java:toString(createRandomUUID()); 78 | if (stringUUID is string) { 79 | stringUUID = 'string:substring(regex:replaceAll(stringUUID, "-", ""), 1, 4); 80 | return stringUUID ?: ""; 81 | } else { 82 | return ""; 83 | } 84 | } 85 | 86 | function createRandomUUID() returns handle = @java:Method { 87 | name: "randomUUID", 88 | 'class: "java.util.UUID" 89 | } external; 90 | -------------------------------------------------------------------------------- /native/src/main/java/io/ballerinax/cosmosdb/RecordIteratorUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package io.ballerinax.cosmosdb; 20 | 21 | import com.azure.cosmos.models.CosmosStoredProcedureProperties; 22 | import com.fasterxml.jackson.databind.ObjectMapper; 23 | import io.ballerina.runtime.api.PredefinedTypes; 24 | import io.ballerina.runtime.api.creators.TypeCreator; 25 | import io.ballerina.runtime.api.creators.ValueCreator; 26 | import io.ballerina.runtime.api.types.RecordType; 27 | import io.ballerina.runtime.api.types.UnionType; 28 | import io.ballerina.runtime.api.values.BObject; 29 | import io.ballerina.runtime.api.values.BTypedesc; 30 | import org.ballerinalang.langlib.value.FromJsonStringWithType; 31 | 32 | import java.util.HashMap; 33 | import java.util.Iterator; 34 | import java.util.Map; 35 | 36 | import static io.ballerina.runtime.api.utils.StringUtils.fromString; 37 | import static io.ballerinax.cosmosdb.Constants.STORED_PROCEDURE; 38 | 39 | /** 40 | * This class provides functionality for the `RecordIterator` to iterate. 41 | */ 42 | public class RecordIteratorUtils { 43 | 44 | public static Object nextResult(BObject recordIterator) { 45 | RecordType targetType = (RecordType) recordIterator.getNativeData(Constants.RECORD_TYPE); 46 | if (targetType.getName().equals(STORED_PROCEDURE)) { 47 | Iterator results = (Iterator) 48 | recordIterator.getNativeData(Constants.OBJECT_ITERATOR); 49 | if (results.hasNext()) { 50 | Map objectMap = new HashMap<>(); 51 | CosmosStoredProcedureProperties next = results.next(); 52 | objectMap.put("storedProcedure", fromString(next.getBody())); 53 | objectMap.put("id", fromString(next.getId())); 54 | objectMap.put("eTag", next.getETag()); 55 | return ValueCreator.createRecordValue(ModuleUtils.getModule(), targetType.getName(), objectMap); 56 | } 57 | return null; 58 | } else { 59 | Iterator results = (Iterator) recordIterator.getNativeData(Constants.OBJECT_ITERATOR); 60 | if (results.hasNext()) { 61 | try { 62 | String result = new ObjectMapper().writeValueAsString(results.next()); 63 | RecordType recordType = (RecordType) recordIterator.getNativeData(Constants.RECORD_TYPE); 64 | UnionType responseType = TypeCreator.createUnionType(recordType, PredefinedTypes.TYPE_ERROR, 65 | PredefinedTypes.TYPE_NULL); 66 | BTypedesc responseTypedescValue = ValueCreator.createTypedescValue(responseType); 67 | return FromJsonStringWithType.fromJsonStringWithType(fromString(result), responseTypedescValue); 68 | } catch (Exception e) { 69 | return BallerinaErrorGenerator.createBallerinaDatabaseError(e); 70 | } 71 | } 72 | return null; 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /examples/admin-operations/offers/offer_operations.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/jballerina.java; 18 | import ballerina/log; 19 | import ballerina/os; 20 | import ballerina/regex; 21 | import ballerinax/azure_cosmosdb as cosmosdb; 22 | 23 | cosmosdb:ManagementClientConfig config = { 24 | baseUrl: os:getEnv("BASE_URL"), 25 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 26 | }; 27 | 28 | cosmosdb:ManagementClient managementClient = check new (config); 29 | 30 | public function main() { 31 | string databaseId = "my_database"; 32 | string containerId = "my_container"; 33 | var uuid = createRandomUUIDWithoutHyphens(); 34 | string? offerId = (); 35 | string? resourceId = (); 36 | 37 | // Get database container to get the resource ids of them. 38 | cosmosdb:Database database = checkpanic managementClient->getDatabase(databaseId); 39 | cosmosdb:Container container = checkpanic managementClient->getContainer(databaseId, containerId); 40 | 41 | log:printInfo("List the offers in the current cosmos db account"); 42 | stream|error offerList = checkpanic managementClient->listOffers(); 43 | 44 | if (offerList is stream) { 45 | record {|cosmosdb:Offer value;|}|error? offer = offerList.next(); 46 | if (offer is record {|cosmosdb:Offer value;|}) { 47 | offerId = offer.value.id; 48 | resourceId = offer?.value?.resourceId; 49 | } 50 | } 51 | 52 | if (offerId is string && resourceId is string) { 53 | log:printInfo("Get information about one offer"); 54 | cosmosdb:Offer result3 = checkpanic managementClient->getOffer(offerId); 55 | 56 | log:printInfo("Replace offer"); 57 | string resourceSelfLink = 58 | string `dbs/${database?.resourceId.toString()}/colls/${container?.resourceId.toString()}/`; 59 | cosmosdb:Offer replaceOfferBody = { 60 | offerVersion: "V2", 61 | offerType: "Invalid", 62 | content: {"offerThroughput": 1000}, 63 | resourceSelfLink: resourceSelfLink, 64 | resourceResourceId: string `${container?.resourceId.toString()}`, 65 | id: offerId, 66 | resourceId: resourceId 67 | }; 68 | cosmosdb:Offer offerReplaceResult = checkpanic managementClient->replaceOffer(replaceOfferBody); 69 | } 70 | 71 | // Replace Offer updating optional parameters 72 | 73 | // Query offers 74 | log:printInfo("Query offers"); 75 | string offersInContainerQuery = 76 | string `SELECT * FROM ${containerId} f WHERE (f["_self"]) = "${container?.selfReference.toString()}"`; 77 | int maximumItemCount = 20; 78 | stream|error result = checkpanic managementClient-> 79 | queryOffer(offersInContainerQuery); 80 | log:printInfo("Success!"); 81 | } 82 | 83 | function createRandomUUIDWithoutHyphens() returns string { 84 | string? stringUUID = java:toString(createRandomUUID()); 85 | if (stringUUID is string) { 86 | stringUUID = 'string:substring(regex:replaceAll(stringUUID, "-", ""), 1, 4); 87 | return stringUUID ?: ""; 88 | } else { 89 | return ""; 90 | } 91 | } 92 | 93 | function createRandomUUID() returns handle = @java:Method { 94 | name: "randomUUID", 95 | 'class: "java.util.UUID" 96 | } external; 97 | -------------------------------------------------------------------------------- /examples/admin-operations/user-defined-functions/user_defined_functions.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/jballerina.java; 18 | import ballerina/log; 19 | import ballerina/os; 20 | import ballerina/regex; 21 | import ballerinax/azure_cosmosdb as cosmosdb; 22 | 23 | cosmosdb:ManagementClientConfig config = { 24 | baseUrl: os:getEnv("BASE_URL"), 25 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 26 | }; 27 | 28 | cosmosdb:ManagementClient managementClient = check new (config); 29 | 30 | public function main() { 31 | string databaseId = "my_database"; 32 | string containerId = "my_container"; 33 | var uuid = createRandomUUIDWithoutHyphens(); 34 | 35 | // Using UDFs, you can extend Azure Cosmos DB's query language. 36 | // UDFs are a great way to express complex business logic in a query's projection. 37 | 38 | log:printInfo("Creating a user defined function"); 39 | string udfId = string `udf_${uuid.toString()}`; 40 | string userDefinedFunctionBody = string `function tax(income){ 41 | if (income == undefined) 42 | throw 'no input'; 43 | 44 | if (income < 1000) 45 | return income * 0.1; 46 | else if (income < 10000) 47 | return income * 0.2; 48 | else 49 | return income * 0.4; 50 | }`; 51 | 52 | cosmosdb:UserDefinedFunction|error udfCreateResult = managementClient->createUserDefinedFunction(databaseId, 53 | containerId, udfId, userDefinedFunctionBody); 54 | 55 | if (udfCreateResult is cosmosdb:UserDefinedFunction) { 56 | log:printInfo(udfCreateResult.toString()); 57 | } else { 58 | log:printError(udfCreateResult.message()); 59 | } 60 | 61 | log:printInfo("Replacing a user defined function"); 62 | string newUserDefinedFunctionBody = string `function taxIncome(income){ 63 | if (income == undefined) 64 | throw 'no input'; 65 | if (income < 1000) 66 | return income * 0.1; 67 | else if (income < 10000) 68 | return income * 0.2; 69 | else 70 | return income * 0.4; 71 | }`; 72 | cosmosdb:UserDefinedFunction|error udfReplaceResult = managementClient->replaceUserDefinedFunction(databaseId, 73 | containerId, udfId, newUserDefinedFunctionBody); 74 | 75 | if (udfReplaceResult is cosmosdb:UserDefinedFunction) { 76 | log:printInfo(udfReplaceResult.toString()); 77 | } else { 78 | log:printError(udfReplaceResult.message()); 79 | } 80 | 81 | log:printInfo("List user defined functions(udf)s"); 82 | stream|error udfList = managementClient->listUserDefinedFunctions(databaseId, containerId); 83 | if (udfList is stream) { 84 | error? e = udfList.forEach(function (cosmosdb:UserDefinedFunction udf) { 85 | log:printInfo(udf.toString()); 86 | }); 87 | log:printInfo("Success!"); 88 | } else { 89 | log:printError(udfList.message()); 90 | } 91 | 92 | log:printInfo("Delete user defined function"); 93 | cosmosdb:DeleteResponse|error deletionResult = managementClient->deleteUserDefinedFunction(databaseId, containerId, 94 | udfId); 95 | 96 | if (deletionResult is cosmosdb:DeleteResponse) { 97 | log:printInfo(deletionResult.toString()); 98 | } else { 99 | log:printError(deletionResult.message()); 100 | } 101 | log:printInfo("End!"); 102 | } 103 | 104 | function createRandomUUIDWithoutHyphens() returns string { 105 | string? stringUUID = java:toString(createRandomUUID()); 106 | if (stringUUID is string) { 107 | stringUUID = 'string:substring(regex:replaceAll(stringUUID, "-", ""), 1, 4); 108 | return stringUUID ?: ""; 109 | } else { 110 | return ""; 111 | } 112 | } 113 | 114 | function createRandomUUID() returns handle = @java:Method { 115 | name: "randomUUID", 116 | 'class: "java.util.UUID" 117 | } external; 118 | -------------------------------------------------------------------------------- /ballerina/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) 3 | * 4 | * WSO2 LLC. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | import org.apache.tools.ant.taskdefs.condition.Os 20 | 21 | plugins { 22 | id 'io.ballerina.plugin' 23 | } 24 | 25 | description = 'Ballerina - Azure Cosmosdb Ballerina Connector' 26 | 27 | def packageName = "azure_cosmosdb" 28 | def packageOrg = "ballerinax" 29 | def tomlVersion = stripBallerinaExtensionVersion("${project.version}") 30 | def ballerinaTomlFilePlaceHolder = new File("${project.rootDir}/build-config/resources/Ballerina.toml") 31 | def ballerinaTomlFile = new File("$project.projectDir/Ballerina.toml") 32 | 33 | def stripBallerinaExtensionVersion(String extVersion) { 34 | if (extVersion.matches(project.ext.timestampedVersionRegex)) { 35 | def splitVersion = extVersion.split('-') 36 | if (splitVersion.length > 3) { 37 | def strippedValues = splitVersion[0..-4] 38 | return strippedValues.join('-') 39 | } else { 40 | return extVersion 41 | } 42 | } else { 43 | return extVersion.replace("${project.ext.snapshotVersion}", "") 44 | } 45 | } 46 | 47 | apply plugin: 'io.ballerina.plugin' 48 | 49 | ballerina { 50 | packageOrganization = packageOrg 51 | module = packageName 52 | langVersion = ballerinaLangVersion 53 | testCoverageParam = "--code-coverage --coverage-format=xml" 54 | isConnector = true 55 | platform = "java17" 56 | } 57 | 58 | configurations { 59 | externalJars 60 | } 61 | 62 | dependencies { 63 | /* Azure dependencies */ 64 | externalJars(group: 'com.azure', name: 'azure-cosmos', version: "${azureCosmosVersion}") { 65 | transitive = false 66 | } 67 | 68 | /* Netty dependencies */ 69 | externalJars(group: 'io.netty', name: 'netty-resolver-dns', version: "${nettyVersion}") { 70 | transitive = false 71 | } 72 | externalJars(group: 'io.netty', name: 'netty-handler', version: "${nettyVersion}") { 73 | transitive = false 74 | } 75 | externalJars(group: 'io.netty', name: 'netty-transport-native-unix-common', version: "${nettyVersion}") { 76 | transitive = false 77 | } 78 | 79 | /* Reactor Netty dependencies */ 80 | externalJars(group: 'io.projectreactor.netty', name: 'reactor-netty', version: "${reactorNettyVersion}") { 81 | transitive = false 82 | } 83 | externalJars(group: 'io.projectreactor.netty', name: 'reactor-netty-core', version: "${reactorNettyVersion}") { 84 | transitive = false 85 | } 86 | externalJars(group: 'io.projectreactor.netty', name: 'reactor-netty-http', version: "${reactorNettyVersion}") { 87 | transitive = false 88 | } 89 | 90 | /* Micrometer dependencies */ 91 | externalJars(group: 'io.micrometer', name: 'micrometer-core', version: "${micrometerVersion}") { 92 | transitive = false 93 | } 94 | externalJars(group: 'io.micrometer', name: 'micrometer-observation', version: "${micrometerVersion}") { 95 | transitive = false 96 | } 97 | externalJars(group: 'io.micrometer', name: 'micrometer-commons', version: "${micrometerVersion}") { 98 | transitive = false 99 | } 100 | } 101 | 102 | task updateTomlFiles { 103 | doLast { 104 | def stdlibDependentAzureCosmosVersion = project.azureCosmosVersion 105 | def stdlibDependentNettyVersion = project.nettyVersion 106 | def stdlibDependentReactorNettyVersion = project.reactorNettyVersion; 107 | def stdlibDependentMicrometerVersion = project.micrometerVersion; 108 | def newConfig = ballerinaTomlFilePlaceHolder.text.replace("@project.version@", project.version) 109 | newConfig = newConfig.replace("@toml.version@", tomlVersion) 110 | newConfig = newConfig.replace("@azure.cosmosdb.version@", stdlibDependentAzureCosmosVersion) 111 | newConfig = newConfig.replace("@netty.version@", stdlibDependentNettyVersion) 112 | newConfig = newConfig.replace("@reactor.netty.version@", stdlibDependentReactorNettyVersion) 113 | newConfig = newConfig.replace("@micrometer.version@", stdlibDependentMicrometerVersion) 114 | ballerinaTomlFile.text = newConfig 115 | } 116 | } 117 | 118 | task commitTomlFiles { 119 | doLast { 120 | project.exec { 121 | ignoreExitValue true 122 | if (Os.isFamily(Os.FAMILY_WINDOWS)) { 123 | commandLine 'cmd', '/c', "git commit -m \"[Automated] Update the native jar versions\" Ballerina.toml Dependencies.toml" 124 | } else { 125 | commandLine 'sh', '-c', "git commit -m '[Automated] Update the native jar versions' Ballerina.toml Dependencies.toml" 126 | } 127 | } 128 | } 129 | } 130 | 131 | build.dependsOn copyToLib 132 | build.dependsOn ":azure-cosmosdb-native:build" 133 | test.dependsOn ":azure-cosmosdb-native:build" 134 | -------------------------------------------------------------------------------- /examples/admin-operations/database/database_operations.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerinax/azure_cosmosdb as cosmosdb; 18 | import ballerina/jballerina.java; 19 | import ballerina/log; 20 | import ballerina/os; 21 | import ballerina/regex; 22 | 23 | cosmosdb:ManagementClientConfig config = { 24 | baseUrl: os:getEnv("BASE_URL"), 25 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 26 | }; 27 | 28 | cosmosdb:ManagementClient managementClient = check new (config); 29 | 30 | public function main() { 31 | 32 | var uuid = createRandomUUIDWithoutHyphens(); 33 | 34 | string databaseId = "my_database"; 35 | string databaseIfNotExistId = string `databasex_${uuid.toString()}`; 36 | string databaseManualId = string `databasem_${uuid.toString()}`; 37 | string databaseAutoScalingId = string `databasea_${uuid.toString()}`; 38 | 39 | log:printInfo("Creating database"); 40 | cosmosdb:Database|error databaseResult = managementClient->createDatabase(databaseId); 41 | 42 | if (databaseResult is cosmosdb:Database) { 43 | log:printInfo(databaseResult.toString()); 44 | } else { 45 | log:printError(databaseResult.message()); 46 | } 47 | 48 | log:printInfo("Creating database only if it does not exist"); 49 | cosmosdb:Database?|error databaseIfNotExist = managementClient->createDatabaseIfNotExist(databaseIfNotExistId); 50 | 51 | if (databaseIfNotExist is cosmosdb:Database?) { 52 | log:printInfo(databaseIfNotExist.toString()); 53 | } else { 54 | log:printError(databaseIfNotExist.message()); 55 | } 56 | 57 | log:printInfo("Creating database with manual throughput"); 58 | int throughput = 600; 59 | cosmosdb:Database|error databaseWithManualThroughput = managementClient->createDatabase(databaseManualId, 60 | throughput); 61 | 62 | if (databaseWithManualThroughput is cosmosdb:Database) { 63 | log:printInfo(databaseWithManualThroughput.toString()); 64 | } else { 65 | log:printError(databaseWithManualThroughput.message()); 66 | } 67 | 68 | log:printInfo("Creating database with autoscaling throughput"); 69 | record {|int maxThroughput;|} maxThroughput = { maxThroughput: 4000 }; 70 | cosmosdb:Database|error databaseWithAutoThroughput = managementClient->createDatabase(databaseAutoScalingId, 71 | maxThroughput); 72 | 73 | if (databaseWithAutoThroughput is cosmosdb:Database) { 74 | log:printInfo(databaseWithAutoThroughput.toString()); 75 | } else{ 76 | log:printError(databaseWithAutoThroughput.message()); 77 | } 78 | 79 | string? etag; 80 | string? sessiontoken; 81 | log:printInfo("Reading database by ID"); 82 | cosmosdb:Database|error databaseInfo = managementClient->getDatabase(databaseId); 83 | 84 | if (databaseInfo is cosmosdb:Database) { 85 | log:printInfo(databaseInfo.toString()); 86 | etag = databaseInfo?.eTag; 87 | sessiontoken = databaseInfo?.sessionToken; 88 | } else { 89 | log:printError(databaseInfo.message()); 90 | } 91 | 92 | log:printInfo("Reading database with consistancy level option"); 93 | cosmosdb:ResourceReadOptions options = { 94 | consistancyLevel: cosmosdb:BOUNDED_STALENESS 95 | }; 96 | cosmosdb:Database|error databaseInfoWithDifferentConsistancy = managementClient->getDatabase(databaseId, options); 97 | 98 | if (databaseInfoWithDifferentConsistancy is cosmosdb:Database) { 99 | log:printInfo(databaseInfoWithDifferentConsistancy.toString()); 100 | } else{ 101 | log:printError(databaseInfoWithDifferentConsistancy.message()); 102 | } 103 | 104 | log:printInfo("Getting list of databases"); 105 | stream|error databaseList = managementClient->listDatabases(); 106 | 107 | if (databaseList is stream) { 108 | error? e = databaseList.forEach(function (cosmosdb:Database database) { 109 | log:printInfo(database.toString()); 110 | }); 111 | } else { 112 | log:printError(databaseList.message()); 113 | } 114 | 115 | log:printInfo("Deleting databases"); 116 | _ = checkpanic managementClient->deleteDatabase(databaseIfNotExistId); 117 | _ = checkpanic managementClient->deleteDatabase(databaseManualId); 118 | _ = checkpanic managementClient->deleteDatabase(databaseAutoScalingId); 119 | log:printInfo("End!"); 120 | } 121 | 122 | function createRandomUUIDWithoutHyphens() returns string { 123 | string? stringUUID = java:toString(createRandomUUID()); 124 | if (stringUUID is string) { 125 | stringUUID = 'string:substring(regex:replaceAll(stringUUID, "-", ""), 1, 4); 126 | return stringUUID ?: ""; 127 | } else { 128 | return ""; 129 | } 130 | } 131 | 132 | function createRandomUUID() returns handle = @java:Method { 133 | name: "randomUUID", 134 | 'class: "java.util.UUID" 135 | } external; 136 | -------------------------------------------------------------------------------- /native/src/main/java/io/ballerinax/cosmosdb/Constants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 3 | * 4 | * WSO2 Inc. licenses this file to you under the Apache License, 5 | * Version 2.0 (the "License"); you may not use this file except 6 | * in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, 12 | * software distributed under the License is distributed on an 13 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | * KIND, either express or implied. See the License for the 15 | * specific language governing permissions and limitations 16 | * under the License. 17 | */ 18 | 19 | package io.ballerinax.cosmosdb; 20 | 21 | import io.ballerina.runtime.api.values.BString; 22 | 23 | import static io.ballerina.runtime.api.utils.StringUtils.fromString; 24 | 25 | /** 26 | * The class holds the constants relevant to the module. 27 | */ 28 | public class Constants { 29 | 30 | public static final BString BASEURL = fromString("baseUrl"); 31 | public static final BString TOKEN = fromString("primaryKeyOrResourceToken"); 32 | 33 | public static final BString CONSISTENCY_LEVEL = fromString("consistencyLevel"); 34 | public static final String STRONG = "Strong"; 35 | public static final String BOUNDED_STALENESS = "BoundedStaleness"; 36 | public static final String SESSION = "Session"; 37 | public static final String EVENTUAL = "Eventual"; 38 | public static final String CONSISTENT_PREFIX = "ConsistentPrefix"; 39 | public static final BString DIRECT_MODE = fromString("directMode"); 40 | public static final BString DIRECT_CONNECTION_CONFIG = fromString("directConnectionConfig"); 41 | public static final BString GATEWAY_CONNECTION_CONFIG = fromString("gatewayConnectionConfig"); 42 | 43 | public static final BString CONNECTION_TIMEOUT = fromString("connectTimeout"); 44 | public static final BString IDLE_CONNECTION_TIMEOUT = fromString("idleConnectionTimeout"); 45 | public static final BString IDLE_ENDPOINT_TIMEOUT = fromString("idleEndpointTimeout"); 46 | public static final BString MAX_CONNECTIONS_PER_ENDPOINT = fromString("maxConnectionsPerEndpoint"); 47 | public static final BString MAX_REQUESTS_PER_CONNECTION = fromString("maxRequestsPerConnection"); 48 | public static final BString NETWORK_TIMEOUT = fromString("networkRequestTimeout"); 49 | public static final BString CONNECTION_ENDPOINT_REDESCOVERY = fromString("connectionEndpointRediscoveryEnabled"); 50 | 51 | public static final BString MAX_CONNECTION_POOL_SIZE = fromString("maxConnectionPoolSize"); 52 | 53 | public static final BString CONNECTION_SHARING_ACROSS_CLIENTS = fromString("connectionSharingAcrossClientsEnabled"); 54 | public static final BString USER_AGENT_SUFFIX = fromString("userAgentSuffix"); 55 | public static final BString PREFERRED_REGIONS = fromString("preferredRegions"); 56 | public static final BString CONTENT_RESPONSE_ON_WRITE_ENABLED = fromString("contentResponseOnWriteEnabled"); 57 | 58 | public static final BString INDEXING_DIRECTIVE = fromString("indexingDirective"); 59 | public static final String INCLUDE = "Include"; 60 | public static final String EXCLUDE = "Exclude"; 61 | public static final BString DEDICATED_GATEWAY_REQUEST_OPTIONS = fromString("dedicatedGatewayRequestOptions"); 62 | public static final BString IF_MATCH_ETAG = fromString("ifMatchETag"); 63 | public static final BString IF_NONE_MATCH_ETAG = fromString("ifNoneMatchETag"); 64 | public static final BString POST_TRIGGER_INCLUDE = fromString("postTriggerInclude"); 65 | public static final BString PRE_TRIGGER_INCLUDE = fromString("preTriggerInclude"); 66 | public static final BString SESSION_TOKEN = fromString("sessionToken"); 67 | public static final BString THRESHOLD_FOR_DIAGNOSTICS = fromString("throughputControlGroupName"); 68 | public static final BString THROUHPUT_CONTROL = fromString("throughputControlGroupName"); 69 | 70 | public static final BString INDEX_METRICS_ENABLED = fromString("indexMetricsEnabled"); 71 | public static final BString MAX_BUFFERED_ITEM_COUNT = fromString("maxBufferedItemCount"); 72 | public static final BString MAX_DEGREE_PARALLELISM = fromString("maxDegreeOfParallelism"); 73 | public static final BString PARTITION_KEY = fromString("partitionkey"); 74 | public static final BString QUERY_METRICS_ENABLED = fromString("queryMetricsEnabled"); 75 | public static final BString LIMIT_KB = fromString("limitInKb"); 76 | public static final BString SCAN_QUERY_ENABLED = fromString("scanInQueryEnabled"); 77 | public static final BString THRESHOLD_DIAGNOSIS_TRACER = fromString("thresholdForDiagnosticsOnTracer"); 78 | 79 | public static final BString MAX_INTEGRATED_CACHE_STALENESS = fromString("maxIntegratedCacheStaleness"); 80 | public static final BString SP_PROCEDURE_REQUEST_OPTIONS = fromString("cosmosStoredProcedureRequestOptions"); 81 | public static final BString PARAMETERS = fromString("parameters"); 82 | public static final BString SCRIPT_LOGGING_ENABLED = fromString("scriptLoggingEnabled"); 83 | 84 | public static final String RESULT_ITERATOR_OBJECT = "ResultIterator"; 85 | public static final String COSMOS_RESULT_ITERATOR_OBJECT = "CosmosResultIterator"; 86 | public static final String RECORD_TYPE = "recordType"; 87 | public static final String OBJECT_ITERATOR = "ObjectIterator"; 88 | public static final String STORED_PROCEDURE = "StoredProcedure"; 89 | public static final String DIAGNOSTICS = "Diagnostics"; 90 | public static final String DOCUMENT_RESPONSE = "DocumentResponse"; 91 | public static final String STORED_PROCEDURE_RESPONSE = "StoredProcedureResponse"; 92 | 93 | } 94 | -------------------------------------------------------------------------------- /examples/admin-operations/triggers/trigger_operations.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/jballerina.java; 18 | import ballerina/log; 19 | import ballerina/os; 20 | import ballerina/regex; 21 | import ballerinax/azure_cosmosdb as cosmosdb; 22 | 23 | cosmosdb:ManagementClientConfig config = { 24 | baseUrl: os:getEnv("BASE_URL"), 25 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 26 | }; 27 | 28 | cosmosdb:ManagementClient managementClient = check new (config); 29 | 30 | public function main() { 31 | string databaseId = "my_database"; 32 | string containerId = "my_container"; 33 | var uuid = createRandomUUIDWithoutHyphens(); 34 | 35 | log:printInfo("Creating a trigger"); 36 | string triggerId = string `trigger_${uuid.toString()}`; 37 | string createTriggerBody = 38 | string `function updateMetadata() { 39 | var context = getContext(); 40 | var collection = context.getCollection(); 41 | var response = context.getResponse(); 42 | var createdDocument = response.getBody(); 43 | 44 | // query for metadata document 45 | var filterQuery = 'SELECT * FROM root r WHERE r.id = "_metadata"'; 46 | var accept = collection.queryDocuments(collection.getSelfLink(), filterQuery, updateMetadataCallback); 47 | if(!accept) throw "Unable to update metadata, abort"; 48 | } 49 | 50 | function updateMetadataCallback(err, documents, responseOptions) { 51 | if(err) throw new Error("Error" + err.message); 52 | if(documents.length != 1) throw "Unable to find metadata document"; 53 | var metadataDocument = documents[0]; 54 | // update metadata 55 | metadataDocument.createdDocuments += 1; 56 | metadataDocument.createdNames += " " + createdDocument.id; 57 | var accept = collection.replaceDocument(metadataDocument._self, metadataDocument, function(err, docReplaced) { 58 | if(err) throw "Unable to update metadata, abort"; 59 | }); 60 | 61 | if(!accept) throw "Unable to update metadata, abort"; 62 | return; 63 | }`; 64 | cosmosdb:TriggerOperation createTriggerOperationType = "All"; 65 | cosmosdb:TriggerType createTriggerType = "Post"; 66 | 67 | cosmosdb:Trigger|error triggerCreationResult = managementClient->createTrigger(databaseId, containerId, triggerId, 68 | createTriggerBody, createTriggerOperationType, createTriggerType); 69 | 70 | if (triggerCreationResult is cosmosdb:Trigger) { 71 | log:printInfo(triggerCreationResult.toString()); 72 | } else { 73 | log:printError(triggerCreationResult.message()); 74 | } 75 | 76 | log:printInfo("Replacing a trigger"); 77 | string replaceTriggerBody = 78 | string `function replaceMetadata() { 79 | var context = getContext(); 80 | var collection = context.getCollection(); 81 | var response = context.getResponse(); 82 | var createdDocument = response.getBody(); 83 | 84 | // query for metadata document 85 | var filterQuery = 'SELECT * FROM root r WHERE r.id = "_metadata"'; 86 | var accept = collection.queryDocuments(collection.getSelfLink(), filterQuery, updateMetadataCallback); 87 | if(!accept) throw "Unable to update metadata, abort"; 88 | } 89 | 90 | function updateMetadataCallback(err, documents, responseOptions) { 91 | if(err) throw new Error("Error" + err.message); 92 | if(documents.length != 1) throw "Unable to find metadata document"; 93 | var metadataDocument = documents[0]; 94 | // update metadata 95 | metadataDocument.createdDocuments += 1; 96 | metadataDocument.createdNames += " " + createdDocument.id; 97 | var accept = collection.replaceDocument(metadataDocument._self, metadataDocument, function(err, docReplaced) { 98 | if(err) throw "Unable to update metadata, abort"; 99 | }); 100 | 101 | if(!accept) throw "Unable to update metadata, abort"; 102 | return; 103 | }`; 104 | cosmosdb:TriggerOperation replaceTriggerOperation = "All"; 105 | cosmosdb:TriggerType replaceTriggerType = "Post"; 106 | 107 | cosmosdb:Trigger|error triggerReplaceResult = managementClient->replaceTrigger(databaseId, containerId, triggerId, 108 | replaceTriggerBody, replaceTriggerOperation, replaceTriggerType); 109 | 110 | if (triggerReplaceResult is cosmosdb:Trigger) { 111 | log:printInfo(triggerReplaceResult.toString()); 112 | } else { 113 | log:printError(triggerReplaceResult.message()); 114 | } 115 | 116 | log:printInfo("List available triggers"); 117 | stream|error triggerList = managementClient->listTriggers(databaseId, containerId); 118 | 119 | if (triggerList is stream) { 120 | error? e = triggerList.forEach(function (cosmosdb:Trigger trigger) { 121 | log:printInfo(trigger.toString()); 122 | }); 123 | log:printInfo("Success!"); 124 | } else { 125 | log:printError(triggerList.message()); 126 | } 127 | 128 | log:printInfo("Deleting trigger"); 129 | cosmosdb:DeleteResponse|error deletionResult = managementClient->deleteTrigger(databaseId, containerId, triggerId); 130 | 131 | if (deletionResult is cosmosdb:DeleteResponse) { 132 | log:printInfo(deletionResult.toString()); 133 | } else { 134 | log:printError(deletionResult.message()); 135 | } 136 | log:printInfo("End!"); 137 | } 138 | 139 | function createRandomUUIDWithoutHyphens() returns string { 140 | string? stringUUID = java:toString(createRandomUUID()); 141 | if (stringUUID is string) { 142 | stringUUID = 'string:substring(regex:replaceAll(stringUUID, "-", ""), 1, 4); 143 | return stringUUID ?: ""; 144 | } else { 145 | return ""; 146 | } 147 | } 148 | 149 | function createRandomUUID() returns handle = @java:Method { 150 | name: "randomUUID", 151 | 'class: "java.util.UUID" 152 | } external; 153 | -------------------------------------------------------------------------------- /examples/data-operations/documents/document_operations.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/io; 18 | import ballerina/jballerina.java; 19 | import ballerina/log; 20 | import ballerina/os; 21 | import ballerina/regex; 22 | import ballerinax/azure_cosmosdb as cosmosdb; 23 | 24 | cosmosdb:ConnectionConfig config = { 25 | baseUrl: os:getEnv("BASE_URL"), 26 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 27 | }; 28 | 29 | cosmosdb:DataPlaneClient azureCosmosClient = check new (config); 30 | 31 | public function main() returns error? { 32 | string databaseId = "my_database"; 33 | string containerId = "my_container"; 34 | var uuid = createRandomUUIDWithoutHyphens(); 35 | 36 | log:printInfo("Create a new document"); 37 | string documentId = string `document_${uuid.toString()}`; 38 | map documentBody = { 39 | id: documentId, 40 | "LastName": "Sam", 41 | "Parents": [{ 42 | "FamilyName": null, 43 | "FirstName": "Thomas" 44 | }, { 45 | "FamilyName": null, 46 | "FirstName": "Mary Kay" 47 | }], 48 | "gender": 0 49 | }; 50 | int partitionKeyValue = 0; 51 | 52 | cosmosdb:DocumentResponse documentResponse = check azureCosmosClient->createDocument(databaseId, containerId, 53 | documentId, documentBody, partitionKeyValue); 54 | 55 | log:printInfo("Creating a new document allowing to include it in the indexing."); 56 | string id = string `documenti_${uuid.toString()}`; 57 | map documentWithIndexing = { 58 | "LastName": "Tom", 59 | "Parents": [{ 60 | "FamilyName": null, 61 | "FirstName": "Thomas" 62 | }, { 63 | "FamilyName": null, 64 | "FirstName": "Mary Kay" 65 | }], 66 | "gender": 1 67 | }; 68 | partitionKeyValue = 1; 69 | 70 | cosmosdb:RequestOptions indexingOptions = { 71 | indexingDirective: "Include" 72 | }; 73 | 74 | cosmosdb:DocumentResponse documentResponseResult = check azureCosmosClient->createDocument(databaseId, containerId, 75 | id, documentWithIndexing, partitionKeyValue, 76 | indexingOptions); 77 | 78 | // Create the document which already existing id and specify that it is an upsert request. If not this will show an 79 | // error. 80 | log:printInfo("Upserting the document"); 81 | map upsertDocument = { 82 | "LastName": "Tim", 83 | "Parents": [{ 84 | "FamilyName": null, 85 | "FirstName": "Thomas" 86 | }, { 87 | "FamilyName": null, 88 | "FirstName": "Mary Kay" 89 | }], 90 | "gender": 0 91 | }; 92 | partitionKeyValue = 0; 93 | 94 | cosmosdb:RequestOptions upsertOptions = { 95 | isUpsertRequest: true 96 | }; 97 | 98 | cosmosdb:DocumentResponse documentResponseOut = check azureCosmosClient->createDocument(databaseId, containerId, id, 99 | upsertDocument, partitionKeyValue, upsertOptions); 100 | 101 | log:printInfo("Replacing document"); 102 | map newDocumentBody = { 103 | "LastName": "Helena", 104 | "Parents": [{ 105 | "FamilyName": null, 106 | "FirstName": "Thomas" 107 | }, { 108 | "FamilyName": null, 109 | "FirstName": "Mary Kay" 110 | }], 111 | "gender": 0 112 | }; 113 | partitionKeyValue = 0; 114 | 115 | cosmosdb:DocumentResponse documentResponseValue = check azureCosmosClient->replaceDocument(databaseId, containerId, 116 | documentId, newDocumentBody, partitionKeyValue); 117 | 118 | log:printInfo("Read the document by id"); 119 | cosmosdb:Document returnedDocument = check azureCosmosClient->getDocument(databaseId, containerId, documentId, 120 | partitionKeyValue); 121 | 122 | log:printInfo(returnedDocument.toString()); 123 | 124 | log:printInfo("Read the document with request options"); 125 | cosmosdb:RequestOptions options = { 126 | consistancyLevel: "Eventual" 127 | }; 128 | cosmosdb:Document returnedDocumentWithOptions = check azureCosmosClient->getDocument(databaseId, 129 | containerId, documentId, partitionKeyValue, options); 130 | 131 | log:printInfo(returnedDocumentWithOptions.toString()); 132 | 133 | log:printInfo("Getting list of documents"); 134 | stream documentList = check azureCosmosClient->getDocumentList(databaseId, containerId, 135 | partitionKeyValue); 136 | 137 | error? e = documentList.forEach(function (record{} document) { 138 | log:printInfo(document.toString()); 139 | }); 140 | log:printInfo("Success!"); 141 | 142 | 143 | log:printInfo("Deleting the document"); 144 | cosmosdb:DocumentResponse b = check azureCosmosClient->deleteDocument(databaseId, containerId, documentId, 145 | partitionKeyValue); 146 | 147 | log:printInfo("End!"); 148 | } 149 | 150 | function read(string path) returns @tainted json|error { 151 | io:ReadableByteChannel rbc = check io:openReadableFile(path); 152 | io:ReadableCharacterChannel rch = new (rbc, "UTF8"); 153 | var result = rch.readJson(); 154 | closeRc(rch); 155 | return result; 156 | } 157 | 158 | function closeRc(io:ReadableCharacterChannel rc) { 159 | var result = rc.close(); 160 | if (result is error) { 161 | log:printError("Error occurred while closing character stream "); 162 | } 163 | } 164 | 165 | # Create a random UUID removing the unnecessary hyphens which will interrupt querying opearations. 166 | # 167 | # + return - A string UUID without hyphens 168 | function createRandomUUIDWithoutHyphens() returns string { 169 | string? stringUUID = java:toString(createRandomUUID()); 170 | if (stringUUID is string) { 171 | stringUUID = 'string:substring(regex:replaceAll(stringUUID, "-", ""), 1, 4); 172 | return stringUUID ?: ""; 173 | } else { 174 | return ""; 175 | } 176 | } 177 | 178 | function createRandomUUID() returns handle = @java:Method { 179 | name: "randomUUID", 180 | 'class: "java.util.UUID" 181 | } external; 182 | -------------------------------------------------------------------------------- /examples/admin-operations/container/container_operations.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/jballerina.java; 18 | import ballerina/log; 19 | import ballerina/os; 20 | import ballerina/regex; 21 | import ballerinax/azure_cosmosdb as cosmosdb; 22 | 23 | cosmosdb:ManagementClientConfig config = { 24 | baseUrl: os:getEnv("BASE_URL"), 25 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 26 | }; 27 | 28 | cosmosdb:ManagementClient managementClient = check new (config); 29 | 30 | public function main() { 31 | 32 | string databaseId = "my_database"; 33 | var uuid = createRandomUUIDWithoutHyphens(); 34 | 35 | string containerId = "my_new_container"; 36 | string containerWithIndexingId = string `containero_${uuid.toString()}`; 37 | string containerManualId = string `containerm_${uuid.toString()}`; 38 | string containerAutoscalingId = string `containera_${uuid.toString()}`; 39 | string containerIfnotExistId = string `containerx_${uuid.toString()}`; 40 | 41 | log:printInfo("Creating container"); 42 | cosmosdb:PartitionKey partitionKey = { 43 | paths: ["/id"], 44 | keyVersion: 2 45 | }; 46 | 47 | cosmosdb:Container|error containerResult = managementClient->createContainer(databaseId, containerId, partitionKey); 48 | if (containerResult is cosmosdb:Container) { 49 | log:printInfo(containerResult.toString()); 50 | } else { 51 | log:printError(containerResult.message()); 52 | } 53 | 54 | log:printInfo("Creating container with indexing policy"); 55 | cosmosdb:IndexingPolicy indexingPolicy = { 56 | indexingMode: "consistent", 57 | automatic: true, 58 | includedPaths: [{ 59 | path: "/*", 60 | indexes: [{ 61 | dataType: "String", 62 | precision: -1, 63 | kind: "Range" 64 | }] 65 | }] 66 | }; 67 | cosmosdb:PartitionKey partitionKeyWithIndexing = { 68 | paths: ["/id"], 69 | kind: "Hash", 70 | keyVersion: 2 71 | }; 72 | 73 | cosmosdb:Container|error containerWithOptionsResult = managementClient->createContainer(databaseId, 74 | containerWithIndexingId, partitionKeyWithIndexing, indexingPolicy); 75 | 76 | if (containerWithOptionsResult is cosmosdb:Container) { 77 | log:printInfo(containerWithOptionsResult.toString()); 78 | } else { 79 | log:printError(containerWithOptionsResult.message()); 80 | } 81 | 82 | log:printInfo("Creating container with manual throughput policy"); 83 | int throughput = 600; 84 | cosmosdb:PartitionKey partitionKeyManual = { 85 | paths: ["/AccountNumber"], 86 | kind: "Hash", 87 | keyVersion: 2 88 | }; 89 | 90 | cosmosdb:Container|error manualPolicyContainer = managementClient->createContainer(databaseId, containerManualId, 91 | partitionKeyManual, (), throughput); 92 | if (manualPolicyContainer is cosmosdb:Container) { 93 | log:printInfo(manualPolicyContainer.toString()); 94 | } else { 95 | log:printError(manualPolicyContainer.message()); 96 | } 97 | 98 | log:printInfo("Creating container with autoscaling throughput policy"); 99 | record {|int maxThroughput;|} maxThroughput = { maxThroughput: 4000 }; 100 | cosmosdb:PartitionKey partitionKeyAutoscaling = { 101 | paths: ["/id"], 102 | kind: "Hash", 103 | keyVersion: 2 104 | }; 105 | 106 | cosmosdb:Container|error autoPolicyContainer = managementClient->createContainer(databaseId, containerManualId, 107 | partitionKeyManual, (), maxThroughput); 108 | if (autoPolicyContainer is cosmosdb:Container) { 109 | log:printInfo(autoPolicyContainer.toString()); 110 | } else { 111 | log:printError(autoPolicyContainer.message()); 112 | } 113 | 114 | log:printInfo("Creating container if not exist"); 115 | cosmosdb:PartitionKey partitionKeyDefinition = { 116 | paths: ["/AccountNumber"], 117 | kind: "Hash", 118 | keyVersion: 2 119 | }; 120 | cosmosdb:Container?|error containerIfNotExistResult = managementClient->createContainer(databaseId, 121 | containerIfnotExistId, partitionKeyDefinition); 122 | if (containerIfNotExistResult is cosmosdb:Container?) { 123 | log:printInfo(containerIfNotExistResult.toString()); 124 | } else { 125 | log:printError(containerIfNotExistResult.message()); 126 | } 127 | 128 | string? etag; 129 | string? sessiontoken; 130 | log:printInfo("Reading container info"); 131 | cosmosdb:Container|error existingContainer = managementClient->getContainer(databaseId, containerId); 132 | 133 | if (existingContainer is cosmosdb:Container) { 134 | log:printInfo(existingContainer.toString()); 135 | etag = existingContainer?.eTag; 136 | sessiontoken = existingContainer?.sessionToken; 137 | } else { 138 | log:printError(existingContainer.message()); 139 | } 140 | 141 | log:printInfo("Reading container info with request options"); 142 | cosmosdb:ResourceReadOptions options = { 143 | consistancyLevel: cosmosdb:BOUNDED_STALENESS 144 | }; 145 | cosmosdb:Container|error getContainerWithOptions = managementClient->getContainer(databaseId, containerId, options); 146 | 147 | if (getContainerWithOptions is cosmosdb:Container) { 148 | log:printInfo(getContainerWithOptions.toString()); 149 | } else { 150 | log:printError(getContainerWithOptions.message()); 151 | } 152 | 153 | log:printInfo("Getting list of containers"); 154 | stream|error containerList = managementClient->listContainers(databaseId); 155 | 156 | if (containerList is stream) { 157 | error? e = containerList.forEach(function (cosmosdb:Container container) { 158 | log:printInfo(container.toString()); 159 | }); 160 | } else { 161 | log:printError(containerList.message()); 162 | } 163 | 164 | log:printInfo("Deleting the container"); 165 | cosmosdb:DeleteResponse|error deletionResult = managementClient->deleteContainer(databaseId, containerId); 166 | 167 | if (deletionResult is cosmosdb:DeleteResponse) { 168 | log:printInfo(deletionResult.toString()); 169 | } else{ 170 | log:printError(deletionResult.message()); 171 | } 172 | log:printInfo("End!"); 173 | } 174 | 175 | function createRandomUUIDWithoutHyphens() returns string { 176 | string? stringUUID = java:toString(createRandomUUID()); 177 | if (stringUUID is string) { 178 | stringUUID = 'string:substring(regex:replaceAll(stringUUID, "-", ""), 1, 4); 179 | return stringUUID ?: ""; 180 | } else { 181 | return ""; 182 | } 183 | } 184 | 185 | function createRandomUUID() returns handle = @java:Method { 186 | name: "randomUUID", 187 | 'class: "java.util.UUID" 188 | } external; 189 | -------------------------------------------------------------------------------- /examples/admin-operations/users-permissions/users_access_control.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | import ballerina/jballerina.java; 18 | import ballerina/log; 19 | import ballerina/os; 20 | import ballerina/regex; 21 | import ballerinax/azure_cosmosdb as cosmosdb; 22 | 23 | cosmosdb:ManagementClientConfig config = { 24 | baseUrl: os:getEnv("BASE_URL"), 25 | primaryKeyOrResourceToken: os:getEnv("MASTER_OR_RESOURCE_TOKEN") 26 | }; 27 | 28 | cosmosdb:ManagementClient managementClient = check new (config); 29 | 30 | public function main() { 31 | string databaseId = "my_database"; 32 | string containerId = "my_container"; 33 | var uuid = createRandomUUIDWithoutHyphens(); 34 | 35 | // Get database container to get the resource ids of them. 36 | cosmosdb:Database database = checkpanic managementClient->getDatabase(databaseId); 37 | cosmosdb:Container container = checkpanic managementClient->getContainer(databaseId, containerId); 38 | 39 | log:printInfo("Creating user"); 40 | string userId = string `user_${uuid.toString()}`; 41 | cosmosdb:User|error userCreationResult = managementClient->createUser(databaseId, userId); 42 | 43 | if (userCreationResult is cosmosdb:User) { 44 | log:printInfo(userCreationResult.toString()); 45 | log:printInfo("Success!"); 46 | } else { 47 | log:printError(userCreationResult.message()); 48 | } 49 | 50 | log:printInfo("Replace user id"); 51 | string newUserId = string `user_${uuid.toString()}`; 52 | cosmosdb:User|error userReplaceResult = managementClient->replaceUserId(databaseId, userId, newUserId); 53 | 54 | if (userReplaceResult is cosmosdb:User) { 55 | log:printInfo(userReplaceResult.toString()); 56 | log:printInfo("Success!"); 57 | } else { 58 | log:printError(userReplaceResult.message()); 59 | } 60 | 61 | log:printInfo("Get user information"); 62 | cosmosdb:User|error user = managementClient->getUser(databaseId, userId); 63 | 64 | if (user is cosmosdb:User) { 65 | log:printInfo(user.toString()); 66 | log:printInfo("Success!"); 67 | } else { 68 | log:printError(user.message()); 69 | } 70 | 71 | log:printInfo("List users"); 72 | stream|error userList = managementClient->listUsers(databaseId); 73 | if (userList is stream) { 74 | error? e = userList.forEach(function (cosmosdb:User storedPrcedure) { 75 | log:printInfo(storedPrcedure.toString()); 76 | }); 77 | log:printInfo("Success!"); 78 | } else { 79 | log:printError("Error!"); 80 | } 81 | 82 | //------------------------------------------------Permissions------------------------------------------------------- 83 | 84 | log:printInfo("Create permission for a user"); 85 | string permissionId = string `permission_${uuid.toString()}`; 86 | cosmosdb:PermisssionMode permissionMode = "All"; 87 | string permissionResource = 88 | string `dbs/${database?.resourceId.toString()}/colls/${container?.resourceId.toString()}`; 89 | 90 | cosmosdb:Permission|error permission = managementClient->createPermission(databaseId, userId, permissionId, 91 | permissionMode, permissionResource); 92 | 93 | if (permission is cosmosdb:Permission) { 94 | log:printInfo(permission.toString()); 95 | log:printInfo("Success!"); 96 | } else { 97 | log:printError(permission.message()); 98 | } 99 | 100 | // Create permission with time to live 101 | // 102 | // string newPermissionMode = "Read"; 103 | // string newPermissionResource = string `dbs/${database?.resourceId.toString()}/colls/${container?.resourceId. 104 | // toString()}`; 105 | // int validityPeriod = 9000; 106 | // cosmosdb:Permission newPermission = { 107 | // id: string `permissionttl_${uuid.toString()}`, 108 | // permissionMode: newPermissionMode, 109 | // resourcePath: newPermissionResource 110 | // }; 111 | // var result7 = azureCosmosClient->createPermission(databaseId, userId, newPermission, validityPeriod); 112 | // if (result7 is cosmosdb:Permission) { 113 | // io:println("Permission is successfully created!"); 114 | // } else { 115 | // io:println("Permission is not created ", result7.message()); 116 | // } 117 | 118 | log:printInfo("Replace permission"); 119 | cosmosdb:PermisssionMode permissionModeReplace = "All"; 120 | string permissionResourceReplace = string `dbs/${databaseId}/colls/${containerId}`; 121 | 122 | permission = managementClient->replacePermission(databaseId, userId, permissionId, 123 | permissionModeReplace, permissionResourceReplace); 124 | 125 | if (permission is cosmosdb:Permission) { 126 | log:printInfo(permission.toString()); 127 | log:printInfo("Success!"); 128 | } else { 129 | log:printError(permission.message()); 130 | } 131 | 132 | log:printInfo("List permissions"); 133 | stream|error permissionList = managementClient->listPermissions(databaseId, userId); 134 | if (permissionList is stream) { 135 | error? e = permissionList.forEach(function (cosmosdb:Permission storedPrcedure) { 136 | log:printInfo(storedPrcedure.toString()); 137 | }); 138 | log:printInfo("Success!"); 139 | } else { 140 | log:printError(permissionList.message()); 141 | } 142 | 143 | log:printInfo("Get intormation about one permission"); 144 | permission = managementClient->getPermission(databaseId, userId, permissionId); 145 | 146 | if (permission is cosmosdb:Permission) { 147 | log:printInfo(permission.toString()); 148 | log:printInfo("Success!"); 149 | } else { 150 | log:printError(permission.message()); 151 | } 152 | 153 | log:printInfo("Delete permission"); 154 | cosmosdb:DeleteResponse|error deleteResponse = managementClient->deletePermission(databaseId, userId, permissionId); 155 | 156 | if (deleteResponse is cosmosdb:DeleteResponse) { 157 | log:printInfo(deleteResponse.toString()); 158 | log:printInfo("Success!"); 159 | } else { 160 | log:printError(deleteResponse.message()); 161 | } 162 | 163 | log:printInfo("Delete user"); 164 | deleteResponse = managementClient->deleteUser(databaseId, userId); 165 | 166 | if (deleteResponse is cosmosdb:DeleteResponse) { 167 | log:printInfo(deleteResponse.toString()); 168 | log:printInfo("Success!"); 169 | } else { 170 | log:printError(deleteResponse.message()); 171 | } 172 | 173 | log:printInfo("Success!"); 174 | } 175 | 176 | function createRandomUUIDWithoutHyphens() returns string { 177 | string? stringUUID = java:toString(createRandomUUID()); 178 | if (stringUUID is string) { 179 | stringUUID = 'string:substring(regex:replaceAll(stringUUID, "-", ""), 1, 4); 180 | return stringUUID ?: ""; 181 | } else { 182 | return ""; 183 | } 184 | } 185 | 186 | function createRandomUUID() returns handle = @java:Method { 187 | name: "randomUUID", 188 | 'class: "java.util.UUID" 189 | } external; 190 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 87 | 88 | # Use the maximum available, or set MAX_FD != -1 to use that value. 89 | MAX_FD=maximum 90 | 91 | warn () { 92 | echo "$*" 93 | } >&2 94 | 95 | die () { 96 | echo 97 | echo "$*" 98 | echo 99 | exit 1 100 | } >&2 101 | 102 | # OS specific support (must be 'true' or 'false'). 103 | cygwin=false 104 | msys=false 105 | darwin=false 106 | nonstop=false 107 | case "$( uname )" in #( 108 | CYGWIN* ) cygwin=true ;; #( 109 | Darwin* ) darwin=true ;; #( 110 | MSYS* | MINGW* ) msys=true ;; #( 111 | NONSTOP* ) nonstop=true ;; 112 | esac 113 | 114 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 115 | 116 | 117 | # Determine the Java command to use to start the JVM. 118 | if [ -n "$JAVA_HOME" ] ; then 119 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 120 | # IBM's JDK on AIX uses strange locations for the executables 121 | JAVACMD=$JAVA_HOME/jre/sh/java 122 | else 123 | JAVACMD=$JAVA_HOME/bin/java 124 | fi 125 | if [ ! -x "$JAVACMD" ] ; then 126 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 127 | 128 | Please set the JAVA_HOME variable in your environment to match the 129 | location of your Java installation." 130 | fi 131 | else 132 | JAVACMD=java 133 | if ! command -v java >/dev/null 2>&1 134 | then 135 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 136 | 137 | Please set the JAVA_HOME variable in your environment to match the 138 | location of your Java installation." 139 | fi 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 147 | # shellcheck disable=SC3045 148 | MAX_FD=$( ulimit -H -n ) || 149 | warn "Could not query maximum file descriptor limit" 150 | esac 151 | case $MAX_FD in #( 152 | '' | soft) :;; #( 153 | *) 154 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 155 | # shellcheck disable=SC3045 156 | ulimit -n "$MAX_FD" || 157 | warn "Could not set maximum file descriptor limit to $MAX_FD" 158 | esac 159 | fi 160 | 161 | # Collect all arguments for the java command, stacking in reverse order: 162 | # * args from the command line 163 | # * the main class name 164 | # * -classpath 165 | # * -D...appname settings 166 | # * --module-path (only if needed) 167 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 168 | 169 | # For Cygwin or MSYS, switch paths to Windows format before running java 170 | if "$cygwin" || "$msys" ; then 171 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 172 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 173 | 174 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 175 | 176 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 177 | for arg do 178 | if 179 | case $arg in #( 180 | -*) false ;; # don't mess with options #( 181 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 182 | [ -e "$t" ] ;; #( 183 | *) false ;; 184 | esac 185 | then 186 | arg=$( cygpath --path --ignore --mixed "$arg" ) 187 | fi 188 | # Roll the args list around exactly as many times as the number of 189 | # args, so each arg winds up back in the position where it started, but 190 | # possibly modified. 191 | # 192 | # NB: a `for` loop captures its iteration list before it begins, so 193 | # changing the positional parameters here affects neither the number of 194 | # iterations, nor the values presented in `arg`. 195 | shift # remove old arg 196 | set -- "$@" "$arg" # push replacement arg 197 | done 198 | fi 199 | 200 | 201 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 202 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 203 | 204 | # Collect all arguments for the java command; 205 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 206 | # shell script including quotes and variable substitutions, so put them in 207 | # double quotes to make sure that they get re-expanded; and 208 | # * put everything else in single quotes, so that it's not re-expanded. 209 | 210 | set -- \ 211 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 212 | -classpath "$CLASSPATH" \ 213 | org.gradle.wrapper.GradleWrapperMain \ 214 | "$@" 215 | 216 | # Stop when "xargs" is not available. 217 | if ! command -v xargs >/dev/null 2>&1 218 | then 219 | die "xargs is not available" 220 | fi 221 | 222 | # Use "xargs" to parse quoted args. 223 | # 224 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 225 | # 226 | # In Bash we could simply go: 227 | # 228 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 229 | # set -- "${ARGS[@]}" "$@" 230 | # 231 | # but POSIX shell has neither arrays nor command substitution, so instead we 232 | # post-process each arg (as a line of input to sed) to backslash-escape any 233 | # character that might be a shell metacharacter, then use eval to reverse 234 | # that process (while maintaining the separation between arguments), and wrap 235 | # the whole thing up as a single "set" statement. 236 | # 237 | # This will of course break if any of these variables contains a newline or 238 | # an unmatched quote. 239 | # 240 | 241 | eval "set -- $( 242 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 243 | xargs -n1 | 244 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 245 | tr '\n' ' ' 246 | )" '"$@"' 247 | 248 | exec "$JAVACMD" "$@" 249 | -------------------------------------------------------------------------------- /ballerina/Dependencies.toml: -------------------------------------------------------------------------------- 1 | # AUTO-GENERATED FILE. DO NOT MODIFY. 2 | 3 | # This file is auto-generated by Ballerina for managing dependency versions. 4 | # It should not be modified by hand. 5 | 6 | [ballerina] 7 | dependencies-toml-version = "2" 8 | distribution-version = "2201.8.0" 9 | 10 | [[package]] 11 | org = "ballerina" 12 | name = "auth" 13 | version = "2.10.0" 14 | dependencies = [ 15 | {org = "ballerina", name = "crypto"}, 16 | {org = "ballerina", name = "jballerina.java"}, 17 | {org = "ballerina", name = "lang.array"}, 18 | {org = "ballerina", name = "lang.string"}, 19 | {org = "ballerina", name = "log"} 20 | ] 21 | 22 | [[package]] 23 | org = "ballerina" 24 | name = "cache" 25 | version = "3.7.0" 26 | dependencies = [ 27 | {org = "ballerina", name = "constraint"}, 28 | {org = "ballerina", name = "jballerina.java"}, 29 | {org = "ballerina", name = "task"}, 30 | {org = "ballerina", name = "time"} 31 | ] 32 | 33 | [[package]] 34 | org = "ballerina" 35 | name = "constraint" 36 | version = "1.5.0" 37 | dependencies = [ 38 | {org = "ballerina", name = "jballerina.java"} 39 | ] 40 | 41 | [[package]] 42 | org = "ballerina" 43 | name = "crypto" 44 | version = "2.5.0" 45 | dependencies = [ 46 | {org = "ballerina", name = "jballerina.java"}, 47 | {org = "ballerina", name = "time"} 48 | ] 49 | modules = [ 50 | {org = "ballerina", packageName = "crypto", moduleName = "crypto"} 51 | ] 52 | 53 | [[package]] 54 | org = "ballerina" 55 | name = "file" 56 | version = "1.9.0" 57 | dependencies = [ 58 | {org = "ballerina", name = "io"}, 59 | {org = "ballerina", name = "jballerina.java"}, 60 | {org = "ballerina", name = "os"}, 61 | {org = "ballerina", name = "time"} 62 | ] 63 | 64 | [[package]] 65 | org = "ballerina" 66 | name = "http" 67 | version = "2.10.5" 68 | dependencies = [ 69 | {org = "ballerina", name = "auth"}, 70 | {org = "ballerina", name = "cache"}, 71 | {org = "ballerina", name = "constraint"}, 72 | {org = "ballerina", name = "crypto"}, 73 | {org = "ballerina", name = "file"}, 74 | {org = "ballerina", name = "io"}, 75 | {org = "ballerina", name = "jballerina.java"}, 76 | {org = "ballerina", name = "jwt"}, 77 | {org = "ballerina", name = "lang.array"}, 78 | {org = "ballerina", name = "lang.decimal"}, 79 | {org = "ballerina", name = "lang.int"}, 80 | {org = "ballerina", name = "lang.regexp"}, 81 | {org = "ballerina", name = "lang.runtime"}, 82 | {org = "ballerina", name = "lang.string"}, 83 | {org = "ballerina", name = "lang.value"}, 84 | {org = "ballerina", name = "log"}, 85 | {org = "ballerina", name = "mime"}, 86 | {org = "ballerina", name = "oauth2"}, 87 | {org = "ballerina", name = "observe"}, 88 | {org = "ballerina", name = "time"}, 89 | {org = "ballerina", name = "url"} 90 | ] 91 | modules = [ 92 | {org = "ballerina", packageName = "http", moduleName = "http"}, 93 | {org = "ballerina", packageName = "http", moduleName = "http.httpscerr"} 94 | ] 95 | 96 | [[package]] 97 | org = "ballerina" 98 | name = "io" 99 | version = "1.6.0" 100 | dependencies = [ 101 | {org = "ballerina", name = "jballerina.java"}, 102 | {org = "ballerina", name = "lang.value"} 103 | ] 104 | 105 | [[package]] 106 | org = "ballerina" 107 | name = "jballerina.java" 108 | version = "0.0.0" 109 | modules = [ 110 | {org = "ballerina", packageName = "jballerina.java", moduleName = "jballerina.java"} 111 | ] 112 | 113 | [[package]] 114 | org = "ballerina" 115 | name = "jwt" 116 | version = "2.10.0" 117 | dependencies = [ 118 | {org = "ballerina", name = "cache"}, 119 | {org = "ballerina", name = "crypto"}, 120 | {org = "ballerina", name = "jballerina.java"}, 121 | {org = "ballerina", name = "lang.int"}, 122 | {org = "ballerina", name = "lang.string"}, 123 | {org = "ballerina", name = "log"}, 124 | {org = "ballerina", name = "time"} 125 | ] 126 | 127 | [[package]] 128 | org = "ballerina" 129 | name = "lang.__internal" 130 | version = "0.0.0" 131 | dependencies = [ 132 | {org = "ballerina", name = "jballerina.java"}, 133 | {org = "ballerina", name = "lang.object"} 134 | ] 135 | 136 | [[package]] 137 | org = "ballerina" 138 | name = "lang.array" 139 | version = "0.0.0" 140 | dependencies = [ 141 | {org = "ballerina", name = "jballerina.java"}, 142 | {org = "ballerina", name = "lang.__internal"} 143 | ] 144 | modules = [ 145 | {org = "ballerina", packageName = "lang.array", moduleName = "lang.array"} 146 | ] 147 | 148 | [[package]] 149 | org = "ballerina" 150 | name = "lang.decimal" 151 | version = "0.0.0" 152 | dependencies = [ 153 | {org = "ballerina", name = "jballerina.java"} 154 | ] 155 | 156 | [[package]] 157 | org = "ballerina" 158 | name = "lang.error" 159 | version = "0.0.0" 160 | scope = "testOnly" 161 | dependencies = [ 162 | {org = "ballerina", name = "jballerina.java"} 163 | ] 164 | 165 | [[package]] 166 | org = "ballerina" 167 | name = "lang.int" 168 | version = "0.0.0" 169 | dependencies = [ 170 | {org = "ballerina", name = "jballerina.java"}, 171 | {org = "ballerina", name = "lang.__internal"}, 172 | {org = "ballerina", name = "lang.object"} 173 | ] 174 | 175 | [[package]] 176 | org = "ballerina" 177 | name = "lang.object" 178 | version = "0.0.0" 179 | 180 | [[package]] 181 | org = "ballerina" 182 | name = "lang.regexp" 183 | version = "0.0.0" 184 | dependencies = [ 185 | {org = "ballerina", name = "jballerina.java"} 186 | ] 187 | 188 | [[package]] 189 | org = "ballerina" 190 | name = "lang.runtime" 191 | version = "0.0.0" 192 | dependencies = [ 193 | {org = "ballerina", name = "jballerina.java"} 194 | ] 195 | modules = [ 196 | {org = "ballerina", packageName = "lang.runtime", moduleName = "lang.runtime"} 197 | ] 198 | 199 | [[package]] 200 | org = "ballerina" 201 | name = "lang.string" 202 | version = "0.0.0" 203 | dependencies = [ 204 | {org = "ballerina", name = "jballerina.java"}, 205 | {org = "ballerina", name = "lang.regexp"} 206 | ] 207 | modules = [ 208 | {org = "ballerina", packageName = "lang.string", moduleName = "lang.string"} 209 | ] 210 | 211 | [[package]] 212 | org = "ballerina" 213 | name = "lang.value" 214 | version = "0.0.0" 215 | dependencies = [ 216 | {org = "ballerina", name = "jballerina.java"} 217 | ] 218 | 219 | [[package]] 220 | org = "ballerina" 221 | name = "log" 222 | version = "2.9.0" 223 | dependencies = [ 224 | {org = "ballerina", name = "io"}, 225 | {org = "ballerina", name = "jballerina.java"}, 226 | {org = "ballerina", name = "lang.value"}, 227 | {org = "ballerina", name = "observe"} 228 | ] 229 | modules = [ 230 | {org = "ballerina", packageName = "log", moduleName = "log"} 231 | ] 232 | 233 | [[package]] 234 | org = "ballerina" 235 | name = "mime" 236 | version = "2.9.0" 237 | dependencies = [ 238 | {org = "ballerina", name = "io"}, 239 | {org = "ballerina", name = "jballerina.java"}, 240 | {org = "ballerina", name = "lang.int"} 241 | ] 242 | 243 | [[package]] 244 | org = "ballerina" 245 | name = "oauth2" 246 | version = "2.10.0" 247 | dependencies = [ 248 | {org = "ballerina", name = "cache"}, 249 | {org = "ballerina", name = "crypto"}, 250 | {org = "ballerina", name = "jballerina.java"}, 251 | {org = "ballerina", name = "log"}, 252 | {org = "ballerina", name = "time"}, 253 | {org = "ballerina", name = "url"} 254 | ] 255 | 256 | [[package]] 257 | org = "ballerina" 258 | name = "observe" 259 | version = "1.2.0" 260 | dependencies = [ 261 | {org = "ballerina", name = "jballerina.java"} 262 | ] 263 | 264 | [[package]] 265 | org = "ballerina" 266 | name = "os" 267 | version = "1.8.0" 268 | dependencies = [ 269 | {org = "ballerina", name = "io"}, 270 | {org = "ballerina", name = "jballerina.java"} 271 | ] 272 | modules = [ 273 | {org = "ballerina", packageName = "os", moduleName = "os"} 274 | ] 275 | 276 | [[package]] 277 | org = "ballerina" 278 | name = "regex" 279 | version = "1.4.3" 280 | dependencies = [ 281 | {org = "ballerina", name = "jballerina.java"}, 282 | {org = "ballerina", name = "lang.string"} 283 | ] 284 | modules = [ 285 | {org = "ballerina", packageName = "regex", moduleName = "regex"} 286 | ] 287 | 288 | [[package]] 289 | org = "ballerina" 290 | name = "task" 291 | version = "2.5.0" 292 | dependencies = [ 293 | {org = "ballerina", name = "jballerina.java"}, 294 | {org = "ballerina", name = "time"} 295 | ] 296 | 297 | [[package]] 298 | org = "ballerina" 299 | name = "test" 300 | version = "0.0.0" 301 | scope = "testOnly" 302 | dependencies = [ 303 | {org = "ballerina", name = "jballerina.java"}, 304 | {org = "ballerina", name = "lang.error"} 305 | ] 306 | modules = [ 307 | {org = "ballerina", packageName = "test", moduleName = "test"} 308 | ] 309 | 310 | [[package]] 311 | org = "ballerina" 312 | name = "time" 313 | version = "2.4.0" 314 | dependencies = [ 315 | {org = "ballerina", name = "jballerina.java"} 316 | ] 317 | modules = [ 318 | {org = "ballerina", packageName = "time", moduleName = "time"} 319 | ] 320 | 321 | [[package]] 322 | org = "ballerina" 323 | name = "url" 324 | version = "2.4.0" 325 | dependencies = [ 326 | {org = "ballerina", name = "jballerina.java"} 327 | ] 328 | modules = [ 329 | {org = "ballerina", packageName = "url", moduleName = "url"} 330 | ] 331 | 332 | [[package]] 333 | org = "ballerinai" 334 | name = "observe" 335 | version = "0.0.0" 336 | dependencies = [ 337 | {org = "ballerina", name = "jballerina.java"}, 338 | {org = "ballerina", name = "observe"} 339 | ] 340 | modules = [ 341 | {org = "ballerinai", packageName = "observe", moduleName = "observe"} 342 | ] 343 | 344 | [[package]] 345 | org = "ballerinax" 346 | name = "azure_cosmosdb" 347 | version = "4.2.0" 348 | dependencies = [ 349 | {org = "ballerina", name = "crypto"}, 350 | {org = "ballerina", name = "http"}, 351 | {org = "ballerina", name = "jballerina.java"}, 352 | {org = "ballerina", name = "lang.array"}, 353 | {org = "ballerina", name = "lang.runtime"}, 354 | {org = "ballerina", name = "lang.string"}, 355 | {org = "ballerina", name = "log"}, 356 | {org = "ballerina", name = "os"}, 357 | {org = "ballerina", name = "regex"}, 358 | {org = "ballerina", name = "test"}, 359 | {org = "ballerina", name = "time"}, 360 | {org = "ballerina", name = "url"}, 361 | {org = "ballerinai", name = "observe"}, 362 | {org = "ballerinax", name = "client.config"} 363 | ] 364 | modules = [ 365 | {org = "ballerinax", packageName = "azure_cosmosdb", moduleName = "azure_cosmosdb"} 366 | ] 367 | 368 | [[package]] 369 | org = "ballerinax" 370 | name = "client.config" 371 | version = "1.0.1" 372 | dependencies = [ 373 | {org = "ballerina", name = "http"}, 374 | {org = "ballerina", name = "oauth2"} 375 | ] 376 | modules = [ 377 | {org = "ballerinax", packageName = "client.config", moduleName = "client.config"} 378 | ] 379 | 380 | -------------------------------------------------------------------------------- /ballerina/constants.bal: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2021 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 2 | // 3 | // WSO2 Inc. licenses this file to you under the Apache License, 4 | // Version 2.0 (the "License"); you may not use this file except 5 | // in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, 11 | // software distributed under the License is distributed on an 12 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. See the License for the 14 | // specific language governing permissions and limitations 15 | // under the License. 16 | 17 | # The **Consistency Level Override** for document create and update. 18 | # 19 | # + STRONG - Users are always guaranteed to read the latest committed write 20 | # + BOUNDED - Reads might lag behind writes behind at most K updates of an item or by T time interval 21 | # + SESSION - Reads are guaranteed to honor the consistent-prefix, monotonic reads, monotonic writes, read-your-writes, 22 | # and write-follows-reads guarantees in a single client session 23 | # + EVENTUAL - No ordering guarantee for reads. In the absence of any further writes, the replicas eventually converge 24 | public enum ConsistencyLevel { 25 | STRONG = "Strong", 26 | BOUNDED_STALENESS = "BoundedStaleness", 27 | SESSION = "Session", 28 | EVENTUAL = "Eventual", 29 | CONSISTENT_PREFIX = "ConsistentPrefix" 30 | } 31 | 32 | # Whether to **include** or **exclude** the document in indexing. 33 | # 34 | # + INCLUDE - Adds the document to the index 35 | # + EXCLUDE - Omits the document from indexing 36 | public enum IndexingDirective { 37 | INCLUDE = "Include", 38 | EXCLUDE = "Exclude" 39 | } 40 | 41 | # Type of an Index. 42 | # 43 | # + HASH - Useful for equality comparisons 44 | # + RANGE - Useful for equality, range comparisons and sorting 45 | # + SPATIAL - Useful for spatial queries 46 | public enum IndexType { 47 | HASH = "Hash", 48 | RANGE = "Range", 49 | SPATIAL = "Spatial" 50 | } 51 | 52 | # Datatype for which the indexing behavior is applied to. 53 | # 54 | # + STRING - Represents a string data type 55 | # + NUMBER - Represents a numeric data type 56 | # + POINT - Represents a point data type 57 | # + POLYGON - Represents a polygon data type 58 | # + LINESTRING - Represents a line string data type 59 | public enum IndexDataType { 60 | STRING = "String", 61 | NUMBER = "Number", 62 | POINT = "Point", 63 | POLYGON = "Polygon", 64 | LINESTRING = "LineString" 65 | } 66 | 67 | # Mode of indexing for the container. 68 | # 69 | # + CONSISTENT - The index is updated synchronously as you create, update or delete items 70 | # + NONE - Indexing is disabled on the container 71 | public enum IndexingMode { 72 | CONSISTENT = "consistent", 73 | NONE = "none" 74 | } 75 | 76 | # Type of operation that invokes the trigger. 77 | # 78 | # + ALL - Trigger fires in all **create**, **replace** and **delete** operations 79 | # + CREATE - Trigger fires only in a **create** operations 80 | # + REPLACE - Trigger fires only in a **replace** operations 81 | # + DELETE - Trigger fires only in a **delete** operations 82 | public enum TriggerOperation { 83 | ALL = "All", 84 | CREATE = "Create", 85 | REPLACE = "Replace", 86 | DELETE = "Delete" 87 | } 88 | 89 | # When the trigger is fired. 90 | # 91 | # + PRE - Triggers fire before an operation 92 | # + POST - Triggers fires after an operation 93 | public enum TriggerType { 94 | PRE = "Pre", 95 | POST = "Post" 96 | } 97 | 98 | # Access mode for the resource. 99 | # 100 | # + ALL_PERMISSION - Provides **read**, **write**, and **delete** access to a resource 101 | # + READ_PERMISSION - Restricts the user to have only **read** access to the resource 102 | public enum PermisssionMode { 103 | ALL_PERMISSION = "All", 104 | READ_PERMISSION = "Read" 105 | } 106 | 107 | # Specific version for a given offer. 108 | # 109 | # + PRE_DEFINED - Represents pre-defined throughput levels 110 | # + USER_DEFINED - Represents user-defined throughput levels 111 | public enum OfferVersion { 112 | PRE_DEFINED = "V1", 113 | USER_DEFINED = "V2" 114 | } 115 | 116 | # Performance levels for a specific throughput level.
They depend on the Cosmos DB region which the container 117 | # belongs to and partitioning nature of the container (ie: single partitioned or multiple partitioned). 118 | # 119 | # + LEVEL_S1 - Performance level allows a low throughput and predefined amount of storage 120 | # + LEVEL_S2 - Performance level allows a medium throughput and predefined amount of storage 121 | # + LEVEL_S3 - Performance level allows a high throughput and predefined amount of storage 122 | # + INVALID - Performance level should set `Invalid` for `V2`, user-defined throughput levels 123 | public enum OfferType { 124 | LEVEL_S1 = "S1", 125 | LEVEL_S2 = "S2", 126 | LEVEL_S3 = "S3", 127 | INVALID = "Invalid" 128 | } 129 | 130 | # Incremental changes to documents within the collection. 131 | # 132 | # + INCREMENTAL - Provides a sorted list of documents that were changed in the order in which they were modified 133 | public enum ChangeFeedOption { 134 | INCREMENTAL = "Incremental feed" 135 | } 136 | 137 | # Version of the partition key if it is smaller than 100 bytes 138 | public const PARTITION_KEY_VERSION_1 = 1; 139 | 140 | # Version of the partition key if it is larger than 100 bytes 141 | public const PARTITION_KEY_VERSION_2 = 2; 142 | 143 | # Version of the partition key. 144 | public type PartitionKeyVersion PARTITION_KEY_VERSION_1|PARTITION_KEY_VERSION_2; 145 | 146 | # Used for partition key 147 | const PARTITIONING_ALGORITHM_TYPE_HASH = "Hash"; 148 | 149 | # Indexing Policy 150 | const INDEXING_TYPE_INCLUDE = "Include"; 151 | const INDEXING_TYPE_EXCLUDE = "Exclude"; 152 | const int MAX_PRECISION = -1; 153 | 154 | # Request headers 155 | const API_VERSION_HEADER = "x-ms-version"; 156 | const HOST_HEADER = "Host"; 157 | const ACCEPT_HEADER = "Accept"; 158 | const DATE_HEADER = "x-ms-date"; 159 | const THROUGHPUT_HEADER = "x-ms-offer-throughput"; 160 | const AUTOPILET_THROUGHPUT_HEADER = "x-ms-cosmos-offer-autopilot-settings"; 161 | const INDEXING_DIRECTIVE_HEADER = "x-ms-indexing-directive"; 162 | const IS_UPSERT_HEADER = "x-ms-documentdb-is-upsert"; 163 | const MAX_ITEM_COUNT_HEADER = "x-ms-max-item-count"; 164 | const CONSISTANCY_LEVEL_HEADER = "x-ms-consistency-level"; 165 | const A_IM_HEADER = "A-IM"; 166 | const PARTITIONKEY_RANGE_HEADER = "x-ms-documentdb-partitionkeyrangeid"; 167 | const ISQUERY_HEADER = "x-ms-documentdb-isquery"; 168 | const PARTITION_KEY_HEADER = "x-ms-documentdb-partitionkey"; 169 | const EXPIRY_HEADER = "x-ms-documentdb-expiry-seconds"; 170 | const IS_ENABLE_CROSS_PARTITION_HEADER = "x-ms-documentdb-query-enablecrosspartition"; 171 | 172 | # Values for request headers 173 | const CONTENT_TYPE_QUERY = "application/query+json"; 174 | const ACCEPT_ALL = "*/*"; 175 | const CONNECTION_KEEP_ALIVE = "keep-alive"; 176 | 177 | # Response headers 178 | const CONTINUATION_HEADER = "x-ms-continuation"; 179 | const SESSION_TOKEN_HEADER = "x-ms-session-token"; 180 | const REQUEST_CHARGE_HEADER = "x-ms-request-charge"; 181 | const RETRY_AFTER_MILLISECONDS = "x-ms-retry-after-ms"; 182 | const ITEM_COUNT_HEADER = "x-ms-item-count"; 183 | 184 | # Time Zone 185 | const GMT_ZONE = "Europe/London"; 186 | const TIME_ZONE_FORMAT = "E, dd MMM yyyy HH:mm:ss"; 187 | 188 | # Resources 189 | const RESOURCE_TYPE_DATABASES = "dbs"; 190 | const RESOURCE_TYPE_COLLECTIONS = "colls"; 191 | const RESOURCE_TYPE_DOCUMENTS = "docs"; 192 | const RESOURCE_TYPE_STORED_POCEDURES = "sprocs"; 193 | const RESOURCE_TYPE_PK_RANGES = "pkranges"; 194 | const RESOURCE_TYPE_UDF = "udfs"; 195 | const RESOURCE_TYPE_TRIGGER = "triggers"; 196 | const RESOURCE_TYPE_USER = "users"; 197 | const RESOURCE_TYPE_PERMISSION = "permissions"; 198 | const RESOURCE_TYPE_OFFERS = "offers"; 199 | 200 | # Cosmos DB SQL API version 201 | const API_VERSION = "2018-12-31"; 202 | 203 | # Token information 204 | const TOKEN_TYPE_MASTER = "master"; 205 | const TOKEN_TYPE_RESOURCE = "resource"; 206 | const TOKEN_VERSION = "1.0"; 207 | 208 | # Encoding types 209 | const UTF8_URL_ENCODING = "UTF-8"; 210 | 211 | # Error messages 212 | const MINIMUM_MANUAL_THROUGHPUT_ERROR = "The minimum manual throughput is 400 RU/s"; 213 | const SETTING_BOTH_VALUES_ERROR = "Cannot set both throughput and maxThroughput headers at once"; 214 | const NULL_PARTITIONKEY_VALUE_ERROR = "Partition key values are null"; 215 | const INDEXING_DIRECTIVE_ERROR = "Indexing directive should be either Exclude or Include"; 216 | const CONSISTANCY_LEVEL_ERROR = "Consistency level should be one of Strong, Bounded, Session, or Eventual"; 217 | const VALIDITY_PERIOD_ERROR = "Resource token validity period must be between 3600 and 18000"; 218 | const MASTER_KEY_ERROR = "Enter a valid master key and token type should be master key"; 219 | const JSON_PAYLOAD_ACCESS_ERROR = "Error occurred while accessing the JSON payload of the response"; 220 | const REST_API_INVOKING_ERROR = "Error occurred while invoking the REST API"; 221 | const NULL_RESOURCE_TYPE_ERROR = "ResourceType is incorrect/null"; 222 | const NULL_DATE_ERROR = "Date is invalid/null"; 223 | const NULL_AUTHORIZATION_SIGNATURE_ERROR = "Authorization token is null"; 224 | const DECODING_ERROR = "Base64 Decoding error"; 225 | const TIME_STRING_ERROR = "Time is not correct"; 226 | const INVALID_RESPONSE_PAYLOAD_ERROR = "Invalid response payload"; 227 | const INVALID_RECORD_TYPE_ERROR = "Invalid record type"; 228 | const STREAM_IS_NOT_TYPE_ERROR = "The stream is not type"; 229 | const INVALID_STREAM_TYPE = "Invalid stream type"; 230 | const AZURE_ERROR = "Error occured"; 231 | const PAYLOAD_IS_NOT_JSON_ERROR = "Request payload is not json"; 232 | const EMPTY_BASE_URL_ERROR = "Base URL cannot be empty"; 233 | const EMPTY_MASTER_TOKEN_ERROR = "Master token cannot be empty"; 234 | const INVALID_MASTER_TOKEN_ERROR = "Master token is not valid"; 235 | 236 | # JSON keys in response 237 | const JSON_KEY_ID = "id"; 238 | const JSON_KEY_RESOURCE_ID = "_rid"; 239 | const JSON_KEY_SELF_REFERENCE = "_self"; 240 | const JSON_KEY_ETAG = "_etag"; 241 | const JSON_KEY_TIMESTAMP = "_ts"; 242 | const JSON_KEY_ATTACHMENTS = "_attachments"; 243 | const JSON_KEY_DOCUMENTS = "Documents"; 244 | const JSON_KEY_OFFERS = "Offers"; 245 | 246 | # Fields in record types 247 | const JSON_KEY_PERMISSIONMODE = "permissionMode"; 248 | const JSON_KEY_RESOURCE = "resource"; 249 | const JSON_KEY_OFFER_RESOURCE_ID = "offerResourceId"; 250 | const JSON_KEY_OFFER_TYPE = "offerType"; 251 | const JSON_KEY_OFFER_VERSION = "offerVersion"; 252 | const JSON_KEY_CONTENT = "content"; 253 | 254 | # Property in record type representing headers 255 | const RESPONSE_HEADERS = "reponseMetadata"; 256 | 257 | # Elements in an error response 258 | const ACTIVITY_ID = "ActivityId"; 259 | const STATUS = "status"; 260 | const STATUS_NOT_FOUND_STRING = "404"; 261 | 262 | # Numeric constants 263 | const MIN_REQUEST_UNITS = 400; 264 | const MIN_TIME_TO_LIVE_IN_SECONDS = 3600; 265 | const MAX_TIME_TO_LIVE_IN_SECONDS = 18000; 266 | 267 | # String constants 268 | const SPACE_STRING = " "; 269 | const COLON_WITH_SPACE = " : "; 270 | const FORWARD_SLASH = "/"; 271 | const EMPTY_STRING = ""; 272 | const NEW_LINE = "\n"; 273 | const HTTPS_REGEX = "^(https):#"; 274 | const TRUE = "true"; 275 | const EMPTY_ARRAY_STRING = "[]"; 276 | --------------------------------------------------------------------------------