Skip to content
| Marketplace
Sign in
Visual Studio Code>Programming Languages>DbcubeNew to Visual Studio Code? Get it now.
Dbcube

Dbcube

Dbcube

|
1 install
| (0) | Free
Comprehensive language support for .cube files with intelligent validation, contextual auto-completion, and advanced syntax highlighting
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

Dbcube VS Code Extension - .cube Files Guide

Language/Lenguaje

  • English
  • Español

English Documentation

Table of Contents 🚀

  • Introduction
  • Installation
  • File Types
  • .cube File Syntax
    • Core Annotations
    • Data Types
    • Column Options
  • Table Definition (.table.cube)
    • Basic Structure
    • Column Definition
    • Foreign Keys
    • Complex Examples
  • Seeder Definition (.seeder.cube)
    • Basic Structure
    • Data Insertion
    • Complex Examples
  • Trigger Definition (.trigger.cube)
    • Trigger Types
    • Function Parameters
    • Examples
  • Extension Features
  • Configuration
  • Troubleshooting
  • Best Practices

Introduction

The Dbcube VS Code Extension provides comprehensive language support for .cube files used in the Dbcube ecosystem. This extension offers intelligent validation, contextual auto-completion, syntax highlighting, and formatting for three types of cube files:

  • .table.cube - Database table schema definitions
  • .seeder.cube - Data seeding files
  • .trigger.cube - Database trigger definitions

Installation

  1. Install the extension from the VS Code marketplace
  2. Look for "Cube Language Support" by Dbcube
  3. Once installed, all .cube files will be automatically recognized

File Types

The extension recognizes three specific cube file patterns:

Pattern Purpose Description
*.table.cube Table Schema Define database table structure, columns, and relationships
*.seeder.cube Data Seeding Insert initial or test data into tables
*.trigger.cube Database Triggers Define before/after operation hooks

.cube File Syntax

Core Annotations

All cube files use annotation-based syntax with the @ symbol:

Annotation Required Purpose Used In
@database("name") ✅ Specify target database All files
@table("name") ✅ Specify target table Seeders, Triggers
@meta({...}) ❌ Table metadata Tables
@columns({...}) ✅ Define table columns Tables
@fields(...) ✅ Define field order Seeders
@dataset(...) ✅ Define data rows Seeders
@beforeAdd({...}) ❌ Before insert trigger Triggers
@afterAdd({...}) ❌ After insert trigger Triggers
@beforeUpdate({...}) ❌ Before update trigger Triggers
@afterUpdate({...}) ❌ After update trigger Triggers
@beforeDelete({...}) ❌ Before delete trigger Triggers
@afterDelete({...}) ❌ After delete trigger Triggers

Data Types

Supported column data types:

Type Description Example
varchar Variable-length string (requires length) type: "varchar"; length: "255";
int Integer number type: "int";
text Long text content type: "text";
boolean True/false values type: "boolean";
date Date only (YYYY-MM-DD) type: "date";
datetime Date and time type: "datetime";
timestamp Timestamp with timezone type: "timestamp";
decimal Precise decimal numbers type: "decimal"; length: "10,2";
float Floating-point numbers type: "float";
double Double precision float type: "double";
enum Predefined value list type: "enum"; enumValues: ["value1", "value2"];
json JSON data structure type: "json";

Column Options

Available column constraints and modifiers:

Option Description Compatible Types
not null Column cannot be NULL All types
null Column can be NULL (default) All types
primary Primary key column int, varchar, string
autoincrement Auto-incrementing values int only
unique Unique constraint int, varchar, string, text
index Create database index Most types
unsigned Unsigned numbers only int, decimal, float, double
zerofill Zero-filled numbers int, decimal, float, double

Table Definition (.table.cube)

Basic Structure

Every table cube file must follow this structure:

@database("your_database_name");

@meta({
    name: "table_name";
    description: "Table description";
});

@columns({
    // Column definitions here
});

Column Definition

Each column is defined with the following syntax:

column_name: {
    type: "data_type";
    length: "size";                    // Optional, required for varchar
    options: ["option1", "option2"];   // Optional
    defaultValue: "default";           // Optional
    foreign: {                         // Optional
        table: "referenced_table";
        column: "referenced_column";
    };
    enumValues: ["val1", "val2"];     // Required for enum type
};

