شعار Backend Bulk Import

Backend Bulk Import

المجتمع
j4flmao
backend-bulk-import

Use this skill when the user says 'bulk import', 'CSV upload', 'Excel import', 'import pipeline', 'import validation', 'upsert from file', 'import progress', 'import error report'. Designs file-based bulk import: upload handling, streaming CSV/Excel parsing, row validation with error reports, preview/confirm flow, batched background processing with progress, deduplication and rollback. Do NOT use for: real-time or streaming ingestion (backend-data-streaming), warehouse ETL (data etl skills), report/export generation (backend-report-generation).

نظرة عامة

الناشرj4flmao
المستودعagent-skills
اسم المهارةbackend-bulk-import
النجوم
41
التفريعات
6
الملفات المرفقة
8
الترخيصMIT
الروابط
  • تعليمات بصيغة Markdown

    ملف SKILL.md يُحمّله النموذج عند الحاجة، فلا يستهلك توكنات إلا عندما يَرِد طلب ذو صلة فعلًا.

  • تعمل مع أي نموذج لغوي كبير

    مهارات الذكاء الاصطناعي مكتوبة بصيغة Markdown وليست شيفرة خاصة بمزوّد معيّن، لذا تعمل مع GPT أو Claude أو Gemini أو Grok أو نموذج محلي.

  • الملفات المرفقة: 8

    نصوص برمجية وقوالب ومراجع يمكن للنموذج قراءتها أثناء عمله. الملفات للقراءة فقط ولا تُنفّذ أبدًا.

  • مفتوحة المصدر

    نشرها j4flmao على GitHub. اطّلع على المصدر قبل تثبيتها.

التثبيت

ثبّت مهارة الذكاء الاصطناعي Backend Bulk Import في TypingMind لاستخدامها مع أي نموذج لغوي كبير، أو أضفها إلى وكيل ذكاء اصطناعي آخر يقرأ SKILL.md.

1

التثبيت في TypingMind

يُثبّت TypingMind المهارة مباشرةً من مجلدها على GitHub — فيقرأ SKILL.md، ويجمع ملفات الموارد في حزمة، ويحفظ النتيجة محليًا.

  1. افتح التطبيق وانتقل إلى «الإضافات» ثم «المهارات».
  2. اختر «تثبيت من GitHub».
  3. الصق رابط مجلد المهارة الموضّح أدناه وأكّد التثبيت.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/bulk-import
  4. فعّل المهارة في كل محادثة تريد إتاحتها فيها.
الإضافات ← المهارات ← إضافة مهارة ← من رابط GitHub، ثم الصق رابط المجلد واضغط على «متابعة».
2

التثبيت في وكيل ذكاء اصطناعي آخر

يمكن لأي وكيل ذكاء اصطناعي يقرأ تنسيق Agent Skills استخدام هذه المهارة — انسخ المجلد إلى مجلد المهارات الخاص بذلك الوكيل.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/bulk-import .claude/skills/backend-bulk-import
أعد تشغيل Claude Code بعد النسخ ليتعرّف على المهارة الجديدة.

استخدمها في TypingMind

فعّل Backend Bulk Import في أي محادثة على TypingMind وسيتولى النموذج الباقي. تتضمن مطالبة النظام اسمها ووصفها، وبمجرد ورود طلب ذي صلة، يُحمّل النموذج التعليمات الكاملة تلقائيًا — فلا تحتاج إلى استدعائها يدويًا، ولا تستهلك أي توكنات حتى تُستخدم فعليًا.

يُحمّل النموذج مهارة Backend Bulk Import تلقائيًا بمجرد ورود طلب ذي صلة بها.

تعمل مع أي نموذج ذكاء اصطناعي

