Docs

Create, Update, and Delete Records

Create, Update, and Delete Records Create Create a new record in the table. Automatically returns the full created record including ID and timestamps. Basic Usage const result = await $ctx.$repos.products.create({ data: { name: 'New Product', price: 99.99, category: 'electronics'

Create, Update, and Delete Records

Create

Create a new record in the table. Automatically returns the full created record including ID and timestamps.

Basic Usage

const result = await $ctx.$repos.products.create({
  data: {
    name: 'New Product',
    price: 99.99,
    category: 'electronics'
  }
});

const newProduct = result.data[0];  // Full product record with ID, timestamps, etc.

Parameters

await $ctx.$repos.tableName.create({
  data: { ... },       // Data to insert (required)
  fields: '...'        // Fields to return (optional)
})

Creating Records

Simple create

const result = await $ctx.$repos.products.create({
  data: {
    name: 'iPhone 15',
    price: 999,
    category: 'electronics'
  }
});

Create with all fields

const result = await $ctx.$repos.products.create({
  data: {
    name: 'iPhone 15',
    price: 999,
    category: 'electronics',
    description: 'Latest iPhone model',
    isActive: true,
    stock: 50
  }
});

Return specific fields after create

const result = await $ctx.$repos.products.create({
  data: {
    name: 'iPhone 15',
    price: 999
  },
  fields: 'id,name,price'  // Only return these fields
});

Important Notes

  1. ID is auto-generated: Never include id in the data object - it will be automatically generated by the database
  2. Timestamps are auto-generated: createdAt and updatedAt are automatically added by the system
  3. Full record is returned: The method automatically calls find() after insertion to return the complete record
  4. Validation happens automatically: System validates table schema and system protection rules

Create with Relations

// Create order with related items
const orderResult = await $ctx.$repos.orders.create({
  data: {
    customerId: 123,
    total: 299.99,
    status: 'pending'
  }
});

const order = orderResult.data[0];

// Create order items
const itemResult = await $ctx.$repos.order_items.create({
  data: {
    orderId: order.id,
    productId: 456,
    quantity: 2,
    price: 149.99
  }
});

Error Handling

try {
  const result = await $ctx.$repos.products.create({
    data: {
      name: 'Product Name',
      price: 99.99
    }
  });
} catch (error) {
  // Handle validation errors, constraint violations, etc.
  $ctx.$logs(`Failed to create product: ${error.message}`);
}

Update

Update an existing record by ID. Automatically returns the full updated record.

Basic Usage

const result = await $ctx.$repos.products.update({
  id: 123,
  data: {
    price: 89.99,
    isOnSale: true
  }
});

const updatedProduct = result.data[0];  // Full updated product record

Parameters

await $ctx.$repos.tableName.update({
  id: 123,              // Record ID to update (required)
  data: { ... },        // Fields to update (required)
  fields: '...'         // Fields to return (optional)
})

Updating Records

Update single field

const result = await $ctx.$repos.products.update({
  id: 123,
  data: {
    price: 89.99
  }
});

Update multiple fields

const result = await $ctx.$repos.products.update({
  id: 123,
  data: {
    price: 89.99,
    isOnSale: true,
    description: 'Updated description'
  }
});

Return specific fields after update

const result = await $ctx.$repos.products.update({
  id: 123,
  data: {
    price: 89.99
  },
  fields: 'id,name,price'  // Only return these fields
});

Important Notes

  1. ID must exist: The record with the given ID must exist, otherwise an error is thrown
  2. Partial updates: You only need to include fields you want to update
  3. Full record is returned: The method automatically calls find() after update to return the complete record
  4. Timestamps are auto-updated: updatedAt is automatically updated by the system
  5. Validation happens automatically: System validates table schema and system protection rules

Check if Record Exists First

// Find the record first
const findResult = await $ctx.$repos.products.find({
  filter: { id: { _eq: 123 } }
});

if (findResult.data.length === 0) {
  $ctx.$throw['404']('Product not found');
  return;
}

// Update the record
const result = await $ctx.$repos.products.update({
  id: 123,
  data: {
    price: 89.99
  }
});

Error Handling

try {
  const result = await $ctx.$repos.products.update({
    id: 123,
    data: {
      price: 89.99
    }
  });
} catch (error) {
  // Handle errors: record not found, validation errors, etc.
  $ctx.$logs(`Failed to update product: ${error.message}`);
}

Delete

Delete a record by ID. Returns a success message.

Basic Usage

const result = await $ctx.$repos.products.delete({
  id: 123
});

// result: { message: 'Delete successfully!', statusCode: 200 }

Parameters

await $ctx.$repos.tableName.delete({
  id: 123  // Record ID to delete (required)
})

Deleting Records

Simple delete

const result = await $ctx.$repos.products.delete({
  id: 123
});

Check if record exists before deleting

// Find the record first
const findResult = await $ctx.$repos.products.find({
  filter: { id: { _eq: 123 } }
});

if (findResult.data.length === 0) {
  $ctx.$throw['404']('Product not found');
  return;
}

// Delete the record
const result = await $ctx.$repos.products.delete({
  id: 123
});

Important Notes

  1. ID must exist: The record with the given ID must exist, otherwise an error is thrown
  2. Cascade behavior: If the table has relations with onDelete: 'cascade', related records will be deleted automatically
  3. Returns success message: The method returns { message: 'Delete successfully!', statusCode: 200 }
  4. Cannot be undone: Deletion is permanent - make sure to validate before deleting

Error Handling

try {
  const result = await $ctx.$repos.products.delete({
    id: 123
  });
} catch (error) {
  // Handle errors: record not found, constraint violations, etc.
  $ctx.$logs(`Failed to delete product: ${error.message}`);
}

Batch create, update, and delete

Use batch repository methods only in dynamic handlers, hooks, and flows. Generated REST CRUD endpoints remain single-record endpoints.

Batch methods are deliberately limited to plain generic tables. Enfyra rejects schema/metadata tables and tables with custom normalization or lifecycle behavior. It validates and authorizes every supplied target before one bulk write, then runs one runtime reload and emits one mutation event. Use a secure repository for user-facing code and still enforce owner, tenant, and membership rules in the handler.

Create many

const result = await $ctx.$repos.secure.products.createMany({
  data: [
    { name: 'Keyboard', price: 99.99 },
    { name: 'Mouse', price: 49.99 }
  ],
  fields: ['id', 'name', 'price']
});

// result.data contains created records; result.count is 2

Update many

updateMany applies the same data object to every ID. It does not accept relation payloads; update one record at a time when relation changes are required.

const result = await $ctx.$repos.secure.products.updateMany({
  ids: [101, 102, 103],
  data: { isActive: false },
  fields: ['id', 'isActive']
});

// result.data contains updated records; result.count is 3

Delete many

const result = await $ctx.$repos.secure.products.deleteMany({
  ids: [101, 102, 103]
});

// result: { message: 'Delete successfully!', statusCode: 200, count: 3 }

Next Steps