Foreign Keys

Define relationships between tables:

user_id: {
    type: "int";
    options: ["not null", "index"];
    foreign: {
        table: "users";
        column: "id";
    };
};

Complex Examples

Complete User Table

@database("ecommerce");

@meta({
    name: "users";
    description: "User accounts and authentication";
});

@columns({
    id: {
        type: "int";
        options: ["primary", "autoincrement"];
    };
    username: {
        type: "varchar";
        length: "50";
        options: ["not null", "unique"];
    };
    email: {
        type: "varchar";
        length: "255";
        options: ["not null", "unique"];
    };
    password: {
        type: "varchar";
        length: "255";
        options: ["not null"];
    };
    status: {
        type: "enum";
        enumValues: ["active", "inactive", "suspended"];
        defaultValue: "active";
        options: ["not null"];
    };
    profile_data: {
        type: "json";
        defaultValue: {};
    };
    created_at: {
        type: "timestamp";
        options: ["not null"];
    };
    updated_at: {
        type: "timestamp";
        options: ["not null"];
    };
});

Orders Table with Foreign Keys

@database("ecommerce");

@meta({
    name: "orders";
    description: "Customer orders and transactions";
});

@columns({
    id: {
        type: "int";
        options: ["primary", "autoincrement"];
    };
    user_id: {
        type: "int";
        options: ["not null", "index"];
        foreign: {
            table: "users";
            column: "id";
        };
    };
    total_amount: {
        type: "decimal";
        length: "10,2";
        options: ["not null"];
    };
    order_status: {
        type: "enum";
        enumValues: ["pending", "processing", "shipped", "delivered", "cancelled"];
        defaultValue: "pending";
        options: ["not null"];
    };
    order_date: {
        type: "datetime";
        options: ["not null"];
    };
    shipping_address: {
        type: "json";
    };
    notes: {
        type: "text";
    };
});

Seeder Definition (.seeder.cube)

Basic Structure

Seeder files populate tables with initial or test data:

@database("database_name");
@table("table_name");

@fields("field1", "field2", "field3");

@dataset(
    ("value1", "value2", "value3"),
    ("value4", "value5", "value6"),
);

Data Insertion

The @fields annotation defines column order, and @dataset provides the actual data rows.

Complex Examples

User Seeder

@database("ecommerce");
@table("users");

@fields("username", "email", "password", "status", "created_at", "updated_at");

@dataset(
    ("admin", "admin@ecommerce.com", "hashed_password_123", "active", "2024-01-01 10:00:00", "2024-01-01 10:00:00"),
    ("john_doe", "john@example.com", "hashed_password_456", "active", "2024-01-02 09:30:00", "2024-01-02 09:30:00"),
    ("jane_smith", "jane@example.com", "hashed_password_789", "active", "2024-01-03 14:15:00", "2024-01-03 14:15:00"),
    ("bob_wilson", "bob@example.com", "hashed_password_000", "inactive", "2024-01-04 16:45:00", "2024-01-04 16:45:00"),
);

Orders Seeder

@database("ecommerce");
@table("orders");

@fields("user_id", "total_amount", "order_status", "order_date", "shipping_address");

@dataset(
    (1, "149.99", "delivered", "2024-02-01 10:30:00", '{"street": "123 Main St", "city": "New York", "zip": "10001"}'),
    (2, "89.50", "shipped", "2024-02-02 14:20:00", '{"street": "456 Oak Ave", "city": "Los Angeles", "zip": "90210"}'),
    (1, "299.99", "processing", "2024-02-03 09:15:00", '{"street": "123 Main St", "city": "New York", "zip": "10001"}'),
    (3, "45.75", "pending", "2024-02-04 11:00:00", '{"street": "789 Pine Rd", "city": "Chicago", "zip": "60601"}'),
);

Product Categories Seeder

@database("ecommerce");
@table("categories");

@fields("name", "slug", "description", "is_active", "sort_order");

@dataset(
    ("Electronics", "electronics", "Electronic devices and accessories", "true", "1"),
    ("Clothing", "clothing", "Apparel and fashion items", "true", "2"),
    ("Home & Garden", "home-garden", "Home improvement and gardening supplies", "true", "3"),
    ("Sports & Outdoors", "sports-outdoors", "Sports equipment and outdoor gear", "true", "4"),
    ("Books", "books", "Books and educational materials", "true", "5"),
);

