summaryrefslogtreecommitdiff
path: root/lib/oracle-db/nonsap/3.generate-postgres-drizzle-schema.ts
blob: cfafb1e040d098890c965826d3c105c6c52d03fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import fs from 'fs';
import path from 'path';

interface TableColumn {
  owner: string;
  tableName: string;
  columnName: string;
  dataType: string;
  dataLength: number;
  nullable: string;
  tableComments: string;
  columnComments: string;
  constraints: string;
}

interface TableSchema {
  tableName: string;
  tableComments: string;
  columns: TableColumn[];
}

// 컬러 로그 함수들
const log = {
  info: (msg: string) => console.log(`\x1b[34mℹ\x1b[0m ${msg}`),
  success: (msg: string) => console.log(`\x1b[32m✓\x1b[0m ${msg}`),
  warning: (msg: string) => console.log(`\x1b[33m⚠\x1b[0m ${msg}`),
  error: (msg: string) => console.log(`\x1b[31m✗\x1b[0m ${msg}`),
};

// Oracle -> PostgreSQL 타입 매핑 (nonsap용)
function mapOracleTypeToPostgres(oracleType: string, dataLength: number): string {
  const type = oracleType.toUpperCase();
  
  switch (type) {
    case 'VARCHAR2':
      if (dataLength <= 255) {
        return `varchar({ length: ${dataLength} })`;
      } else {
        return 'text()';
      }
    case 'NUMBER':
      return 'numeric()';
    case 'DATE':
      return 'timestamp()';
    case 'CHAR':
      return `char({ length: ${dataLength} })`;
    case 'CLOB':
      return 'text()';
    case 'BLOB':
      return 'bytea()';
    case 'INTEGER':
      return 'integer()';
    case 'DECIMAL':
      return 'decimal()';
    case 'FLOAT':
      return 'real()';
    case 'DOUBLE':
      return 'doublePrecision()';
    default:
      log.warning(`Unknown Oracle type: ${type}, defaulting to text()`);
      return 'text()';
  }
}

// 테이블명을 camelCase로 변환
function toCamelCase(str: string): string {
  return str.toLowerCase().replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
}

// 컬럼명을 camelCase로 변환
function toColumnName(str: string): string {
  return str.toLowerCase().replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
}

// CSV 파싱 함수
function parseCSV(csvContent: string): TableColumn[] {
  const lines = csvContent.split('\n');
  const data: TableColumn[] = [];

  for (let i = 1; i < lines.length; i++) {
    const line = lines[i].trim();
    if (!line) continue;

    const values = line.split(',');
    if (values.length < 9) continue;

    data.push({
      owner: values[0],
      tableName: values[1],
      columnName: values[2],
      dataType: values[3],
      dataLength: parseInt(values[4]) || 0,
      nullable: values[5],
      tableComments: values[6],
      columnComments: values[7],
      constraints: values[8] || '',
    });
  }

  return data;
}

// 테이블별로 그룹화
function groupByTable(columns: TableColumn[]): TableSchema[] {
  const tables = new Map<string, TableSchema>();

  for (const column of columns) {
    if (!tables.has(column.tableName)) {
      tables.set(column.tableName, {
        tableName: column.tableName,
        tableComments: column.tableComments,
        columns: [],
      });
    }
    tables.get(column.tableName)!.columns.push(column);
  }

  return Array.from(tables.values());
}

// 제약조건 파싱 및 처리
function parseConstraints(constraints: string) {
  const result = {
    isPrimaryKey: false,
    isUnique: false,
    hasCheck: false,
    hasForeignKey: false,
  };

  if (!constraints) return result;

  const constraintUpper = constraints.toUpperCase();
  result.isPrimaryKey = constraintUpper.includes('PK');
  result.isUnique = constraintUpper.includes('UNIQUE');
  result.hasCheck = constraintUpper.includes('CHECK');
  result.hasForeignKey = constraintUpper.includes('FK') || constraintUpper.includes('FOREIGN');

  return result;
}

