Skip to main content

append_stream/common/
mod.rs

1// Copyright 2024 ScopeDB, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#![allow(dead_code)]
16
17use std::io;
18
19use scopedb_client::Client;
20use scopedb_client::Table;
21
22pub fn endpoint() -> String {
23    std::env::var("SCOPEDB_ENDPOINT").unwrap_or_else(|_| "http://127.0.0.1:6543".to_string())
24}
25
26pub fn database() -> String {
27    std::env::var("SCOPEDB_DATABASE").unwrap_or_else(|_| "scopedb".to_string())
28}
29
30pub fn schema() -> String {
31    std::env::var("SCOPEDB_SCHEMA").unwrap_or_else(|_| "public".to_string())
32}
33
34pub fn client() -> Result<Client, Box<dyn std::error::Error>> {
35    let api_key = std::env::var("SCOPEDB_API_KEY")
36        .ok()
37        .filter(|value| !value.is_empty())
38        .or_else(|| {
39            std::env::var("SCOPEDB_TOKEN")
40                .ok()
41                .filter(|value| !value.is_empty())
42        });
43    let mut builder = Client::builder(endpoint());
44    if let Some(api_key) = api_key {
45        builder = builder.api_key(api_key);
46    }
47    Ok(builder.build()?)
48}
49
50pub fn write_table(client: &Client) -> Result<Table, io::Error> {
51    let table = std::env::var("SCOPEDB_TABLE")
52        .ok()
53        .filter(|value| !value.is_empty())
54        .ok_or_else(|| {
55            io::Error::new(
56                io::ErrorKind::InvalidInput,
57                "set SCOPEDB_TABLE to a disposable table before running this write example",
58            )
59        })?;
60
61    Ok(client
62        .table(table)
63        .with_database(database())
64        .with_schema(schema()))
65}