مهارات الذكاء الاصطناعي هي تعليمات بصيغة Markdown وليست شيفرة خاصة بمزوّد معيّن، لذا لا ترتبط Backend Bulk Import بالنموذج الذي كُتبت له. ثبّتها مرة واحدة في TypingMind واستخدمها مع GPT-5 أو Claude أو Gemini أو Grok أو DeepSeek أو Mistral أو Llama أو نموذج محلي تشغّله بنفسك — كل ذلك باستخدام مفاتيح API الخاصة بك.

  • تُحمَّل عند الحاجة فقط

    تتضمن مطالبة النظام الاسم والوصف فقط. وتُجلب التعليمات عند أول طلب ذي صلة، لذا لا تستهلك تعليمات المهارة أي توكنات ما دامت المهارة غير مستخدمة.

  • بدّل النماذج أثناء المحادثة

    لأن المهارة تعليمات وليست شيفرة، فإن تغيير النموذج لا يعطّلها — فالنموذج التالي يقرأ ملف SKILL.md نفسه.

تعليمات المهارة

هذا هو محتوى SKILL.md الذي يُحمّله النموذج. اقرأه قبل التثبيت — فالمهارة عبارة عن تعليمات سيتبعها نموذجك.

Bulk Import Skill

Purpose

Design robust bulk import systems that handle large CSV/Excel files with validation, progress tracking, error recovery, and audit trails.

Architecture Decision Trees

Import Mode Selection

CriterionInsertUpsertReplace
Duplicate handlingFails on conflictUpdates existingTruncate all first
PerformanceFastestModerate (check per row)Fast (truncate + insert)
IdempotentNoYes (by dedup field)No (destructive)
Risk levelLowLowHigh (data loss)
Audit trailAll insertsUpdates loggedLost on truncate
Rollback complexitySimple (transaction)ModerateComplex (needs backup)
Use caseNew data ingestionSync with external systemFull reimport/replace

Decision: Upsert for production syncs. Insert for immutable audit data. Replace only with pre-import backup.

Parsing Strategy

CriterionStreaming (CSV)Full load (Excel)Hybrid (chunked)
MemoryO(1) rows in memoryFull file in memoryO(batch size)
Max file sizeUnlimited~100MB practical~500MB
Row validationPer-batchAll before processingPer-batch
Error collectionPer-batchFull before processPer-batch
Progress trackingYes (real-time)No (must parse first)Yes (per chunk)
Random accessNoYesNo

Decision: Streaming for CSV. Chunked for Excel > 10MB. Full load for Excel < 10MB.

Deduplication Strategy

ApproachPrecisionPerformanceImplementation
DB unique constraintExactFast (index)Schema definition
Pre-check with SELECTExactSlow on large tablesQuery existing values
Row content hash (SHA-256 of normalized row, stored in a unique column)Exact on normalized contentFast (index)Hash + unique index
External dedup (Redis set)Exact within the set's lifetimeVery fastSADD returns 0 for duplicates
Bloom filter (RedisBloom BF.ADD)Probabilistic: false positives possibleVery fast, small memoryOnly where wrongly skipping a few unique rows is acceptable

Decision: DB unique constraint (with ON CONFLICT) for exact dedup. Bloom filters only as a pre-filter, never as the final decision for business data.

Agent Protocol

Trigger

User mentions bulk import, CSV upload, Excel import, data ingestion, batch processing, data migration, import pipeline, file upload processing, import validation, or ETL pipeline.

Input Context

  • Source file format (CSV, Excel, JSON)
  • Expected file size and row count
  • Data schema and validation rules
  • Import mode (insert, upsert, replace)
  • Deduplication strategy
  • Error handling requirements
  • Background processing needs
  • Target system and database

Output Artifact

SKILL.md adherence document plus implemented import pipeline, validation logic, progress tracking, error handling, and rollback mechanisms.

Response Format

No preamble. No postamble. No explanations. No filler/hedging/transitions. Compress output — why use many token when few do trick.

