Skip to content

Commit

Permalink
init db script (#2)
Browse files Browse the repository at this point in the history
* init db script

* fix readme
  • Loading branch information
pasqualespica authored Jun 16, 2022
1 parent 06e4a35 commit 182e9f0
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 4 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
target/**/*
.vscode
/.idea/
emulatorcert.crt
emulatorcert.crt
.env
15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,18 @@ The easiest way to develop locally is start only db container and run spring-boo
### Configure Cosmos emulator
Launch the script in `utilities` folder:

`
sh cosmos.sh <port> <java_home>
`

To start CosmosDB
```sh
sh cosmos_start.sh <port> <java_home>
```

To init db/containers
```py
python cosmos_init_db.py
```
> NOTE : install `pip install python-dotenv && pip install azure-cosmos` and copy env file `cp .env.exmaple .env`
### Testing 🧪

#### Unit testing
Expand Down
5 changes: 5 additions & 0 deletions utilities/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
URI=https://localhost:8081
PRIMARY_KEY=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==
DB_NAME=db
CONTAINER_NAMES=creditor_institutions,services
PARTITION_KEYS=fiscalCode,transferCategory
41 changes: 41 additions & 0 deletions utilities/cosmos_init_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from azure.cosmos import exceptions, CosmosClient, PartitionKey
import os
from dotenv import load_dotenv

load_dotenv()

URI = os.getenv('URI')
PRIMARY_KEY = os.getenv('PRIMARY_KEY')
DB_NAME = os.getenv('DB_NAME')
CONTAINER_NAMES = os.getenv('CONTAINER_NAMES')
PARTITION_KEYS = os.getenv('PARTITION_KEYS')

# Initialize the Cosmos client
endpoint = URI
key = PRIMARY_KEY

# <create_cosmos_client>
client = CosmosClient(endpoint, key)
# </create_cosmos_client>

# Create a database
# <create_database_if_not_exists>
database_name = DB_NAME
database = client.create_database_if_not_exists(id=database_name)
# </create_database_if_not_exists>

# Create a container
# Using a good partition key improves the performance of database operations.
# <create_container_if_not_exists>
container_names = CONTAINER_NAMES.split(',')
partition_keys = PARTITION_KEYS.split(',')

containers_infra = zip(container_names, partition_keys)

for container in containers_infra:
container = database.create_container_if_not_exists(
id=container[0], # container name
partition_key=PartitionKey(path=f"/{container[1]}"),
offer_throughput=400
)
# </create_container_if_not_exists>
File renamed without changes.

0 comments on commit 182e9f0

Please sign in to comment.