### Clone and Start QuestDB Documentation Locally Source: https://github.com/questdb/documentation/blob/main/README.md Instructions to clone the QuestDB documentation repository, install dependencies using Yarn, and start the local development server. This setup allows for live preview of changes without server restarts. ```shell git clone git@github.com:questdb/documentation.git cd documentation yarn yarn start ``` -------------------------------- ### Shell Commands for Directory Setup and Docker Launch Source: https://github.com/questdb/documentation/blob/main/documentation/third-party-tools/cube.md These shell commands guide the user through setting up the project directory, creating a Dockerfile, and launching the QuestDB and Cube services using Docker Compose. It ensures the necessary file structure and running environment are established. ```shell mkdir questdb-cube && cd $_ ``` ```shell mkdir model ``` ```shell docker-compose up -d ``` -------------------------------- ### Execute SQL Query Source: https://github.com/questdb/documentation/blob/main/documentation/partials/_go.exec.query.partial.mdx This section details how to execute SQL queries against the QuestDB server. It includes an example of constructing the URL and sending an HTTP GET request. ```APIDOC ## GET /exec ### Description Executes a SQL query against the QuestDB server and returns the results. ### Method GET ### Endpoint `/exec` ### Query Parameters - **query** (string) - Required - The SQL query to execute. ### Request Example (This endpoint is typically called via HTTP GET with query parameters, not a request body. The Go example demonstrates URL construction.) ### Response #### Success Response (200) - **body** (string) - The query results, typically in a tabular format (e.g., CSV or JSON, depending on server configuration). #### Response Example ``` x 0 1 2 3 4 ``` ``` -------------------------------- ### Start QuestDB Documentation with Docker Compose Source: https://github.com/questdb/documentation/blob/main/README.md Command to start the QuestDB documentation development environment using Docker Compose. This is a convenient way to get the project running locally with all necessary services. ```bash docker-compose up ``` -------------------------------- ### C: Basic Connection with libpq Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/c-and-cpp.md Establishes a basic connection to QuestDB using the libpq C client library and executes a query to retrieve the server version. It includes error handling and demonstrates how to connect, query, and disconnect. This example requires the libpq library to be installed. ```c #include #include #include static void die(PGconn *conn, const char *msg) { fprintf(stderr, "%s: %s\n", msg, PQerrorMessage(conn)); PQfinish(conn); exit(1); } int main(void) { const char *conninfo = "host=127.0.0.1 port=8812 dbname=qdb user=admin password=quest"; PGconn *conn = PQconnectdb(conninfo); if (PQstatus(conn) != CONNECTION_OK) die(conn, "Connection failed"); PGresult *res = PQexec(conn, "SELECT version()"); if (PQresultStatus(res) != PGRES_TUPLES_OK) die(conn, "Query failed"); printf("Connected. Server reports: %s\n", PQgetvalue(res, 0, 0)); PQclear(res); PQfinish(conn); return 0; } ``` ```sh cc -O2 -Wall c_pgwire_basic.c -o c_pgwire_basic $(pkg-config --cflags --libs libpq) ``` -------------------------------- ### QuestDB Java Client - Quick Start Source: https://github.com/questdb/documentation/blob/main/documentation/clients/java-ilp.md This section guides you through adding the QuestDB Java client as a dependency to your project and provides a basic example of sending data to QuestDB using HTTP transport. It demonstrates creating a client instance, configuring it for a local QuestDB server, and sending rows with timestamp assignment. ```APIDOC ## QuestDB Java Client - Quick Start ### Description This section provides instructions on how to integrate the QuestDB Java Client into your project and includes a basic code example for sending data to a QuestDB server. It covers adding the dependency via Maven or Gradle and demonstrates an initial client setup for HTTP transport. ### Dependencies **Maven:** ```xml org.questdb questdb ${release.name} ``` **Gradle:** ```text compile group: 'org.questdb', name: 'questdb', version: '${release.name}' ``` ### Basic Usage Example This example shows how to configure the client for HTTP transport to a local QuestDB server and send two rows of data. The client is configured to let the server assign timestamps based on its wall-clock time. ```java // Example of sending data using ILP/HTTP // ... (Full example available in the remote repository: ilp-http) ``` ### Configuration String Format Client configuration is done via a string following this format: `::=;=;...;` Common protocols include `http`, `https`, `tcp`, and `tcps`. The `addr` key specifies the server's hostname and port (defaults to 9000 for HTTP/S and 9009 for TCP/S). ``` -------------------------------- ### Install psycopg2-binary Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/python.md Installs the psycopg2-binary package, which is a pre-compiled binary distribution of the psycopg2 adapter for PostgreSQL. This is the recommended way to install psycopg2 for ease of use. ```bash pip install psycopg2-binary ``` -------------------------------- ### Interact with QuestDB using Go and pgx Source: https://github.com/questdb/documentation/blob/main/documentation/partials/_go.sql.insert.partial.mdx This snippet demonstrates connecting to QuestDB, creating a table, executing prepared statements within a transaction for data insertion, and querying data using the pgx driver in Go. Ensure you have the pgx library installed and a QuestDB instance running. ```go package main import ( "context" "fmt" "log" "time" "github.com/jackc/pgx/v4" ) var conn *pgx.Conn var err error func main() { ctx := context.Background() conn, _ = pgx.Connect(ctx, "postgresql://admin:quest@localhost:8812/qdb") defer conn.Close(ctx) // text-based query _, err := conn.Exec(ctx, ("CREATE TABLE IF NOT EXISTS trades (" + " ts TIMESTAMP, date DATE, name STRING, value INT" + ") timestamp(ts);")) if err != nil { log.Fatalln(err) } // Prepared statement given the name 'ps1' _, err = conn.Prepare(ctx, "ps1", "INSERT INTO trades VALUES($1,$2,$3,$4)") if err != nil { log.Fatalln(err) } // Insert all rows in a single commit tx, err := conn.Begin(ctx) if err != nil { log.Fatalln(err) } for i := 0; i < 10; i++ { // Execute 'ps1' statement with a string and the loop iterator value _, err = conn.Exec( ctx, "ps1", time.Now(), time.Now().Round(time.Millisecond), "go prepared statement", i + 1) if err != nil { log.Fatalln(err) } } // Commit the transaction err = tx.Commit(ctx) if err != nil { log.Fatalln(err) } // Read all rows from table rows, err := conn.Query(ctx, "SELECT * FROM trades") fmt.Println("Reading from trades table:") for rows.Next() { var name string var value int64 var ts time.Time var date time.Time err = rows.Scan(&ts, &date, &name, &value) fmt.Println(ts, date, name, value) } err = conn.Close(ctx) } ``` -------------------------------- ### C++: Basic Connection and Query with libpqxx Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/c-and-cpp.md This C++ code snippet demonstrates a basic connection to QuestDB and executing a simple query using the libpqxx library. It establishes a connection, starts a transaction, executes a SELECT statement, iterates over the results, and commits the transaction. Error handling is included via a try-catch block. Ensure libpqxx is installed. ```cpp // cpp_pqxx_basic.cpp #include #include int main() { try { std::string conninfo = "host=127.0.0.1 port=8812 dbname=qdb user=admin password=quest"; pqxx::connection c{conninfo}; if (!c.is_open()) { std::cerr << "Connection failed\n"; return 1; } pqxx::work tx{c}; auto r = tx.exec("SELECT timestamp, symbol, price FROM trades ORDER BY timestamp DESC LIMIT 5"); for (const auto &row : r) { std::cout << row["timestamp"].c_str() << " " << row["symbol"].c_str() << " " << row["price"].c_str() << "\n"; } tx.commit(); } catch (const std::exception &e) { std::cerr << "Error: " << e.what() << "\n"; return 1; } return 0; } ``` ```sh c++ -std=c++17 -O2 cpp_pqxx_basic.cpp -o cpp_pqxx_basic $(pkg-config --cflags --libs libpqxx) ``` -------------------------------- ### Verify Telegraf Startup Output Source: https://github.com/questdb/documentation/blob/main/documentation/third-party-tools/telegraf.md This is an example of the expected output when Telegraf starts successfully and connects to QuestDB. It shows loaded inputs, aggregators, processors, and outputs. ```bash 2021-01-29T12:11:32Z I! Loaded inputs: cpu mem 2021-01-29T12:11:32Z I! Loaded aggregators: 2021-01-29T12:11:32Z I! Loaded processors: 2021-01-29T12:11:32Z I! Loaded outputs: influxdb_v2 ... ``` -------------------------------- ### MDX with React Components for Tabs and Examples Source: https://context7.com/questdb/documentation/llms.txt An example of an MDX (Markdown with JSX) file demonstrating the use of React components like Tabs and TabItems for displaying content in different formats (e.g., Docker, Homebrew installation). It also shows how to embed remote code examples using a custom component. ```mdx --- title: Quick Start Guide description: Get started with QuestDB quickly --- import { RemoteRepoExample } from '@theme/RemoteRepoExample' import Tabs from '@theme/Tabs' import TabItem from '@theme/TabItem' ## Install QuestDB ```bash docker run -p 9000:9000 -p 9009:9009 questdb/questdb ``` ```bash brew install questdb ``` ## Insert Data (Python) ``` -------------------------------- ### psycopg3 Connection Pooling Example Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/python.md Demonstrates how to set up and use a connection pool with psycopg3. It shows initializing the pool with minimum and maximum sizes, configuring connection parameters, and executing queries within a pooled connection context. The pool is closed after use. ```python from psycopg_pool import ConnectionPool pool = ConnectionPool( min_size=5, max_size=20, kwargs={ 'host': '127.0.0.1', 'port': 8812, 'user': 'admin', 'password': 'quest', 'dbname': 'qdb', 'autocommit': True } ) with pool.connection() as conn: with conn.cursor(binary=True) as cur: cur.execute("SELECT * FROM trades LIMIT 10") rows = cur.fetchall() print(f"Fetched {len(rows)} rows") pool.close() ``` -------------------------------- ### User Creation and Permissions Source: https://github.com/questdb/documentation/blob/main/documentation/guides/enterprise-quick-start.md This section details how to create interactive users in QuestDB, assign them roles, and grant specific permissions for accessing and manipulating data, including examples for read-only users and users with full table access. ```APIDOC ## CREATE USER ### Description Creates interactive users in QuestDB with specified passwords and grants them access permissions. ### Method SQL (executed via Web Console or client) ### Endpoint N/A (SQL command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```questdb-sql -- Read only user, can read all tables: CREATE USER readonly WITH PASSWORD 'xyz'; GRANT HTTP, PGWIRE TO readonly; GRANT SELECT ON ALL TABLES TO readonly; -- User with all permissions on a specific table: CREATE USER user1 WITH PASSWORD 'abc'; GRANT HTTP, PGWIRE TO user1; GRANT ALL ON table1 TO user1; -- User who can manage access to a specific table: CREATE USER user2 WITH PASSWORD 'abc'; GRANT HTTP, PGWIRE TO user2; GRANT ALL ON table2 TO user2 WITH GRANT OPTION; ``` ### Response #### Success Response (200) User creation and permission grants are confirmed via SQL execution status. #### Response Example None (SQL command output indicates success or failure) ``` -------------------------------- ### SSH into Azure VM and Install QuestDB Source: https://github.com/questdb/documentation/blob/main/documentation/deployment/azure.md Connect to your Azure VM via SSH and download, extract, and start the QuestDB server. This requires the VM's IP address and the SSH key file. Ensure you use the correct QuestDB binary URL for the latest version. ```bash export YOUR_INSTANCE_IP=172.xxx.xxx.xxx chmod 400 ~/download/questdb_key.pem ssh -i ~/download/questdb_key.pem azureuser@$YOUR_INSTANCE_IP ``` ```bash wget https://github.com/questdb/questdb/releases/download/X.Y.Z/questdb-X.Y.Z-rt-linux-x86-64.tar.gz tar -xvf questdb-X.Y.Z-rt-linux-x86-64.tar.gz cd questdb-X.Y.Z-rt-linux-x86-64/bin ./questdb.sh start ``` -------------------------------- ### Connect to QuestDB and Query with Go Source: https://github.com/questdb/documentation/blob/main/documentation/partials/_go.sql.query.partial.mdx This Go code snippet demonstrates establishing a connection to a QuestDB instance using the 'github.com/lib/pq' driver. It then prepares and executes a SQL query, iterates over the results, and prints each row. Error handling is included for connection, query preparation, execution, and row scanning. Ensure the 'pq' driver is installed and QuestDB is accessible at the specified host and port. ```go package main import ( "database/sql" "fmt" _ "github.com/lib/pq" ) const ( host = "localhost" port = 8812 user = "admin" password = "quest" dbname = "qdb" ) func main() { connStr := fmt.Sprintf( "host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname) db, err := sql.Open("postgres", connStr) checkErr(err) defer db.Close() stmt, err := db.Prepare("SELECT x FROM long_sequence(5);") checkErr(err) defer stmt.Close() rows, err := stmt.Query() checkErr(err) defer rows.Close() var num string for rows.Next() { err = rows.Scan(&num) checkErr(err) fmt.Println(num) } err = rows.Err() checkErr(err) } func checkErr(err error) { if err != nil { panic(err) } } ``` -------------------------------- ### Add QuestDB Connect Requirement for Docker Source: https://github.com/questdb/documentation/blob/main/documentation/third-party-tools/superset.md Creates a local requirements file and adds 'questdb-connect' to it, ensuring it's installed with the Dockerized Superset setup. This requires Docker and a QuestDB version of 7.1.2 or later. ```bash touch ./docker/requirements-local.txt echo "questdb-connect==1.1.3" > docker/requirements-local.txt ``` -------------------------------- ### Run Apache Superset via Docker Compose Source: https://github.com/questdb/documentation/blob/main/documentation/third-party-tools/superset.md Pulls the necessary Docker images and starts the Apache Superset service using Docker Compose. This command assumes Docker and Docker Compose are installed and configured. ```bash docker compose -f docker-compose-image-tag.yml pull docker compose -f docker-compose-image-tag.yml up ``` -------------------------------- ### Install QuestDB Go Client Source: https://github.com/questdb/documentation/blob/main/documentation/clients/ingest-go.md This command installs the QuestDB Go client library into your project. It requires Go 1.19 or later and assumes QuestDB is already running. ```toml go get github.com/questdb/go-questdb-client/ ``` -------------------------------- ### QuestDB Latest On Query with Node.js 'postgres' Client Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/javascript.md This example shows how to use the 'postgres' Node.js client to fetch the latest record for each symbol using the 'LATEST ON' clause in QuestDB. It establishes a connection, executes the query, and then iterates through the results. Make sure to install the 'postgres' library (`npm install postgres`) and have QuestDB accessible. ```javascript const postgres = require('postgres') // Set the client timezone to UTC process.env.TZ = 'UTC'; const sql = postgres({ host: '127.0.0.1', port: 8812, username: 'admin', password: 'quest', database: 'qdb', ssl: false }) async function latestByQuery() { try { // Get the latest values for each symbol const latest = await sql` SELECT * FROM trades LATEST ON timestamp PARTITION BY symbol ` console.log(`Latest prices for ${latest.length} symbols: `) for (const trade of latest) { console.log(`${trade.symbol}: ${trade.price} @ ${trade.ts}`) } } catch (error) { console.error('Query error:', error) } finally { await sql.end() } } latestByQuery() ``` -------------------------------- ### Quick Docker Installation (Bash) Source: https://github.com/questdb/documentation/blob/main/documentation/deployment/hetzner.md This script downloads and installs Docker on an Ubuntu system using the official convenience script. It then adds the current user to the 'docker' group, allowing them to run Docker commands without sudo. ```bash questdb01$ curl -fsSL https://get.docker.com -o get-docker.sh questdb01$ sudo sh get-docker.sh questdb01$ sudo usermod -aG docker $USER ``` -------------------------------- ### Install QuestDB with Homebrew Source: https://github.com/questdb/documentation/blob/main/documentation/quick-start.mdx Installs QuestDB using the Homebrew package manager on macOS. After installation, QuestDB's data and configuration files will be located in a platform-specific directory. ```shell brew install questdb ``` -------------------------------- ### Download and Install JDK and QuestDB Source: https://github.com/questdb/documentation/blob/main/documentation/deployment/systemd.md This script downloads and installs the specified JDK version and the latest QuestDB snapshot (without JRE). It sets up the necessary directories and environment variables for Java and QuestDB. ```bash #!/bin/bash # Download and install the JDK curl -s https://download.oracle.com/java/17/latest/jdk-17_linux-x64_bin.tar.gz -o jdk.tar.gz mkdir -p ~/jdk tar -xzf jdk.tar.gz -C ~/jdk --strip-components=1 export JAVA_HOME=~/jdk export PATH=$JAVA_HOME/bin:$PATH # Download and set up QuestDB curl -s https://dl.questdb.io/snapshots/questdb-latest-no-jre-bin.tar.gz -o questdb.tar.gz mkdir -p ~/questdb/binary tar -xzf questdb.tar.gz -C ~/questdb/binary --strip-components 1 mv ~/questdb/binary/questdb.jar ~/bin/ ``` -------------------------------- ### Create Users and Service Accounts in QuestDB SQL Source: https://github.com/questdb/documentation/blob/main/documentation/operations/rbac.md Demonstrates the SQL commands to create new users and service accounts. It shows how to set an initial password during creation. User and service account names must be unique. ```questdb-sql CREATE USER user0; CREATE USER user1 WITH PASSWORD pwd1; CREATE SERVICE ACCOUNT application0; CREATE SERVICE ACCOUNT application1 WITH PASSWORD pwd1; ``` -------------------------------- ### QuestDB SQL: LATEST ON Query Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/rpostgres.md Illustrates the QuestDB SQL LATEST ON clause, which efficiently retrieves the most recent row for each partition. This example selects all columns from the 'trades' table for the current day, partitioning by 'symbol' to get the latest trade for each symbol. This is highly performant for finding the last known state. ```questdb-sql SELECT * FROM trades WHERE timestamp IN today() LATEST ON timestamp PARTITION BY symbol; ``` -------------------------------- ### Install QuestDB Connect with Pip Source: https://github.com/questdb/documentation/blob/main/documentation/third-party-tools/superset.md Installs the QuestDB Connect Python package using pip. This is required for standalone Superset installations and requires Python versions 3.9 to 3.11. ```bash pip install 'questdb-connect==1.1.3' ``` -------------------------------- ### Install QuestDB psycopg3 Adapter Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/python.md Installs the binary version of the psycopg3 library for Python, which is recommended for better performance compared to the pure-Python version. Ensure you have pip installed. ```bash pip install psycopg[binary] ``` -------------------------------- ### Authenticate QuestDB Go Client via Configuration String Source: https://github.com/questdb/documentation/blob/main/documentation/clients/ingest-go.md Demonstrates how to create a QuestDB client instance using a configuration string that includes HTTP basic authentication details. This method requires the Go client library and a running QuestDB instance. ```Go package main import ( "context" "github.com/questdb/go-questdb-client/v4" ) func main() { ctx := context.TODO() client, err := questdb.LineSenderFromConf(ctx, "http::addr=localhost:9000;username=admin;password=quest;") if err != nil { panic("Failed to create client") } // Utilize the client for your operations... } ``` -------------------------------- ### Install Borg Backup and Borgmatic Source: https://github.com/questdb/documentation/blob/main/documentation/deployment/hetzner.md Installs BorgBackup and Borgmatic using the apt package manager. This is the initial step for setting up data backups. ```bash apt update && apt install -y borgbackup borgmatic ``` -------------------------------- ### Install asyncpg with pip Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/python.md Installs the asyncpg Python library, an asynchronous PostgreSQL client for high performance and asyncio support. ```bash pip install asyncpg ``` -------------------------------- ### QuestDB SQL - Create Users with Varied Permissions Source: https://github.com/questdb/documentation/blob/main/documentation/guides/enterprise-quick-start.md Demonstrates creating read-only users, users with all permissions on specific tables, and users with grantable permissions for table management using QuestDB SQL. It requires the Web Console or a PGWIRE client for execution. ```questdb-sql -- Read only user, can read all tables: CREATE USER readonly WITH PASSWORD 'xyz'; GRANT HTTP, PGWIRE TO readonly; GRANT SELECT ON ALL TABLES TO readonly; -- User with all permissions on a specific table: CREATE USER user1 WITH PASSWORD 'abc'; GRANT HTTP, PGWIRE TO user1; GRANT ALL ON table1 TO user1; -- User who can manage access to a specific table: CREATE USER user2 WITH PASSWORD 'abc'; GRANT HTTP, PGWIRE TO user2; GRANT ALL ON table2 TO user2 WITH GRANT OPTION; ``` -------------------------------- ### Install R Packages for QuestDB Connection Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/rpostgres.md Installs the RPostgres and DBI packages required for connecting to QuestDB. These packages are available on CRAN. ```r install.packages(c("RPostgres", "DBI"), repos = "https://cloud.r-project.org") ``` -------------------------------- ### Java JDBC Client for Querying QuestDB Source: https://github.com/questdb/documentation/blob/main/documentation/guides/enterprise-quick-start.md This Java code example illustrates how to establish a JDBC connection to QuestDB using a service account's credentials (username and password) and execute a basic SQL query to retrieve data. It utilizes standard JDBC practices for connection management and result set processing. ```java import java.sql.*; import java.util.Properties; public class App { public static void main(String[] args) throws SQLException { Properties properties = new Properties(); properties.setProperty("user", "dashboard"); properties.setProperty("password", "pwd"); properties.setProperty("sslmode", "require"); final Connection connection = DriverManager.getConnection( "jdbc:postgresql://localhost:8812/qdb", properties); try (PreparedStatement preparedStatement = connection.prepareStatement( "SELECT x, timestamp_sequence('2023-07-20', 1000000) FROM long_sequence(5);", Statement.RETURN_GENERATED_KEYS)) { try (ResultSet rs = preparedStatement.executeQuery()) { while (rs.next()) { System.out.println(rs.getLong(1)); System.out.println(rs.getTimestamp(2)); } } } connection.close(); } } ``` -------------------------------- ### Get Server Start Time with pg_postmaster_start_time() Source: https://github.com/questdb/documentation/blob/main/documentation/reference/function/date-time.md The pg_postmaster_start_time() function returns the timestamp indicating when the QuestDB server was last started. This function does not accept any arguments and returns a timestamp value. ```questdb-sql SELECT pg_postmaster_start_time(); ``` -------------------------------- ### Execute QuestDB Query in Go Source: https://github.com/questdb/documentation/blob/main/documentation/partials/_go.exec.query.partial.mdx This Go code snippet demonstrates how to connect to a QuestDB instance, construct a SQL query, send it, and read the response. It utilizes the `net/http` package for making requests and handles potential errors. ```go package main import ( "fmt" "io/ioutil" "log" "net/http" "net/url" ) func main() { u, err := url.Parse("http://localhost:9000") checkErr(err) u.Path += "exec" params := url.Values{} params.Add("query", "SELECT x FROM long_sequence(5);") u.RawQuery = params.Encode() url := fmt.Sprintf("%v", u) res, err := http.Get(url) checkErr(err) defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) checkErr(err) log.Println(string(body)) } func checkErr(err error) { if err != nil { panic(err) } } ``` -------------------------------- ### GET /api/Trades/latest Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/c-sharp.md Retrieves the most recent trades available in the system. ```APIDOC ## GET /api/Trades/latest ### Description Retrieves the most recent trades recorded in the system. ### Method GET ### Endpoint /api/Trades/latest ### Parameters None ### Request Example ``` GET /api/Trades/latest ``` ### Response #### Success Response (200) - **trades** (array of objects) - A list of the latest trade objects. Each trade object may contain fields like: - **symbol** (string) - The trading symbol. - **price** (number) - The price of the trade. - **timestamp** (string) - The timestamp of the trade. #### Response Example ```json [ { "symbol": "GOOGL", "price": 130.20, "timestamp": "2023-10-27T10:05:00Z" }, { "symbol": "MSFT", "price": 340.10, "timestamp": "2023-10-27T10:04:00Z" } ] ``` ``` -------------------------------- ### Show All Server Parameters in QuestDB SQL Source: https://github.com/questdb/documentation/blob/main/documentation/reference/sql/show.md Retrieves all server configuration parameters, their corresponding environment variables, current values, value sources (default, conf, env), sensitivity, and reloadability. This command helps in monitoring and managing QuestDB configurations. ```questdb-sql SHOW PARAMETERS; ``` ```questdb-sql (SHOW PARAMETERS) WHERE value ILIKE '%tmp%'; ``` ```questdb-sql (SHOW PARAMETERS) WHERE property_path NOT IN ('cairo.root', 'cairo.sql.backup.root') ORDER BY 1; ``` ```questdb-sql (SHOW PARAMETERS) WHERE value_source = 'env'; ``` ```questdb-sql (SHOW PARAMETERS) WHERE value_source <> 'default'; ``` -------------------------------- ### Install pg (node-postgres) Client Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/javascript.md This command installs the 'pg' npm package, which is a Node.js module for interfacing with PostgreSQL databases, recommended for use with QuestDB. ```bash npm install pg ``` -------------------------------- ### File Copying - cp Example Source: https://github.com/questdb/documentation/blob/main/documentation/operations/backup.md This example shows how to use the `cp` command to copy the QuestDB root directory. While simpler than `rsync`, `cp` creates a full copy each time. Use this command after issuing `CHECKPOINT CREATE`. ```bash cp -a /path/to/questdb_data/ /path/to/backup/questdb_data/ ``` -------------------------------- ### Basic Sampling Examples Source: https://github.com/questdb/documentation/blob/main/documentation/reference/sql/sample-by.md Provides fundamental examples of the `SAMPLE BY` clause for common use cases like hourly, 30-minute, and daily intervals, including alignment to calendar dates. ```APIDOC ## Basic SAMPLE BY Examples ### Description This section provides practical examples of using the `SAMPLE BY` clause in QuestDB SQL for different time intervals such as hourly, 30-minute, and daily. It also demonstrates how to align these samples to calendar dates using `ALIGN TO CALENDAR`. ### Method SQL Query ### Endpoint N/A (SQL Operation) ### Parameters #### Query Parameters - **SAMPLE BY** (string) - Specifies the interval for sampling (e.g., `1h`, `30m`, `1d`). - **ALIGN TO CALENDAR** (boolean) - Optional. If set, aligns samples to calendar boundaries. ### Request Example (Hourly) ```questdb-sql title="Hourly interval" SELECT ts, count() FROM trades SAMPLE BY 1h; ``` ### Response Example (Hourly) | ts | count | | --------------------------- | ----- | | 2021-05-31T23:45:10.000000Z | 3 | | 2021-06-01T00:45:10.000000Z | 1 | | 2021-05-31T23:45:10.000000Z | 1 | | 2021-06-01T00:45:10.000000Z | 1 | ### Request Example (30 Minute Interval) ```questdb-sql title="30 minute interval" SELECT ts, sum(quantity*price) FROM trades SAMPLE BY 30m; ``` ### Response Example (30 Minute Interval) | ts | sum | | --------------------------- | ------ | | 2021-05-31T23:45:10.000000Z | 1000.5 | | 2021-06-01T00:15:10.000000Z | 16024 | | 2021-06-01T00:45:10.000000Z | 8000 | | 2021-06-01T00:15:10.000000Z | 8012 | | 2021-06-01T00:45:10.000000Z | 8000 | ### Request Example (Daily Interval with Calendar Alignment) ```questdb-sql title="Daily interval" SELECT ts, avg(quantity*price) FROM trades SAMPLE BY 1d ALIGN TO CALENDAR; ``` ### Response Example (Daily Interval with Calendar Alignment) | ts | avg | | --------------------------- | ------ | | 2021-05-31T00:00:00.000000Z | 1000.5 | | 2021-06-01T00:00:00.000000Z | 8007.2 | ``` -------------------------------- ### Execute Prepared Statements with libpqxx C++ Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/c-and-cpp.md This example demonstrates how to use prepared statements in C++ with libpqxx to query trades data. It constructs a time-series filter for trades within the last 7 days for a specific symbol and retrieves the latest 10 results. Dependencies include the libpqxx library and standard C++ time utilities. ```cpp // cpp_pqxx_prepared.cpp #include #include #include #include #include int main() { try { pqxx::connection c{ "host=127.0.0.1 port=8812 dbname=qdb user=admin password=quest" }; pqxx::work tx{c}; // --- compute 7 days ago in UTC --- std::time_t now = std::time(nullptr); std::time_t seven_days_ago = now - 7 * 24 * 60 * 60; std::tm gmt{}; gmtime_r(&seven_days_ago, &gmt); std::ostringstream oss; oss << std::put_time(&gmt, "%Y-%m-%dT%H:%M:%S") << ".000000Z"; std::string start = oss.str(); const std::string sym = "BTC-USD"; pqxx::params p; p.append(sym); p.append(start); pqxx::result r = tx.exec( "SELECT timestamp, symbol, price " "FROM trades WHERE symbol=$1 AND timestamp >= $2 " "ORDER BY timestamp LIMIT 10", p ); for (const auto &row : r) { std::cout << row["timestamp"].c_str() << " " << row["symbol"].c_str() << " " << row["price"].c_str() << "\n"; } tx.commit(); } catch (const std::exception &e) { std::cerr << "Error: " << e.what() << "\n"; return 1; } return 0; } ``` -------------------------------- ### Install pgx Go Client Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/go.md Installs the latest version (v5) of the pgx Go PostgreSQL driver using Go modules. This is a prerequisite for using pgx to connect to QuestDB. ```bash go get github.com/jackc/pgx/v5 ``` -------------------------------- ### Install PostgreSQL Client Source: https://github.com/questdb/documentation/blob/main/documentation/deployment/hetzner.md Installs the PostgreSQL client package, which is necessary for running checkpoint management commands required for consistent QuestDB backups. ```bash apt update && apt install -y postgresql-client ``` -------------------------------- ### GET /api/Trades/stats Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/c-sharp.md Retrieves statistics for trades within a specified number of past days. ```APIDOC ## GET /api/Trades/stats ### Description Retrieves aggregated statistics for trades over a specified period, defaulting to the last 7 days. ### Method GET ### Endpoint /api/Trades/stats ### Parameters #### Query Parameters - **days** (integer) - Optional - The number of past days to include in the statistics. Defaults to 7. ### Request Example ``` GET /api/Trades/stats?days=30 ``` ### Response #### Success Response (200) - **stats** (object) - An object containing trade statistics. The specific fields may vary but could include: - **totalTrades** (integer) - Total number of trades. - **averagePrice** (number) - Average trade price. - **volume** (number) - Total volume traded. - **startDate** (string) - The start date for the statistics period. - **endDate** (string) - The end date for the statistics period. #### Response Example ```json { "totalTrades": 15000, "averagePrice": 175.60, "volume": 2634000, "startDate": "2023-09-27T00:00:00Z", "endDate": "2023-10-27T00:00:00Z" } ``` ``` -------------------------------- ### Run QuestDB Executable (Windows) Source: https://github.com/questdb/documentation/blob/main/documentation/quick-start.mdx This command starts, stops, checks the status, or installs/removes the QuestDB service on Windows using `questdb.exe`. It allows specifying the data directory, forcing operations, setting the Java home, or a tag. ```shell questdb.exe [start|stop|status|install|remove] \ [-d dir] [-f] [-j JAVA_HOME] [-t tag] ``` -------------------------------- ### C/C++ Client Configuration String Example Source: https://github.com/questdb/documentation/blob/main/documentation/clients/ingest-c-and-cpp.md Demonstrates the format of the configuration string for the C/C++ QuestDB client. This string specifies the transport protocol, address, and various parameters for connecting to QuestDB. ```text ::addr=host:port;param1=val1;param2=val2;... ``` -------------------------------- ### Install psycopg_pool for Connection Pooling Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/python.md Installs the necessary package for enabling connection pooling with psycopg3. This is crucial for managing database connections efficiently by reusing existing ones, reducing overhead. ```bash pip install psycopg_pool ``` -------------------------------- ### GET /api/Trades Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/c-sharp.md Retrieves a list of recent trades. Supports filtering by symbol and limiting the number of results. ```APIDOC ## GET /api/Trades ### Description Retrieves a list of recent trades. You can filter trades by a specific symbol and limit the number of returned trades. ### Method GET ### Endpoint /api/Trades ### Parameters #### Query Parameters - **symbol** (string) - Optional - Filter trades by a specific trading symbol. - **limit** (integer) - Optional - The maximum number of trades to return. Defaults to 10. ### Request Example ``` GET /api/Trades?symbol=AAPL&limit=5 ``` ### Response #### Success Response (200) - **trades** (array of objects) - A list of trade objects. Each trade object may contain fields like: - **symbol** (string) - The trading symbol. - **price** (number) - The price of the trade. - **timestamp** (string) - The timestamp of the trade. #### Response Example ```json [ { "symbol": "AAPL", "price": 170.50, "timestamp": "2023-10-27T10:00:00Z" }, { "symbol": "AAPL", "price": 170.55, "timestamp": "2023-10-27T10:01:00Z" } ] ``` ``` -------------------------------- ### CREATE MATERIALIZED VIEW Examples Source: https://github.com/questdb/documentation/blob/main/documentation/reference/sql/create-mat-view.md Examples demonstrating the creation of materialized views with different configurations, including partitioning, TTL, refresh periods, and manual refresh. ```APIDOC ## CREATE MATERIALIZED VIEW Examples ### Description Examples demonstrating the creation of materialized views with different configurations, including partitioning, TTL, refresh periods, and manual refresh. ### Examples ```questdb-sql title="Creating a materialized view with PARTITION BY and TTL" CREATE MATERIALIZED VIEW trades_hourly_prices AS ( SELECT timestamp, symbol, avg(price) AS avg_price FROM trades SAMPLE BY 1h ) PARTITION BY DAY TTL 7 DAYS; ``` ```questdb-sql title="Creating a materialized view with one day period" CREATE MATERIALIZED VIEW trades_hourly_prices REFRESH PERIOD (LENGTH 1d TIME ZONE 'Europe/London' DELAY 2h) AS SELECT timestamp, symbol, avg(price) AS avg_price FROM trades SAMPLE BY 1h; ``` ```questdb-sql title="Creating a materialized view with compact period syntax" CREATE MATERIALIZED VIEW trades_hourly_prices REFRESH PERIOD (SAMPLE BY INTERVAL) AS SELECT timestamp, symbol, avg(price) AS avg_price FROM trades SAMPLE BY 1h ALIGN CALENDAR TIME ZONE 'Europe/London'; ``` ```questdb-sql title="Creating a materialized view with timer refresh each 10 minutes" CREATE MATERIALIZED VIEW trades_hourly_prices REFRESH EVERY 10m START '2025-06-18T00:00:00.000000000' AS SELECT timestamp, symbol, avg(price) AS avg_price FROM trades SAMPLE BY 1h; ``` ```questdb-sql title="Creating a materialized view with manual refresh" CREATE MATERIALIZED VIEW trades_hourly_prices REFRESH MANUAL AS SELECT timestamp, symbol, avg(price) AS avg_price FROM trades SAMPLE BY 1h; ``` ``` -------------------------------- ### Install ZFS on Ubuntu Source: https://github.com/questdb/documentation/blob/main/documentation/guides/compression-zfs.md Installs the necessary ZFS utilities on an Ubuntu system using apt package manager. This is a prerequisite for creating ZFS pools and enabling compression. ```bash sudo apt update sudo apt install zfsutils-linux ``` -------------------------------- ### Extract and Install QuestDB Kafka Connector JARs Source: https://github.com/questdb/documentation/blob/main/documentation/third-party-tools/redpanda.md Unzips the downloaded connector package and copies the resulting JAR files into the Kafka client's library directory. Requires unzip and standard shell utilities. ```shell unzip kafka-questdb-connector-*-bin.zip cd kafka-questdb-connector cp ./*.jar /path/to/kafka/libs ``` -------------------------------- ### Change Directory to Superset Source: https://github.com/questdb/documentation/blob/main/documentation/third-party-tools/superset.md Changes the current directory to the cloned Superset repository. This is necessary for subsequent setup steps. ```bash cd superset ``` -------------------------------- ### Install Npgsql using Package Manager Console Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/c-sharp.md This command installs the Npgsql NuGet package into your .NET project via the Package Manager Console in Visual Studio. Npgsql allows .NET applications to connect to and query QuestDB using the PostgreSQL wire protocol. ```powershell Install-Package Npgsql ``` -------------------------------- ### QuestDB SAMPLE BY Query Example Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/php.md An example of a QuestDB SQL query utilizing the `SAMPLE BY` clause for time-based data downsampling. This query calculates aggregated price statistics (average, min, max) for trades within the last 7 days, grouped by hour. ```questdb-sql SELECT timestamp, symbol, avg(price) as avg_price, min(price) as min_price, max(price) as max_price FROM trades WHERE timestamp >= dateadd('d', -7, now()) SAMPLE BY 1h; ``` -------------------------------- ### psycopg2 Fetching Data Methods Source: https://github.com/questdb/documentation/blob/main/documentation/pgwire/python.md Illustrates different methods for fetching query results using psycopg2: `fetchall()` to get all rows, `fetchone()` to retrieve rows one by one, and `fetchmany(size)` to get results in batches. It demonstrates iterating through results and processing them. ```python import psycopg2 from datetime import datetime, timedelta conn = psycopg2.connect( host='127.0.0.1', port=8812, user='admin', password='quest', dbname='qdb' ) conn.autocommit = True try: with conn.cursor() as cur: cur.execute("SELECT * FROM trades LIMIT 10") rows = cur.fetchall() print(f"Fetched {len(rows)} rows") for row in rows: print(f"Timestamp: {row[0]}, Symbol: {row[1]}, Price: {row[2]}") # Fetch one row at a time cur.execute("SELECT * FROM trades LIMIT 5") print("\nFetching one row at a time:") row = cur.fetchone() while row: print(row) row = cur.fetchone() # Fetch many rows at a time cur.execute("SELECT * FROM trades LIMIT 100") print("\nFetching 10 rows at a time:") while True: rows = cur.fetchmany(10) if not rows: break print(f"Batch of {len(rows)} rows") finally: conn.close() ``` -------------------------------- ### Run QuestDB Script (Linux/macOS) Source: https://github.com/questdb/documentation/blob/main/documentation/quick-start.mdx Provides commands to start, stop, or check the status of the QuestDB server on Linux and macOS using the `questdb.sh` script. Optional flags allow specifying the data directory, forcing operations, or setting a tag. ```shell ./questdb.sh [start|stop|status] [-d dir] [-f] [-n] [-t tag] ``` -------------------------------- ### Start Kafka Connect Standalone Source: https://github.com/questdb/documentation/blob/main/documentation/third-party-tools/redpanda.md Initiates the Kafka Connect worker in standalone mode, using the specified connector and standalone properties files. This command should be run from the Kafka installation directory. ```shell ./bin/connect-standalone.sh config/connect-standalone.properties config/questdb-connector.properties ``` -------------------------------- ### Connect to QuestDB and Query using libpq in C Source: https://github.com/questdb/documentation/blob/main/documentation/partials/_c.sql.query.partial.mdx This C code snippet demonstrates how to establish a connection to a QuestDB instance using the libpq library. It then executes a SQL query ('SELECT x FROM long_sequence(5);') and iterates through the returned rows, printing each value. Ensure you have libpq installed and linked correctly during compilation. The compilation command is provided as a comment. ```c // compile with // g++ libpq_example.c -o libpq_example.exe -I pgsql\include -L dev\pgsql\lib // -std=c++17 -lpthread -lpq #include #include #include void do_exit(PGconn *conn) { PQfinish(conn); exit(1); } int main() { PGconn *conn = PQconnectdb( "host=localhost user=admin password=quest port=8812 dbname=testdb"); if (PQstatus(conn) == CONNECTION_BAD) { fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn)); do_exit(conn); } PGresult *res = PQexec(conn, "SELECT x FROM long_sequence(5);"); if (PQresultStatus(res) != PGRES_TUPLES_OK) { printf("No data retrieved\n"); PQclear(res); do_exit(conn); } int rows = PQntuples(res); for (int i = 0; i < rows; i++) { printf("%s\n", PQgetvalue(res, i, 0)); } PQclear(res); PQfinish(conn); return 0; } ```