( tableDefinition: Record<string, unknown>, pluginId?: string, )
| 292 | * Generates CREATE TABLE SQL from a Drizzle table definition |
| 293 | */ |
| 294 | export function generateCreateTableSQL( |
| 295 | tableDefinition: Record<string, unknown>, |
| 296 | pluginId?: string, |
| 297 | ): string { |
| 298 | const drizzleNameSymbol = Symbol.for("drizzle:Name"); |
| 299 | const drizzleColumnsSymbol = Symbol.for("drizzle:Columns"); |
| 300 | |
| 301 | const originalTableName = |
| 302 | (tableDefinition[ |
| 303 | drizzleNameSymbol as unknown as keyof typeof tableDefinition |
| 304 | ] as string) || "unknown_table"; |
| 305 | |
| 306 | // If plugin ID is provided and table name doesn't already start with pluginId, prefix it |
| 307 | const tableName = |
| 308 | pluginId && !originalTableName.startsWith(`${pluginId}_`) |
| 309 | ? `${pluginId}_${originalTableName.replace(/^plugin_/, "")}` |
| 310 | : originalTableName; |
| 311 | |
| 312 | // Warn if table name was automatically prefixed |
| 313 | if ( |
| 314 | pluginId && |
| 315 | !originalTableName.startsWith(`${pluginId}_`) && |
| 316 | tableName !== originalTableName |
| 317 | ) { |
| 318 | warnAboutTablePrefixing(originalTableName, tableName, pluginId); |
| 319 | } |
| 320 | |
| 321 | const columns = |
| 322 | (tableDefinition[ |
| 323 | drizzleColumnsSymbol as unknown as keyof typeof tableDefinition |
| 324 | ] as Record<string, unknown>) || {}; |
| 325 | |
| 326 | const columnDefinitions: string[] = []; |
| 327 | const constraints: string[] = []; |
| 328 | |
| 329 | for (const [columnName, column] of Object.entries(columns)) { |
| 330 | const col = column as { |
| 331 | name?: string; |
| 332 | notNull?: boolean; |
| 333 | primary?: boolean; |
| 334 | default?: unknown; |
| 335 | hasDefault?: boolean; |
| 336 | defaultFn?: unknown; |
| 337 | unique?: boolean; |
| 338 | }; // Cast to specific type to avoid TypeScript issues with dynamic column types |
| 339 | |
| 340 | // Use the actual database column name from Drizzle, not the JavaScript property name |
| 341 | const dbColumnName = col.name || columnName; |
| 342 | let columnDef = `"${dbColumnName}" ${drizzleTypeToPostgresType(col)}`; |
| 343 | |
| 344 | // Handle NOT NULL constraint |
| 345 | if (col.notNull) { |
| 346 | columnDef += " NOT NULL"; |
| 347 | } |
| 348 | |
| 349 | // Handle PRIMARY KEY constraint |
| 350 | if (col.primary) { |
| 351 | columnDef += " PRIMARY KEY"; |
no test coverage detected