Completion Criteria

  • File upload endpoint with size/type validation implemented
  • CSV/Excel parser configured with header mapping and encoding detection
  • Validation pipeline with row-level error collection operational
  • Preview step (show sample + errors before confirm) implemented
  • Batch processing with progress tracking and throttling
  • Import template with downloadable sample file ready
  • Deduplication logic implemented (configurable per field)
  • Rollback mechanism for partial failures
  • Import history and audit log stored
  • Webhook notification on import completion
  • Rate limiting on import endpoints

Max Response Length

4096 tokens

Workflow

  1. File Upload & Validation: Accept upload with strict type/size checks.
typescript
import multer from 'multer';
import { randomUUID } from 'node:crypto';

const ALLOWED_MIME = [
  'text/csv',
  'application/vnd.ms-excel',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
];
const MAX_SIZE = 50 * 1024 * 1024; // 50MB

// Disk (or object storage) instead of memory: the worker streams the file later.
const upload = multer({
  storage: multer.diskStorage({
    destination: process.env.IMPORT_DIR ?? '/var/app/imports',
    filename: (_req, _file, cb) => cb(null, randomUUID()), // never trust client file names
  }),
  limits: { fileSize: MAX_SIZE },
  fileFilter: (_req, file, cb) => {
    // mimetype is client-supplied: treat as a hint and re-validate content when parsing.
    if (!ALLOWED_MIME.includes(file.mimetype)) {
      cb(new Error('Unsupported file type. Only CSV and Excel files are allowed.'));
      return;
    }
    cb(null, true);
  },
});

app.post('/api/imports/upload', upload.single('file'), async (req, res) => {
  const importJob = await ImportJob.create({
    userId: req.user.id,
    fileName: req.file.originalname,
    fileSize: req.file.size,
    mimeType: req.file.mimetype,
    filePath: req.file.path,
    status: 'uploaded',
  });

  // Preview reads only the first rows; full validation runs in a background job.
  const preview = await readPreview(req.file.path, req.file.mimetype, 5);
  importJob.columnCount = preview.headers.length;
  importJob.preview = preview.rows;
  await importJob.save();
  await validationQueue.add('validate', { importId: importJob.id });

  res.status(202).json({ jobId: importJob.id, preview: importJob.preview });
});
  1. CSV Parsing with Streaming: Handle large files without memory overflow.
typescript
import { parse } from 'csv-parse';
import { createReadStream } from 'fs';

async function* streamCsvRows(filePath: string, batchSize = 500): AsyncGenerator<Record<string, string>[]> {
  const parser = createReadStream(filePath).pipe(parse({
    columns: true,
    skip_empty_lines: true,
    trim: true,
    relax_column_count: true,
    encoding: 'utf-8',
    bom: true,
  }));

  let batch: Record<string, string>[] = [];

  for await (const record of parser) {
    batch.push(record);
    if (batch.length >= batchSize) {
      yield batch;
      batch = [];
    }
  }

  if (batch.length > 0) yield batch;
}
  1. Validation Pipeline: Row-level validation with comprehensive error collection.
typescript
class ImportValidator {
  private validators: Map<string, FieldValidator[]> = new Map();

  register(field: string, ...validators: FieldValidator[]): void {
    this.validators.set(field, [...(this.validators.get(field) || []), ...validators]);
  }

  async validate(rows: Record<string, unknown>[]): Promise<ValidationResult> {
    const errors: ValidationError[] = [];
    const validRows: Record<string, unknown>[] = [];

    for (let i = 0; i < rows.length; i++) {
      const row = rows[i];
      const rowErrors: ValidationError[] = [];

      for (const [field, fieldValidators] of this.validators.entries()) {
        const value = row[field];
        for (const validator of fieldValidators) {
          const error = await validator.validate(field, value, row);
          if (error) rowErrors.push({ ...error, row: i + 1 });
        }
      }

      if (rowErrors.length > 0) {
        errors.push(...rowErrors);
      } else {
        validRows.push(row);
      }
    }

    return { validRows, errors, totalRows: rows.length, validCount: validRows.length, errorCount: errors.length };
  }
}

