Smart Tables SDK
SmartTablesSDK は、高度なクエリ、フィルタリング、ソート、データ操作機能を備えた構造化データテーブルの包括的な管理ソリューションを提供します。カスタムビュー、データのインポート/エクスポート、AI 搭載データ処理のサポートにより、強力なデータ管理アプリケーションを簡単に構築できます。
インストール
npm install @odin-ai-staging/sdk
クイックスタート
この例では、SmartTablesSDK を使用して EKB API を介してプログラムから構造化データテーブルを作成および管理する方法を学びます。まず、API 資格情報(ベース URL、プロジェクト ID、API キー、シークレット)で SDK を初期化し、シンプルなワークフローに従って機能するデータベースを構築します。最初に、createTable() で名前と説明を指定して新しいテーブルを作成します(この場合は「Customer Database」)。次に、addColumn() で列を追加してテーブルの構造を定義し、各列の名前、データ型(例:'text' または 'email')、説明を指定します。テーブルの構造が設定されたら、addRow() を使用してレコードをキーと値のペアとして挿入し、データを入力できます。最後に、queryTable() でデータをクエリします。これにはフィルタリング('contains' などの演算子を使用)、ページネーション、その他のクエリパラメーターがサポートされており、必要なデータを正確に取得できます。これにより、AI 搭載機能を備えたデータベースライクな構造をprogrammatically 作成する完全なソリューションが得られ、動的データ管理システム、CRM ツール、または API を通じて構造化情報を保存、整理、照会する必要があるアプリケーションに最適です。従来のデータベースインフラストラクチャを管理する必要はありません。
import { SmartTablesSDK } from '@odin-ai-staging/sdk';
// Initialize the SDK
const smartTablesSDK = new SmartTablesSDK({
baseUrl: 'https://your-api-endpoint.com/',
projectId: 'your-project-id',
apiKey: 'your-api-key',
apiSecret: 'your-api-secret'
});
// Quick example: Create table and add data
async function quickExample() {
// Create a new table
const table = await smartTablesSDK.createTable(
'Customer Database',
'Manage customer information'
);
// Add columns
await smartTablesSDK.addColumn(table.id, {
name: 'name',
type: 'text',
description: 'Customer name'
});
await smartTablesSDK.addColumn(table.id, {
name: 'email',
type: 'email',
description: 'Customer email address'
});
// Add data
await smartTablesSDK.addRow(table.id, {
name: 'John Doe',
email: 'john@example.com'
});
// Query data
const results = await smartTablesSDK.queryTable(table.id, {
filters: [{ column: 'name', operator: 'contains', value: 'John' }],
pagination: { limit: 10, page: 1 }
});
console.log('Query results:', results.data);
}
設定
SmartTablesSDKConfig インターフェース
interface SmartTablesSDKConfig {
baseUrl: string; // API endpoint URL
projectId: string; // Your project identifier
apiKey?: string; // API key for authentication
apiSecret?: string; // API secret for authentication
accessToken?: string; // Access token for web app usage
}
SmartTablesSDK は他の SDK コンポーネントと同じ設定を使用し、BaseClientConfig を拡張します。
コンセプト
SmartTable
SmartTable は、スキーマ、メタデータ、データ管理機能を備えた構造化データテーブルを表します。
interface SmartTable {
id: string; // Unique table identifier
project_id: string; // Project this table belongs to
title: string; // Display name of the table
description: string; // Table description
schema: SmartTableColumn[]; // Column definitions
table_name: string; // Internal table name
created_at?: number; // Creation timestamp
updated_at?: number; // Last update timestamp
}
SmartTableColumn
テーブルの列の構造とプロパティを定義します。
interface SmartTableColumn {
name: string; // Column name
type: ColumnType; // Data type
description?: string; // Column description
notNull?: boolean; // Required field
unique?: boolean; // Unique constraint
defaultValue?: string | number | boolean | null; // Default value
options?: Record<string, unknown>; // Additional options
}
type ColumnType = 'text' | 'number' | 'boolean' | 'date' | 'email' | 'url' | 'json';
フィルタリングとクエリ
複数の演算子とソートオプションを備えた高度なフィルタリングシステムです。
interface TableFilter {
column: string;
operator: FilterOperator;
value: string | number | boolean | null;
}
type FilterOperator = 'eq' | 'ne' | 'gt' | 'lt' | 'gte' | 'lte' | 'contains' | 'startswith' | 'endswith';
interface TableSort {
column: string;
direction: 'asc' | 'desc';
}
interface TablePagination {
page?: number;
limit?: number;
search?: string;
}
テーブル管理
getAllTables()
プロジェクト内のすべてのテーブルを取得します。
async getAllTables(): Promise<SmartTable[]>
例:
const tables = await smartTablesSDK.getAllTables();
tables.forEach(table => {
console.log(`Table: ${table.title} (${table.id})`);
console.log(`Columns: ${table.schema.length}`);
});
getTable(tableId)
ID で特定のテーブルを取得します。
async getTable(tableId: string): Promise<SmartTable>
例:
const table = await smartTablesSDK.getTable('table_123');
console.log('Table schema:', table.schema);
createTable(title, description, metadata?)
新しいテーブルを作成します。
async createTable(
title: string,
description: string,
metadata?: Record<string, unknown>
): Promise<SmartTable>
例:
const table = await smartTablesSDK.createTable(
'Product Catalog',
'Manage product information and inventory',
{ category: 'inventory', owner: 'admin' }
);
updateTable(tableId, title, description?, metadata?)
テーブルのメタデータを更新します。
async updateTable(
tableId: string,
title: string,
description?: string,
metadata?: Record<string, unknown>
): Promise<void>
例:
await smartTablesSDK.updateTable(
'table_123',
'Updated Product Catalog',
'Enhanced product management system',
{ version: '2.0' }
);
deleteTable(tableId)
テーブルとそのすべてのデータを完全に削除します。
async deleteTable(tableId: string): Promise<void>
例:
await smartTablesSDK.deleteTable('table_123');
列操作
addColumn(tableId, column)
テーブルに新しい列を追加します。
async addColumn(tableId: string, column: SmartTableColumn): Promise<void>
例:
// Add a text column
await smartTablesSDK.addColumn('table_123', {
name: 'product_name',
type: 'text',
description: 'Name of the product',
notNull: true
});
// Add a number column with default value
await smartTablesSDK.addColumn('table_123', {
name: 'price',
type: 'number',
description: 'Product price in USD',
defaultValue: 0,
notNull: true
});
// Add an email column with validation
await smartTablesSDK.addColumn('table_123', {
name: 'supplier_email',
type: 'email',
description: 'Supplier contact email',
unique: true
});
updateColumn(tableId, columnName, updates)
列のプロパティを更新します。
async updateColumn(
tableId: string,
columnName: string,
updates: Partial<SmartTableColumn>
): Promise<void>
例:
await smartTablesSDK.updateColumn('table_123', 'product_name', {
description: 'Updated product name field',
notNull: true,
unique: true
});
deleteColumn(tableId, columnName)
テーブルから列を削除します。
async deleteColumn(tableId: string, columnName: string): Promise<void>
例:
await smartTablesSDK.deleteColumn('table_123', 'obsolete_column');
データ操作
addRow(tableId, data)
テーブルに新しい行を追加します。
async addRow(tableId: string, data: Record<string, any>): Promise<any>
例:
const newRow = await smartTablesSDK.addRow('table_123', {
product_name: 'Wireless Headphones',
price: 99.99,
supplier_email: 'supplier@example.com',
in_stock: true
});
console.log('New row ID:', newRow.id);
updateRow(tableId, rowId, columnName, newValue)
テーブルの特定のセルを更新します。
async updateRow(
tableId: string,
rowId: string,
columnName: string,
newValue: any
): Promise<void>
例:
// Update product price
await smartTablesSDK.updateRow(
'table_123',
'row_456',
'price',
89.99
);
// Update stock status
await smartTablesSDK.updateRow(
'table_123',
'row_456',
'in_stock',
false
);
deleteRow(tableId, rowId)
テーブルから行を削除します。
async deleteRow(tableId: string, rowId: string): Promise<void>
例:
await smartTablesSDK.deleteRow('table_123', 'row_456');
クエリとフィルタリング
queryTable(tableId, options?)
高度なフィルタリング、ソート、ページネーションを使用してテーブルデータをクエリします。
async queryTable(
tableId: string,
options?: TableQueryOptions
): Promise<TableQueryResponse>
TableQueryOptions:
interface TableQueryOptions {
filters?: TableFilter[]; // Filter conditions
sort?: TableSort[]; // Sort configurations
pagination?: TablePagination; // Pagination settings
}
例:
基本クエリ
const results = await smartTablesSDK.queryTable('table_123');
console.log('All data:', results.data);
フィルタリングクエリ
const results = await smartTablesSDK.queryTable('table_123', {
filters: [
{ column: 'price', operator: 'gte', value: 50 },
{ column: 'in_stock', operator: 'eq', value: true },
{ column: 'product_name', operator: 'contains', value: 'headphones' }
]
});
ソートとページネーション付きクエリ
const results = await smartTablesSDK.queryTable('table_123', {
sort: [
{ column: 'price', direction: 'desc' },
{ column: 'product_name', direction: 'asc' }
],
pagination: {
page: 2,
limit: 20,
search: 'wireless'
}
});
console.log(`Found ${results.total} items`);
console.log(`Page ${results.page} of ${Math.ceil(results.total / results.limit)}`);
データのインポート/エクスポート
importTable(title, description, columnMappings, file)
CSV または Excel ファイルからデータをインポートします。
async importTable(
title: string,
description: string,
columnMappings: ColumnMapping[],
file: File
): Promise<ImportResult>
ColumnMapping インターフェース:
interface ColumnMapping {
sourceColumn: string; // Column name in source file
targetColumn: string; // Column name in target table
dataType: string; // Target data type
}
例:
const fileInput = document.getElementById('csvFile') as HTMLInputElement;
const file = fileInput.files[0];
const columnMappings: ColumnMapping[] = [
{ sourceColumn: 'Name', targetColumn: 'product_name', dataType: 'text' },
{ sourceColumn: 'Price', targetColumn: 'price', dataType: 'number' },
{ sourceColumn: 'Email', targetColumn: 'supplier_email', dataType: 'email' }
];
const result = await smartTablesSDK.importTable(
'Imported Products',
'Products imported from CSV',
columnMappings,
file
);
console.log(`Imported ${result.rows_imported} rows`);
console.log(`Table ID: ${result.data_type_id}`);
AI 搭載機能
computeRowColumns(dataTypeId, rowId, columnNames?)
特定の行の列に対して AI 計算をトリガーします。
async computeRowColumns(
dataTypeId: string,
rowId: string,
columnNames?: string[]
): Promise<void>
例:
// Compute specific columns for a row
await smartTablesSDK.computeRowColumns(
'table_123',
'row_456',
['ai_summary', 'sentiment_score']
);
computeAllRows(dataTypeId)
テーブル内のすべての行に対して AI 計算をトリガーします。
async computeAllRows(dataTypeId: string): Promise<{
message: string;
total_rows_processed: number;
total_columns_updated: number;
updated_columns: string[];
failed_rows: number[];
stopped_due_to_failures: boolean;
retry_attempts: Record<number, number>;
computation_id?: string;
history_table?: string;
}>
例:
const result = await smartTablesSDK.computeAllRows('table_123');
console.log(`Processed ${result.total_rows_processed} rows`);
console.log(`Updated ${result.total_columns_updated} columns`);
console.log(`Updated columns: ${result.updated_columns.join(', ')}`);
if (result.failed_rows.length > 0) {
console.log(`Failed rows: ${result.failed_rows.join(', ')}`);
}
エラーハンドリング
SmartTablesSDK は他の SDK コンポーネントと同じエラーハンドリングを使用します:
try {
const table = await smartTablesSDK.createTable('My Table', 'Description');
} catch (error) {
if (error instanceof APIError) {
console.error(`API Error ${error.status}: ${error.message}`);
if (error.detail) {
console.error('Details:', error.detail);
}
} else {
console.error('Unexpected error:', error);
}
}
例
完全なデータ管理アプリケーション
この例では、SmartTablesSDK を使用してインベントリと商品情報を処理する適切に構造化されたクラスで、完全な商品管理システムを構築する方法を学びます。ProductManager クラスは環境変数で SDK を初期化し、商品カタログ管理の完全なワークフローを提供します。initializeTable() メソッドは新しい「Product Catalog」テーブルを作成し、notNull で必須フィールドを、defaultValue で在庫状況を指定した 8 つの列(text、number、boolean、email、url、date など various データ型を含む)の包括的なスキーマを設定します。初期化後、addProduct() で新しい行を挿入し、各エントリに現在の日付を自動的にタイムスタンプとして付与できます。searchProducts() でカテゴリ、価格範囲('gte' と 'lte' 演算子を使用した以上/以下の比較)、テキスト検索、商品名のアルファベット順ソートなど高度な検索を実行できます。これにより、高度なクエリ機能を備えた構造化データ管理が必要な電子商取引インベントリシステム、商品データベース、またはあらゆるアプリケーションに対応する本番環境向けパターンが提供されます。複数のフィルタ条件、ページネーション、ソート、検索機能を統合したデータ管理ソリューションの構築方法が実演されます。
import { SmartTablesSDK } from '@odin-ai-staging/sdk';
class ProductManager {
private sdk: SmartTablesSDK;
private tableId?: string;
constructor() {
this.sdk = new SmartTablesSDK({
baseUrl: process.env.API_BASE_URL,
projectId: process.env.PROJECT_ID,
apiKey: process.env.API_KEY,
apiSecret: process.env.API_SECRET
});
}
async initializeTable() {
try {
// Create table
const table = await this.sdk.createTable(
'Product Catalog',
'Manage product inventory and information'
);
this.tableId = table.id;
// Add columns
await this.addColumns();
console.log('Table initialized:', this.tableId);
return table;
} catch (error) {
console.error('Failed to initialize table:', error);
throw error;
}
}
private async addColumns() {
const columns = [
{ name: 'name', type: 'text', description: 'Product name', notNull: true },
{ name: 'description', type: 'text', description: 'Product description' },
{ name: 'price', type: 'number', description: 'Price in USD', notNull: true },
{ name: 'category', type: 'text', description: 'Product category' },
{ name: 'in_stock', type: 'boolean', description: 'Stock availability', defaultValue: true },
{ name: 'supplier_email', type: 'email', description: 'Supplier contact' },
{ name: 'website', type: 'url', description: 'Product website' },
{ name: 'created_at', type: 'date', description: 'Creation date' }
];
for (const column of columns) {
await this.sdk.addColumn(this.tableId!, column);
}
}
async addProduct(productData: any) {
if (!this.tableId) throw new Error('Table not initialized');
try {
const result = await this.sdk.addRow(this.tableId, {
...productData,
created_at: new Date().toISOString()
});
console.log('Product added:', result);
return result;
} catch (error) {
console.error('Failed to add product:', error);
throw error;
}
}
async searchProducts(searchTerm: string, category?: string, minPrice?: number, maxPrice?: number) {
if (!this.tableId) throw new Error('Table not initialized');
const filters = [];
if (category) {
filters.push({ column: 'category', operator: 'eq', value: category });
}
if (minPrice !== undefined) {
filters.push({ column: 'price', operator: 'gte', value: minPrice });
}
if (maxPrice !== undefined) {
filters.push({ column: 'price', operator: 'lte', value: maxPrice });
}
try {
const results = await this.sdk.queryTable(this.tableId, {
filters,
pagination: {
search: searchTerm,
limit: 50
},
sort: [
{ column: 'name', direction: 'asc' }
]
});
return results;
} catch (error) {
console.error('Search failed:', error);
throw error;
}
}
}
// Usage
const productManager = new ProductManager();
await productManager.initializeTable();
await productManager.addProduct({
name: 'Wireless Headphones',
price: 199.99,
category: 'Electronics'
});
ベストプラクティス
効率的なクエリ
- 大規模データセットにはページネーションを使用します
- フィルタリングを適用してデータ転送量を削減します
- 可能な場合は複数の操作をまとめます
// Good: Efficient query with filters and pagination
const results = await smartTablesSDK.queryTable(tableId, {
filters: [{ column: 'status', operator: 'eq', value: 'active' }],
pagination: { limit: 50, page: 1 },
sort: [{ column: 'created_at', direction: 'desc' }]
});
// Bad: Fetching all data without filters
const allResults = await smartTablesSDK.queryTable(tableId);
スキーマ設計
- 適切な列型を定義します
- 制約(notNull、unique)を適切に使用します
- 意味のある説明を提供します
// Good: Well-defined column schema
await smartTablesSDK.addColumn(tableId, {
name: 'email',
type: 'email',
description: 'Customer email address',
notNull: true,
unique: true
});
// Bad: Vague column definition
await smartTablesSDK.addColumn(tableId, {
name: 'data',
type: 'text'
});
エラーハンドリングとバリデーション
- 常にエラーを適切にハンドリングします
- 操作前にデータを検証します
- 関連する操作にはトランザクションを使用します
async function safeTableOperation(tableId: string, data: any) {
try {
// Validate data first
if (!data.email || !data.email.includes('@')) {
throw new Error('Invalid email format');
}
// Perform operation
const result = await smartTablesSDK.addRow(tableId, data);
return result;
} catch (error) {
console.error('Operation failed:', error);
// Handle specific error types
if (error.message.includes('unique constraint')) {
throw new Error('Email already exists');
}
throw error;
}
}