### Python: Database Connection and Client Setup Source: https://context7.com/scylladb/care-pet/llms.txt Demonstrates how to set up a ScyllaDB client in Python using the cassandra-driver with token-aware load balancing. ```APIDOC ## Python ScyllaDB Client ### Description This Python class `ScyllaClient` provides a robust way to connect to ScyllaDB, manage sessions, and perform database operations. It utilizes the `cassandra-driver` with token-aware load balancing and supports batch inserts and fetching data for owners, pets, and sensors. ### Usage Example ```python from cassandra.cluster import Cluster, ExecutionProfile, EXEC_PROFILE_DEFAULT from cassandra.policies import DCAwareRoundRobinPolicy, TokenAwarePolicy from cassandra.auth import PlainTextAuthProvider from cassandra.query import BatchStatement, dict_factory from cassandra import ConsistencyLevel import uuid class ScyllaClient(): def __init__(self, config): self.cluster = self._get_cluster(config) self.session = self.cluster.connect() def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.shutdown() def shutdown(self): self.cluster.shutdown() def _get_cluster(self, config): profile = ExecutionProfile( load_balancing_policy=TokenAwarePolicy( DCAwareRoundRobinPolicy(local_dc=config["datacenter"]) ), row_factory=dict_factory ) return Cluster( execution_profiles={EXEC_PROFILE_DEFAULT: profile}, contact_points=[config["hosts"]], auth_provider=PlainTextAuthProvider( username=config["username"], password=config["password"] ) ) def insert_batch_data(self, table, data_list): columns = list(data_list[0].keys()) insert_batch_query = self.session.prepare(f""" INSERT INTO {table} ({','.join(columns)}) VALUES ({','.join(['?' for c in columns])}) """) batch = BatchStatement(consistency_level=ConsistencyLevel.QUORUM) for data_dict in data_list: batch.add(insert_batch_query, list(data_dict.values())) self.session.execute(batch) def fetch_owner(self, owner_id): query = "SELECT * FROM carepet.owner WHERE owner_id = %s;" return self.session.execute(query, (uuid.UUID(owner_id), )) def fetch_pets(self, owner_id): query = "SELECT * FROM carepet.pet WHERE owner_id = %s;" return self.session.execute(query, (uuid.UUID(owner_id), )) def fetch_sensors(self, pet_id): query = "SELECT * FROM carepet.sensor WHERE pet_id = %s;" return self.session.execute(query, (uuid.UUID(pet_id), )) # Usage example with ScyllaClient({"hosts": "127.0.0.1", "datacenter": "datacenter1", "username": "user", "password": "pass"}) as client: owner = client.fetch_owner("a05fd0df-0f97-4eec-a211-cad28a6e5360") pets = client.fetch_pets("a05fd0df-0f97-4eec-a211-cad28a6e5360") ``` ``` -------------------------------- ### Start and Manage Local ScyllaDB Cluster with Docker Source: https://context7.com/scylladb/care-pet/llms.txt This snippet shows how to start a ScyllaDB cluster using Docker Compose, check its status, and access the CQLSH shell for direct database interaction. It also includes commands to run Go applications for database migrations and sensor simulation. ```bash # Start the cluster docker-compose up -d # Wait for cluster to be ready, then check status docker exec -it carepet-scylla1 nodetool status # Run database migrations (Go example) docker exec -it go-app run ./cmd/migrate # Start sensor simulator docker exec -it go-app run ./cmd/sensor # Start REST API server docker exec -it go-app run ./cmd/server --port 8000 # Access CQLSH for direct database queries docker exec -it carepet-scylla1 cqlsh ``` -------------------------------- ### Docker Compose Setup for ScyllaDB and PHP Environment Source: https://github.com/scylladb/care-pet/blob/master/docs/build-with-php.md This command initiates a local ScyllaDB cluster with three nodes and the PHP environment using Docker and Docker Compose. It requires Docker and Docker Compose to be installed. ```shell $ docker-compose up -d ``` -------------------------------- ### Start Care Pet Server Source: https://github.com/scylladb/care-pet/blob/master/docs/build-with-rust.md Commands to start the Care Pet server service. It first retrieves the IP address of the ScyllaDB node and then runs the Cargo project with the database host as an argument. ```bash NODE1=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' carepet-scylla1) cargo run -- --hosts $NODE1 ``` -------------------------------- ### Initialize ScyllaDB Database Schema with Go Source: https://github.com/scylladb/care-pet/blob/master/go/README.md This Go command initializes the ScyllaDB database by creating the 'carepet' keyspace and necessary tables. It requires Go and Docker to be installed. The output confirms the successful creation of keyspace and table metadata. ```bash docker exec -it go-app run ./cmd/migrate ``` -------------------------------- ### Initialize NodeJS Project and Install Cassandra Driver Source: https://github.com/scylladb/care-pet/blob/master/javascript/README.md This snippet shows the command-line steps to create a new NodeJS project, initialize npm, and install the necessary Cassandra driver for ScyllaDB interaction. ```bash mkdir project_name && cd project_name && npm init npm install cassandra-driver ``` -------------------------------- ### Start and Test REST API Server Source: https://github.com/scylladb/care-pet/blob/master/python/README.md Instructions on how to start the REST API server and verify its functionality. ```APIDOC ## Start and Test REST API Server ### Description Starts the REST API server and provides a basic test to ensure it is running correctly. ### Start Server Command ```bash source env/bin/activate NODE1=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' carepet-scylla1) python src/api.py -h $NODE1 ``` ### Server Information - The API server runs on `http://127.0.0.1:8000`. - Ensure port 8000 is free before starting. ### Test Server Command ```bash curl http://127.0.0.1:8000 ``` ### Expected Response ```json {"message":"Pet collar simulator API"} ``` ``` -------------------------------- ### Start the Care Pet PHP REST API Service Source: https://github.com/scylladb/care-pet/blob/master/docs/build-with-php.md This command starts the built-in PHP development server, making the Care Pet REST API accessible. It indicates the service is running and provides the local development URL. ```shell $ php scylla serve [INFO] CarePet Web started! [INFO] Development Server: http://0.0.0.0:8000 [Thu Jan 5 17:32:01 2023] PHP 7.4.33 Development Server (http://0.0.0.0:8000) started ``` -------------------------------- ### Go: Database Connection with gocqlx Source: https://context7.com/scylladb/care-pet/llms.txt Provides an example of connecting to ScyllaDB using the scylladb/gocqlx driver in Go, including ORM support and query builders. ```APIDOC ## Go ScyllaDB Client with gocqlx ### Description This Go program demonstrates how to connect to ScyllaDB using the `scylladb/gocqlx` library, which offers ORM capabilities and query builders for streamlined database interactions. It includes examples for defining table metadata, creating a session, querying data using the ORM, and executing raw CQL queries. ### Usage Example ```go package main import ( "log" "github.com/gocql/gocql" "github.com/scylladb/gocqlx/v2" "github.com/scylladb/gocqlx/v2/table" ) // Define table metadata for ORM var ownerMetadata = table.Metadata{ Name: "owner", Columns: []string{"owner_id", "address", "name"}, PartKey: []string{"owner_id"}, } var TableOwner = table.New(ownerMetadata) // Owner model type Owner struct { OwnerID gocql.UUID `db:"owner_id"` Address string `db:"address"` Name string `db:"name"` } func main() { // Create cluster configuration cfg := gocql.NewCluster("127.0.0.1") cfg.Keyspace = "carepet" // Create session with gocqlx wrapper session, err := gocqlx.WrapSession(cfg.CreateSession()) if err != nil { log.Fatal("Failed to create session:", err) } defer session.Close() // Query using ORM var owner Owner id, _ := gocql.ParseUUID("a05fd0df-0f97-4eec-a211-cad28a6e5360") err = TableOwner.GetQuery(session).Bind(id).GetRelease(&owner) if err == gocql.ErrNotFound { log.Println("Owner not found") } else if err != nil { log.Fatal("Query error:", err) } log.Printf("Owner: %+v\n", owner) // Raw CQL query iter := session.Session.Query("SELECT * FROM pet WHERE owner_id = ?", id).Iter() for { var petID gocql.UUID var name string if !iter.Scan(&petID, &name) { break } log.Printf("Pet: %s - %s\n", petID, name) } if err := iter.Close(); err != nil { log.Fatal("Iterator error:", err) } } ``` ``` -------------------------------- ### Start Pet Health Tracking REST API with Go Source: https://github.com/scylladb/care-pet/blob/master/go/README.md This Go command starts the REST API service for the Care Pet application, allowing users to track pet health states. It requires the 'sensor' component to be running and data to be present in ScyllaDB. The service listens on a specified port, defaulting to 8000. ```bash docker exec -it go-app run ./cmd/server --port 8000 ``` -------------------------------- ### Python: Database Connection and Client Setup Source: https://context7.com/scylladb/care-pet/llms.txt Sets up a ScyllaDB client in Python using the 'cassandra-driver'. It configures token-aware load balancing for optimal performance and provides methods for inserting batched data and fetching owner, pet, and sensor information. The client supports context management for automatic shutdown. ```python from cassandra.cluster import Cluster, ExecutionProfile, EXEC_PROFILE_DEFAULT from cassandra.policies import DCAwareRoundRobinPolicy, TokenAwarePolicy from cassandra.auth import PlainTextAuthProvider from cassandra.query import BatchStatement, dict_factory from cassandra import ConsistencyLevel import uuid class ScyllaClient(): def __init__(self, config): self.cluster = self._get_cluster(config) self.session = self.cluster.connect() def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.shutdown() def shutdown(self): self.cluster.shutdown() def _get_cluster(self, config): profile = ExecutionProfile( load_balancing_policy=TokenAwarePolicy( DCAwareRoundRobinPolicy(local_dc=config["datacenter"]) ), row_factory=dict_factory ) return Cluster( execution_profiles={EXEC_PROFILE_DEFAULT: profile}, contact_points=[config["hosts"]], auth_provider=PlainTextAuthProvider( username=config["username"], password=config["password"] ) ) def insert_batch_data(self, table, data_list): columns = list(data_list[0].keys()) insert_batch_query = self.session.prepare(f""" INSERT INTO {table} ({','.join(columns)}) VALUES ({','.join(['?' for c in columns])}) """) batch = BatchStatement(consistency_level=ConsistencyLevel.QUORUM) for data_dict in data_list: batch.add(insert_batch_query, list(data_dict.values())) self.session.execute(batch) def fetch_owner(self, owner_id): query = "SELECT * FROM carepet.owner WHERE owner_id = %s;" return self.session.execute(query, (uuid.UUID(owner_id), )) def fetch_pets(self, owner_id): query = "SELECT * FROM carepet.pet WHERE owner_id = %s;" return self.session.execute(query, (uuid.UUID(owner_id), )) def fetch_sensors(self, pet_id): query = "SELECT * FROM carepet.sensor WHERE pet_id = %s;" return self.session.execute(query, (uuid.UUID(pet_id), )) # Usage example with ScyllaClient({"hosts": "127.0.0.1", "datacenter": "datacenter1", "username": "user", "password": "pass"}) as client: owner = client.fetch_owner("a05fd0df-0f97-4eec-a211-cad28a6e5360") pets = client.fetch_pets("a05fd0df-0f97-4eec-a211-cad28a6e5360") ``` -------------------------------- ### Simulate Environment Sensors using PHP CLI Source: https://github.com/scylladb/care-pet/blob/master/docs/build-with-php.md This command initiates the sensor simulation process. It starts by displaying informational messages and then proceeds to generate and process batches of fake owner, pet, and sensor data. The simulation relies on repositories for data persistence and factories for data generation. ```shell $ php scylla simulate [INFO] Starting Sensor simulator... [INFO] Batch: 0 [INFO] Owner 593dec12-6bea-3c93-8f49-26d8b6d589b1 [INFO] Pet: 14d9f304-5600-34af-8622-3d4505d617d7 | Owner 593dec12-6bea-3c93-8f49-26d8b6d589b1 [INFO] Sensor: 869bd01e-e0ba-364f-bbfb-8c7c496a3318 (R) | Pet 14d9f304-5600-34af-8622-3d4505d617d7 [INFO] Sensor: c86f63b0-1439-3404-8750-b71b90a685cb (L) | Pet 14d9f304-5600-34af-8622-3d4505d617d7 [INFO] Sensor: e0550426-8832-3d17-9025-77726b3009c5 (P) | Pet 14d9f304-5600-34af-8622-3d4505d617d7 [INFO] Sensor: bf960c81-8e0f-3012-b50d-18596b50db18 (P) | Pet 14d9f304-5600-34af-8622-3d4505d617d7 [INFO] Sensor: 933245de-812e-34e4-8d50-2ab072726217 (T) | Pet 14d9f304-5600-34af-8622-3d4505d617d7 [INFO] Pet: 319ec566-d6b0-3868-ac5e-76253ee7c236 | Owner 593dec12-6bea-3c93-8f49-26d8b6d589b1 [INFO] ... ``` -------------------------------- ### Start CarePet Web Server (.NET) Source: https://github.com/scylladb/care-pet/blob/master/csharp/README.md This command starts the CarePet web server using the .NET CLI. It specifies the project to run and the host and datacenter configurations. The server will be accessible via HTTP. ```bash $ dotnet run --project CarePet.csproj --hosts $NODE1 --datacenter datacenter1 ``` -------------------------------- ### Start Pet Collar Simulation Source: https://github.com/scylladb/care-pet/blob/master/javascript/README.md Starts the pet collar simulation service, which generates and sends sensor data to the ScyllaDB database. It requires the IP address of a ScyllaDB node and configuration for measurement and buffer intervals. ```bash NODE1=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' carepet-scylla1) npm run sensor -- --hosts $NODE1 --measure 5s --buffer-interval 1m --datacenter datacenter1 ``` -------------------------------- ### Execute CQL Commands with ScyllaDB Driver Source: https://github.com/scylladb/care-pet/blob/master/java/README.md This Java example demonstrates various ways to execute CQL commands using the ScyllaDB driver, including direct execution of strings, using prepared statements for efficiency, and fetching results. ```java import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.CqlSessionBuilder; import com.datastax.oss.driver.api.core.cql.PreparedStatement;import com.datastax.oss.driver.api.core.cql.ResultSet; import com.datastax.oss.driver.api.core.cql.Row; class Example { public static void main(String []args) { CqlSession session = CqlSession.builder().build(); session.execute("INSERT INTO table VALUE(1, 2, 3)"); // or PreparedStatement statement = session.prepare("INSERT INTO table VALUE(?, ?, ?)"); session.execute(statement.bind(1, 2, 3)); // or ResultSet s = session.execute("SELECT * FROM table"); for (Row r: s) { // r.get() } } } ``` -------------------------------- ### Rust: Main Migration Function Source: https://github.com/scylladb/care-pet/blob/master/docs/build-with-rust.md The `main` function in `bin/migrate/main.rs` orchestrates the database setup. It initializes logging, parses application arguments, establishes a new database session using `db::new_session`, and then calls `db::create_keyspace` and `db::migrate` to set up the schema. ```rust // migrate/main.rs async fn main() -> Result<()> { care_pet::log::init(); let app = App::from_args(); debug!("Configuration = {:?}", app); info!("Bootstrapping database..."); let sess = db::new_session(&app.db_config).await?; db::create_keyspace(&sess).await?; db::migrate(&sess).await?; Ok(()) } ``` -------------------------------- ### Docker Compose Local ScyllaDB Cluster Setup Source: https://context7.com/scylladb/care-pet/llms.txt Sets up a three-node ScyllaDB cluster locally using Docker Compose. This configuration is suitable for development and testing purposes, allowing easy deployment and management of a distributed ScyllaDB environment. It specifies image versions, ports, memory allocation, and inter-node communication via seeds. ```yaml # docker-compose.yml version: "3" services: carepet-scylla1: container_name: carepet-scylla1 image: scylladb/scylla:5.1 ports: - "9042:9042" command: --smp 1 --memory 750M --overprovisioned 1 --api-address 0.0.0.0 carepet-scylla2: container_name: carepet-scylla2 image: scylladb/scylla:5.1 command: --smp 1 --memory 750M --overprovisioned 1 --api-address 0.0.0.0 --seeds carepet-scylla1 depends_on: - carepet-scylla1 carepet-scylla3: container_name: carepet-scylla3 image: scylladb/scylla:5.1 command: --smp 1 --memory 750M --overprovisioned 1 --api-address 0.0.0.0 --seeds carepet-scylla1 depends_on: - carepet-scylla1 ``` -------------------------------- ### Initialize and Run Sensor Service Main Function Source: https://github.com/scylladb/care-pet/blob/master/docs/build-with-rust.md The main function for the sensor service initializes logging, parses application arguments, establishes a database connection, generates initial owner and pet data, saves it, and then starts the continuous sensor data collection and saving process. ```rust // sensor/main.rs #[tokio::main] async fn main() -> Result<()> { care_pet::log::init(); let app = App::from_args(); debug!("Configuration = {:?}", &app); info!("Welcome to the Pet collar simulator"); let sess = db::new_session_with_keyspace(&app.db_config).await?; let (owner, pet, sensors) = random_data(); save_data(&sess, &owner, &pet, &sensors).await?; run_sensor_data(&app, &sess, sensors).await?; Ok(()) } ``` -------------------------------- ### Configure ScyllaDB Connection in PHP Environment Source: https://github.com/scylladb/care-pet/blob/master/docs/build-with-php.md This snippet shows how to copy the example environment file and configure ScyllaDB connection details for local development or ScyllaDB Cloud. It specifies keyspace, nodes, username, password, and port. ```shell $ cp .env.example .env ``` ```dotenv # Development DB_KEYSPACE="carepet" DB_NODES="localhost" DB_USERNAME="" DB_PASSWORD="" DB_PORT=9042 # Production (Cloud) #DB_KEYSPACE="carepet" #DB_NODES="node-0.aws_sa_east_1.c106d1ac5f3117a20bf0.clusters.scylla.cloud" #DB_USERNAME="scylla" #DB_PASSWORD="p50bonFq8cuxwXS" #DB_PORT=9042 ``` -------------------------------- ### Clone Repository and Install Dependencies (Bash) Source: https://github.com/scylladb/care-pet/blob/master/docs/build-with-python.md This snippet demonstrates how to clone the ScyllaDB Care Pet repository, navigate to the Python directory, create and activate a virtual environment, and install project dependencies using pip. ```bash git clone https://github.com/scylladb/care-pet cd care-pet/python virtualenv env source env/bin/activate pip install -r requirements.txt ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/scylladb/care-pet/blob/master/docs/build-with-javascript.md Installs all necessary Node.js dependencies for the project. This command should be run after cloning the repository and navigating to the project's JavaScript directory. ```bash npm install ``` -------------------------------- ### Start REST API Server Source: https://github.com/scylladb/care-pet/blob/master/rust/README.md This command starts the REST API server for the Care Pet project. The server will connect to the ScyllaDB cluster and is typically accessible on port 8000. ```bash cargo run server ``` -------------------------------- ### Run Sensor Service with Docker and Cargo Source: https://github.com/scylladb/care-pet/blob/master/docs/build-with-rust.md This command starts the sensor service using Docker to get the ScyllaDB node IP and then runs the Rust binary with specified measurement and buffer intervals. ```bash NODE1=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' carepet-scylla1) cargo run --bin sensor -- --hosts $NODE1 --measure 5s --buffer-interval 1m ``` -------------------------------- ### Running Help for ScyllaDB C# Driver Commands Source: https://github.com/scylladb/care-pet/blob/master/csharp/README.md This example shows how to run the help command for different projects within the ScyllaDB CarePet repository, utilizing the ScyllaDB C# driver. It demonstrates how to view all available options for each command. ```bash dotnet run --project CarePet.Migrate.csproj --help dotnet run --project CarePet.Sensor.csproj --help dotnet run --project CarePet.csproj --help ``` -------------------------------- ### Go Module Initialization and Dependency Management Source: https://github.com/scylladb/care-pet/blob/master/go/README.md This snippet shows the commands to initialize a new Go module and add the ScyllaDB gocqlx driver as a dependency. It includes updating the `go.mod` file to use a specific version of the gocql driver. ```bash $ go mod init github.com/my_name/my_module $ go get -u github.com/scylladb/gocqlx/v2 # Example go.mod content after get: # module github.com/blah/blah # # go 1.14 # # require ( # github.com/gocql/gocql v0.0.0-20200624222514-34081eda590e // indirect # github.com/scylladb/gocqlx/v2 v2.1.0 // indirect # ) # Add gocql driver replacement: # replace github.com/gocql/gocql => github.com/scylladb/gocql v1.4.0 # Example go.mod content after replace: # module github.com/blah/blah # # go 1.14 # # require ( # github.com/gocql/gocql v0.0.0-20200624222514-34081eda590e // indirect # github.com/scylladb/gocqlx/v2 v2.1.0 // indirect # ) # # replace github.com/gocql/gocql => github.com/scylladb/gocql v1.4.0 ``` -------------------------------- ### Get Owner Data Source: https://github.com/scylladb/care-pet/blob/master/go/README.md Retrieves detailed information about a specific owner using their unique owner ID. ```APIDOC ## GET /api/owner/{owner_id} ### Description Retrieves the details of a specific owner. ### Method GET ### Endpoint `/api/owner/{owner_id}` ### Parameters #### Path Parameters - **owner_id** (string) - Required - The unique identifier for the owner. ### Request Example ```bash curl http://127.0.0.1:8000/api/owner/a05fd0df-0f97-4eec-a211-cad28a6e5360 ``` ### Response #### Success Response (200) - **owner_id** (string) - The unique identifier for the owner. - **name** (string) - The name of the owner. - **address** (string) - The address of the owner. #### Response Example ```json { "address": "home", "name": "gmwjgsap", "owner_id": "a05fd0df-0f97-4eec-a211-cad28a6e5360" } ``` ``` -------------------------------- ### Get Daily Sensor Average Source: https://github.com/scylladb/care-pet/blob/master/go/README.md Retrieves the daily average of sensor measurements for a specific sensor on a given date. ```APIDOC ## GET /api/sensor/{sensor_id}/values/day/{date} ### Description Retrieves the daily average of sensor measurements for a specific sensor on a given date. ### Method GET ### Endpoint `/api/sensor/{sensor_id}/values/day/{date}` ### Parameters #### Path Parameters - **sensor_id** (string) - Required - The unique identifier for the sensor. - **date** (string) - Required - The date for which to retrieve the daily average, in `YYYY-MM-DD` format. ### Request Example ```bash curl http://127.0.0.1:8000/api/sensor/5a9da084-ea49-4ab1-b2f8-d3e3d9715e7d/values/day/2020-08-06 ``` ### Response #### Success Response (200) - **daily_average** (array of numbers) - A list representing the hourly average values for the day. The array typically contains 24 elements, one for each hour. #### Response Example ```json [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42.55736 // ... potentially more values if the day spans more than 24 hours or includes partial hours ] ``` ``` -------------------------------- ### Get Sensor Values Source: https://github.com/scylladb/care-pet/blob/master/go/README.md Retrieves sensor measurement values for a given sensor within a specified time range. ```APIDOC ## GET /api/sensor/{sensor_id}/values ### Description Retrieves sensor measurement values for a specific sensor within a given time range. ### Method GET ### Endpoint `/api/sensor/{sensor_id}/values` ### Parameters #### Path Parameters - **sensor_id** (string) - Required - The unique identifier for the sensor. #### Query Parameters - **from** (string) - Required - The start of the time range in ISO 8601 format (e.g., `YYYY-MM-DDTHH:mm:ssZ`). - **to** (string) - Required - The end of the time range in ISO 8601 format (e.g., `YYYY-MM-DDTHH:mm:ssZ`). ### Request Example ```bash curl "http://127.0.0.1:8000/api/sensor/5a9da084-ea49-4ab1-b2f8-d3e3d9715e7d/values?from=\"2020-08-06T00:00:00Z\"&to=\"2020-08-06T23:59:59Z\"" ``` ### Response #### Success Response (200) - **values** (array of numbers) - A list of sensor measurement values. #### Response Example ```json [ 51.360596, 26.737432, 77.88015 // ... more values ] ``` ``` -------------------------------- ### Go: Database Connection with gocqlx Source: https://context7.com/scylladb/care-pet/llms.txt Establishes a ScyllaDB connection in Go using the 'scylladb/gocqlx' driver, which offers ORM capabilities and query builders. This example demonstrates defining table metadata, creating a client session, querying data using the ORM, and executing raw CQL queries. ```go package main import ( "log" "github.com/gocql/gocql" "github.com/scylladb/gocqlx/v2" "github.com/scylladb/gocqlx/v2/table" ) // Define table metadata for ORM var ownerMetadata = table.Metadata{ Name: "owner", Columns: []string{"owner_id", "address", "name"}, PartKey: []string{"owner_id"}, } var TableOwner = table.New(ownerMetadata) // Owner model type Owner struct { OwnerID gocql.UUID `db:"owner_id"` Address string `db:"address"` Name string `db:"name"` } func main() { // Create cluster configuration cfg := gocql.NewCluster("127.0.0.1") cfg.Keyspace = "carepet" // Create session with gocqlx wrapper session, err := gocqlx.WrapSession(cfg.CreateSession()) if err != nil { log.Fatal("Failed to create session:", err) } defer session.Close() // Query using ORM var owner Owner id, _ := gocql.ParseUUID("a05fd0df-0f97-4eec-a211-cad28a6e5360") err = TableOwner.GetQuery(session).Bind(id).GetRelease(&owner) if err == gocql.ErrNotFound { log.Println("Owner not found") } else if err != nil { log.Fatal("Query error:", err) } log.Printf("Owner: %+v\n", owner) // Raw CQL query iter := session.Session.Query("SELECT * FROM pet WHERE owner_id = ?", id).Iter() for { var petID gocql.UUID var name string if !iter.Scan(&petID, &name) { break } log.Printf("Pet: %s - %s\n", petID, name) } if err := iter.Close(); err != nil { log.Fatal("Iterator error:", err) } } ``` -------------------------------- ### Get Daily Average Sensor Values Source: https://github.com/scylladb/care-pet/blob/master/java/README.md Retrieves the daily average of sensor measurements for a specific sensor on a given date. ```APIDOC ## GET /api/sensor/{sensor_id}/values/day/{date} ### Description Retrieves the daily average of sensor measurements for a specific sensor on a particular date. ### Method GET ### Endpoint /api/sensor/{sensor_id}/values/day/{date} #### Path Parameters - **sensor_id** (string) - Required - The unique identifier for the sensor. - **date** (string) - Required - The date for which to retrieve the daily average, in `YYYY-MM-DD` format (e.g., `2020-09-11`). ### Response #### Success Response (200) - An array of numerical values representing the hourly averages for the specified day. #### Response Example ```json [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 37.0] ``` ``` -------------------------------- ### Set up and Test REST API Server (Bash) Source: https://github.com/scylladb/care-pet/blob/master/python/README.md This command starts the REST API server for the pet collar simulator. It requires activating the virtual environment and then running a Python script. The API server listens on port 8000 and provides endpoints to query owner and pet data. Ensure port 8000 is free before running. ```bash source env/bin/activate NODE1=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' carepet-scylla1) python src/api.py -h $NODE1 ``` -------------------------------- ### Build and Initialize Database with Maven Source: https://github.com/scylladb/care-pet/blob/master/java/README.md This sequence of commands first builds the Java project using Maven and then initializes the ScyllaDB database schema. It requires JDK, Maven, and Docker with a running ScyllaDB cluster. The migration script uses the dynamically obtained IP address of the first ScyllaDB node. ```bash mvn package NODE1=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' carepet-scylla1) ./bin/migrate.sh --hosts $NODE1 --datacenter datacenter1 ``` -------------------------------- ### Initialize Database with Migrations Source: https://github.com/scylladb/care-pet/blob/master/javascript/README.md Initializes the ScyllaDB database by creating the necessary keyspace and running migrations. It requires the IP address of a ScyllaDB node and the datacenter name. ```bash NODE1=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' carepet-scylla1) npm run migrate -- --hosts $NODE1 --datacenter datacenter1 ``` -------------------------------- ### Get Daily Average Sensor Values Source: https://github.com/scylladb/care-pet/blob/master/rust/README.md This command retrieves the daily average sensor values for a given sensor_id and date. It provides an example of the expected numerical array output, representing hourly averages. ```shell $ curl http://0.0.0.0:8000/api/sensor/{sensor_id}/values/day/{date} # Example: $ curl http://0.0.0.0:8000/api/sensor/5a9da084-ea49-4ab1-b2f8-d3e3d9715e7d/values/day/2020-08-06 # Expected output: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,42.55736] ``` -------------------------------- ### REST API: Get Daily Sensor Averages Source: https://context7.com/scylladb/care-pet/llms.txt Retrieves hourly aggregated sensor data for a specific day. The data is lazily evaluated and cached. ```APIDOC ## GET /api/sensor/{sensor_id}/values/day/{date} ### Description Returns hourly aggregated sensor data for a specific day. Uses lazy evaluation - aggregates are computed on first request and cached in sensor_avg table. ### Method GET ### Endpoint `/api/sensor/{sensor_id}/values/day/{date}` ### Parameters #### Path Parameters - **sensor_id** (string) - Required - The unique identifier for the sensor. - **date** (string) - Required - The date for which to retrieve daily averages in YYYY-MM-DD format. ### Request Example ```bash curl http://127.0.0.1:8000/api/sensor/5a9da084-ea49-4ab1-b2f8-d3e3d9715e7d/values/day/2020-08-06 ``` ### Response #### Success Response (200) - **Array of numbers** (array) - An array containing 24 values, one for each hour of the day. A value of 0 indicates no data. #### Response Example ```json [0,0,0,0,0,0,0,0,0,0,0,0,0,0,42.55736,38.2,41.3,39.8,40.1,0,0,0,0,0] ``` ``` -------------------------------- ### Terraform Initialization and Apply Commands Source: https://context7.com/scylladb/care-pet/llms.txt These commands demonstrate how to initialize a Terraform project and apply its configuration to deploy resources. The 'terraform init' command downloads provider plugins, and 'terraform apply' creates or updates infrastructure based on the configuration. The user will be prompted for the ScyllaDB API token during the apply process. ```bash # Initialize Terraform cd terraform/ terraform init # Apply configuration (enter API token when prompted) terraform apply # Expected output after ~10 minutes: # scylladbcloud_cluster.care_pet: Creating... # scylladbcloud_cluster.care_pet: Creation complete after 10m30s # # Apply complete! Resources: 1 added, 0 changed, 0 destroyed. # # Outputs: # cluster_id = "abc123..." # datacenter = "AWS_US_EAST_1" ``` -------------------------------- ### Initialize ScyllaDB Database with Rust Migrations Source: https://github.com/scylladb/care-pet/blob/master/rust/README.md This command runs the Rust migration binary to set up the database schema and keyspace. It requires the host IP address to connect to the ScyllaDB cluster. ```bash cargo run --bin migrate -- --hosts $HOST_IP ``` -------------------------------- ### REST API: Get Owner by ID Source: https://context7.com/scylladb/care-pet/llms.txt Retrieves owner information including name and address by owner UUID. This endpoint maps to the CQL query: `SELECT * FROM owner WHERE owner_id = ?` ```APIDOC ## GET /api/owner/{owner_id} ### Description Retrieves owner information including name and address by owner UUID. ### Method GET ### Endpoint `/api/owner/{owner_id}` #### Path Parameters - **owner_id** (UUID) - Required - The unique identifier of the owner. ### Request Example ```bash curl http://127.0.0.1:8000/api/owner/a05fd0df-0f97-4eec-a211-cad28a6e5360 ``` ### Response #### Success Response (200) - **owner_id** (UUID) - The unique identifier of the owner. - **name** (TEXT) - The name of the owner. - **address** (TEXT) - The address of the owner. #### Response Example ```json { "address": "home", "name": "John Smith", "owner_id": "a05fd0df-0f97-4eec-a211-cad28a6e5360" } ``` ``` -------------------------------- ### List Owner's Pets (cURL) Source: https://github.com/scylladb/care-pet/blob/master/docs/build-with-rust.md Example cURL command to list all pets belonging to a specific owner. The API endpoint is '/owner/{id}/pets'. ```bash curl http://127.0.0.1:8000/owner/{id}/pets ``` -------------------------------- ### Connect to ScyllaDB with Basic Configuration Source: https://github.com/scylladb/care-pet/blob/master/java/README.md Demonstrates how to establish a basic connection to ScyllaDB using the CqlSession builder. It includes setting the application name and client ID, which are useful for monitoring and identification. ```java import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.CqlSessionBuilder; class Example { public static void main(String []args) { CqlSessionBuilder builder = CqlSession.builder() .withApplicationName(applicationName) .withClientId(clientId); CqlSession session = builder.build(); } } ``` -------------------------------- ### List Active Pet Sensors (cURL) Source: https://github.com/scylladb/care-pet/blob/master/docs/build-with-rust.md Example cURL command to list all active sensors associated with a specific pet. The API endpoint is '/pet/{pet_id}/sensors'. ```bash curl http://127.0.0.1:8000/pet/{pet_id}/sensors ``` -------------------------------- ### Connect to ScyllaDB Database using Go Source: https://github.com/scylladb/care-pet/blob/master/go/README.md Establishes a connection to a ScyllaDB database using the gocql and gocqlx libraries. It configures cluster hosts and keyspace, then wraps the session for enhanced functionality. Dependencies include 'github.com/gocql/gocql' and 'github.com/scylladb/gocqlx/v2'. ```go import ( "github.com/gocql/gocql" "github.com/scylladb/gocqlx/v2" ) var cfg *gocql.ClusterConfig = gocql.NewCluster() cfg.Hosts = []string{"127.0.0.1"} cfg.Keyspace = "my_keyspace" ses := gocqlx.WrapSession(gocql.NewSession(cfg)) ``` -------------------------------- ### Retrieve Pet Owner Information (cURL) Source: https://github.com/scylladb/care-pet/blob/master/docs/build-with-rust.md Example cURL command to retrieve information for a specific pet owner using their ID. The API endpoint is '/owner/{id}'. ```bash curl http://127.0.0.1:8000/owner/{id} ``` -------------------------------- ### REST API: Get Sensor Values by Time Range Source: https://context7.com/scylladb/care-pet/llms.txt Retrieves raw sensor measurements within a specified time range. Returns an array of float values representing the sensor readings. ```APIDOC ## GET /api/sensor/{sensor_id}/values ### Description Retrieves raw sensor measurements within a specified time range. ### Method GET ### Endpoint `/api/sensor/{sensor_id}/values` #### Path Parameters - **sensor_id** (UUID) - Required - The unique identifier of the sensor. #### Query Parameters - **from** (string) - Required - The start of the time range in ISO 8601 format (e.g., `2020-08-06T00:00:00Z`). - **to** (string) - Required - The end of the time range in ISO 8601 format (e.g., `2020-08-06T23:59:59Z`). ### Request Example ```bash curl "http://127.0.0.1:8000/api/sensor/5a9da084-ea49-4ab1-b2f8-d3e3d9715e7d/values?from=2020-08-06T00:00:00Z&to=2020-08-06T23:59:59Z" ``` ### Response #### Success Response (200) - An array of float values representing the sensor readings within the specified time range. #### Response Example ```json [ 51.360596, 26.737432, 77.88015, 35.234, 42.891 ] ``` ``` -------------------------------- ### REST API: Get Owner by ID (Bash) Source: https://context7.com/scylladb/care-pet/llms.txt Retrieves owner information (name and address) using their UUID via a cURL command. This endpoint corresponds to a ScyllaDB query to fetch data from the 'owner' table. ```bash # Get owner details by UUID curl http://127.0.0.1:8000/api/owner/a05fd0df-0f97-4eec-a211-cad28a6e5360 # Expected response: # {"address":"home","name":"John Smith","owner_id":"a05fd0df-0f97-4eec-a211-cad28a6e5360"} ``` -------------------------------- ### Server Startup Output (.NET) Source: https://github.com/scylladb/care-pet/blob/master/csharp/README.md This log output indicates the successful startup of the CarePet server. It shows the server starting on port 8000 and listening for connections. ```text info: CarePet.Program[0] Starting CarePet server on port 8000... info: Microsoft.Hosting.Lifetime[14] Now listening on: http://0.0.0.0:8000 info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down. ``` -------------------------------- ### Enable Unsigned Plugins in Grafana (Script) Source: https://github.com/scylladb/care-pet/blob/master/quick-start/grafana/provisioning/plugins/scylla-plugin/README.md This command demonstrates how to start the Scylla monitoring setup with an unsigned plugin enabled using a command-line flag. It specifies the configuration file and the unsigned plugin to allow. ```bash ./start-all.sh -s scylla_servers.yml -c "GF_PLUGINS_ALLOW_LOADING_UNSIGNED_PLUGINS=scylladb-scylla-datasource" ``` -------------------------------- ### REST API: Get Sensor Values by Time Range (Bash) Source: https://context7.com/scylladb/care-pet/llms.txt Fetches raw sensor measurements for a given sensor ID within a specified time range (ISO 8601 format). The response is an array of float values representing the sensor readings. ```bash # Get sensor readings between two timestamps (ISO 8601 format) curl "http://127.0.0.1:8000/api/sensor/5a9da084-ea49-4ab1-b2f8-d3e3d9715e7d/values?from=2020-08-06T00:00:00Z&to=2020-08-06T23:59:59Z" # Expected response (array of float measurements): # [51.360596,26.737432,77.88015,35.234,42.891,...] ``` -------------------------------- ### Check ScyllaDB Cluster Status Source: https://github.com/scylladb/care-pet/blob/master/docs/build-with-rust.md After starting the Docker Compose stack, this command allows you to verify the status of the ScyllaDB cluster nodes. It connects to the first node ('carepet-scylla1') and executes 'nodetool status'. All nodes should be in the 'UN' (Up Normal) state before proceeding. ```bash docker exec -it carepet-scylla1 nodetool status ``` -------------------------------- ### Verify REST API Service with Curl (Shell) Source: https://github.com/scylladb/care-pet/blob/master/java/README.md Tests the running REST API service by sending an HTTP GET request to the root endpoint using `curl`. This command verifies that the API is accessible at `http://127.0.0.1:8080/` and displays the HTTP response headers and body. ```shell $ curl -v http://127.0.0.1:8080/ ``` -------------------------------- ### Generate and Ingest IoT Data with ScyllaDB (Bash) Source: https://github.com/scylladb/care-pet/blob/master/python/README.md This command initiates a process to generate and ingest simulated IoT data from pet collars into ScyllaDB. It requires activation of a virtual environment and uses a Python script to simulate sensor readings. Data is buffered and inserted in batches, with configurable intervals for data generation and batch insertion. The process runs indefinitely until manually stopped. ```bash source env/bin/activate NODE1=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' carepet-scylla1) python src/sensor.py -h $NODE1 --measure 2 --buffer-interval 10 ``` ```bash source env/bin/activate NODE1=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' carepet-scylla1) python src/sensor.py -h $NODE1 --measure 3 --buffer-interval 30 ```