// Usage
const validator = new ImportValidator();
validator.register('email', { validate: async (field, value) => {
  if (!value || typeof value !== 'string') return { field, message: 'Email is required' };
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return { field, message: 'Invalid email format' };
  return null;
}});
validator.register('age', { validate: async (field, value) => {
  const num = Number(value);
  if (isNaN(num) || num < 0 || num > 150) return { field, message: 'Age must be between 0 and 150' };
  return null;
}});
  1. Import Pipeline Lifecycle: Upload → Validate → Preview → Confirm → Process.
typescript
interface ImportJob {
  id: string;
  userId: string;
  fileName: string;
  fileSize: number;
  rowCount: number;
  status: ImportStatus;
  importMode: 'insert' | 'upsert' | 'replace';
  dedupField?: string;
  validationErrors?: ValidationError[];
  processingProgress?: { processed: number; total: number; failed: number };
  createdAt: Date;
  completedAt?: Date;
}

type ImportStatus =
  | 'uploaded'
  | 'validating'
  | 'validation_complete'
  | 'preview'
  | 'confirmed'
  | 'processing'
  | 'completed'
  | 'partial'
  | 'failed';

app.post('/api/imports/:id/confirm', async (req, res) => {
  const job = await ImportJob.findById(req.params.id);
  if (job.status !== 'validation_complete') {
    return res.status(400).json({ error: 'Import must complete validation first' });
  }

  job.status = 'confirmed';
  await job.save();

  await importQueue.add('process', {
    importId: job.id,
    batchSize: req.body.batchSize || 500,
    importMode: job.importMode,
    dedupField: job.dedupField,
  });

  res.json({ status: 'processing', jobId: job.id });
});
  1. Batch Processing with Progress: Process in batches with transaction support.
typescript
import { Queue, Worker } from 'bullmq';

const connection = { host: process.env.REDIS_HOST, port: Number(process.env.REDIS_PORT ?? 6379) };
export const importQueue = new Queue('import-processing', { connection });

new Worker('import-processing', async (job) => {
  const { importId, batchSize, importMode, dedupField } = job.data;
  const importJob = await ImportJob.findById(importId);

  importJob.status = 'processing';
  await importJob.save();

  // Replace mode: clear once, up front (or load into a staging table and swap).
  if (importMode === 'replace') {
    await backupTargetTable(importId);
    await db('target_table').delete();
  }

  const fileStream = createReadStream(importJob.filePath);
  const parser = fileStream.pipe(parse({ columns: true, skip_empty_lines: true }));

  let batch: Record<string, unknown>[] = [];
  let processed = 0;
  let failed = 0;
  const errors: ProcessingError[] = [];

  for await (const record of parser) {
    batch.push(record);

    if (batch.length >= batchSize) {
      const result = await processBatch(batch, importMode, dedupField);
      processed += result.processed;
      failed += result.failed;
      errors.push(...result.errors);

      importJob.processingProgress = { processed, total: importJob.rowCount, failed };
      await importJob.save();
      await job.updateProgress({ processed, total: importJob.rowCount, failed });

      batch = [];
    }
  }

  if (batch.length > 0) {
    const result = await processBatch(batch, importMode, dedupField);
    processed += result.processed;
    failed += result.failed;
    errors.push(...result.errors);
  }

  importJob.status = failed > 0 && processed > 0 ? 'partial' : 'completed';
  importJob.completedAt = new Date();
  importJob.processingProgress = { processed, total: importJob.rowCount, failed };
  await importJob.save();

  await notifyWebhook(importJob);

  return { processed, failed, errors: errors.slice(0, 100) };
}, { connection, concurrency: 2 });

