Table Management
Complete guide to creating, modifying, and managing database tables using the Ductape SDK. Supports PostgreSQL, MySQL, MariaDB, MongoDB, DynamoDB, and Cassandra.
Quick Example
- TypeScript
- Java
- Go
- .NET
import Ductape from '@ductape/sdk';
// Initialize Ductape
const ductape = new Ductape({
accessKey: 'your-access-key',
});
// Connect to database
await ductape.databases.connect({ database: 'main-db' });
// Create a table with Mongoose-style schema
await ductape.databases.schema.create('users', {
id: { type: 'uuid', primaryKey: true },
email: { type: 'string', maxLength: 255, required: true, unique: true },
name: { type: 'string', maxLength: 100 },
age: 'integer', // Shorthand syntax
status: { type: 'enum', enum: ['active', 'inactive'], default: 'active' },
metadata: 'json',
}, { timestamps: true });
// List all tables
const tables = await ductape.databases.schema.list();
// Check if table exists
const exists = await ductape.databases.schema.exists('users');
import app.ductape.sdk.Ductape;
import app.ductape.sdk.core.EnvType;
import app.ductape.sdk.core.RequestContext;
// Initialize Ductape
RequestContext auth = new RequestContext(null, null, null, null, 'your-access-key');
Ductape ductape = new Ductape(EnvType.PRODUCTION, auth);
// Connect to database
ductape.databases().connect(Map<String, Object>.of(
"database", "main-db" ));
// Create a table with Mongoose-style schema
ductape.databases.schema.create('users', Map.of(
id: Map.of( "type", "uuid", "primaryKey", true ),
email: Map.of( "type", "string", "maxLength", 255, "required", true, "unique", true ),
name: Map.of( "type", "string", "maxLength", 100 ),
"age", "integer", // Shorthand syntax
status: Map.of( "type", "enum", enum: ['active', 'inactive'], "default", "active" ),
"metadata", "json"
), Map.of( "timestamps", true ));
// List all tables
Map<String, Object> tables = ductape.databases.schema.list();
// Check if table exists
Map<String, Object> exists = ductape.databases.schema.exists('users');
import (
"context"
"github.com/ductape/ductape/sdk/go/core"
ductapesdk "github.com/ductape/ductape/sdk/go/ductape"
)
// Initialize Ductape
auth := core.NewRequestContext("", "", "", "", 'your-access-key')
client, err := ductapesdk.New(core.EnvProduction, auth)
if err != nil {
return err
}
// Connect to database
client.Databases.Connect(ctx, map[string]any{
"database": "main-db" });
// Create a table with Mongoose-style schema
client.databases.schema.create('users', {
id: { "type": "uuid", "primaryKey": true },
email: { "type": "string", "maxLength": 255, "required": true, "unique": true },
name: { "type": "string", "maxLength": 100 },
"age": "integer", // Shorthand syntax
status: { "type": "enum", enum: ['active', 'inactive'], "default": "active" },
"metadata": "json",
}, { "timestamps": true });
// List all tables
tables := client.databases.schema.list();
// Check if table exists
exists := client.databases.schema.exists('users');
using Ductape.Sdk;
using Ductape.Sdk.Core;
// Initialize Ductape
var auth = new RequestContext(null, null, null, null, 'your-access-key', null);
var ductape = new Ductape(EnvType.Production, auth);
// Connect to database
await ductape.Database.Connect(new Dictionary<string, object?>
{
["database"] = "main-db" });
// Create a table with Mongoose-style schema
await ductape.databases.schema.create('users', {
id: { ["type"] = "uuid", ["primaryKey"] = true },
email: { ["type"] = "string", ["maxLength"] = 255, ["required"] = true, ["unique"] = true },
name: { ["type"] = "string", ["maxLength"] = 100 },
["age"] = "integer", // Shorthand syntax
status: { ["type"] = "enum", enum: ['active', 'inactive'], ["default"] = "active" },
["metadata"] = "json",
}, { ["timestamps"] = true });
// List all tables
var tables = await ductape.databases.schema.list();
// Check if table exists
var exists = await ductape.databases.schema.exists('users');
Connection Context
Establish a connection context once, then all schema operations use it automatically:
- TypeScript
- Java
- Go
- .NET
import Ductape from '@ductape/sdk';
const ductape = new Ductape({
accessKey: 'your-access-key',
});
// Connect once
await ductape.databases.connect({
database: 'main-db',
});
// All operations now use this context
await ductape.databases.schema.create('products', { ... });
await ductape.databases.schema.list();
await ductape.databases.schema.exists('users');
import app.ductape.sdk.Ductape;
import app.ductape.sdk.core.EnvType;
import app.ductape.sdk.core.RequestContext;
RequestContext auth = new RequestContext(null, null, null, null, 'your-access-key');
Ductape ductape = new Ductape(EnvType.PRODUCTION, auth);
// Connect once
ductape.databases().connect(Map<String, Object>.of(
"database", "main-db"
));
// All operations now use this context
ductape.databases.schema.create('products', Map.of( ... ));
ductape.databases.schema.list();
ductape.databases.schema.exists('users');
import (
"context"
"github.com/ductape/ductape/sdk/go/core"
ductapesdk "github.com/ductape/ductape/sdk/go/ductape"
)
auth := core.NewRequestContext("", "", "", "", 'your-access-key')
client, err := ductapesdk.New(core.EnvProduction, auth)
if err != nil {
return err
}
// Connect once
client.Databases.Connect(ctx, map[string]any{
"database": "main-db",
});
// All operations now use this context
client.databases.schema.create('products', { ... });
client.databases.schema.list();
client.databases.schema.exists('users');
using Ductape.Sdk;
using Ductape.Sdk.Core;
var auth = new RequestContext(null, null, null, null, 'your-access-key', null);
var ductape = new Ductape(EnvType.Production, auth);
// Connect once
await ductape.Database.Connect(new Dictionary<string, object?>
{
["database"] = "main-db",
});
// All operations now use this context
await ductape.databases.schema.create('products', { ... });
await ductape.databases.schema.list();
await ductape.databases.schema.exists('users');
Creating Tables
Basic Table Creation
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.create('users', {
id: { type: 'uuid', primaryKey: true },
email: { type: 'string', maxLength: 255, required: true, unique: true },
name: { type: 'string', maxLength: 100 },
age: 'integer',
}, { timestamps: true });
ductape.databases.schema.create('users', Map.of(
id: Map.of( "type", "uuid", "primaryKey", true ),
email: Map.of( "type", "string", "maxLength", 255, "required", true, "unique", true ),
name: Map.of( "type", "string", "maxLength", 100 ),
"age", "integer"
), Map.of( "timestamps", true ));
client.databases.schema.create('users', {
id: { "type": "uuid", "primaryKey": true },
email: { "type": "string", "maxLength": 255, "required": true, "unique": true },
name: { "type": "string", "maxLength": 100 },
"age": "integer",
}, { "timestamps": true });
await ductape.databases.schema.create('users', {
id: { ["type"] = "uuid", ["primaryKey"] = true },
email: { ["type"] = "string", ["maxLength"] = 255, ["required"] = true, ["unique"] = true },
name: { ["type"] = "string", ["maxLength"] = 100 },
["age"] = "integer",
}, { ["timestamps"] = true });
Table with All Field Types
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.create('products', {
// Primary key
id: { type: 'uuid', primaryKey: true },
// Strings
sku: { type: 'string', maxLength: 50, required: true },
name: { type: 'string', maxLength: 255, required: true },
description: 'text',
// Numbers
stock: 'integer',
views: 'bigint',
price: { type: 'decimal', precision: 10, scale: 2 },
rating: 'float',
// Boolean
is_active: { type: 'boolean', default: true },
// Dates
launch_date: 'date',
scheduled_at: 'datetime',
// JSON
settings: 'json',
metadata: 'json',
// Enum
status: { type: 'enum', enum: ['draft', 'published', 'archived'], default: 'draft' },
}, { timestamps: true });
ductape.databases.schema.create('products', Map.of(
// Primary key
id: Map.of( "type", "uuid", "primaryKey", true ),
// Strings
sku: Map.of( "type", "string", "maxLength", 50, "required", true ),
name: Map.of( "type", "string", "maxLength", 255, "required", true ),
"description", "text",
// Numbers
"stock", "integer",
"views", "bigint",
price: Map.of( "type", "decimal", "precision", 10, "scale", 2 ),
"rating", "float",
// Boolean
is_active: Map.of( "type", "boolean", "default", true ),
// Dates
"launch_date", "date",
"scheduled_at", "datetime",
// JSON
"settings", "json",
"metadata", "json",
// Enum
status: Map.of( "type", "enum", enum: ['draft', 'published', 'archived'], "default", "draft" )
), Map.of( "timestamps", true ));
client.databases.schema.create('products', {
// Primary key
id: { "type": "uuid", "primaryKey": true },
// Strings
sku: { "type": "string", "maxLength": 50, "required": true },
name: { "type": "string", "maxLength": 255, "required": true },
"description": "text",
// Numbers
"stock": "integer",
"views": "bigint",
price: { "type": "decimal", "precision": 10, "scale": 2 },
"rating": "float",
// Boolean
is_active: { "type": "boolean", "default": true },
// Dates
"launch_date": "date",
"scheduled_at": "datetime",
// JSON
"settings": "json",
"metadata": "json",
// Enum
status: { "type": "enum", enum: ['draft', 'published', 'archived'], "default": "draft" },
}, { "timestamps": true });
await ductape.databases.schema.create('products', {
// Primary key
id: { ["type"] = "uuid", ["primaryKey"] = true },
// Strings
sku: { ["type"] = "string", ["maxLength"] = 50, ["required"] = true },
name: { ["type"] = "string", ["maxLength"] = 255, ["required"] = true },
["description"] = "text",
// Numbers
["stock"] = "integer",
["views"] = "bigint",
price: { ["type"] = "decimal", ["precision"] = 10, ["scale"] = 2 },
["rating"] = "float",
// Boolean
is_active: { ["type"] = "boolean", ["default"] = true },
// Dates
["launch_date"] = "date",
["scheduled_at"] = "datetime",
// JSON
["settings"] = "json",
["metadata"] = "json",
// Enum
status: { ["type"] = "enum", enum: ['draft', 'published', 'archived'], ["default"] = "draft" },
}, { ["timestamps"] = true });
Table with Indexes
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.create('users', {
id: { type: 'uuid', primaryKey: true },
email: { type: 'string', maxLength: 255, required: true },
username: { type: 'string', maxLength: 100, required: true },
status: { type: 'string', maxLength: 20 },
}, {
timestamps: true,
indexes: [
{ fields: ['email'], unique: true },
{ fields: ['username'], unique: true },
{ fields: ['status', 'created_at'] },
],
});
ductape.databases.schema.create('users', Map.of(
id: Map.of( "type", "uuid", "primaryKey", true ),
email: Map.of( "type", "string", "maxLength", 255, "required", true ),
username: Map.of( "type", "string", "maxLength", 100, "required", true ),
status: Map.of( "type", "string", "maxLength", 20 )
), Map.of(
"timestamps", true,
indexes: [
Map.of( fields: ['email'], "unique", true ),
Map.of( fields: ['username'], "unique", true ),
Map.of( fields: ['status', 'created_at'] ),
]
));
client.databases.schema.create('users', {
id: { "type": "uuid", "primaryKey": true },
email: { "type": "string", "maxLength": 255, "required": true },
username: { "type": "string", "maxLength": 100, "required": true },
status: { "type": "string", "maxLength": 20 },
}, {
"timestamps": true,
indexes: [
{ fields: ['email'], "unique": true },
{ fields: ['username'], "unique": true },
{ fields: ['status', 'created_at'] },
],
});
await ductape.databases.schema.create('users', {
id: { ["type"] = "uuid", ["primaryKey"] = true },
email: { ["type"] = "string", ["maxLength"] = 255, ["required"] = true },
username: { ["type"] = "string", ["maxLength"] = 100, ["required"] = true },
status: { ["type"] = "string", ["maxLength"] = 20 },
}, {
["timestamps"] = true,
indexes: [
{ fields: ['email'], ["unique"] = true },
{ fields: ['username'], ["unique"] = true },
{ fields: ['status', 'created_at'] },
],
});
Advanced Field Definition
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.create('orders', {
id: { type: 'uuid', primaryKey: true },
customer_id: { type: 'uuid', required: true },
status: {
type: 'enum',
enum: ['pending', 'processing', 'completed', 'cancelled'],
default: 'pending',
required: true,
},
total: {
type: 'decimal',
precision: 10,
scale: 2,
required: true,
},
notes: 'text',
}, { timestamps: true });
ductape.databases.schema.create('orders', Map.of(
id: Map.of( "type", "uuid", "primaryKey", true ),
customer_id: Map.of( "type", "uuid", "required", true ),
status: Map.of(
"type", "enum",
enum: ['pending', 'processing', 'completed', 'cancelled'],
"default", "pending",
"required", true
),
total: Map.of(
"type", "decimal",
"precision", 10,
"scale", 2,
"required", true
),
"notes", "text"
), Map.of( "timestamps", true ));
client.databases.schema.create('orders', {
id: { "type": "uuid", "primaryKey": true },
customer_id: { "type": "uuid", "required": true },
status: {
"type": "enum",
enum: ['pending', 'processing', 'completed', 'cancelled'],
"default": "pending",
"required": true,
},
total: {
"type": "decimal",
"precision": 10,
"scale": 2,
"required": true,
},
"notes": "text",
}, { "timestamps": true });
await ductape.databases.schema.create('orders', {
id: { ["type"] = "uuid", ["primaryKey"] = true },
customer_id: { ["type"] = "uuid", ["required"] = true },
status: {
["type"] = "enum",
enum: ['pending', 'processing', 'completed', 'cancelled'],
["default"] = "pending",
["required"] = true,
},
total: {
["type"] = "decimal",
["precision"] = 10,
["scale"] = 2,
["required"] = true,
},
["notes"] = "text",
}, { ["timestamps"] = true });
Field Types Reference
Available Types
| Type | Description | Example |
|---|---|---|
integer | Whole numbers | 42 |
bigint | Large integers | 9007199254740991 |
smallint | Small integers | -32768 to 32767 |
float | Floating point | 3.14 |
double | Double precision | 3.141592653589793 |
decimal | Fixed precision | 99.99 |
string | Variable text | "hello" |
text | Long text | Long content |
boolean | True/false | true, false |
date | Date only | 2024-01-15 |
time | Time only | 14:30:00 |
datetime | Date and time | 2024-01-15 14:30:00 |
timestamp | Timestamp | Auto-managed |
json | JSON data | {"key": "value"} |
uuid | UUID | a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11 |
enum | Enumeration | 'pending' |
array | Array type | [1, 2, 3] |
binary | Binary data | Binary content |
blob | Binary large object | Large binary |
Mongoose-Style Aliases
For convenience, you can use Mongoose-style type names:
| Mongoose Type | Maps To |
|---|---|
String | string |
Number | integer |
Boolean | boolean |
Date | datetime |
ObjectId | uuid |
Array | array |
Object | json |
Mixed | json |
- TypeScript
- Java
- Go
- .NET
// Both are equivalent
await ductape.databases.schema.create('users', {
name: 'String', // Mongoose-style
age: 'integer', // Native style
});
// Both are equivalent
ductape.databases.schema.create('users', Map.of(
"name", "String", // Mongoose-style
"age", "integer", // Native style
));
// Both are equivalent
client.databases.schema.create('users', {
"name": "String", // Mongoose-style
"age": "integer", // Native style
});
// Both are equivalent
await ductape.databases.schema.create('users', {
["name"] = "String", // Mongoose-style
["age"] = "integer", // Native style
});
Field Options
- TypeScript
- Java
- Go
- .NET
{
type: 'string', // Field type (required)
required: true, // NOT NULL constraint
unique: true, // Unique constraint
primaryKey: true, // Primary key
autoIncrement: true, // Auto-increment (integers)
default: 'value', // Default value
minLength: 1, // Min length for validation (strings)
maxLength: 255, // Max length / column size (strings)
precision: 10, // Precision (decimals)
scale: 2, // Scale (decimals)
enum: ['a', 'b'], // Enum values
comment: 'Description', // Column comment
}
Map.of(
"type", "string", // Field type (required)
"required", true, // NOT NULL constraint
"unique", true, // Unique constraint
"primaryKey", true, // Primary key
"autoIncrement", true, // Auto-increment (integers)
"default", "value", // Default value
"minLength", 1, // Min length for validation (strings)
"maxLength", 255, // Max length / column size (strings)
"precision", 10, // Precision (decimals)
"scale", 2, // Scale (decimals)
enum: ['a', 'b'], // Enum values
"comment", "Description", // Column comment
)
{
"type": "string", // Field type (required)
"required": true, // NOT NULL constraint
"unique": true, // Unique constraint
"primaryKey": true, // Primary key
"autoIncrement": true, // Auto-increment (integers)
"default": "value", // Default value
"minLength": 1, // Min length for validation (strings)
"maxLength": 255, // Max length / column size (strings)
"precision": 10, // Precision (decimals)
"scale": 2, // Scale (decimals)
enum: ['a', 'b'], // Enum values
"comment": "Description", // Column comment
}
{
["type"] = "string", // Field type (required)
["required"] = true, // NOT NULL constraint
["unique"] = true, // Unique constraint
["primaryKey"] = true, // Primary key
["autoIncrement"] = true, // Auto-increment (integers)
["default"] = "value", // Default value
["minLength"] = 1, // Min length for validation (strings)
["maxLength"] = 255, // Max length / column size (strings)
["precision"] = 10, // Precision (decimals)
["scale"] = 2, // Scale (decimals)
enum: ['a', 'b'], // Enum values
["comment"] = "Description", // Column comment
}
Listing Tables
List All Tables
- TypeScript
- Java
- Go
- .NET
const tables = await ductape.databases.schema.list();
console.log('Tables:', tables);
// Output: ["users", "products", "orders", ...]
Map<String, Object> tables = ductape.databases.schema.list();
System.out.println('Tables:', tables);
// Output: ["users", "products", "orders", ...]
tables := client.databases.schema.list();
fmt.Println('Tables:', tables);
// Output: ["users", "products", "orders", ...]
var tables = await ductape.databases.schema.list();
Console.WriteLine('Tables:', tables);
// Output: ["users", "products", "orders", ...]
List Tables in Schema (PostgreSQL)
- TypeScript
- Java
- Go
- .NET
const tables = await ductape.databases.schema.list('public');
Map<String, Object> tables = ductape.databases.schema.list('public');
tables := client.databases.schema.list('public');
var tables = await ductape.databases.schema.list('public');
Checking Table Existence
- TypeScript
- Java
- Go
- .NET
const exists = await ductape.databases.schema.exists('users');
if (exists) {
console.log('Table exists');
} else {
console.log('Table does not exist');
}
Map<String, Object> exists = ductape.databases.schema.exists('users');
if (exists) Map.of(
System.out.println('Table exists');
) else Map.of(
System.out.println('Table does not exist');
)
exists := client.databases.schema.exists('users');
if (exists) {
fmt.Println('Table exists');
} else {
fmt.Println('Table does not exist');
}
var exists = await ductape.databases.schema.exists('users');
if (exists) {
Console.WriteLine('Table exists');
} else {
Console.WriteLine('Table does not exist');
}
Getting Table Schema
Retrieve Table Schema
- TypeScript
- Java
- Go
- .NET
const schema = await ductape.databases.schema.describe('users');
console.log('Table name:', schema.name);
console.log('Columns:', schema.columns);
console.log('Indexes:', schema.indexes);
console.log('Constraints:', schema.constraints);
Map<String, Object> schema = ductape.databases.schema.describe('users');
System.out.println('Table "name", ", schema.name);
System.out.println(""Columns", ", schema.columns);
System.out.println(""Indexes", ", schema.indexes);
System.out.println("Constraints:', schema.constraints);
schema := client.databases.schema.describe('users');
fmt.Println('Table "name": ", schema.name);
fmt.Println(""Columns": ", schema.columns);
fmt.Println(""Indexes": ", schema.indexes);
fmt.Println("Constraints:', schema.constraints);
var schema = await ductape.databases.schema.describe('users');
Console.WriteLine('Table ["name"] = ", schema.name);
Console.WriteLine("["Columns"] = ", schema.columns);
Console.WriteLine("["Indexes"] = ", schema.indexes);
Console.WriteLine("Constraints:', schema.constraints);
Inspect Table Structure
- TypeScript
- Java
- Go
- .NET
const schema = await ductape.databases.schema.describe('orders');
// List all columns
schema.columns.forEach((col) => {
console.log(`${col.name}: ${col.type}${col.nullable ? '' : ' NOT NULL'}`);
});
// Find primary key
const pk = schema.columns.find(col => col.isPrimaryKey);
console.log('Primary key:', pk?.name);
// List indexes
schema.indexes?.forEach((idx) => {
console.log(`${idx.name}: ${idx.columns.join(', ')} (unique: ${idx.unique})`);
});
Map<String, Object> schema = ductape.databases.schema.describe('orders');
// List all columns
schema.columns.forEach((col) => Map.of(
System.out.println(`$Map.of(col.name): $Map.of(col.type)$Map.of(col.nullable ? '' : ' NOT NULL')`);
));
// Find primary key
Map<String, Object> pk = schema.columns.find(col => col.isPrimaryKey);
System.out.println('Primary "key", ", pk?.name);
// List indexes
schema.indexes?.forEach((idx) => Map.of(
System.out.println(`$Map.of(idx.name): $Map.of(idx.columns.join(", ')) (unique: $Map.of(idx.unique))`);
));
schema := client.databases.schema.describe('orders');
// List all columns
schema.columns.forEach((col) => {
fmt.Println(`${col.name}: ${col.type}${col.nullable ? '' : ' NOT NULL'}`);
});
// Find primary key
pk := schema.columns.find(col => col.isPrimaryKey);
fmt.Println('Primary "key": ", pk?.name);
// List indexes
schema.indexes?.forEach((idx) => {
fmt.Println(`${idx.name}: ${idx.columns.join(", ')} (unique: ${idx.unique})`);
});
var schema = await ductape.databases.schema.describe('orders');
// List all columns
schema.columns.forEach((col) => {
Console.WriteLine(`${col.name}: ${col.type}${col.nullable ? '' : ' NOT NULL'}`);
});
// Find primary key
var pk = schema.columns.find(col => col.isPrimaryKey);
Console.WriteLine('Primary ["key"] = ", pk?.name);
// List indexes
schema.indexes?.forEach((idx) => {
Console.WriteLine(`${idx.name}: ${idx.columns.join(", ')} (unique: ${idx.unique})`);
});
Modifying Tables
Add Field
- TypeScript
- Java
- Go
- .NET
// Full definition
await ductape.databases.schema.addField('users', 'phone', {
type: 'string',
maxLength: 20,
required: false,
});
// Shorthand
await ductape.databases.schema.addField('users', 'avatar_url', 'string');
// Full definition
ductape.databases.schema.addField('users', 'phone', Map.of(
"type", "string",
"maxLength", 20,
"required", false
));
// Shorthand
ductape.databases.schema.addField('users', 'avatar_url', 'string');
// Full definition
client.databases.schema.addField('users', 'phone', {
"type": "string",
"maxLength": 20,
"required": false,
});
// Shorthand
client.databases.schema.addField('users', 'avatar_url', 'string');
// Full definition
await ductape.databases.schema.addField('users', 'phone', {
["type"] = "string",
["maxLength"] = 20,
["required"] = false,
});
// Shorthand
await ductape.databases.schema.addField('users', 'avatar_url', 'string');
Drop Field
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.dropField('users', 'phone');
ductape.databases.schema.dropField('users', 'phone');
client.databases.schema.dropField('users', 'phone');
await ductape.databases.schema.dropField('users', 'phone');
Rename Field
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.renameField('users', 'name', 'full_name');
ductape.databases.schema.renameField('users', 'name', 'full_name');
client.databases.schema.renameField('users', 'name', 'full_name');
await ductape.databases.schema.renameField('users', 'name', 'full_name');
Modify Field
- TypeScript
- Java
- Go
- .NET
// Change type/constraints
await ductape.databases.schema.modifyField('users', 'email', {
maxLength: 500,
required: true,
});
// Change default value
await ductape.databases.schema.modifyField('users', 'status', {
default: 'inactive',
});
// Change type/constraints
ductape.databases.schema.modifyField('users', 'email', Map.of(
"maxLength", 500,
"required", true
));
// Change default value
ductape.databases.schema.modifyField('users', 'status', Map.of(
"default", "inactive"
));
// Change type/constraints
client.databases.schema.modifyField('users', 'email', {
"maxLength": 500,
"required": true,
});
// Change default value
client.databases.schema.modifyField('users', 'status', {
"default": "inactive",
});
// Change type/constraints
await ductape.databases.schema.modifyField('users', 'email', {
["maxLength"] = 500,
["required"] = true,
});
// Change default value
await ductape.databases.schema.modifyField('users', 'status', {
["default"] = "inactive",
});
Index Management
Create Index
- TypeScript
- Java
- Go
- .NET
// Simple index
await ductape.databases.schema.createIndex('users', ['email']);
// Composite unique index
await ductape.databases.schema.createIndex('users', ['email', 'status'], {
unique: true,
name: 'idx_users_email_status',
});
// Sparse index (MongoDB)
await ductape.databases.schema.createIndex('users', ['phone'], {
sparse: true,
});
// Partial index (SQL)
await ductape.databases.schema.createIndex('users', ['status'], {
where: "status = 'active'",
});
// TTL index (MongoDB)
await ductape.databases.schema.createIndex('sessions', ['expires_at'], {
expireAfterSeconds: 3600,
});
// Simple index
ductape.databases.schema.createIndex('users', ['email']);
// Composite unique index
ductape.databases.schema.createIndex('users', ['email', 'status'], Map.of(
"unique", true,
"name", "idx_users_email_status"
));
// Sparse index (MongoDB)
ductape.databases.schema.createIndex('users', ['phone'], Map.of(
"sparse", true
));
// Partial index (SQL)
ductape.databases.schema.createIndex('users', ['status'], Map.of(
"where", "status = 'active'"
));
// TTL index (MongoDB)
ductape.databases.schema.createIndex('sessions', ['expires_at'], Map.of(
"expireAfterSeconds", 3600
));
// Simple index
client.databases.schema.createIndex('users', ['email']);
// Composite unique index
client.databases.schema.createIndex('users', ['email', 'status'], {
"unique": true,
"name": "idx_users_email_status",
});
// Sparse index (MongoDB)
client.databases.schema.createIndex('users', ['phone'], {
"sparse": true,
});
// Partial index (SQL)
client.databases.schema.createIndex('users', ['status'], {
"where": "status = 'active'",
});
// TTL index (MongoDB)
client.databases.schema.createIndex('sessions', ['expires_at'], {
"expireAfterSeconds": 3600,
});
// Simple index
await ductape.databases.schema.createIndex('users', ['email']);
// Composite unique index
await ductape.databases.schema.createIndex('users', ['email', 'status'], {
["unique"] = true,
["name"] = "idx_users_email_status",
});
// Sparse index (MongoDB)
await ductape.databases.schema.createIndex('users', ['phone'], {
["sparse"] = true,
});
// Partial index (SQL)
await ductape.databases.schema.createIndex('users', ['status'], {
["where"] = "status = 'active'",
});
// TTL index (MongoDB)
await ductape.databases.schema.createIndex('sessions', ['expires_at'], {
["expireAfterSeconds"] = 3600,
});
List Indexes
- TypeScript
- Java
- Go
- .NET
const indexes = await ductape.databases.schema.indexes('users');
indexes.forEach(idx => {
console.log(`${idx.name}: ${idx.columns.join(', ')} (unique: ${idx.unique})`);
});
Map<String, Object> indexes = ductape.databases.schema.indexes('users');
indexes.forEach(idx => Map.of(
System.out.println(`$Map.of(idx.name): $Map.of(idx.columns.join(', ')) (unique: $Map.of(idx.unique))`);
));
indexes := client.databases.schema.indexes('users');
indexes.forEach(idx => {
fmt.Println(`${idx.name}: ${idx.columns.join(', ')} (unique: ${idx.unique})`);
});
var indexes = await ductape.databases.schema.indexes('users');
indexes.forEach(idx => {
Console.WriteLine(`${idx.name}: ${idx.columns.join(', ')} (unique: ${idx.unique})`);
});
Drop Index
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.dropIndex('users', 'idx_users_email_status');
ductape.databases.schema.dropIndex('users', 'idx_users_email_status');
client.databases.schema.dropIndex('users', 'idx_users_email_status');
await ductape.databases.schema.dropIndex('users', 'idx_users_email_status');
Constraint Management (SQL)
Add Constraint
- TypeScript
- Java
- Go
- .NET
// Foreign key
await ductape.databases.schema.addConstraint('posts', {
name: 'fk_posts_author',
type: 'foreignKey',
columns: ['author_id'],
references: {
table: 'users',
columns: ['id'],
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
},
});
// Unique constraint
await ductape.databases.schema.addConstraint('users', {
name: 'uq_users_email_org',
type: 'unique',
columns: ['email', 'org_id'],
});
// Check constraint
await ductape.databases.schema.addConstraint('users', {
name: 'chk_users_age',
type: 'check',
columns: ['age'],
expression: 'age >= 0 AND age <= 150',
});
// Foreign key
ductape.databases.schema.addConstraint('posts', Map.of(
"name", "fk_posts_author",
"type", "foreignKey",
columns: ['author_id'],
references: Map.of(
"table", "users",
columns: ['id'],
"onDelete", "CASCADE",
"onUpdate", "CASCADE"
)
));
// Unique constraint
ductape.databases.schema.addConstraint('users', Map.of(
"name", "uq_users_email_org",
"type", "unique",
columns: ['email', 'org_id']
));
// Check constraint
ductape.databases.schema.addConstraint('users', Map.of(
"name", "chk_users_age",
"type", "check",
columns: ['age'],
"expression", "age >= 0 AND age <= 150"
));
// Foreign key
client.databases.schema.addConstraint('posts', {
"name": "fk_posts_author",
"type": "foreignKey",
columns: ['author_id'],
references: {
"table": "users",
columns: ['id'],
"onDelete": "CASCADE",
"onUpdate": "CASCADE",
},
});
// Unique constraint
client.databases.schema.addConstraint('users', {
"name": "uq_users_email_org",
"type": "unique",
columns: ['email', 'org_id'],
});
// Check constraint
client.databases.schema.addConstraint('users', {
"name": "chk_users_age",
"type": "check",
columns: ['age'],
"expression": "age >= 0 AND age <= 150",
});
// Foreign key
await ductape.databases.schema.addConstraint('posts', {
["name"] = "fk_posts_author",
["type"] = "foreignKey",
columns: ['author_id'],
references: {
["table"] = "users",
columns: ['id'],
["onDelete"] = "CASCADE",
["onUpdate"] = "CASCADE",
},
});
// Unique constraint
await ductape.databases.schema.addConstraint('users', {
["name"] = "uq_users_email_org",
["type"] = "unique",
columns: ['email', 'org_id'],
});
// Check constraint
await ductape.databases.schema.addConstraint('users', {
["name"] = "chk_users_age",
["type"] = "check",
columns: ['age'],
["expression"] = "age >= 0 AND age <= 150",
});
Drop Constraint
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.dropConstraint('posts', 'fk_posts_author');
ductape.databases.schema.dropConstraint('posts', 'fk_posts_author');
client.databases.schema.dropConstraint('posts', 'fk_posts_author');
await ductape.databases.schema.dropConstraint('posts', 'fk_posts_author');
Renaming Tables
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.rename('users', 'app_users');
ductape.databases.schema.rename('users', 'app_users');
client.databases.schema.rename('users', 'app_users');
await ductape.databases.schema.rename('users', 'app_users');
Dropping Tables
- TypeScript
- Java
- Go
- .NET
// Simple drop
await ductape.databases.schema.drop('old_table');
// With options
await ductape.databases.schema.drop('users', {
ifExists: true,
cascade: true, // Drop dependent objects
});
// Simple drop
ductape.databases.schema.drop('old_table');
// With options
ductape.databases.schema.drop('users', Map.of(
"ifExists", true,
"cascade", true, // Drop dependent objects
));
// Simple drop
client.databases.schema.drop('old_table');
// With options
client.databases.schema.drop('users', {
"ifExists": true,
"cascade": true, // Drop dependent objects
});
// Simple drop
await ductape.databases.schema.drop('old_table');
// With options
await ductape.databases.schema.drop('users', {
["ifExists"] = true,
["cascade"] = true, // Drop dependent objects
});
Database-Specific Features
PostgreSQL
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.create('documents', {
id: { type: 'uuid', primaryKey: true },
data: 'json',
tags: 'array',
}, {
sqlOptions: {
unlogged: true, // Faster, no crash recovery
tablespace: 'fast_storage',
},
});
ductape.databases.schema.create('documents', Map.of(
id: Map.of( "type", "uuid", "primaryKey", true ),
"data", "json",
"tags", "array"
), Map.of(
sqlOptions: Map.of(
"unlogged", true, // Faster, no crash recovery
"tablespace", "fast_storage"
)
));
client.databases.schema.create('documents', {
id: { "type": "uuid", "primaryKey": true },
"data": "json",
"tags": "array",
}, {
sqlOptions: {
"unlogged": true, // Faster, no crash recovery
"tablespace": "fast_storage",
},
});
await ductape.databases.schema.create('documents', {
id: { ["type"] = "uuid", ["primaryKey"] = true },
["data"] = "json",
["tags"] = "array",
}, {
sqlOptions: {
["unlogged"] = true, // Faster, no crash recovery
["tablespace"] = "fast_storage",
},
});
MongoDB
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.create('users', {
_id: { type: 'uuid', primaryKey: true },
email: { type: 'string', required: true },
profile: 'json',
}, {
mongoOptions: {
capped: false,
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['email'],
properties: {
email: { bsonType: 'string' }
}
}
},
validationLevel: 'strict',
},
});
ductape.databases.schema.create('users', Map.of(
_id: Map.of( "type", "uuid", "primaryKey", true ),
email: Map.of( "type", "string", "required", true ),
"profile", "json"
), Map.of(
mongoOptions: Map.of(
"capped", false,
validator: Map.of(
$jsonSchema: Map.of(
"bsonType", "object",
required: ['email'],
properties: Map.of(
email: Map.of( "bsonType", "string" )
)
)
),
"validationLevel", "strict"
)
));
client.databases.schema.create('users', {
_id: { "type": "uuid", "primaryKey": true },
email: { "type": "string", "required": true },
"profile": "json",
}, {
mongoOptions: {
"capped": false,
validator: {
$jsonSchema: {
"bsonType": "object",
required: ['email'],
properties: {
email: { "bsonType": "string" }
}
}
},
"validationLevel": "strict",
},
});
await ductape.databases.schema.create('users', {
_id: { ["type"] = "uuid", ["primaryKey"] = true },
email: { ["type"] = "string", ["required"] = true },
["profile"] = "json",
}, {
mongoOptions: {
["capped"] = false,
validator: {
$jsonSchema: {
["bsonType"] = "object",
required: ['email'],
properties: {
email: { ["bsonType"] = "string" }
}
}
},
["validationLevel"] = "strict",
},
});
DynamoDB
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.create('users', {
id: { type: 'string', primaryKey: true },
email: 'string',
created_at: 'timestamp',
}, {
dynamoOptions: {
partitionKey: { name: 'id', type: 'S' },
sortKey: { name: 'created_at', type: 'N' },
billingMode: 'PAY_PER_REQUEST',
globalSecondaryIndexes: [{
name: 'email-index',
partitionKey: { name: 'email', type: 'S' },
projection: 'ALL',
}],
},
});
ductape.databases.schema.create('users', Map.of(
id: Map.of( "type", "string", "primaryKey", true ),
"email", "string",
"created_at", "timestamp"
), Map.of(
dynamoOptions: Map.of(
partitionKey: Map.of( "name", "id", "type", "S" ),
sortKey: Map.of( "name", "created_at", "type", "N" ),
"billingMode", "PAY_PER_REQUEST",
globalSecondaryIndexes: [Map.of(
"name", "email-index",
partitionKey: Map.of( "name", "email", "type", "S" ),
"projection", "ALL"
)]
)
));
client.databases.schema.create('users', {
id: { "type": "string", "primaryKey": true },
"email": "string",
"created_at": "timestamp",
}, {
dynamoOptions: {
partitionKey: { "name": "id", "type": "S" },
sortKey: { "name": "created_at", "type": "N" },
"billingMode": "PAY_PER_REQUEST",
globalSecondaryIndexes: [{
"name": "email-index",
partitionKey: { "name": "email", "type": "S" },
"projection": "ALL",
}],
},
});
await ductape.databases.schema.create('users', {
id: { ["type"] = "string", ["primaryKey"] = true },
["email"] = "string",
["created_at"] = "timestamp",
}, {
dynamoOptions: {
partitionKey: { ["name"] = "id", ["type"] = "S" },
sortKey: { ["name"] = "created_at", ["type"] = "N" },
["billingMode"] = "PAY_PER_REQUEST",
globalSecondaryIndexes: [{
["name"] = "email-index",
partitionKey: { ["name"] = "email", ["type"] = "S" },
["projection"] = "ALL",
}],
},
});
Cassandra
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.create('events', {
id: { type: 'uuid', primaryKey: true },
user_id: 'uuid',
event_type: 'string',
data: 'json',
}, {
cassandraOptions: {
partitionKey: ['user_id'],
clusteringColumns: ['id'],
clusteringOrder: [{ column: 'id', order: 'DESC' }],
defaultTTL: 86400,
},
});
ductape.databases.schema.create('events', Map.of(
id: Map.of( "type", "uuid", "primaryKey", true ),
"user_id", "uuid",
"event_type", "string",
"data", "json"
), Map.of(
cassandraOptions: Map.of(
partitionKey: ['user_id'],
clusteringColumns: ['id'],
clusteringOrder: [Map.of( "column", "id", "order", "DESC" )],
"defaultTTL", 86400
)
));
client.databases.schema.create('events', {
id: { "type": "uuid", "primaryKey": true },
"user_id": "uuid",
"event_type": "string",
"data": "json",
}, {
cassandraOptions: {
partitionKey: ['user_id'],
clusteringColumns: ['id'],
clusteringOrder: [{ "column": "id", "order": "DESC" }],
"defaultTTL": 86400,
},
});
await ductape.databases.schema.create('events', {
id: { ["type"] = "uuid", ["primaryKey"] = true },
["user_id"] = "uuid",
["event_type"] = "string",
["data"] = "json",
}, {
cassandraOptions: {
partitionKey: ['user_id'],
clusteringColumns: ['id'],
clusteringOrder: [{ ["column"] = "id", ["order"] = "DESC" }],
["defaultTTL"] = 86400,
},
});
Common Patterns
Soft Delete Tables
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.create('users', {
id: { type: 'uuid', primaryKey: true },
email: { type: 'string', maxLength: 255, required: true },
deleted_at: 'timestamp',
}, { timestamps: true });
// Query excluding deleted records
await ductape.databases.query({
table: 'users',
where: { deleted_at: null },
});
ductape.databases.schema.create('users', Map.of(
id: Map.of( "type", "uuid", "primaryKey", true ),
email: Map.of( "type", "string", "maxLength", 255, "required", true ),
"deleted_at", "timestamp"
), Map.of( "timestamps", true ));
// Query excluding deleted records
ductape.databases.query(Map.of(
"table", "users",
where: Map.of( deleted_at: null )
));
client.databases.schema.create('users', {
id: { "type": "uuid", "primaryKey": true },
email: { "type": "string", "maxLength": 255, "required": true },
"deleted_at": "timestamp",
}, { "timestamps": true });
// Query excluding deleted records
client.databases.query({
"table": "users",
where: { deleted_at: null },
});
await ductape.databases.schema.create('users', {
id: { ["type"] = "uuid", ["primaryKey"] = true },
email: { ["type"] = "string", ["maxLength"] = 255, ["required"] = true },
["deleted_at"] = "timestamp",
}, { ["timestamps"] = true });
// Query excluding deleted records
await ductape.databases.query({
["table"] = "users",
where: { deleted_at: null },
});
Audit Tables
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.create('audit_logs', {
id: { type: 'uuid', primaryKey: true },
user_id: 'uuid',
action: { type: 'string', maxLength: 100, required: true },
entity_type: { type: 'string', maxLength: 100 },
entity_id: 'integer',
changes: 'json',
ip_address: { type: 'string', maxLength: 45 },
}, {
timestamps: true,
indexes: [
{ fields: ['user_id', 'action'] },
{ fields: ['entity_type', 'entity_id'] },
],
});
ductape.databases.schema.create('audit_logs', Map.of(
id: Map.of( "type", "uuid", "primaryKey", true ),
"user_id", "uuid",
action: Map.of( "type", "string", "maxLength", 100, "required", true ),
entity_type: Map.of( "type", "string", "maxLength", 100 ),
"entity_id", "integer",
"changes", "json",
ip_address: Map.of( "type", "string", "maxLength", 45 )
), Map.of(
"timestamps", true,
indexes: [
Map.of( fields: ['user_id', 'action'] ),
Map.of( fields: ['entity_type', 'entity_id'] ),
]
));
client.databases.schema.create('audit_logs', {
id: { "type": "uuid", "primaryKey": true },
"user_id": "uuid",
action: { "type": "string", "maxLength": 100, "required": true },
entity_type: { "type": "string", "maxLength": 100 },
"entity_id": "integer",
"changes": "json",
ip_address: { "type": "string", "maxLength": 45 },
}, {
"timestamps": true,
indexes: [
{ fields: ['user_id', 'action'] },
{ fields: ['entity_type', 'entity_id'] },
],
});
await ductape.databases.schema.create('audit_logs', {
id: { ["type"] = "uuid", ["primaryKey"] = true },
["user_id"] = "uuid",
action: { ["type"] = "string", ["maxLength"] = 100, ["required"] = true },
entity_type: { ["type"] = "string", ["maxLength"] = 100 },
["entity_id"] = "integer",
["changes"] = "json",
ip_address: { ["type"] = "string", ["maxLength"] = 45 },
}, {
["timestamps"] = true,
indexes: [
{ fields: ['user_id', 'action'] },
{ fields: ['entity_type', 'entity_id'] },
],
});
Polymorphic Associations
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.create('comments', {
id: { type: 'uuid', primaryKey: true },
user_id: 'uuid',
content: 'text',
commentable_type: { type: 'string', maxLength: 100 },
commentable_id: 'integer',
}, {
timestamps: true,
indexes: [
{ fields: ['commentable_type', 'commentable_id'] },
],
});
ductape.databases.schema.create('comments', Map.of(
id: Map.of( "type", "uuid", "primaryKey", true ),
"user_id", "uuid",
"content", "text",
commentable_type: Map.of( "type", "string", "maxLength", 100 ),
"commentable_id", "integer"
), Map.of(
"timestamps", true,
indexes: [
Map.of( fields: ['commentable_type', 'commentable_id'] ),
]
));
client.databases.schema.create('comments', {
id: { "type": "uuid", "primaryKey": true },
"user_id": "uuid",
"content": "text",
commentable_type: { "type": "string", "maxLength": 100 },
"commentable_id": "integer",
}, {
"timestamps": true,
indexes: [
{ fields: ['commentable_type', 'commentable_id'] },
],
});
await ductape.databases.schema.create('comments', {
id: { ["type"] = "uuid", ["primaryKey"] = true },
["user_id"] = "uuid",
["content"] = "text",
commentable_type: { ["type"] = "string", ["maxLength"] = 100 },
["commentable_id"] = "integer",
}, {
["timestamps"] = true,
indexes: [
{ fields: ['commentable_type', 'commentable_id'] },
],
});
Migrations
Every schema operation automatically generates a migration that's tracked and can be replayed across environments. The simplified API handles this transparently:
- TypeScript
- Java
- Go
- .NET
// This creates AND applies a migration
await ductape.databases.schema.create('users', {
id: { type: 'uuid', primaryKey: true },
email: { type: 'string', required: true },
});
// The migration is stored and can be viewed
// See the Migrations documentation for details
// This creates AND applies a migration
ductape.databases.schema.create('users', Map.of(
id: Map.of( "type", "uuid", "primaryKey", true ),
email: Map.of( "type", "string", "required", true )
));
// The migration is stored and can be viewed
// See the Migrations documentation for details
// This creates AND applies a migration
client.databases.schema.create('users', {
id: { "type": "uuid", "primaryKey": true },
email: { "type": "string", "required": true },
});
// The migration is stored and can be viewed
// See the Migrations documentation for details
// This creates AND applies a migration
await ductape.databases.schema.create('users', {
id: { ["type"] = "uuid", ["primaryKey"] = true },
email: { ["type"] = "string", ["required"] = true },
});
// The migration is stored and can be viewed
// See the Migrations documentation for details
For more control over migrations, see the Migrations documentation.
Best Practices
1. Always Include Timestamps
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.create('products', {
id: { type: 'uuid', primaryKey: true },
name: { type: 'string', required: true },
}, { timestamps: true }); // Adds created_at, updated_at
ductape.databases.schema.create('products', Map.of(
id: Map.of( "type", "uuid", "primaryKey", true ),
name: Map.of( "type", "string", "required", true )
), Map.of( "timestamps", true )); // Adds created_at, updated_at
client.databases.schema.create('products', {
id: { "type": "uuid", "primaryKey": true },
name: { "type": "string", "required": true },
}, { "timestamps": true }); // Adds created_at, updated_at
await ductape.databases.schema.create('products', {
id: { ["type"] = "uuid", ["primaryKey"] = true },
name: { ["type"] = "string", ["required"] = true },
}, { ["timestamps"] = true }); // Adds created_at, updated_at
2. Define Indexes at Creation
- TypeScript
- Java
- Go
- .NET
await ductape.databases.schema.create('users', {
id: { type: 'uuid', primaryKey: true },
email: { type: 'string', required: true },
}, {
indexes: [
{ fields: ['email'], unique: true },
],
});
ductape.databases.schema.create('users', Map.of(
id: Map.of( "type", "uuid", "primaryKey", true ),
email: Map.of( "type", "string", "required", true )
), Map.of(
indexes: [
Map.of( fields: ['email'], "unique", true ),
]
));
client.databases.schema.create('users', {
id: { "type": "uuid", "primaryKey": true },
email: { "type": "string", "required": true },
}, {
indexes: [
{ fields: ['email'], "unique": true },
],
});
await ductape.databases.schema.create('users', {
id: { ["type"] = "uuid", ["primaryKey"] = true },
email: { ["type"] = "string", ["required"] = true },
}, {
indexes: [
{ fields: ['email'], ["unique"] = true },
],
});
3. Use Appropriate Field Types
- TypeScript
- Java
- Go
- .NET
// Good: VARCHAR with appropriate maxLength
email: { type: 'string', maxLength: 255 }
// Bad: TEXT for short strings
email: 'text' // Wastes space
// Good: VARCHAR with appropriate maxLength
email: Map.of( "type", "string", "maxLength", 255 )
// Bad: TEXT for short strings
"email", "text" // Wastes space
// Good: VARCHAR with appropriate maxLength
email: { "type": "string", "maxLength": 255 }
// Bad: TEXT for short strings
"email": "text" // Wastes space
// Good: VARCHAR with appropriate maxLength
email: { ["type"] = "string", ["maxLength"] = 255 }
// Bad: TEXT for short strings
["email"] = "text" // Wastes space
4. Name Tables and Columns Consistently
- TypeScript
- Java
- Go
- .NET
// Good naming conventions:
// - Tables: plural, snake_case
// - Columns: snake_case
// - Indexes: idx_{table}_{columns}
// - Foreign keys: {related_table_singular}_id
await ductape.databases.schema.create('order_items', {
id: { type: 'uuid', primaryKey: true },
order_id: 'uuid',
product_id: 'uuid',
quantity: 'integer',
unit_price: { type: 'decimal', precision: 10, scale: 2 },
});
// Good naming conventions:
// - Tables: plural, snake_case
// - Columns: snake_case
// - Indexes: idx_Map.of(table)_Map.of(columns)
// - Foreign keys: Map.of(related_table_singular)_id
ductape.databases.schema.create('order_items', Map.of(
id: Map.of( "type", "uuid", "primaryKey", true ),
"order_id", "uuid",
"product_id", "uuid",
"quantity", "integer",
unit_price: Map.of( "type", "decimal", "precision", 10, "scale", 2 )
));
// Good naming conventions:
// - Tables: plural, snake_case
// - Columns: snake_case
// - Indexes: idx_{table}_{columns}
// - Foreign keys: {related_table_singular}_id
client.databases.schema.create('order_items', {
id: { "type": "uuid", "primaryKey": true },
"order_id": "uuid",
"product_id": "uuid",
"quantity": "integer",
unit_price: { "type": "decimal", "precision": 10, "scale": 2 },
});
// Good naming conventions:
// - Tables: plural, snake_case
// - Columns: snake_case
// - Indexes: idx_{table}_{columns}
// - Foreign keys: {related_table_singular}_id
await ductape.databases.schema.create('order_items', {
id: { ["type"] = "uuid", ["primaryKey"] = true },
["order_id"] = "uuid",
["product_id"] = "uuid",
["quantity"] = "integer",
unit_price: { ["type"] = "decimal", ["precision"] = 10, ["scale"] = 2 },
});
Error Handling
- TypeScript
- Java
- Go
- .NET
import { DatabaseError, DatabaseErrorType } from '@ductape/sdk';
try {
await ductape.databases.schema.create('users', { ... });
} catch (error) {
if (error instanceof DatabaseError) {
switch (error.type) {
case DatabaseErrorType.SCHEMA_ERROR:
console.error('Invalid schema definition');
break;
case DatabaseErrorType.TABLE_EXISTS:
console.error('Table already exists');
break;
case DatabaseErrorType.CONNECTION_ERROR:
console.error('Database connection failed');
break;
default:
throw error;
}
}
}
import Map.of( DatabaseError, DatabaseErrorType ) from '@ductape/sdk';
try Map.of(
ductape.databases.schema.create('users', Map.of( ... ));
) catch (error) Map.of(
if (error instanceof DatabaseError) Map.of(
switch (error.type) Map.of(
case DatabaseErrorType.SCHEMA_ERROR:
console.error('Invalid schema definition');
break;
case DatabaseErrorType.TABLE_EXISTS:
console.error('Table already exists');
break;
case DatabaseErrorType.CONNECTION_ERROR:
console.error('Database connection failed');
break;
default:
throw error;
)
)
)
import { DatabaseError, DatabaseErrorType } from '@ductape/sdk';
try {
client.databases.schema.create('users', { ... });
} catch (error) {
if (error instanceof DatabaseError) {
switch (error.type) {
case DatabaseErrorType.SCHEMA_ERROR:
console.error('Invalid schema definition');
break;
case DatabaseErrorType.TABLE_EXISTS:
console.error('Table already exists');
break;
case DatabaseErrorType.CONNECTION_ERROR:
console.error('Database connection failed');
break;
default:
throw error;
}
}
}
import { DatabaseError, DatabaseErrorType } from '@ductape/sdk';
try {
await ductape.databases.schema.create('users', { ... });
} catch (error) {
if (error instanceof DatabaseError) {
switch (error.type) {
case DatabaseErrorType.SCHEMA_ERROR:
console.error('Invalid schema definition');
break;
case DatabaseErrorType.TABLE_EXISTS:
console.error('Table already exists');
break;
case DatabaseErrorType.CONNECTION_ERROR:
console.error('Database connection failed');
break;
default:
throw error;
}
}
}
Next Steps
- Migrations - Version-controlled schema changes
- Indexing - Optimize query performance
- Direct Queries - Full database API reference
- Best Practices - Production patterns