Skip to content
Last updated

SDK Overview

Under Active Development

SDK APIs are subject to change (2026)

The tdx SDK provides a TypeScript/JavaScript API for interacting with Treasure Data, usable in both Node.js and browser environments.

Installation

npm install @treasuredata/tdx

Quick Start

Node.js

import { TDX } from '@treasuredata/tdx/sdk';

// Create TDX instance (loads API key from environment if not provided)
const tdx = TDX.create({
  site: 'us01',
  apiKey: 'your_key_id/your_key_secret'  // Optional: omit to load from env
});

// List databases
const databases = await tdx.query.listDatabases();

// Run a query
const result = await tdx.query.execute('SELECT * FROM mydb.users LIMIT 10');

Browser

<script type="module">
  import { TDX, LogLevel } from 'https://unpkg.com/@treasuredata/tdx';

  // Browser: pass API key directly
  const tdx = TDX.create({
    site: 'us01',
    apiKey: 'your_key_id/your_key_secret',
    logLevel: LogLevel.INFO
  });

  const result = await tdx.query.execute('SELECT * FROM mydb.users LIMIT 10');
</script>

Configuration

SDKConfig Options

OptionTypeDescriptionDefault
sitestringTD site (us01, jp01, eu01, ap02)us01
apiKeystringAPI key (key_id/key_secret)from env
logLevelLogLevelLog level (TRACE, DEBUG, INFO, WARN, ERROR)INFO
proxystringHTTP proxy URL for corporate networksfrom config/env

Creating TDX Instance

import { TDX, LogLevel } from '@treasuredata/tdx/sdk';

// Load API key from environment variables
const tdx = TDX.create();

// Override specific options
const tdx = TDX.create({
  site: 'jp01',
  logLevel: LogLevel.DEBUG
});

// Pass API key directly
const tdx = TDX.create({
  apiKey: 'your_key_id/your_key_secret'
});

// Use an HTTP proxy (corporate networks)
const tdx = TDX.create({
  site: 'us01',
  proxy: 'http://proxy.corp.com:8080'
});

API Modules

The SDK exposes several API modules via the TDX class:

ModulePropertyDescription
QuerySDKtdx.queryExecute queries, list databases/tables, describe schemas
JobSDKtdx.jobsSubmit and manage jobs
SegmentSDKtdx.segmentCDP segment operations
WorkflowSDKtdx.workflowWorkflow management
LLMSDKtdx.llmLLM projects and agents
RawAPItdx.apiRaw HTTP requests to TD APIs

The QuerySDK module provides all query and schema operations via tdx.query.*.

API Reference

See the full API Reference for detailed documentation of all classes, interfaces, and types.

Examples

List Databases

const databases = await tdx.query.listDatabases();
for (const db of databases) {
  console.log(db.database_name);
}

// Filter by pattern
const prodDbs = await tdx.query.listDatabases('prod_*');

List Tables

// List all tables in a database
const tables = await tdx.query.listTables('mydb');

// Filter by pattern
const userTables = await tdx.query.listTables('mydb', 'user_*');

Run a Query

const result = await tdx.query.execute('SELECT * FROM mydb.users LIMIT 10');
for (const row of result.data) {
  console.log(row);
}

// Access column metadata
console.log('Columns:', result.columns.map(c => c.name));

Get Table Schema

const columns = await tdx.query.describeTable('mydb', 'users');
for (const col of columns) {
  console.log(col.column_name, col.data_type, col.is_nullable);
}

Show Table Contents

const result = await tdx.query.showTable('mydb', 'users', 10);
for (const row of result.data) {
  console.log(row);
}

Submit a Job

const job = await tdx.jobs.submit('mydb', 'SELECT * FROM users', 'trino');
console.log('Job ID:', job.job_id);

// Get job results
const results = await tdx.jobs.result(job.job_id);

Error Handling

import { SDKError, ErrorCode } from '@treasuredata/tdx/sdk';

try {
  await tdx.query.execute('INVALID SQL');
} catch (error) {
  if (error instanceof SDKError) {
    console.error('Error code:', error.code);
    console.error('Message:', error.message);

    // Check for specific error types
    if (error.code === ErrorCode.TRINO_SYNTAX_ERROR) {
      console.error('SQL syntax error');
    }
  }
}

TypeScript Support

The SDK is written in TypeScript and provides full type definitions:

import type {
  SDKConfig,
  DatabaseInfo,
  TableInfo,
  ColumnInfo,
  CompleteQueryResult
} from '@treasuredata/tdx/sdk';

// Typed query results
const result: CompleteQueryResult<{ id: number; name: string }> =
  await tdx.query.execute<{ id: number; name: string }>('SELECT id, name FROM users');

// result.data is typed as { id: number; name: string }[]

Architecture

The tdx project is designed with a layered architecture that separates the CLI interface from the core SDK.

High-Level Architecture

Treasure Data APIs

TDX SDK (TypeScript)

Client Environments

Node.js / CLI
tdx commands

Web Browser
Client-side Apps

TypeScript/JavaScript API

TD REST API
(DB, Table, Job)

Trino API
(Queries)

CDP API
(Segments)

LLM API
(AI/Chat)

Key Architectural Patterns

SDK Configuration Pattern

Configuration is separated from object instantiation:

  • Configuration is a pure data structure - No loading logic in config objects
  • Load configuration outside constructors - Use dedicated loading functions
  • Pass configuration objects to constructors - Not individual parameters
// Config loading function: loadConfigOnce(options) → Config
// SDK/Client constructors: constructor(config: Config)
// CLI creates config once, passes to all components

Dependency Injection

Dependencies are passed instead of created:

  • Commands receive SDK instance via context - Don't instantiate inside commands
  • Clients receive config object - Don't load config inside clients
  • Create instances at application entry point - CLI creates once, passes down

Command Pattern

Commands are thin wrappers over SDK:

  • Receive dependencies via context (SDK instance, options, args)
  • Call SDK methods for business logic
  • Handle output formatting and display
  • Return exit codes (0 = success, 1 = error)

SDK Layer

The SDK layer contains all business logic:

  • Testable without CLI concerns
  • Reusable programmatically
  • Independent of framework (Commander.js, etc.)
  • Works in multiple environments (Node.js, browser)

Client Layer

API clients handle HTTP communication:

  • Accept configuration object in constructor
  • Implement API protocols (REST, streaming, etc.)
  • Handle retries, rate limiting, error handling
  • Return structured data

Configuration Loading

Configuration is loaded with priority order:

  1. Explicitly passed values (highest priority)
  2. Environment variables (site-specific, then generic)
  3. Config files (site-specific, then generic)
  4. Defaults (lowest priority)

Multi-Site Support

SiteAPI Endpoint
us01 (default)api.treasuredata.com
jp01api.treasuredata.co.jp
eu01api.eu01.treasuredata.com
ap02api.ap02.treasuredata.com

Site aliases are supported (us → us01, jp → jp01).