async function processBatch(
  rows: Record<string, unknown>[],
  mode: string,
  dedupField?: string
): Promise<{ processed: number; failed: number; errors: ProcessingError[] }> {
  const errors: ProcessingError[] = [];

  if (dedupField) {
    const existingValues = await getExistingValues(rows, dedupField);
    rows = filterDuplicates(rows, dedupField, existingValues);
  }

  const trx = await db.transaction(); // knex

  try {
    switch (mode) {
      case 'insert':
      case 'replace': // table already cleared once before the first batch
        await trx('target_table').insert(rows);
        break;
      case 'upsert':
        await trx('target_table').insert(rows).onConflict(dedupField || 'id').merge();
        break;
    }
    await trx.commit();
    return { processed: rows.length, failed: 0, errors: [] };
  } catch (error) {
    await trx.rollback();
    errors.push({ message: (error as Error).message, rows: rows.length });
    return { processed: 0, failed: rows.length, errors };
  }
}
  1. Import Templates: Generate downloadable sample files.
typescript
function generateImportTemplate(headers: ImportColumn[]): string {
  const headerRow = headers.map(h => h.label).join(',');
  const sampleRow = headers.map(h => h.example || '').join(',');
  return `${headerRow}\n${sampleRow}\n`;
}

app.get('/api/imports/templates/:type', (req, res) => {
  const template = getImportTemplateConfig(req.params.type);
  const csv = generateImportTemplate(template.columns);

  res.setHeader('Content-Type', 'text/csv');
  res.setHeader('Content-Disposition', `attachment; filename="${template.name}-template.csv"`);
  res.send(csv);
});

Implementation Patterns

Pattern: Column Header Mapping

typescript
interface ColumnMapping {
  displayName: string;    // From CSV header
  fieldName: string;      // Internal field name
  required: boolean;
  defaultValue?: unknown;
  transform?: (value: string) => unknown;
}

class HeaderMapper {
  async detectHeaders(file: Buffer, mimeType: string): Promise<ColumnMapping[]> {
    const headers = await this.parseHeaders(file, mimeType);
    const mapping = this.fuzzyMatch(headers, this.expectedColumns);
    const unmatched = headers.filter(h => !mapping.find(m => m.displayName === h));
    if (unmatched.length > 0) {
      throw new ImportError(`Unrecognized columns: ${unmatched.join(', ')}`);
    }
    return mapping;
  }

  private fuzzyMatch(actual: string[], expected: ColumnMapping[]): ColumnMapping[] {
    return actual.map(header => {
      const match = expected.find(e =>
        e.displayName.toLowerCase() === header.toLowerCase() ||
        e.fieldName.toLowerCase() === header.toLowerCase()
      );
      if (!match) return null;
      return { ...match, displayName: header };
    }).filter(Boolean) as ColumnMapping[];
  }
}

Pattern: Error Report Generation

typescript
interface ImportError {
  row: number;
  column: string;
  value: string;
  message: string;
  code: string;
}

async function generateErrorReport(errors: ImportError[], format: 'csv' | 'xlsx'): Promise<Buffer> {
  if (format === 'csv') {
    const header = 'Row,Column,Value,Error,Code\n';
    const rows = errors.map(e =>
      `"${e.row}","${e.column}","${e.value.replace(/"/g, '""')}","${e.message.replace(/"/g, '""')}","${e.code}"`
    ).join('\n');
    return Buffer.from(header + rows, 'utf-8');
  }

  const workbook = new ExcelJS.Workbook();
  const sheet = workbook.addWorksheet('Import Errors');
  sheet.columns = [
    { header: 'Row', key: 'row', width: 10 },
    { header: 'Column', key: 'column', width: 20 },
    { header: 'Value', key: 'value', width: 30 },
    { header: 'Error', key: 'message', width: 50 },
    { header: 'Code', key: 'code', width: 15 },
  ];
  errors.forEach(e => sheet.addRow(e));
  sheet.getRow(1).font = { bold: true };
  return await workbook.xlsx.writeBuffer() as Buffer;
}

Pattern: Import Webhook Notifications

typescript
interface ImportNotification {
  importId: string;
  status: 'completed' | 'partial' | 'failed';
  summary: { total: number; processed: number; failed: number; skipped: number };
  downloadUrl?: string;
  errorReportUrl?: string;
}