// Drizzle 스키마 생성
function generateDrizzleSchema(tables: TableSchema[]): string {
  let schema = `import { pgSchema, varchar, text, numeric, timestamp, char, bytea, integer, decimal, real, doublePrecision, primaryKey } from 'drizzle-orm/pg-core';

// NonSAP Oracle 데이터베이스 스키마
export const nonsapSchema = pgSchema('nonsap');

`;

  // Primary key 정보를 추적하기 위한 Map
  const primaryKeys = new Map<string, string[]>();

  // 각 테이블에 대한 스키마 생성
  for (const table of tables) {
    const tableName = toCamelCase(table.tableName);
    const pkColumns: string[] = [];

    // Primary key 컬럼 찾기
    for (const column of table.columns) {
      const constraintInfo = parseConstraints(column.constraints);
      if (constraintInfo.isPrimaryKey) {
        pkColumns.push(column.columnName); // 원본 컬럼명 그대로 사용
      }
    }
    
    if (pkColumns.length > 0) {
      primaryKeys.set(tableName, pkColumns);
    }

    // 테이블 코멘트 추가
    if (table.tableComments) {
      schema += `// ${table.tableComments}\n`;
    }
    
    schema += `export const ${tableName} = nonsapSchema.table('${table.tableName.toLowerCase()}', {\n`;

    table.columns.forEach((column) => {
      const columnName = column.columnName; // 원본 컬럼명 그대로 사용
      const postgresType = mapOracleTypeToPostgres(column.dataType, column.dataLength);
      const nullable = column.nullable === 'Y' ? '' : '.notNull()';
      const constraintInfo = parseConstraints(column.constraints);
      
      // 컬럼 코멘트 추가
      if (column.columnComments) {
        schema += `  // ${column.columnComments}\n`;
      }
      
      let columnDef = `  ${columnName}: ${postgresType}${nullable}`;
      
      // Primary key는 별도로 처리되므로 여기서는 제외
      if (constraintInfo.isUnique && !constraintInfo.isPrimaryKey) {
        columnDef += '.unique()';
      }
      
      columnDef += ',\n';
      schema += columnDef;
    });

    schema += '}';

    // Primary key 추가
    if (pkColumns.length > 0) {
      if (pkColumns.length === 1) {
        schema += `, (table) => ({\n  pk: primaryKey({ columns: [table.${pkColumns[0]}] })\n})`;
      } else {
        const pkColumnsStr = pkColumns.map(col => `table.${col}`).join(', ');
        schema += `, (table) => ({\n  pk: primaryKey({ columns: [${pkColumnsStr}] })\n})`;
      }
    }

    schema += ');\n\n';
  }

  // 타입 export 추가
  schema += `// 타입 정의\n`;
  for (const table of tables) {
    const tableName = toCamelCase(table.tableName);
    const typeName = tableName.charAt(0).toUpperCase() + tableName.slice(1);
    schema += `export type ${typeName} = typeof ${tableName}.$inferSelect;\n`;
    schema += `export type New${typeName} = typeof ${tableName}.$inferInsert;\n`;
  }

  return schema;
}

async function main() {
  try {
    log.info('Starting NonSAP Oracle to PostgreSQL Drizzle schema generation...');
    
    // CSV 파일 읽기
    const csvPath = path.join(__dirname, '1.table-and-columns-info.csv');
    const csvContent = fs.readFileSync(csvPath, 'utf-8');
    
    log.info('Parsing CSV data...');
    const columns = parseCSV(csvContent);
    
    if (columns.length === 0) {
      throw new Error('No data found in CSV file');
    }
    
    log.info(`Parsed ${columns.length} column definitions`);
    
    // 테이블별로 그룹화
    const tables = groupByTable(columns);
    
    log.info(`Found ${tables.length} tables`);
    
    // Drizzle 스키마 생성
    log.info('Generating Drizzle schema...');
    const schemaCode = generateDrizzleSchema(tables);
    
    // 파일 저장
    const outputPath = path.join(__dirname, 'schema.ts');
    fs.writeFileSync(outputPath, schemaCode, 'utf-8');
    
    log.success(`Generated Drizzle schema: ${outputPath}`);
    log.success(`Generated ${tables.length} table schemas with ${columns.length} total columns`);
    
  } catch (error: unknown) {
    if (error instanceof Error) {
      log.error(`Failed to generate schema: ${error.message}`);
    } else {
      log.error('Failed to generate schema: Unknown error');
    }
    process.exit(1);
  }
}

if (require.main === module) {
  main();
}

export { main };