bknd-delete-entity
Use when removing an entity from Bknd. Covers safely deleting entities, handling relationships and dependencies, data backup, the sync workflow with --drop flag, and cleaning up orphaned data.
What this skill does
# Delete Entity
Safely remove an entity (table) from Bknd, handling dependencies and avoiding data loss.
## Prerequisites
- Existing Bknd app with entities (see `bknd-create-entity`)
- For code mode: Access to `bknd.config.ts`
- **Critical:** Backup database before deletion
## Warning: Destructive Operation
Deleting an entity:
- Permanently removes the table and ALL its data
- Removes all relationships involving this entity
- May break application code referencing this entity
- Cannot be undone without database restore
## When to Use UI vs Code
### Use UI Mode When
- Quick prototype cleanup
- Development/testing environments
- Exploring what dependencies exist
### Use Code Mode When
- Production changes
- Version control needed
- Team collaboration
- Reproducible deployments
---
## Pre-Deletion Checklist
Before deleting an entity, verify:
### 1. Check for Relationships
Entities may be referenced by other entities via:
- Foreign keys (many-to-one)
- Junction tables (many-to-many)
- Self-references
### 2. Check for Data
```typescript
const api = app.getApi();
const count = await api.data.count("entity_to_delete");
console.log(`Records to delete: ${count.data.count}`);
```
### 3. Check for Code References
Search codebase for:
- Entity name in queries: `"entity_name"`
- Type references: `DB["entity_name"]`
- API calls: `api.data.*("entity_name")`
### 4. Backup Data (If Needed)
```typescript
// Export data before deletion
const api = app.getApi();
const allRecords = await api.data.readMany("entity_to_delete", {
limit: 100000,
});
// Save to file
import { writeFileSync } from "fs";
writeFileSync(
"backup-entity_to_delete.json",
JSON.stringify(allRecords.data, null, 2)
);
```
---
## Code Approach
### Step 1: Identify Dependencies
Check your schema for relationships:
```typescript
// Look for relationships involving this entity
const schema = em(
{
users: entity("users", { email: text().required() }),
posts: entity("posts", { title: text().required() }),
comments: entity("comments", { body: text() }),
},
({ relation }, { users, posts, comments }) => {
// posts depends on users (foreign key)
relation(posts).manyToOne(users);
// comments depends on posts (foreign key)
relation(comments).manyToOne(posts);
}
);
```
**Dependency order matters:** Delete children before parents.
### Step 2: Remove Relationships First
If entity is a target of relationships, update schema to remove them:
```typescript
// BEFORE: posts references users
const schema = em(
{
users: entity("users", { email: text().required() }),
posts: entity("posts", { title: text().required() }),
},
({ relation }, { users, posts }) => {
relation(posts).manyToOne(users);
}
);
// AFTER: Remove relationship before deleting users
const schema = em({
users: entity("users", { email: text().required() }),
posts: entity("posts", { title: text().required() }),
});
```
### Step 3: Remove Entity from Schema
Simply remove the entity definition from your `bknd.config.ts`:
```typescript
// BEFORE
const schema = em({
users: entity("users", { email: text().required() }),
posts: entity("posts", { title: text().required() }),
deprecated_entity: entity("deprecated_entity", { data: text() }),
});
// AFTER - entity removed
const schema = em({
users: entity("users", { email: text().required() }),
posts: entity("posts", { title: text().required() }),
});
```
### Step 4: Preview Changes
```bash
# See what will be dropped (dry run)
npx bknd sync
```
Output shows:
```
Tables to drop: deprecated_entity
Columns affected: (none on other tables)
```
### Step 5: Apply Deletion
```bash
# Apply with drop flag (destructive)
npx bknd sync --drop
```
Or with force (enables all destructive operations):
```bash
npx bknd sync --force
```
### Step 6: Clean Up Code
Remove all references:
- Delete type definitions
- Remove API calls
- Update imports
---
## UI Approach
### Step 1: Open Admin Panel
Navigate to `http://localhost:1337` (or your configured URL).
### Step 2: Go to Data Section
Click **Data** in the sidebar.
### Step 3: Select Entity
Click on the entity you want to delete.
### Step 4: Check Dependencies
Look for:
- **Relations** tab/section showing connected entities
- Warning messages about dependencies
### Step 5: Export Data (Optional)
If you need the data:
1. Go to entity's data view
2. Export or manually copy records
3. Save backup externally
### Step 6: Delete Entity
1. Open entity settings (gear icon or settings tab)
2. Look for **Delete Entity** or **Remove** button
3. Confirm deletion
4. Entity and all data removed
### Step 7: Sync Database
After deletion, ensure database is synced:
- Click **Sync Database** if prompted
- Or run `npx bknd sync --drop` from CLI
---
## Handling Dependencies
### Scenario: Entity Has Child Records
**Problem:** Deleting `users` when `posts` has `users_id` foreign key.
**Solution 1: Delete Children First**
```typescript
// 1. Delete all posts referencing users
const api = app.getApi();
await api.data.deleteMany("posts", {});
// 2. Then delete users
// (via schema removal + sync)
```
**Solution 2: Remove Relationship First**
```typescript
// 1. Remove relationship from schema
// 2. Sync to remove foreign key
// 3. Remove entity from schema
// 4. Sync again with --drop
```
### Scenario: Entity is Junction Table Target
**Problem:** `tags` is used in `posts_tags` junction table.
**Solution:**
```typescript
// 1. Remove many-to-many relationship
const schema = em(
{
posts: entity("posts", { title: text() }),
tags: entity("tags", { name: text() }),
}
// Remove: ({ relation }, { posts, tags }) => { relation(posts).manyToMany(tags); }
);
// 2. Sync to drop junction table
// npx bknd sync --drop
// 3. Remove tags entity
const schema = em({
posts: entity("posts", { title: text() }),
});
// 4. Sync again to drop tags table
// npx bknd sync --drop
```
### Scenario: Self-Referencing Entity
**Problem:** `categories` references itself (parent/children).
**Solution:**
```typescript
// 1. Remove self-reference relation
const schema = em({
categories: entity("categories", { name: text() }),
// Remove self-referencing relation definition
});
// 2. Sync to remove foreign key
// npx bknd sync --drop
// 3. Remove entity
// (then sync again)
```
---
## Deleting Multiple Entities
Order matters. Delete in dependency order (children first):
```typescript
// Dependency tree:
// users <- posts <- comments
// <- likes
// Delete order:
// 1. comments (depends on posts)
// 2. likes (depends on posts)
// 3. posts (depends on users)
// 4. users (no dependencies)
```
### Batch Deletion Script
```typescript
// scripts/cleanup-entities.ts
import { App } from "bknd";
async function cleanup() {
const app = new App({
connection: { url: process.env.DB_URL! },
});
await app.build();
const api = app.getApi();
// Delete in order
const entitiesToDelete = ["comments", "likes", "posts"];
for (const entity of entitiesToDelete) {
const count = await api.data.count(entity);
console.log(`Deleting ${count.data.count} records from ${entity}...`);
await api.data.deleteMany(entity, {});
console.log(`Deleted all records from ${entity}`);
}
console.log("Data cleanup complete. Now remove from schema and sync.");
}
cleanup().catch(console.error);
```
---
## Common Pitfalls
### Foreign Key Constraint Error
**Error:** `Cannot drop table: foreign key constraint`
**Cause:** Another entity references this one.
**Fix:** Remove relationship first, sync, then remove entity.
### Junction Table Not Dropped
**Problem:** After removing many-to-many relation, junction table remains.
**Fix:** Run `npx bknd sync --drop` to include destructive operations.
### Entity Still Appears in UI
**Problem:** Deleted from code but still shows in admin panel.
**Fix:**
- Ensure you ran `npx bknd sync --drop`
- Restart the Bknd server
- CleaRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.