async function notifyImportComplete(job: ImportJob): Promise<void> {
  const notification: ImportNotification = {
    importId: job.id,
    status: job.status,
    summary: {
      total: job.rowCount,
      processed: job.processingProgress?.processed || 0,
      failed: job.processingProgress?.failed || 0,
      skipped: job.rowCount - (job.processingProgress?.processed || 0) - (job.processingProgress?.failed || 0),
    },
  };

  if (job.webhookUrl) {
    await fetch(job.webhookUrl, {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(notification),
    });
  }

  if (job.notifyUserId) {
    await notificationService.send(job.notifyUserId, {
      type: 'import_complete',
      title: `Import ${job.status}: ${job.fileName}`,
      ...notification,
    });
  }
}

Production Considerations

Scalability

  • Queue workers: scale horizontally by import type; dedicated worker pools for large imports
  • DB connections: batch processing uses pooled connections; release between batches
  • Memory: streaming parsers for files > 50MB; never load entire file into memory
  • Storage: upload files to S3/Blob storage; process from stream without local temp file

Monitoring

  • Metrics: import duration, rows/second, error rate by type, queue depth, failure rate
  • Alerts: error rate > 5%, queue backlog > 100 jobs, same file re-upload > 3 times
  • Logging: structured logs per import job (importId, userId, status, rowCount, duration)

Error Recovery

  • Partial success: import valid rows, report errors, allow retry of failed rows only
  • Rollback: transaction per batch; failed batch rolls back without affecting previous batches
  • Retry: exponential backoff for transient DB errors; manual retry for data errors after fix
  • Cancellation: set cancel flag; worker checks flag between batches and stops gracefully

Anti-Patterns

Anti-PatternWhyFix
Direct INSERT without validationBad data corrupts databaseValidation pipeline before any insert
Single transaction for entire fileFailure loses all progress; locks tableBatch per transaction (500-1000 rows)
Processing on main threadBlocks HTTP response; no retryBackground queue always
Ignoring BOM/encodingCorrupted strings for special charsAuto-detect encoding with chardet or iconv-lite
Overwriting data without backupReplace mode can't be undoneAuto-backup before replace; transaction rollback
No header validationWrong column mapping = wrong dataValidate headers before processing any rows
Synchronous progress trackingUsers refresh waiting; no feedbackWebSocket push or poll endpoint for progress
Storing full file content in DBDB bloat; file storage is cheaperObject storage with metadata reference in DB
Too-large batch size (10K+)Long transaction; deadlock riskOptimal batch size: 500-1000 rows
No dedup before importDuplicate records; manual cleanupDedup check per batch; fail or skip duplicates

Security Considerations

  • File validation: do not trust extension or client MIME type. XLSX is a ZIP container (check the PK signature and parse it with a hardened library); CSV has no signature, so validate it by parsing (encoding, column count) and reject on failure. Cap rows, columns and cell length to stop zip bombs and memory exhaustion
  • Upload path traversal: sanitize filename; use UUID-based storage keys, never user-provided names
  • CSV injection: don't open generated CSV in Excel directly (formulas starting with =, +, -, @ can execute)
    • Mitigation: prefix dangerous-starting values with tab or single quote in CSV output
  • Rate limiting: per-user, per-hour import limits (e.g., 5 imports/hour, 500MB/hour total)
  • PII: mask sensitive fields in preview; enforce field-level access control
  • Audit: log every import action (upload, validate, confirm, cancel) with userId, timestamp, row count
  • File retention: auto-delete uploaded files after 30 days; allow user-triggered immediate deletion

Testing Strategies

typescript
import { describe, it, expect } from 'vitest';
import { parse } from 'csv-parse';

