Database Operations (sdk.db)
The Server SDK provides intelligent routing between databases, along with schema introspection and batch capabilities.
Introduction
Access your databases with a unified interface:
import { AerostackServer } from '@aerostack/sdk';
export default {
async fetch(request, env) {
const sdk = new AerostackServer(env);
// Automatic routing based on query complexity
const { results } = await sdk.db.query('SELECT * FROM users');
}
}Features
Intelligent Routing
The SDK automatically routes queries:
- Database (SQL): For simple reads and high-performance edge access.
- Postgres: For complex queries (JOINs, aggregations) or large writes.
You can also force routing:
-- Force Postgres
SELECT * FROM orders /* aerostack:target=postgres */Schema Introspection (getSchema)
Inspect your database structure at runtime:
// Get schema for primary database (usually Database or Postgres based on config)
const schema = await sdk.db.getSchema();
console.log(schema.tables);
// [{ name: 'users', columns: [...] }]Batch Operations (batch)
Execute multiple independent queries in a single round-trip:
const batchResult = await sdk.db.batch([
{ sql: 'INSERT INTO logs ...', params: [...] },
{ sql: 'UPDATE stats ...', params: [...] }
]);Transactions
(Coming soon for Postgres)
⚠️
Always use prepared statements (parameterized queries) to prevent SQL injection.
sdk.db.query('SELECT * FROM users WHERE id = ?', [userId])
Error Handling
Database errors are structured:
try {
await sdk.db.query('SELECT * FROM ghost_table');
} catch (error) {
if (error.code === 'DB_TABLE_NOT_FOUND') {
// Suggestion: "Run migrations first: aerostack db migrate apply"
console.log(error.details.suggestion);
}
}