Trigger Definition (.trigger.cube)

Trigger Types

Dbcube supports six types of triggers:

Trigger When It Fires Use Cases
@beforeAdd Before INSERT operations Validation, auto-fill fields, data transformation
@afterAdd After INSERT operations Logging, notifications, related record updates
@beforeUpdate Before UPDATE operations Validation, field updates, conflict checking
@afterUpdate After UPDATE operations Audit trails, notifications, cache invalidation
@beforeDelete Before DELETE operations Dependency checking, soft deletes, validation
@afterDelete After DELETE operations Cleanup, logging, cascade operations

Function Parameters

All trigger functions receive these parameters:

Parameter Type Description
db Database Database connection for queries
oldData Object Previous record state (null for INSERT)
newData Object New/updated record state (null for DELETE)
gdb Global DB Global database access

Examples

Before Add Trigger - Validation

@database("ecommerce");
@table("users");

@beforeAdd({
    name: "validate_user_registration";
    description: "Validate user data before registration";
    function: ({db, oldData, newData, gdb}) => {
        // Validate email format
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(newData.email)) {
            throw new Error('Invalid email format');
        }

        // Check password strength
        if (newData.password.length < 8) {
            throw new Error('Password must be at least 8 characters long');
        }

        // Auto-generate timestamps
        const now = new Date();
        newData.created_at = now;
        newData.updated_at = now;

        // Set default status
        if (!newData.status) {
            newData.status = 'active';
        }

        console.log('User validation completed for:', newData.username);
    };
});

After Add Trigger - Welcome Email

@database("ecommerce");
@table("users");

@afterAdd({
    name: "send_welcome_email";
    description: "Send welcome email to new users";
    function: ({db, oldData, newData, gdb}) => {
        // Log new user registration
        console.log(`New user registered: ${newData.username} (${newData.email})`);

        // Send welcome email (pseudo-code)
        // await emailService.sendWelcomeEmail(newData.email, newData.username);

        // Create user preferences record
        const userPrefs = {
            user_id: newData.id,
            email_notifications: true,
            marketing_emails: true,
            created_at: new Date()
        };

        // Insert user preferences
        // await db.table('user_preferences').insert(userPrefs);

        console.log('Welcome process completed for user:', newData.id);
    };
});

Before Update Trigger - Email Change Verification

@database("ecommerce");
@table("users");

@beforeUpdate({
    name: "verify_email_change";
    description: "Verify email changes and prevent duplicates";
    function: ({db, oldData, newData, gdb}) => {
        // Check if email is being changed
        if (newData.email && newData.email !== oldData.email) {
            // Verify email format
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(newData.email)) {
                throw new Error('Invalid email format');
            }

            // Check for duplicate email (pseudo-code)
            // const existing = await db.query('SELECT id FROM users WHERE email = ? AND id != ?', [newData.email, newData.id]);
            // if (existing.length > 0) {
            //     throw new Error('Email already exists');
            // }

            console.log(`Email change requested: ${oldData.email} -> ${newData.email}`);
        }

        // Always update the modified timestamp
        newData.updated_at = new Date();

        console.log('User update validation completed for:', newData.id);
    };
});

After Update Trigger - Profile Change Log

@database("ecommerce");
@table("users");

@afterUpdate({
    name: "log_profile_changes";
    description: "Log user profile changes for audit trail";
    function: ({db, oldData, newData, gdb}) => {
        const changes = {};
        
        // Track specific field changes
        const trackedFields = ['username', 'email', 'status'];
        
        trackedFields.forEach(field => {
            if (oldData[field] !== newData[field]) {
                changes[field] = {
                    from: oldData[field],
                    to: newData[field]
                };
            }
        });

        // If there are changes, log them
        if (Object.keys(changes).length > 0) {
            const auditLog = {
                user_id: newData.id,
                action: 'profile_update',
                changes: JSON.stringify(changes),
                timestamp: new Date(),
                ip_address: '127.0.0.1' // Would come from request context
            };

            console.log('Profile changes detected:', changes);
            // await db.table('audit_logs').insert(auditLog);
        }

        console.log('Profile change audit completed for user:', newData.id);
    };
});

Before Delete Trigger - Dependency Check

@database("ecommerce");
@table("users");