describe('Bulk Import', () => {
  it('parses CSV with headers', async () => {
    const csv = 'name,email,age\nAlice,alice@test.com,30\nBob,bob@test.com,25';
    const records: Record<string, string>[] = [];
    const parser = parse(csv, { columns: true, skip_empty_lines: true });
    for await (const record of parser) records.push(record);
    expect(records).toHaveLength(2);
    expect(records[0].name).toBe('Alice');
  });

  it('validates required fields', async () => {
    const validator = new ImportValidator();
    validator.register('email', { validate: async (f, v) => !v ? { field: f, message: 'Required' } : null });
    const result = await validator.validate([{ email: '' }, { email: 'test@test.com' }]);
    expect(result.errorCount).toBe(1);
    expect(result.validCount).toBe(1);
  });

  it('detects encoding', async () => {
    const buf = Buffer.from('name,email\nJalapeño,test@test.com', 'utf-8');
    const encoding = await detectEncoding(buf);
    expect(encoding).toBe('UTF-8');
  });

  it('rejects oversized files', () => {
    const file = { size: 100 * 1024 * 1024, mimetype: 'text/csv' };
    expect(validateFile(file, { maxSize: 50 * 1024 * 1024 })).toBe(false);
  });

  it('processes batch with transaction rollback on error', async () => {
    // db is a mocked knex instance whose insert rejects (name NOT NULL)
    const result = await processBatch(
      [{ id: 1, name: 'Valid' }, { id: 2, name: null }],
      'insert',
    );
    expect(result.processed).toBe(0);
    expect(result.failed).toBe(2);
  });

  it('generates downloadable error report', async () => {
    const errors = [{ row: 1, column: 'email', value: 'bad', message: 'Invalid format', code: 'INVALID_EMAIL' }];
    const report = await generateErrorReport(errors, 'csv');
    expect(report.toString()).toContain('Row,Column,Value,Error,Code');
    expect(report.toString()).toContain('"1","email","bad","Invalid format","INVALID_EMAIL"');
  });
});
  • Test with real CSV/Excel files containing edge cases: BOM, UTF-16, emoji, null bytes, quote-escaped fields
  • Load test with a realistic large file (e.g. 500K rows) and record rows/second as a regression baseline
  • Test cancel: start import, cancel mid-way, verify no partial data committed
  • Test replace mode: verify old data is backed up before truncate, can be restored

Rules

  • Never parse a whole large file in the HTTP request; upload, then process in a background job.
  • Validate headers before rows; collect row errors instead of failing on the first.
  • One transaction per batch (hundreds to a few thousand rows); never one transaction for a huge file unless using a staging table.
  • Database constraints are the final authority for uniqueness and integrity.
  • Replace mode only with a backup or staging-table swap.

References

  • references/bulk-export.md — Bulk Export
  • references/bulk-import-advanced.md — Bulk Import Advanced Topics
  • references/bulk-import-fundamentals.md — Bulk Import Fundamentals
  • references/csv-parsing.md — CSV Parsing
  • references/import-monitoring.md — Import Monitoring
  • references/import-workflow.md — Import Workflow
  • references/rollback-recovery.md — Rollback and Recovery
  • references/validation-pipeline.md — Validation Pipeline

Handoff

  • backend/report-generation — Export/import round-trip patterns
  • skills/data/etl-pipeline — ETL pipeline integration for bulk imports
  • skills/backend/universal/background-jobs — Queue management for import jobs

الملفات المرفقة

يقرأ النموذج هذه الملفات عند الحاجة ما دامت المهارة محمّلة. وهي متاحة للقراءة ولا تُنفّذ أبدًا.

الأسئلة الشائعة

ماذا تفعل مهارة الذكاء الاصطناعي Backend Bulk Import؟

Use this skill when the user says 'bulk import', 'CSV upload', 'Excel import', 'import pipeline', 'import validation', 'upsert from file', 'import progress', 'import error report'. Designs file-based bulk import: upload handling, streaming CSV/Excel parsing, row validation with error reports, preview/confirm flow, batched background processing with progress, deduplication and rollback. Do NOT use for: real-time or streaming ingestion (backend-data-streaming), warehouse ETL (data etl skills), report/export generation (backend-report-generation).

