bulk-inserter.ts 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import { PrismaClient } from '@prisma/client';
  2. import { ReadSectionData } from './types';
  3. export class BulkInserter {
  4. private prisma: PrismaClient;
  5. constructor() {
  6. this.prisma = new PrismaClient();
  7. }
  8. async insertSectionData(
  9. sectionData: ReadSectionData,
  10. importId: number,
  11. onProgress: (rows: number) => void
  12. ): Promise<number> {
  13. const batchSize = 5000;
  14. const totalRows = sectionData.data.length;
  15. let insertedRows = 0;
  16. try {
  17. // Handle specific table names with Prisma models
  18. const tableName = sectionData.tableName;
  19. for (let i = 0; i < totalRows; i += batchSize) {
  20. const batch = sectionData.data.slice(i, i + batchSize);
  21. if (batch.length === 0) continue;
  22. // Prepare data for insertion with proper field mapping
  23. const values = batch.map(row => {
  24. const mappedRow: any = {
  25. importId: importId
  26. };
  27. // Map the row data to match Prisma model field names
  28. Object.keys(row).forEach(key => {
  29. // Convert snake_case to camelCase for Prisma model compatibility
  30. const camelKey = key.replace(/_([a-z0-9])/g, (g) => g[1].toUpperCase());
  31. mappedRow[camelKey] = row[key];
  32. });
  33. return mappedRow;
  34. });
  35. // Use appropriate Prisma model based on table name
  36. if (tableName === 'cintas_install_calendar') {
  37. await this.prisma.cintasInstallCalendar.createMany({
  38. data: values,
  39. skipDuplicates: false
  40. });
  41. } else if (tableName === 'cintas_install_calendar_summary') {
  42. await this.prisma.cintasSummary.createMany({
  43. data: values,
  44. skipDuplicates: false
  45. });
  46. } else if (tableName === 'gow_data') {
  47. await this.prisma.gowData.createMany({
  48. data: values,
  49. skipDuplicates: false
  50. });
  51. } else if (tableName === 'gow_fac_id') {
  52. await this.prisma.gowFacId.createMany({
  53. data: values,
  54. skipDuplicates: false
  55. });
  56. } else if (tableName === 'gow_corp_ref') {
  57. await this.prisma.gowCorpRef.createMany({
  58. data: values,
  59. skipDuplicates: false
  60. });
  61. } else {
  62. // Fallback to raw SQL for other tables
  63. await this.prisma.$executeRawUnsafe(
  64. this.buildInsertQuery(tableName, values)
  65. );
  66. }
  67. insertedRows += batch.length;
  68. onProgress(insertedRows);
  69. }
  70. return insertedRows;
  71. } catch (error) {
  72. console.error('Error inserting section data:', error);
  73. throw error;
  74. }
  75. }
  76. private buildInsertQuery(tableName: string, values: any[]): string {
  77. if (values.length === 0) return '';
  78. const keys = Object.keys(values[0]);
  79. const columns = keys.map(key => `"${key}"`).join(', ');
  80. const placeholders = values.map(row => {
  81. const valuesList = keys.map(key => {
  82. const value = row[key];
  83. if (value === null || value === undefined) {
  84. return 'NULL';
  85. }
  86. if (typeof value === 'string') {
  87. return `'${value.replace(/'/g, "''")}'`;
  88. }
  89. return value;
  90. });
  91. return `(${valuesList.join(', ')})`;
  92. }).join(', ');
  93. return `INSERT INTO "${tableName}" (${columns}) VALUES ${placeholders}`;
  94. }
  95. }