@beforeDelete({
    name: "check_user_dependencies";
    description: "Prevent deletion of users with active orders";
    function: ({db, oldData, newData, gdb}) => {
        // Check if user has active orders (pseudo-code)
        // const activeOrders = await db.query('SELECT COUNT(*) as count FROM orders WHERE user_id = ? AND order_status IN ("pending", "processing")', [oldData.id]);
        
        // Simulate check
        const hasActiveOrders = false; // This would be the actual query result
        
        if (hasActiveOrders) {
            throw new Error('Cannot delete user with active orders. Please complete or cancel all orders first.');
        }

        // Check if user is an admin
        if (oldData.status === 'admin') {
            throw new Error('Admin users cannot be deleted');
        }

        console.log('User deletion validation passed for:', oldData.username);
    };
});

After Delete Trigger - Cleanup

@database("ecommerce");
@table("users");

@afterDelete({
    name: "cleanup_user_data";
    description: "Clean up related user data after deletion";
    function: ({db, oldData, newData, gdb}) => {
        console.log(`Cleaning up data for deleted user: ${oldData.username}`);

        // Clean up related data (pseudo-code)
        // await db.query('DELETE FROM user_preferences WHERE user_id = ?', [oldData.id]);
        // await db.query('DELETE FROM user_sessions WHERE user_id = ?', [oldData.id]);
        // await db.query('UPDATE orders SET user_id = NULL WHERE user_id = ?', [oldData.id]);

        // Log the deletion
        const auditLog = {
            action: 'user_deleted',
            user_data: JSON.stringify({
                id: oldData.id,
                username: oldData.username,
                email: oldData.email
            }),
            timestamp: new Date()
        };

        // await db.table('audit_logs').insert(auditLog);

        console.log('User cleanup completed for:', oldData.id);
    };
});

Extension Features

Syntax Highlighting

  • Color coding for annotations, keywords, and data types
  • JavaScript syntax highlighting within trigger functions
  • Proper highlighting for strings, numbers, and comments

Auto-completion

  • Intelligent suggestions for annotations
  • Data type completion
  • Column option suggestions
  • Property name completion

Validation

  • Real-time syntax validation
  • Data type checking
  • Required property validation
  • Foreign key relationship validation

Code Snippets

  • Quick templates for table, seeder, and trigger files
  • Pre-built column definitions (primary key, timestamps, foreign keys)
  • Common trigger patterns

Formatting

  • Automatic code formatting
  • Consistent indentation
  • Proper bracket and semicolon placement

Hover Information

  • Documentation for annotations and properties
  • Data type information
  • Usage examples

Configuration

Configure the extension in your VS Code settings:

{
  "cube.validation.enabled": true,
  "cube.autocompletion.enabled": true,
  "cube.hover.enabled": true
}

Troubleshooting

Common Issues

Issue: "Unknown annotation" error Solution: Check spelling and ensure you're using valid annotations from the list above.

Issue: "Invalid data type" error Solution: Use only supported data types. VARCHAR requires a length specification.

Issue: "Missing required property" error Solution: All columns need a type property. Primary keys need both type and appropriate options.

Issue: Foreign key validation fails Solution: Ensure the referenced table and column exist, and the data types match.

Database Configuration Issues

Issue: "Database configuration not found" Solution: Ensure your dbcube.config.js file contains the database referenced in your cube files.

File Naming

  • Table files must end with .table.cube
  • Seeder files must end with .seeder.cube
  • Trigger files must end with .trigger.cube

Best Practices

File Organization

dbcube/
├── tables/
│   ├── users.table.cube
│   ├── orders.table.cube
│   └── products.table.cube
├── seeders/
│   ├── users.seeder.cube
│   ├── categories.seeder.cube
│   └── products.seeder.cube
└── triggers/
    ├── user_validation.trigger.cube
    ├── order_notifications.trigger.cube
    └── audit_logging.trigger.cube

Naming Conventions

  • Use snake_case for table and column names
  • Use descriptive names for triggers
  • Keep seeder files simple and focused

Performance Tips

  • Use indexes on frequently queried columns
  • Be cautious with triggers that perform heavy operations
  • Keep seeder data sets manageable

Security

  • Never include sensitive data in seeder files
  • Use environment variables for configuration
  • Validate all trigger inputs thoroughly

