### Project Setup and Execution Source: https://github.com/timescale/timescaledb-ts/blob/main/examples/node-sequelize/README.md Provides commands for setting up the project environment, installing dependencies, building the project, running migrations, and starting the application. ```bash # Setup cp .env.example .env # Update DATABASE_URL pnpm install pnpm build pnpm migrate # Run pnpm start # or # Test pnpm test ``` -------------------------------- ### Setup and Run Example Project Tests Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/TESTING.md Steps to set up and run integration tests for an example project, specifically node-typeorm. Involves copying environment variables, running migrations, and then executing tests. ```bash cd examples/node-typeorm cp .env.example .env pnpm migrate pnpm test ``` -------------------------------- ### Project Setup and Execution Commands Source: https://github.com/timescale/timescaledb-ts/blob/main/examples/node-typeorm/README.md Provides essential bash commands for setting up the project, installing dependencies, building, migrating the database, and running the application or tests. ```bash # Setup cp .env.example .env # Update DATABASE_URL pnpm install pnpm build pnpm migrate # Run pnpm start # or # Test pnpm test ``` -------------------------------- ### Initialize TypeScript Project and Install Dependencies Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/guides/getting-started.md Sets up a new TypeScript project, installs development dependencies like TypeScript and ts-node, and adds TypeORM and TimescaleDB TypeORM integration. It uses pnpm for package management. ```bash mkdir crypto-tracker cd crypto-tracker pnpm init pnpm add -D typescript @types/node ts-node pnpm add typeorm @timescaledb/typeorm reflect-metadata pg dotenv ``` -------------------------------- ### Start TimescaleDB Docker Instance Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/guides/getting-started.md Starts a TimescaleDB instance using Docker with specified port mapping and password. This command ensures a running TimescaleDB database is available for the project. ```bash docker run -d \ --name timescaledb \ -p 5432:5432 \ -e POSTGRES_PASSWORD=password \ timescale/timescaledb-ha:pg17 ``` -------------------------------- ### Candlestick Data Output Example Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/guides/getting-started.md Example JSON output representing hourly candlestick data for BTC prices. It includes open, high, low, close prices, volume, and VWAP. ```json [ { "bucket_time": "2025-01-01T00:00:00.000Z", "open": 42000, "high": 42200, "low": 41900, "close": 42200, "volume": 7.5, "vwap": 42050, "open_time": "2025-01-01T00:00:00.000Z", "high_time": "2025-01-01T00:45:00.000Z", "low_time": "2025-01-01T00:30:00.000Z", "close_time": "2025-01-01T00:45:00.000Z" } ] ``` -------------------------------- ### Run TypeORM Migrations Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/guides/getting-started.md Executes pending TypeORM migrations to update the database schema. This command applies changes, including the creation of the 'crypto_prices' hypertable. ```bash pnpm migration:run ``` -------------------------------- ### Create TimescaleDB Database Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/guides/getting-started.md Connects to the PostgreSQL instance and creates a new database named 'crypto'. This SQL command is executed within the PostgreSQL client. ```sql CREATE DATABASE crypto; ``` -------------------------------- ### TypeORM Scripts for Migrations Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/guides/getting-started.md Adds scripts to `package.json` for generating and running TypeORM migrations. It configures the TypeORM CLI to use the project's data source. ```json { "scripts": { "typeorm": "typeorm-ts-node-commonjs", "migration:generate": "npm run typeorm migration:generate", "migration:run": "npm run typeorm migration:run -- -d src/data-source.ts" } } ``` -------------------------------- ### Start TimescaleDB Docker Container Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/TESTING.md Command to start a TimescaleDB instance using Docker, making it available on port 5432. This is a prerequisite for local integration testing. ```bash docker run -d \ --name timescaledb \ -p 5432:5432 \ -e POSTGRES_PASSWORD=password \ timescale/timescaledb-ha:pg17 ``` -------------------------------- ### Generate TypeORM Migration Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/guides/getting-started.md Generates a new TypeORM migration file for the 'CryptoPrice' entity. The TimescaleDB-specific hypertable creation is handled automatically by the TypeORM integration. ```bash pnpm migration:generate migrations/CreateCryptoPrice -d src/data-source.ts ``` -------------------------------- ### Environment Configuration Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/guides/getting-started.md Defines the database connection URL for TypeORM, specifying the PostgreSQL connection details. This file is used to configure the application's database access. ```env DATABASE_URL=postgres://postgres:password@localhost:5432/crypto ``` -------------------------------- ### TypeORM Data Source Configuration Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/guides/getting-started.md Configures the TypeORM DataSource for a PostgreSQL database, including entity definitions and migration paths. It imports necessary modules for TimescaleDB integration. ```typescript import 'reflect-metadata'; import '@timescaledb/typeorm'; import { DataSource } from 'typeorm'; import { CryptoPrice } from './models/CryptoPrice'; export const AppDataSource = new DataSource({ type: 'postgres', url: process.env.DATABASE_URL, synchronize: false, logging: true, entities: [CryptoPrice], migrations: ['migrations/*.ts'], }); ``` -------------------------------- ### Quick Start: Create Hypertable Source: https://github.com/timescale/timescaledb-ts/blob/main/packages/core/README.md A basic example demonstrating how to create a hypertable using the TimescaleDB class. It shows the instantiation of a hypertable object and building the SQL statement for its creation. ```typescript import { TimescaleDB } from '@timescaledb/core'; // Create a hypertable const hypertable = TimescaleDB.createHypertable('measurements', { by_range: { column_name: 'time' }, }); // Generate SQL to create the hypertable const sql = hypertable.up().build(); // SELECT create_hypertable('measurements', by_range('time')); ``` -------------------------------- ### TypeScript Configuration Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/guides/getting-started.md Configures TypeScript compiler options for a Node.js project, enabling decorators and metadata emission for TypeORM. It targets ES2020 and uses commonjs module format. ```json { "compilerOptions": { "target": "ES2020", "module": "commonjs", "lib": ["es2020"], "strict": true, "esModuleInterop": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, "skipLibCheck": true, "outDir": "./dist" } } ``` -------------------------------- ### Run All Tests Locally Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/TESTING.md Executes the entire test suite from the project root directory using pnpm. May show warnings about single example project execution, which is expected. ```bash pnpm test ``` -------------------------------- ### Execute Analysis Script Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/guides/getting-started.md Runs the TypeScript analysis script using ts-node. This command executes the `analyze.ts` file to fetch and display candlestick data. ```bash ts-node src/analyze.ts ``` -------------------------------- ### Install TimescaleDB TypeORM Plugin Source: https://github.com/timescale/timescaledb-ts/blob/main/packages/typeorm/README.md Installs the necessary packages for the TimescaleDB TypeORM plugin using npm. ```bash npm install typeorm @timescaledb/typeorm ``` -------------------------------- ### CryptoPrice Entity Definition Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/guides/getting-started.md Defines the 'CryptoPrice' entity using TypeORM decorators, including primary columns, time columns, and hypertable configuration for TimescaleDB. It specifies compression policies and segment-by columns. ```typescript import { Entity, PrimaryColumn, Column } from 'typeorm'; import { Hypertable, TimeColumn } from '@timescaledb/typeorm'; @Entity('crypto_prices') @Hypertable({ compression: { compress: true, compress_orderby: 'timestamp', compress_segmentby: 'symbol', policy: { schedule_interval: '7 days', }, }, }) export class CryptoPrice { @PrimaryColumn({ type: 'varchar' }) symbol!: string; @TimeColumn() timestamp!: Date; @Column({ type: 'decimal', precision: 18, scale: 8 }) price!: number; @Column({ type: 'decimal', precision: 18, scale: 8 }) volume!: number; } ``` -------------------------------- ### Install TimescaleDB TypeORM Package Source: https://github.com/timescale/timescaledb-ts/blob/main/README.md Installs the TypeORM package and the TimescaleDB TypeORM adapter using npm. This is the initial step to integrate TimescaleDB features into your TypeORM application. ```bash npm install typeorm @timescaledb/typeorm ``` -------------------------------- ### Analyze Crypto Prices with Candlesticks Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/guides/getting-started.md Fetches and processes cryptocurrency price data to generate candlestick information. It inserts sample data and queries hourly candlesticks using TypeORM's getCandlesticks method. ```typescript import { AppDataSource } from './data-source'; import { CryptoPrice } from './models/CryptoPrice'; import { Between } from 'typeorm'; async function analyzeBTC() { await AppDataSource.initialize(); const repository = AppDataSource.getRepository(CryptoPrice); // First, let's insert some sample data await repository.save([ { symbol: 'BTC', timestamp: new Date('2025-01-01T00:00:00Z'), price: 42000.0, volume: 1.5 }, { symbol: 'BTC', timestamp: new Date('2025-01-01T00:15:00Z'), price: 42100.0, volume: 2.0 }, { symbol: 'BTC', timestamp: new Date('2025-01-01T00:30:00Z'), price: 41900.0, volume: 1.8 }, { symbol: 'BTC', timestamp: new Date('2025-01-01T00:45:00Z'), price: 42200.0, volume: 2.2 }, ]); // Query hourly candlesticks const candlesticks = await repository.getCandlesticks({ timeRange: { start: new Date('2025-01-01T00:00:00Z'), end: new Date('2025-01-02T00:00:00Z'), }, config: { price_column: 'price', volume_column: 'volume', bucket_interval: '1 hour', }, where: { symbol: 'BTC', }, }); console.log(JSON.stringify(candlesticks, null, 2)); await AppDataSource.destroy(); } analyzeBTC().catch(console.error); ``` -------------------------------- ### Install @timescaledb/core Source: https://github.com/timescale/timescaledb-ts/blob/main/packages/core/README.md Installs the @timescaledb/core package using npm. This is the first step to integrate TimescaleDB functionality into your TypeScript or JavaScript project. ```bash npm install @timescaledb/core ``` -------------------------------- ### TimescaleDB API Endpoints Source: https://github.com/timescale/timescaledb-ts/blob/main/examples/node-sequelize/README.md Documents the API endpoints for interacting with the TimescaleDB application, including recording page views and retrieving statistics. ```APIDOC API Endpoints: POST /api/pageview Description: Records a page view with user agent data. Method: POST Endpoint: /api/pageview Request Body: (Assumed JSON payload with user agent data) Returns: (Assumed success status) GET /api/stats?start=YYYY-MM-DD&end=YYYY-MM-DD Description: Retrieves statistics for a specified time range. Method: GET Endpoint: /api/stats Parameters: - start (string, required): The start date for the statistics range (YYYY-MM-DD). - end (string, required): The end date for the statistics range (YYYY-MM-DD). Returns: (Assumed JSON object with time-bucketed stats) GET /api/compression Description: Checks the compression status of TimescaleDB hypertables. Method: GET Endpoint: /api/compression Returns: (Assumed JSON object detailing compression status) ``` -------------------------------- ### Test Continuous Aggregate Data Retrieval Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/TESTING.md An example of an integration test for continuous aggregates using TypeORM. It demonstrates querying data from a repository filtered by a date range. ```typescript it('should create continuous aggregate view', async () => { await AppDataSource.getRepository(HourlyMetrics) .createQueryBuilder() .where('bucket >= :start', { start: startDate }) .andWhere('bucket < :end', { end: endDate }) .getMany(); }); ``` -------------------------------- ### Test Time Bucket Query Generation Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/TESTING.md Demonstrates testing the `timeBucket` functionality of the SQL builder. It generates SQL for time-bucketed queries with aggregations and asserts the output against a snapshot. ```typescript it('should generate time bucket query', () => { const hypertable = TimescaleDB.createHypertable('metrics', { by_range: { column_name: 'time' }, }); const { sql, params } = hypertable .timeBucket({ interval: '1 hour', metrics: [{ type: 'avg', column: 'value', alias: 'avg_value' }], }) .build({ range: { start: new Date('2025-01-01'), end: new Date('2025-01-02'), }, }); expect({ sql, params }).toMatchSnapshot(); }); ``` -------------------------------- ### GitHub Actions CI Service Configuration Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/TESTING.md An excerpt from a GitHub Actions workflow file defining a service for TimescaleDB. This configures a Docker image for TimescaleDB, sets environment variables, and maps ports for use within the CI environment. ```yaml services: timescaledb: image: timescale/timescaledb-ha:pg17 env: POSTGRES_PASSWORD: password ports: - 5432:5432 ``` -------------------------------- ### Monorepo Management Commands (pnpm) Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/CONTRIBUTING.md A collection of essential pnpm commands for managing the timescaledb-ts monorepo. These commands cover dependency installation, building, testing, code quality checks, and repository cleanup. ```shell pnpm install # Install all dependencies for the monorepo. ``` ```shell pnpm build # Build all packages within the monorepo. ``` ```shell pnpm test # Run tests for all packages in the monorepo. ``` ```shell pnpm lint # Perform linting checks on all packages. ``` ```shell pnpm format # Format code across all packages according to project standards. ``` ```shell pnpm clean # Perform a factory reset of the monorepo, useful for debugging. ``` -------------------------------- ### Query Time-Series Data with getTimeBucket Source: https://github.com/timescale/timescaledb-ts/blob/main/README.md Shows an example of querying a Hypertable using the getTimeBucket method provided by the TypeORM repository. This method allows for time-based bucketing and aggregation of data, specifying a time range, filtering conditions, and aggregation metrics. ```typescript import { AppDataSource } from './data-source'; import { PageLoad } from './models/PageLoad'; const repository = AppDataSource.getRepository(PageLoad); const stats = await repository.getTimeBucket({ timeRange: { start: new Date('2025-01-01'), end: new Date('2025-01-02'), }, where: { user_agent: 'Chrome', }, bucket: { interval: '1 hour', metrics: [{ type: 'distinct_count', column: 'user_agent', alias: 'unique_users' }], }, }); console.log(stats); // Expected output format: // [ // { time: '2021-01-01T00:00:00.000Z', unique_users: 5 }, // { time: '2021-01-01T01:00:00.000Z', unique_users: 10 }, // ... // ] ``` -------------------------------- ### API Endpoints Source: https://github.com/timescale/timescaledb-ts/blob/main/examples/node-typeorm/README.md Defines the available API endpoints for interacting with the page view tracking service, including recording page views and retrieving statistics or system status. ```APIDOC POST /api/pageview Description: Records a new page view with associated user agent data. Parameters: (Request Body) - User agent data and other relevant view details. Returns: (Status) - Confirmation of successful recording. GET /api/stats Description: Retrieves statistics for page views within a specified time range. Parameters: start (query string, required): The start date of the time range (e.g., YYYY-MM-DD). end (query string, required): The end date of the time range (e.g., YYYY-MM-DD). Returns: (JSON) - Aggregated statistics for the given period. GET /api/compression Description: Checks the current compression status for TimescaleDB hypertables. Parameters: None. Returns: (JSON) - Information about data compression status and configuration. ``` -------------------------------- ### Internal SQL Generation Example Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/design_decisions/auto-migrations.md Provides an internal view of how the SQL generation logic works within the library. It demonstrates accessing the built SQL query for a hypertable creation, which can be useful for debugging or understanding the generation process. ```typescript // Internal SQL generation can be updated const sql = hypertable.up().build(); await dataSource.query(sql); ``` -------------------------------- ### TimescaleDB: Time Bucket Queries Source: https://github.com/timescale/timescaledb-ts/blob/main/packages/core/README.md Provides examples of generating time-bucketed queries. It covers basic queries with metrics like count and distinct count, as well as queries with WHERE clauses that support simple equality, comparison operators, and IN/NOT IN clauses. ```typescript const hypertable = TimescaleDB.createHypertable('measurements', { by_range: { column_name: 'time' }, }); // Basic time bucket query const { sql, params } = hypertable .timeBucket({ interval: '1 hour', metrics: [ { type: 'count', alias: 'total' }, { type: 'distinct_count', column: 'device_id', alias: 'unique_devices' }, ], }) .build({ range: { start: new Date('2025-01-01'), end: new Date('2025-02-01'), }, }); // With where clause filtering const { sql: filteredSql, params: filteredParams } = hypertable .timeBucket({ interval: '1 hour', metrics: [ { type: 'count', alias: 'total' }, { type: 'distinct_count', column: 'device_id', alias: 'unique_devices' }, ], }) .build({ range: { start: new Date('2025-01-01'), end: new Date('2025-02-01'), }, where: { device_id: 'sensor-123', // Simple equality temperature: { '>': 25 }, // Comparison operator status: { IN: ['active', 'warning'] }, // IN clause location: { 'NOT IN': ['zone-a', 'zone-b'] }, // NOT IN clause }, }); ``` -------------------------------- ### TimescaleDB: Create Candlestick Aggregates Source: https://github.com/timescale/timescaledb-ts/blob/main/packages/core/README.md Demonstrates creating candlestick aggregates for time-series data. It includes examples for basic queries and queries with WHERE clause filtering, specifying the time, price, and optional volume columns, and the bucket interval. ```typescript const candlestick = TimescaleDB.createCandlestickAggregate('stock_prices', { time_column: 'timestamp', price_column: 'price', volume_column: 'volume', // optional bucket_interval: '1 hour', // defaults to '1 hour' }); // Basic candlestick query const { sql, params } = candlestick.build({ range: { start: new Date('2025-01-01'), end: new Date('2025-01-02'), }, }); // With where clause filtering const { sql: filteredSql, params: filteredParams } = candlestick.build({ range: { start: new Date('2025-01-01'), end: new Date('2025-01-02'), }, where: { symbol: 'AAPL', volume: { '>': 1000000 }, exchange: { IN: ['NYSE', 'NASDAQ'] }, }, }); // Returns candlestick data: // bucket_time, open, high, low, close, volume, vwap, etc. // const results = await query(sql, params); ``` -------------------------------- ### Test Hypertable SQL Generation Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/TESTING.md A Jest test case for the SQL builder, verifying that the `createHypertable` function generates the correct SQL for hypertable creation. It uses Jest snapshots for validation and does not require a database connection. ```typescript describe('Hypertable', () => { it('should generate hypertable creation SQL', () => { const hypertable = TimescaleDB.createHypertable('metrics', { by_range: { column_name: 'time' }, }); const sql = hypertable.up().build(); expect(sql).toMatchSnapshot(); }); }); ``` -------------------------------- ### Get Candlesticks Directly with Repository Method Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/guides/candlesticks.md Demonstrates how to use the `getCandlesticks` repository method directly on the `StockPrice` entity. This method fetches candlestick data based on a specified time range, configuration for price and volume columns, and filtering criteria. It requires `AppDataSource` and the `StockPrice` model. ```typescript import { AppDataSource } from './data-source'; import { StockPrice } from './models/StockPrice'; async function getCandlesticksDirectly() { const repository = AppDataSource.getRepository(StockPrice); const candlesticks = await repository.getCandlesticks({ timeRange: { start: new Date('2025-01-01'), end: new Date('2025-01-02'), }, config: { price_column: 'price', volume_column: 'volume', bucket_interval: '1 hour', }, where: { symbol: 'AAPL', }, }); console.log(JSON.stringify(candlesticks, null, 2)); } ``` -------------------------------- ### TimescaleDB: Create Hypertable Source: https://github.com/timescale/timescaledb-ts/blob/main/packages/core/README.md Demonstrates creating a hypertable with advanced options like range partitioning, compression policies (including schedule and segment-by columns), and generating SQL for creation, dropping, and inspecting hypertable existence. ```typescript const hypertable = TimescaleDB.createHypertable('table_name', { by_range: { column_name: 'time', }, compression: { compress: true, compress_orderby: 'time', compress_segmentby: 'device_id', policy: { schedule_interval: '7 days', }, }, }); // Generate creation SQL const createSql = hypertable.up().build(); // Generate drop SQL const dropSql = hypertable.down().build(); // Check if hypertable exists const checkSql = hypertable.inspect().build(); ``` -------------------------------- ### Get Hypertable Compression Statistics Source: https://github.com/timescale/timescaledb-ts/blob/main/packages/typeorm/README.md Fetches compression statistics for a hypertable using the `getCompressionStats` repository method. This provides insights into the number of chunks and compression status. ```typescript import { AppDataSource } from './data-source'; import { PageLoad } from './models/PageLoad'; const repository = AppDataSource.getRepository(PageLoad); const stats = await repository.getCompressionStats(); console.log(stats); // { // total_chunks: 100, // compressed_chunks: 50, // number_compressed_chunks: 10, // } ``` -------------------------------- ### Verify Release Tag Creation Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/RELEASE.md Lists all available Git tags in the repository. This step verifies that the new release tag has been correctly generated and added to the commit history. ```bash $ git tag ``` -------------------------------- ### Update Jest Snapshots Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/TESTING.md Command to update Jest snapshots after making changes to the SQL builders. This is used when test expectations for SQL generation need to be refreshed. ```bash pnpm test -u ``` -------------------------------- ### Generate TimescaleDB Hypertable SQL Source: https://github.com/timescale/timescaledb-ts/blob/main/packages/core/README.md Demonstrates generating SQL for creating a TimescaleDB hypertable and its compression settings. Uses the `up()` and `compression()` methods to build specific SQL statements. ```typescript const hypertable = TimescaleDB.createHypertable('measurements', { by_range: { column_name: 'time' }, }); // Generate only the hypertable creation SQL const createSql = hypertable.up().build(); // Generate only the compression SQL const compressionSql = hypertable .compression() .stats({ select: { total_chunks: true } }) .build(); ``` -------------------------------- ### Run TypeORM Migrations Source: https://github.com/timescale/timescaledb-ts/blob/main/packages/typeorm/README.md Executes TypeORM migrations using the command line. The '@timescaledb/typeorm' integration ensures that TimescaleDB specific objects like hypertables are created or updated. ```bash typeorm-ts-node-commonjs migration:run -d src/data-source.ts ``` -------------------------------- ### TimescaleDB Core API Documentation Source: https://github.com/timescale/timescaledb-ts/blob/main/README.md Provides access to core TimescaleDB functionalities like creating hypertables, managing compression, and setting up continuous aggregates. These are fundamental operations for time-series data management. ```APIDOC create_hypertable(table_name, time_column_name, chunk_time_interval=None, create_tables=True, associated_tables=None, partitioning_column=None, if_not_exists=False, migrate_data=True, chunk_data_format='compressed') - Creates a hypertable from an existing table. - Parameters: - table_name: Name of the table to convert into a hypertable. - time_column_name: Name of the time-series column in the table. - chunk_time_interval: The time interval for chunks (e.g., '1 day', '1 week'). - create_tables: Whether to create associated tables for partitioning. - associated_tables: List of tables to associate with the hypertable. - partitioning_column: Column to use for partitioning. - if_not_exists: If true, do nothing if the hypertable already exists. - migrate_data: Whether to migrate existing data to chunks. - chunk_data_format: Format for chunk data ('compressed' or 'uncompressed'). - Returns: None - Related: alter_table_compression, add_compression_policy, create_materialized_view - Example: SELECT create_hypertable('conditions', 'time'); ``` ```APIDOC alter_table_compression(table_name, compression_level=None, chunk_time_interval=None, if_not_exists=False) - Alters the compression settings for a hypertable. - Parameters: - table_name: Name of the hypertable to alter. - compression_level: Compression level (e.g., 1, 2, 3, 4). - chunk_time_interval: Time interval for chunks to apply compression to. - if_not_exists: If true, do nothing if the hypertable does not exist. - Returns: None - Related: add_compression_policy, create_hypertable - Example: SELECT alter_table_compression('conditions', compression_level => 1); ``` ```APIDOC add_compression_policy(table_name, chunk_time_interval, end_time=None, compress_segmentby=None, if_not_exists=False) - Adds a compression policy to a hypertable. - Parameters: - table_name: Name of the hypertable. - chunk_time_interval: Time interval for chunks to be compressed. - end_time: Optional end time for the policy. - compress_segmentby: Columns to segment data by before compression. - if_not_exists: If true, do nothing if the policy already exists. - Returns: None - Related: alter_table_compression, create_hypertable - Example: SELECT add_compression_policy('conditions', INTERVAL '7 days'); ``` ```APIDOC create_materialized_view(view_name, table_name, column_list, group_by_clause, order_by_clause=None, with_data=True, if_not_exists=False) - Creates a continuous aggregate materialized view. - Parameters: - view_name: Name of the materialized view. - table_name: Name of the hypertable to aggregate. - column_list: List of columns and aggregation functions (e.g., 'time_bucket(1h, time), avg(temp)'). - group_by_clause: Columns to group by (e.g., 'device_id'). - order_by_clause: Optional ordering for the view. - with_data: Whether to populate the view with existing data. - if_not_exists: If true, do nothing if the view already exists. - Returns: None - Related: create_hypertable - Example: SELECT create_materialized_view('conditions_hourly', 'conditions', 'time_bucket(1h, time), device_id, avg(temp)', 'device_id'); ``` ```APIDOC time_bucket(bucket_width, time_value, origin=None, timezone=None) - Returns the start of the time bucket for a given timestamp. - Parameters: - bucket_width: The width of the time bucket (e.g., '1 hour', '1 day'). - time_value: The timestamp to bucket. - origin: Optional origin timestamp for the bucket. - timezone: Optional timezone for bucketing. - Returns: The start timestamp of the bucket. - Related: Candlestick Aggregates, Stats Aggregates - Example: SELECT time_bucket('1 hour', '2023-10-27 10:30:00'); ``` ```APIDOC candlestick_agg(time_bucket, open, high, low, close) - Aggregates time-series data into candlestick intervals. - Parameters: - time_bucket: The time bucket for the candlestick. - open: The opening value. - high: The highest value. - low: The lowest value. - close: The closing value. - Returns: A row representing the candlestick interval. - Related: Time Bucket, Stats Aggregates - Example: SELECT time_bucket('1 hour', time), candlestick_agg(time_bucket, temp, temp, temp, temp) FROM conditions GROUP BY 1; ``` ```APIDOC show_chunks(hypertable_name) - Returns information about the chunks of a hypertable. - Parameters: - hypertable_name: The name of the hypertable. - Returns: A set of rows with chunk information. - Related: create_hypertable - Example: SELECT * FROM show_chunks('conditions'); ``` -------------------------------- ### Analyze Hourly Energy Usage with Time Bucketing Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/guides/energy-data.md Analyzes energy usage by bucketing data into hourly intervals, calculating sums, averages, and maximums for consumption, generation, and voltage. This function demonstrates querying time-series data for aggregated insights. ```typescript async function analyzeEnergyUsage() { const repository = AppDataSource.getRepository(EnergyMetric); const hourlyUsage = await repository.getTimeBucket({ timeRange: { start: new Date('2025-01-01'), end: new Date('2025-01-02'), }, bucket: { interval: '1 hour', metrics: [ { type: 'sum', column: 'consumption_kwh', alias: 'total_consumption' }, { type: 'sum', column: 'generation_kwh', alias: 'total_generation' }, { type: 'avg', column: 'voltage', alias: 'avg_voltage' }, { type: 'max', column: 'consumption_kwh', alias: 'peak_consumption' }, ], }, }); console.log('Hourly Energy Usage:', hourlyUsage); // [ // { // interval: '2025-01-01T00:00:00Z', // total_consumption: 245.6, // kWh // total_generation: 12.8, // kWh from solar // avg_voltage: 120.2, // V // peak_consumption: 12.4 // kWh // }, // ... // ] } ``` -------------------------------- ### TimescaleDB: Manage Compression Statistics Source: https://github.com/timescale/timescaledb-ts/blob/main/packages/core/README.md Illustrates how to retrieve compression statistics for a hypertable. This involves creating a hypertable object and then using the `.compression().stats()` method to build a query for compression-related metrics. ```typescript const hypertable = TimescaleDB.createHypertable('measurements', { by_range: { column_name: 'time' }, compression: { compress: true, compress_orderby: 'time', compress_segmentby: 'device_id', }, }); // Get compression statistics const statsSql = hypertable .compression() .stats({ select: { total_chunks: true, compressed_chunks: true, }, }) .build(); ``` -------------------------------- ### Configure TypeORM Data Source for TimescaleDB Source: https://github.com/timescale/timescaledb-ts/blob/main/packages/typeorm/README.md Sets up the TypeORM DataSource configuration, including importing the '@timescaledb/typeorm' library to enable TimescaleDB specific features during migrations and entity management. ```typescript import '@timescaledb/typeorm'; // This should be the first import in your file to hook into the TypeORM migration process import { DataSource } from 'typeorm'; import { PageLoad, HourlyPageViews } from './models'; export const AppDataSource = new DataSource({ type: 'postgres', url: process.env.DATABASE_URL, synchronize: false, logging: process.env.NODE_ENV === 'development', entities: [PageLoad, HourlyPageViews, StockPrice], // <-- Add your entities here migrations: ['migrations/*.ts'], }); ``` -------------------------------- ### TimescaleDB Feature Compatibility Table Source: https://github.com/timescale/timescaledb-ts/blob/main/README.md This table summarizes the compatibility of TimescaleDB features with different integration methods. It indicates support levels for Core, TypeORM (Automatic/Manual), and Sequelize (Automatic/Manual). ```APIDOC Feature Compatibility Overview: Core Functions: - Create Hypertable: Supported by Core, TypeORM (Auto), Sequelize (Manual via Core). - Add Compression: Supported by Core, TypeORM (Auto), Sequelize (Manual via Core). - Add Compression Policy: Supported by Core, TypeORM (Auto), Sequelize (Manual via Core). - Add Retention Policy: Not Supported. - Continuous Aggregates: Supported by Core, TypeORM (Auto), Sequelize (Manual via Core). Hyperfunctions: - Time Bucket: Supported by Core, TypeORM (Auto), Sequelize (Manual via Core). - Candlestick Aggregates: Supported by Core, TypeORM (Auto), Sequelize (Manual via Core). - Stats Aggregates: Not Supported. - Percentile Approximation: Not Supported. Info Views: - Chunks: Not Supported. - User Defined Actions: Not Supported. - Compression Settings: Supported by Core, TypeORM (Auto), Sequelize (Manual via Core). - Continuous Aggregates: Supported by Core, TypeORM (Auto), Sequelize (Manual via Core). - Hierarchical continuous aggregates: Supported by Core, TypeORM (Auto), Sequelize (Manual via Core). Legend: ✅ Supported ❌ Not Supported Auto = Automatic integration with ORM Manual = Manual integration using Core package ``` -------------------------------- ### Generated TimescaleDB SQL for Hypertable Creation Source: https://github.com/timescale/timescaledb-ts/blob/main/docs/design_decisions/auto-migrations.md Illustrates the SQL commands automatically generated by the TypeORM integration to create a TimescaleDB hypertable and apply compression settings based on the entity's decorators. This SQL is executed during the migration process. ```sql SELECT create_hypertable('page_loads', by_range('time')); ALTER TABLE "page_loads" SET (timescaledb.compress, timescaledb.compress_orderby = "time"); ```