لماذا تستخدم Backend Bulk Import على TypingMind؟

لأنك تثبّتها مرة واحدة وتستخدمها مع أي نموذج. مهارة Backend Bulk Import عبارة عن نص Markdown وليست شيفرة خاصة بمزود بعينه، لذا تعمل المهارة نفسها مع GPT-5 أو Claude أو Gemini أو Grok أو نموذج محلي، ويمكنك تبديل النموذج أثناء المحادثة دون تعطّل المهارة. يعمل TypingMind بمفاتيح API الخاصة بك، فتدفع للمزودين مباشرةً بدلًا من اشتراك لكل مقعد، وتبقى مهاراتك ومحادثاتك في مساحة التخزين الخاصة بك.

كيف أثبّت Backend Bulk Import في TypingMind؟

في TypingMind، افتح «الإضافات»، ثم «المهارات»، ثم اختر «التثبيت من GitHub» والصق https://github.com/j4flmao/agent-skills/tree/main/skills/backend/bulk-import. يقرأ TypingMind ملف SKILL.md الخاص بالمهارة، ويجمع ملفاتها ويثبّتها كمهارة يمكنك تفعيلها لكل محادثة على حدة.

ما نماذج الذكاء الاصطناعي التي يمكنها استخدام Backend Bulk Import؟

أي نموذج تربطه في TypingMind. مهارات الذكاء الاصطناعي عبارة عن تعليمات Markdown وليست شيفرة خاصة بمزود بعينه، لذا يمكن لكل من GPT وClaude وGemini وGrok والنماذج المحلية تحميل هذه المهارة عندما يتوافق الطلب معها.

كم نموذج ذكاء اصطناعي يمكنني استخدامه مع Backend Bulk Import؟

أي عدد تريده. ما دام النموذج يدعم المهارات، يمكنك استخدام Backend Bulk Import معه، سواء كان GPT أو Claude أو Gemini أو Grok أو DeepSeek أو Mistral أو Llama أو غيرها، وكل ذلك على TypingMind باستخدام مفاتيح API الخاصة بك.

هل مهارة الذكاء الاصطناعي Backend Bulk Import مجانية؟

نعم. نشرها j4flmao على GitHub بموجب ترخيص MIT. لا تدفع إلا لمزود الذكاء الاصطناعي الخاص بك مقابل التوكنات التي تستخدمها.

ما هي مهارات الذكاء الاصطناعي؟

مهارة الذكاء الاصطناعي حزمة تعليمات قابلة لإعادة الاستخدام تعلّم نموذج الذكاء الاصطناعي كيفية تنفيذ مهمة محددة. وتتبع تنسيق Agent Skills المفتوح: ملف SKILL.md يتضمن اسمًا ووصفًا، إلى جانب أي نصوص برمجية أو قوالب أو ملفات مرجعية قد يحتاج إليها النموذج. لا يقرأ النموذج التعليمات إلا عندما يتوافق طلبك مع المهارة، لذا لا تترتب على المهارة المثبتة أي تكلفة حتى تُستخدم.

كيف تختلف مهارات الذكاء الاصطناعي عن الإضافات أو موصلات MCP؟

تمنح الإضافة أو موصل MCP النموذج أدوات جديدة يمكنه استدعاؤها، وهي شيفرة تُنفَّذ في مكان ما وتُرجع نتيجة. أما مهارة الذكاء الاصطناعي فتزوّد النموذج بالمعرفة ومنهجية العمل: كيفية التعامل مع مهمة، والخطوات التي ينبغي اتباعها، وما ينبغي أن تكون عليه المخرجات الجيدة. المهارات عبارة عن نصوص Markdown، لذا لا تحتاج إلى خادم أو مفتاح API أو بيئة تشغيل، وتعمل مع أي نموذج.

عرض الكل

أنشئ مساحة عملك للذكاء الاصطناعي الآن

اشترك في نشرتنا الإخبارية لتصلك أخبار الميزات الجديدة والهدايا القادمة 👇