Documentación en español

Tabla de contenidos 🚀

  • Introducción
  • Instalación
  • Tipos de archivos
  • Sintaxis de archivos .cube
    • Anotaciones principales
    • Tipos de datos
    • Opciones de columna
  • Definición de tabla (.table.cube)
    • Estructura básica
    • Definición de columna
    • Claves foráneas
    • Ejemplos complejos
  • Definición de seeder (.seeder.cube)
    • Estructura básica
    • Inserción de datos
    • Ejemplos complejos
  • Definición de trigger (.trigger.cube)
    • Tipos de trigger
    • Parámetros de función
    • Ejemplos
  • Características de la extensión
  • Configuración
  • Solución de problemas
  • Mejores prácticas

Introducción

La Extensión Dbcube para VS Code proporciona soporte completo del lenguaje para archivos .cube utilizados en el ecosistema Dbcube. Esta extensión ofrece validación inteligente, auto-completado contextual, resaltado de sintaxis y formateo para tres tipos de archivos cube:

  • .table.cube - Definiciones de esquema de tabla de base de datos
  • .seeder.cube - Archivos de siembra de datos
  • .trigger.cube - Definiciones de triggers de base de datos

Instalación

  1. Instala la extensión desde el marketplace de VS Code
  2. Busca "Cube Language Support" por Dbcube
  3. Una vez instalada, todos los archivos .cube serán reconocidos automáticamente

Tipos de archivos

La extensión reconoce tres patrones específicos de archivos cube:

Patrón Propósito Descripción
*.table.cube Esquema de tabla Define la estructura de tabla de base de datos, columnas y relaciones
*.seeder.cube Siembra de datos Inserta datos iniciales o de prueba en las tablas
*.trigger.cube Triggers de base de datos Define hooks antes/después de operaciones

Sintaxis de archivos .cube

Anotaciones principales

Todos los archivos cube usan sintaxis basada en anotaciones con el símbolo @:

Anotación Requerida Propósito Usada en
@database("nombre") ✅ Especificar base de datos objetivo Todos los archivos
@table("nombre") ✅ Especificar tabla objetivo Seeders, Triggers
@meta({...}) ❌ Metadatos de tabla Tablas
@columns({...}) ✅ Definir columnas de tabla Tablas
@fields(...) ✅ Definir orden de campos Seeders
@dataset(...) ✅ Definir filas de datos Seeders
@beforeAdd({...}) ❌ Trigger antes de insertar Triggers
@afterAdd({...}) ❌ Trigger después de insertar Triggers
@beforeUpdate({...}) ❌ Trigger antes de actualizar Triggers
@afterUpdate({...}) ❌ Trigger después de actualizar Triggers
@beforeDelete({...}) ❌ Trigger antes de eliminar Triggers
@afterDelete({...}) ❌ Trigger después de eliminar Triggers

Tipos de datos

Tipos de datos de columna soportados:

Tipo Descripción Ejemplo
varchar Cadena de longitud variable (requiere longitud) type: "varchar"; length: "255";
int Número entero type: "int";
text Contenido de texto largo type: "text";
boolean Valores verdadero/falso type: "boolean";
date Solo fecha (YYYY-MM-DD) type: "date";
datetime Fecha y hora type: "datetime";
timestamp Marca de tiempo con zona horaria type: "timestamp";
decimal Números decimales precisos type: "decimal"; length: "10,2";
float Números de punto flotante type: "float";
double Flotante de doble precisión type: "double";
enum Lista de valores predefinidos type: "enum"; enumValues: ["valor1", "valor2"];
json Estructura de datos JSON type: "json";

Opciones de columna

Restricciones y modificadores de columna disponibles:

Opción Descripción Tipos compatibles
not null La columna no puede ser NULL Todos los tipos
null La columna puede ser NULL (por defecto) Todos los tipos
primary Columna de clave primaria int, varchar, string
autoincrement Valores auto-incrementales Solo int
unique Restricción de unicidad int, varchar, string, text
index Crear índice de base de datos La mayoría de tipos
unsigned Solo números sin signo int, decimal, float, double
zerofill Números rellenados con ceros int, decimal, float, double

Definición de tabla (.table.cube)

Estructura básica

Cada archivo de tabla cube debe seguir esta estructura:

@database("nombre_de_tu_base_de_datos");

