@agentdb/sdk
Version:
JavaScript SDK for AgentDB database service
201 lines (165 loc) • 7.7 kB
JavaScript
/**
* Database Management Example
*
* This example demonstrates all database management operations:
* - Creating databases
* - Listing databases
* - Renaming databases
* - Copying databases
* - Deleting databases
* - File upload/download operations
*/
import { DatabaseService } from '../index.js';
async function databaseManagementExample() {
const BASE_URL = 'https://api.agentdb.dev';
const API_KEY = 'your-api-key-here';
const TOKEN = 'your-uuid-token-here';
const BACKUP_TOKEN = 'your-backup-token-here'; // Optional: different token for backups
try {
console.log('=== Database Management Example ===\n');
// Create service instance
const service = new DatabaseService(BASE_URL, API_KEY);
// 1. List existing databases
console.log('1. Listing existing databases...');
const initialDatabases = await service.listDatabases(TOKEN);
console.log('Current databases:', initialDatabases.map(db => `${db.name} (${db.type})`));
// 2. Create a new database by executing SQL
console.log('\n2. Creating a new database...');
const connection = service.connect(TOKEN, 'example-management-db', 'sqlite');
await connection.execute({
sql: `CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)`,
params: []
});
// Insert some sample data
await connection.execute([
{
sql: 'INSERT INTO users (name, email) VALUES (?, ?)',
params: ['Alice Johnson', 'alice@example.com']
},
{
sql: 'INSERT INTO users (name, email) VALUES (?, ?)',
params: ['Bob Smith', 'bob@example.com']
},
{
sql: 'INSERT INTO users (name, email) VALUES (?, ?)',
params: ['Carol Williams', 'carol@example.com']
}
]);
console.log('✓ Created database with sample data');
// 3. Verify the database was created
console.log('\n3. Verifying database creation...');
const updatedDatabases = await service.listDatabases(TOKEN);
const newDb = updatedDatabases.find(db => db.name === 'example-management-db');
if (newDb) {
console.log(`✓ Database created: ${newDb.name} (${newDb.size} bytes)`);
}
// 4. Rename the database
console.log('\n4. Renaming database...');
await service.renameDatabase(TOKEN, 'example-management-db', 'renamed-example-db', 'sqlite');
console.log('✓ Database renamed from "example-management-db" to "renamed-example-db"');
// 5. Copy database (create a backup)
console.log('\n5. Creating database backup...');
await service.copyDatabase(TOKEN, 'renamed-example-db', 'sqlite', TOKEN, 'backup-example-db');
console.log('✓ Database copied to "backup-example-db"');
// 6. List databases again to see changes
console.log('\n6. Listing databases after operations...');
const finalDatabases = await service.listDatabases(TOKEN);
console.log('Updated databases:');
finalDatabases.forEach(db => {
console.log(` - ${db.name} (${db.type}, ${Math.round(db.size / 1024)}KB, modified: ${new Date(db.modified).toLocaleString()})`);
});
// 7. Download database file
console.log('\n7. Downloading database file...');
const { downloadUrl, fileName } = await service.getDownloadUrl(TOKEN, 'renamed-example-db', 'sqlite');
console.log(`✓ Generated download URL for ${fileName}`);
console.log(` URL expires in 1 hour`);
// In a real application, you would use this URL to download the file
// For demonstration, we'll just show the URL structure
console.log(` Download URL: ${downloadUrl.substring(0, 100)}...`);
// 8. Demonstrate upload URL generation
console.log('\n8. Generating upload URL for new database...');
const { uploadUrl, fileName: uploadFileName } = await service.getUploadUrl(TOKEN, 'uploaded-example-db', 'sqlite');
console.log(`✓ Generated upload URL for ${uploadFileName}`);
console.log(` Upload URL: ${uploadUrl.substring(0, 100)}...`);
// 9. Cross-token copy (if backup token is different)
if (BACKUP_TOKEN && BACKUP_TOKEN !== TOKEN) {
console.log('\n9. Copying database to backup token...');
await service.copyDatabase(TOKEN, 'renamed-example-db', 'sqlite', BACKUP_TOKEN, 'cross-token-backup');
console.log('✓ Database copied to backup token');
} else {
console.log('\n9. Skipping cross-token copy (same token or no backup token provided)');
}
// 10. Clean up - delete test databases
console.log('\n10. Cleaning up test databases...');
const databasesToDelete = ['renamed-example-db', 'backup-example-db'];
for (const dbName of databasesToDelete) {
try {
await service.deleteDatabase(TOKEN, dbName, 'sqlite');
console.log(`✓ Deleted database: ${dbName}`);
} catch (error) {
console.log(`✗ Failed to delete ${dbName}: ${error.message}`);
}
}
// 11. Final database list
console.log('\n11. Final database list...');
const cleanedDatabases = await service.listDatabases(TOKEN);
console.log('Remaining databases:', cleanedDatabases.map(db => `${db.name} (${db.type})`));
console.log('\n=== Database Management Example Complete ===');
} catch (error) {
console.error('Error in database management example:', error.message);
if (error.statusCode) {
console.error('Status code:', error.statusCode);
}
console.error('Full error:', error);
}
}
// Helper function to demonstrate file upload/download workflow
async function fileTransferWorkflow() {
const BASE_URL = 'https://api.agentdb.dev';
const API_KEY = 'your-api-key-here';
const TOKEN = 'your-uuid-token-here';
console.log('\n=== File Transfer Workflow ===\n');
try {
const service = new DatabaseService(BASE_URL, API_KEY);
// Create a database to work with
const connection = service.connect(TOKEN, 'transfer-test-db', 'sqlite');
await connection.execute({
sql: 'CREATE TABLE test (id INTEGER PRIMARY KEY, data TEXT)',
params: []
});
// 1. Get download URL
console.log('1. Getting download URL...');
const downloadInfo = await service.getDownloadUrl(TOKEN, 'transfer-test-db', 'sqlite');
console.log(`✓ Download URL generated for ${downloadInfo.fileName}`);
// 2. Simulate file download (in real app, you'd fetch the URL)
console.log('2. Simulating file download...');
console.log(` File: ${downloadInfo.fileName}`);
console.log(` Expires in: ${downloadInfo.expiresIn} seconds`);
// 3. Get upload URL for a new database
console.log('\n3. Getting upload URL for new database...');
const uploadInfo = await service.getUploadUrl(TOKEN, 'uploaded-copy-db', 'sqlite');
console.log(`✓ Upload URL generated for ${uploadInfo.fileName}`);
// 4. Simulate file upload workflow
console.log('4. File upload workflow:');
console.log(` a. Use the upload URL: ${uploadInfo.uploadUrl.substring(0, 80)}...`);
console.log(` b. PUT the file data with Content-Type: application/octet-stream`);
console.log(` c. File will be automatically processed and moved to EFS`);
console.log(` d. Original S3 file will be cleaned up`);
// Clean up
await service.deleteDatabase(TOKEN, 'transfer-test-db', 'sqlite');
console.log('\n✓ Cleaned up test database');
} catch (error) {
console.error('Error in file transfer workflow:', error.message);
}
}
// Run the examples
async function runExamples() {
await databaseManagementExample();
await fileTransferWorkflow();
}
runExamples();