Docs/Development

Database

PostgreSQL-based database system with entities, relationships, and migrations.

Database Management

Overview

AlgorithmShift provides a powerful database management system built on PostgreSQL. Each workspace gets an isolated schema with full support for entities, relationships, indexing, and migrations.


Entity Definition

Field Types

TypePostgreSQLDescriptionExample
uuidUUIDUnique identifier550e8400-...
stringVARCHAR(255)Short text"Product Name"
textTEXTLong textParagraphs
integerINTEGERWhole numbers42
bigintBIGINTLarge integers9007199254740991
decimalDECIMAL(10,2)Precise decimals99.99
floatDOUBLE PRECISIONFloating point3.14159
booleanBOOLEANTrue/falsetrue
dateDATEDate only2024-01-15
timeTIMETime only14:30:00
timestampTIMESTAMPTZDate and time2024-01-15T14:30:00Z
jsonJSONBStructured data{"key": "value"}
arrayARRAYList of values["a", "b", "c"]
enumENUMPredefined values'active'

Relationships

One-to-Many

┌──────────┐       ┌──────────┐
│  Users   │ 1───* │  Orders  │
└──────────┘       └──────────┘
typescript
// In orders entity
{
  name: 'user_id',
  type: 'uuid',
  foreignKey: {
    entity: 'users',
    field: 'id',
    onDelete: 'set_null'  // Keep orders if user deleted
  }
}

Many-to-Many

┌──────────┐       ┌─────────────────┐       ┌──────────┐
│ Products │ *───* │ product_tags    │ *───* │   Tags   │
└──────────┘       │ (junction table)│       └──────────┘
                   └─────────────────┘

Indexes

Index Types

TypeUse CaseExample
StandardEquality queriesWHERE status = 'active'
UniqueEnforce uniquenessemail column
CompositeMulti-column queriesWHERE user_id = ? AND status = ?
PartialConditional indexWHERE deleted_at IS NULL
GINJSON/Array searchWHERE metadata @> '{}'
Full-textText searchWHERE name ILIKE '%search%'

Soft Delete

Enable soft delete to retain records:

typescript
{
  name: 'products',
  enableSoftDelete: true,
  // Adds: deleted_at TIMESTAMP, deleted_by UUID
}

Behavior

OperationWith Soft Delete
DELETESets deleted_at = now()
SELECTExcludes deleted_at IS NOT NULL
findWithDeleted()Includes soft-deleted records
restore()Sets deleted_at = NULL
forceDelete()Permanently removes record

Audit Logging

Track all changes to records:

typescript
{
  name: 'products',
  enableAuditLog: true
}

Audit Log Table

sql
CREATE TABLE audit_logs (
  id UUID PRIMARY KEY,
  entity_name VARCHAR(100),
  record_id UUID,
  action VARCHAR(20),      -- create, update, delete
  old_values JSONB,
  new_values JSONB,
  changed_fields TEXT[],
  user_id UUID,
  ip_address INET,
  user_agent TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

Migrations

Migration Workflow

1. Design Schema (UI)
   └── Visual entity editor

2. Generate Migration
   └── Auto-generate SQL from changes

3. Review Migration
   └── Edit SQL if needed

4. Apply to Development
   └── Test with sample data

5. Promote to Staging
   └── Apply and test integrations

6. Deploy to Production
   └── Backup → Apply → Verify

Backup & Restore

Automated Backups

EnvironmentFrequencyRetention
DevelopmentDaily7 days
StagingDaily14 days
ProductionHourly30 days

Manual Backup

bash
# Create backup
algorithmshift db backup --env production

# Download backup
algorithmshift db backup download backup-20240115.sql

# Restore from backup
algorithmshift db restore backup-20240115.sql --env staging