@meta({
    name: "nombre_tabla";
    description: "Descripción de la tabla";
});

@columns({
    // Definiciones de columnas aquí
});

Definición de columna

Cada columna se define con la siguiente sintaxis:

nombre_columna: {
    type: "tipo_datos";
    length: "tamaño";                    // Opcional, requerido para varchar
    options: ["opcion1", "opcion2"];     // Opcional
    defaultValue: "predeterminado";      // Opcional
    foreign: {                           // Opcional
        table: "tabla_referenciada";
        column: "columna_referenciada";
    };
    enumValues: ["val1", "val2"];       // Requerido para tipo enum
};

Claves foráneas

Define relaciones entre tablas:

user_id: {
    type: "int";
    options: ["not null", "index"];
    foreign: {
        table: "users";
        column: "id";
    };
};

Ejemplos complejos

Tabla completa de usuarios

@database("ecommerce");

@meta({
    name: "usuarios";
    description: "Cuentas de usuario y autenticación";
});

@columns({
    id: {
        type: "int";
        options: ["primary", "autoincrement"];
    };
    nombre_usuario: {
        type: "varchar";
        length: "50";
        options: ["not null", "unique"];
    };
    email: {
        type: "varchar";
        length: "255";
        options: ["not null", "unique"];
    };
    contraseña: {
        type: "varchar";
        length: "255";
        options: ["not null"];
    };
    estado: {
        type: "enum";
        enumValues: ["activo", "inactivo", "suspendido"];
        defaultValue: "activo";
        options: ["not null"];
    };
    datos_perfil: {
        type: "json";
        defaultValue: {};
    };
    fecha_creacion: {
        type: "timestamp";
        options: ["not null"];
    };
    fecha_actualizacion: {
        type: "timestamp";
        options: ["not null"];
    };
});

Definición de seeder (.seeder.cube)

Estructura básica

Los archivos de seeder pueblan las tablas con datos iniciales o de prueba:

@database("nombre_base_datos");
@table("nombre_tabla");

@fields("campo1", "campo2", "campo3");

@dataset(
    ("valor1", "valor2", "valor3"),
    ("valor4", "valor5", "valor6"),
);

Inserción de datos

La anotación @fields define el orden de columnas, y @dataset proporciona las filas de datos reales.

Ejemplos complejos

Seeder de usuarios

@database("ecommerce");
@table("usuarios");

@fields("nombre_usuario", "email", "contraseña", "estado", "fecha_creacion", "fecha_actualizacion");

@dataset(
    ("admin", "admin@ecommerce.com", "contraseña_hasheada_123", "activo", "2024-01-01 10:00:00", "2024-01-01 10:00:00"),
    ("juan_perez", "juan@ejemplo.com", "contraseña_hasheada_456", "activo", "2024-01-02 09:30:00", "2024-01-02 09:30:00"),
    ("maria_garcia", "maria@ejemplo.com", "contraseña_hasheada_789", "activo", "2024-01-03 14:15:00", "2024-01-03 14:15:00"),
    ("carlos_lopez", "carlos@ejemplo.com", "contraseña_hasheada_000", "inactivo", "2024-01-04 16:45:00", "2024-01-04 16:45:00"),
);

Definición de trigger (.trigger.cube)

Tipos de trigger

Dbcube soporta seis tipos de triggers:

Trigger Cuándo se ejecuta Casos de uso
@beforeAdd Antes de operaciones INSERT Validación, auto-completar campos, transformación de datos
@afterAdd Después de operaciones INSERT Registro, notificaciones, actualizaciones de registros relacionados
@beforeUpdate Antes de operaciones UPDATE Validación, actualizaciones de campos, verificación de conflictos
@afterUpdate Después de operaciones UPDATE Pistas de auditoría, notificaciones, invalidación de caché
@beforeDelete Antes de operaciones DELETE Verificación de dependencias, eliminaciones suaves, validación
@afterDelete Después de operaciones DELETE Limpieza, registro, operaciones en cascada

Parámetros de función

Todas las funciones de trigger reciben estos parámetros:

Parámetro Tipo Descripción
db Database Conexión a base de datos para consultas
oldData Object Estado previo del registro (null para INSERT)
newData Object Estado nuevo/actualizado del registro (null para DELETE)
gdb Global DB Acceso global a base de datos

Ejemplos

Trigger Before Add - Validación

@database("ecommerce");
@table("usuarios");

@beforeAdd({
    name: "validar_registro_usuario";
    description: "Validar datos de usuario antes del registro";
    function: ({db, oldData, newData, gdb}) => {
        // Validar formato de email
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(newData.email)) {
            throw new Error('Formato de email inválido');
        }

        // Verificar fortaleza de contraseña
        if (newData.contraseña.length < 8) {
            throw new Error('La contraseña debe tener al menos 8 caracteres');
        }

        // Auto-generar marcas de tiempo
        const ahora = new Date();
        newData.fecha_creacion = ahora;
        newData.fecha_actualizacion = ahora;

        // Establecer estado por defecto
        if (!newData.estado) {
            newData.estado = 'activo';
        }

        console.log('Validación de usuario completada para:', newData.nombre_usuario);
    };
});

Características de la extensión

Resaltado de sintaxis

  • Coloreo para anotaciones, palabras clave y tipos de datos
  • Resaltado de sintaxis JavaScript dentro de funciones de trigger
  • Resaltado adecuado para cadenas, números y comentarios

Auto-completado

  • Sugerencias inteligentes para anotaciones
  • Completado de tipos de datos
  • Sugerencias de opciones de columna
  • Completado de nombres de propiedades

Validación

  • Validación de sintaxis en tiempo real
  • Verificación de tipos de datos
  • Validación de propiedades requeridas
  • Validación de relaciones de clave foránea

Fragmentos de código

  • Plantillas rápidas para archivos de tabla, seeder y trigger
  • Definiciones de columna predefinidas (clave primaria, marcas de tiempo, claves foráneas)
  • Patrones comunes de trigger

Formateo

  • Formateo automático de código
  • Indentación consistente
  • Colocación adecuada de llaves y punto y coma

Información flotante

  • Documentación para anotaciones y propiedades
  • Información de tipos de datos
  • Ejemplos de uso

Configuración

Configura la extensión en tu configuración de VS Code:

{
  "cube.validation.enabled": true,
  "cube.autocompletion.enabled": true,
  "cube.hover.enabled": true
}

Solución de problemas

Problemas comunes

Problema: Error "Anotación desconocida" Solución: Verifica la ortografía y asegúrate de usar anotaciones válidas de la lista anterior.

Problema: Error "Tipo de datos inválido" Solución: Usa solo tipos de datos soportados. VARCHAR requiere especificación de longitud.

Problema: Error "Propiedad requerida faltante" Solución: Todas las columnas necesitan una propiedad type. Las claves primarias necesitan tanto type como opciones apropiadas.

Problema: La validación de clave foránea falla Solución: Asegúrate de que la tabla y columna referenciadas existan, y que los tipos de datos coincidan.

Problemas de configuración de base de datos

Problema: "Configuración de base de datos no encontrada" Solución: Asegúrate de que tu archivo dbcube.config.js contenga la base de datos referenciada en tus archivos cube.

Nomenclatura de archivos

  • Los archivos de tabla deben terminar con .table.cube
  • Los archivos de seeder deben terminar con .seeder.cube
  • Los archivos de trigger deben terminar con .trigger.cube

Mejores prácticas

Organización de archivos

dbcube/
├── tables/
│   ├── usuarios.table.cube
│   ├── pedidos.table.cube
│   └── productos.table.cube
├── seeders/
│   ├── usuarios.seeder.cube
│   ├── categorias.seeder.cube
│   └── productos.seeder.cube
└── triggers/
    ├── validacion_usuario.trigger.cube
    ├── notificaciones_pedido.trigger.cube
    └── registro_auditoria.trigger.cube

Convenciones de nomenclatura

  • Usa snake_case para nombres de tabla y columna
  • Usa nombres descriptivos para triggers
  • Mantén los archivos de seeder simples y enfocados

Consejos de rendimiento

  • Usa índices en columnas consultadas frecuentemente
  • Ten cuidado con triggers que realizan operaciones pesadas
  • Mantén conjuntos de datos de seeder manejables

Seguridad

  • Nunca incluyas datos sensibles en archivos de seeder
  • Usa variables de entorno para configuración
  • Valida todas las entradas de trigger minuciosamente
  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
© 2026 Microsoft