@objectql/cli 1.8.1 → 1.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,328 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import chalk from 'chalk';
4
+ import * as yaml from 'js-yaml';
5
+ import { IntrospectedSchema, IntrospectedTable, IntrospectedColumn, ObjectConfig, IObjectQL, FieldConfig, FieldType } from '@objectql/types';
6
+
7
+ interface SyncOptions {
8
+ config?: string;
9
+ output?: string;
10
+ tables?: string[];
11
+ force?: boolean;
12
+ app?: IObjectQL; // Allow passing app instance directly for testing
13
+ }
14
+
15
+ /**
16
+ * Sync database schema to ObjectQL .object.yml files
17
+ * Introspects existing SQL database and generates object definitions
18
+ */
19
+ export async function syncDatabase(options: SyncOptions) {
20
+ const outputDir = path.resolve(process.cwd(), options.output || './src/objects');
21
+
22
+ console.log(chalk.blue('šŸ”„ Syncing database schema to ObjectQL...'));
23
+ console.log(chalk.gray(`Output directory: ${outputDir}\n`));
24
+
25
+ let app: IObjectQL | undefined = options.app;
26
+ const shouldClose = !options.app; // Only close if we loaded it ourselves
27
+
28
+ try {
29
+ // Load ObjectQL instance from config if not provided
30
+ if (!app) {
31
+ app = await loadObjectQLInstance(options.config);
32
+ }
33
+
34
+ // Check if driver supports introspection
35
+ const driver = app.datasource('default');
36
+ if (!driver || !driver.introspectSchema) {
37
+ const errorMsg = 'The configured driver does not support schema introspection. Only SQL drivers (PostgreSQL, MySQL, SQLite) support this feature.';
38
+ console.error(chalk.red(`āŒ ${errorMsg}`));
39
+ throw new Error(errorMsg);
40
+ }
41
+
42
+ // Introspect database schema
43
+ console.log(chalk.blue('šŸ“Š Introspecting database schema...'));
44
+ const schema: IntrospectedSchema = await driver.introspectSchema();
45
+
46
+ const tableNames = Object.keys(schema.tables);
47
+ if (tableNames.length === 0) {
48
+ console.log(chalk.yellow('⚠ No tables found in database'));
49
+ return;
50
+ }
51
+
52
+ console.log(chalk.green(`āœ“ Found ${tableNames.length} table(s)\n`));
53
+
54
+ // Filter tables if specified
55
+ let tablesToSync = tableNames;
56
+ if (options.tables && options.tables.length > 0) {
57
+ tablesToSync = tableNames.filter(t => options.tables!.includes(t));
58
+ if (tablesToSync.length === 0) {
59
+ console.log(chalk.yellow('⚠ No matching tables found'));
60
+ return;
61
+ }
62
+ }
63
+
64
+ // Create output directory if it doesn't exist
65
+ if (!fs.existsSync(outputDir)) {
66
+ fs.mkdirSync(outputDir, { recursive: true });
67
+ console.log(chalk.gray(`Created directory: ${outputDir}\n`));
68
+ }
69
+
70
+ // Generate .object.yml files
71
+ let createdCount = 0;
72
+ let skippedCount = 0;
73
+
74
+ for (const tableName of tablesToSync) {
75
+ const table = schema.tables[tableName];
76
+ const filename = `${tableName}.object.yml`;
77
+ const filePath = path.join(outputDir, filename);
78
+
79
+ // Check if file already exists
80
+ if (fs.existsSync(filePath) && !options.force) {
81
+ console.log(chalk.yellow(`⊘ ${tableName} (file exists, use --force to overwrite)`));
82
+ skippedCount++;
83
+ continue;
84
+ }
85
+
86
+ // Generate object definition
87
+ const objectDef = generateObjectDefinition(table, schema);
88
+
89
+ // Write to file
90
+ const yamlContent = yaml.dump(objectDef, {
91
+ indent: 2,
92
+ lineWidth: -1,
93
+ noRefs: true,
94
+ sortKeys: false
95
+ });
96
+
97
+ fs.writeFileSync(filePath, yamlContent, 'utf-8');
98
+
99
+ console.log(chalk.green(`āœ“ ${tableName} → ${filename}`));
100
+ createdCount++;
101
+ }
102
+
103
+ console.log(chalk.blue('\nšŸ“Š Summary:'));
104
+ console.log(chalk.gray(`Total tables: ${tablesToSync.length}`));
105
+ console.log(chalk.gray(`Created: ${createdCount}`));
106
+ console.log(chalk.gray(`Skipped: ${skippedCount}`));
107
+
108
+ if (createdCount > 0) {
109
+ console.log(chalk.green(`\nāœ… Successfully synced ${createdCount} table(s) to ${outputDir}`));
110
+ }
111
+
112
+ } catch (error: any) {
113
+ console.error(chalk.red(`āŒ Sync failed: ${error.message}`));
114
+ if (error.stack) {
115
+ console.error(chalk.gray(error.stack));
116
+ }
117
+ throw error;
118
+ } finally {
119
+ // Ensure connection is closed if we opened it
120
+ if (shouldClose && app) {
121
+ if (app.close) {
122
+ await app.close();
123
+ } else {
124
+ // Fallback for older versions if close isn't available
125
+ const driver = app.datasource('default');
126
+ if (driver && (driver as any).disconnect) {
127
+ await (driver as any).disconnect();
128
+ }
129
+ }
130
+ }
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Generate ObjectQL object definition from introspected table
136
+ */
137
+ function generateObjectDefinition(table: IntrospectedTable, schema: IntrospectedSchema): ObjectConfig {
138
+ const obj: ObjectConfig = {
139
+ name: table.name,
140
+ label: formatLabel(table.name),
141
+ fields: {}
142
+ };
143
+
144
+ // Process each column
145
+ for (const column of table.columns) {
146
+ // Skip system fields (id, created_at, updated_at) - they're automatic
147
+ if (['id', 'created_at', 'updated_at'].includes(column.name)) {
148
+ continue;
149
+ }
150
+
151
+ const field: Partial<FieldConfig> = {};
152
+
153
+ // Check if this is a foreign key
154
+ const fk = table.foreignKeys.find(fk => fk.columnName === column.name);
155
+ if (fk) {
156
+ // This is a lookup/relationship field
157
+ field.type = 'lookup';
158
+ field.reference_to = fk.referencedTable;
159
+
160
+ // Add label
161
+ field.label = formatLabel(column.name);
162
+
163
+ // Add required constraint
164
+ if (!column.nullable) {
165
+ field.required = true;
166
+ }
167
+ } else {
168
+ // Regular field - map SQL type to ObjectQL type
169
+ const fieldType = mapSqlTypeToObjectQL(column.type, column);
170
+ field.type = fieldType;
171
+
172
+ // Add label
173
+ field.label = formatLabel(column.name);
174
+
175
+ // Add constraints
176
+ if (!column.nullable) {
177
+ field.required = true;
178
+ }
179
+
180
+ if (column.isUnique) {
181
+ field.unique = true;
182
+ }
183
+
184
+ // Add max_length for text-based fields
185
+ if (column.maxLength && (fieldType === 'text' || fieldType === 'textarea')) {
186
+ field.max_length = column.maxLength;
187
+ }
188
+
189
+ if (column.defaultValue !== undefined && column.defaultValue !== null) {
190
+ // Only include simple default values
191
+ if (typeof column.defaultValue === 'string' ||
192
+ typeof column.defaultValue === 'number' ||
193
+ typeof column.defaultValue === 'boolean') {
194
+ field.defaultValue = column.defaultValue;
195
+ }
196
+ }
197
+ }
198
+
199
+ obj.fields[column.name] = field as FieldConfig;
200
+ }
201
+
202
+ return obj;
203
+ }
204
+
205
+ /**
206
+ * Map SQL native type to ObjectQL field type
207
+ */
208
+ function mapSqlTypeToObjectQL(sqlType: string, column: IntrospectedColumn): FieldType {
209
+ const type = sqlType.toLowerCase();
210
+
211
+ // Integer types - map to 'number'
212
+ if (type.includes('int') || type.includes('serial') || type.includes('bigserial')) {
213
+ return 'number';
214
+ }
215
+
216
+ // Float/Decimal types
217
+ if (type.includes('float') || type.includes('double') ||
218
+ type.includes('decimal') || type.includes('numeric') || type.includes('real')) {
219
+ return 'number';
220
+ }
221
+
222
+ // Boolean
223
+ if (type.includes('bool') || type === 'bit') {
224
+ return 'boolean';
225
+ }
226
+
227
+ // Date/Time types
228
+ if (type.includes('timestamp') || type.includes('datetime')) {
229
+ return 'datetime';
230
+ }
231
+ if (type === 'date') {
232
+ return 'date';
233
+ }
234
+ if (type === 'time') {
235
+ return 'time';
236
+ }
237
+
238
+ // Text types
239
+ if (type.includes('text') || type.includes('clob') || type.includes('long')) {
240
+ return 'textarea';
241
+ }
242
+
243
+ // JSON types - map to 'object'
244
+ if (type.includes('json') || type.includes('jsonb')) {
245
+ return 'object';
246
+ }
247
+
248
+ // Binary/Blob types
249
+ if (type.includes('blob') || type.includes('binary') || type.includes('bytea')) {
250
+ return 'file';
251
+ }
252
+
253
+ // String types (varchar, char, etc.)
254
+ // Default to 'text' for general string fields
255
+ return 'text';
256
+ }
257
+
258
+ /**
259
+ * Format table/column name to human-readable label
260
+ * e.g., "user_profile" -> "User Profile"
261
+ */
262
+ function formatLabel(name: string): string {
263
+ return name
264
+ .split('_')
265
+ .map(word => word.charAt(0).toUpperCase() + word.slice(1))
266
+ .join(' ');
267
+ }
268
+
269
+ /**
270
+ * Load ObjectQL instance from config file
271
+ */
272
+ async function loadObjectQLInstance(configPath?: string): Promise<IObjectQL> {
273
+ const cwd = process.cwd();
274
+
275
+ // Try to load from config file
276
+ let configFile = configPath;
277
+ if (!configFile) {
278
+ const potentialFiles = ['objectql.config.ts', 'objectql.config.js'];
279
+ for (const file of potentialFiles) {
280
+ if (fs.existsSync(path.join(cwd, file))) {
281
+ configFile = path.join(cwd, file);
282
+ break;
283
+ }
284
+ }
285
+ } else if (!path.isAbsolute(configFile)) {
286
+ // If configPath is provided but relative, make it absolute
287
+ configFile = path.join(cwd, configFile);
288
+ }
289
+
290
+ if (!configFile) {
291
+ throw new Error('No configuration file found (objectql.config.ts/js). Please create one with database connection.');
292
+ }
293
+
294
+ // Register ts-node for TypeScript support
295
+ if (configFile.endsWith('.ts')) {
296
+ try {
297
+ require('ts-node').register({
298
+ transpileOnly: true,
299
+ compilerOptions: {
300
+ module: 'commonjs'
301
+ }
302
+ });
303
+ } catch (err) {
304
+ throw new Error('TypeScript config file detected but ts-node is not installed. Please run: npm install --save-dev ts-node');
305
+ }
306
+ }
307
+
308
+ const configModule = require(configFile);
309
+
310
+ // Clear cache to support multiple runs in same process (e.g. tests)
311
+ try {
312
+ const resolvedPath = require.resolve(configFile);
313
+ delete require.cache[resolvedPath];
314
+ } catch (e) {
315
+ // Ignore resolution errors
316
+ }
317
+
318
+ // Support multiple export patterns: default, app, objectql, or db (in order of precedence)
319
+ const app = configModule.default || configModule.app || configModule.objectql || configModule.db;
320
+
321
+ if (!app) {
322
+ throw new Error('Config file must export an ObjectQL instance as default export or named export (app/objectql/db)');
323
+ }
324
+
325
+ // Initialize app (but don't sync schema - we're reading it)
326
+ await app.init();
327
+ return app;
328
+ }
package/src/index.ts CHANGED
@@ -8,6 +8,7 @@ import { newMetadata } from './commands/new';
8
8
  import { i18nExtract, i18nInit, i18nValidate } from './commands/i18n';
9
9
  import { migrate, migrateCreate, migrateStatus } from './commands/migrate';
10
10
  import { aiGenerate, aiValidate, aiChat, aiConversational } from './commands/ai';
11
+ import { syncDatabase } from './commands/sync';
11
12
 
12
13
  const program = new Command();
13
14
 
@@ -153,6 +154,23 @@ migrateCmd
153
154
  }
154
155
  });
155
156
 
157
+ // Sync command - Introspect database and generate .object.yml files
158
+ program
159
+ .command('sync')
160
+ .description('Sync database schema to ObjectQL object definitions')
161
+ .option('-c, --config <path>', 'Path to objectql.config.ts/js')
162
+ .option('-o, --output <path>', 'Output directory for .object.yml files', './src/objects')
163
+ .option('-t, --tables <tables...>', 'Specific tables to sync (default: all)')
164
+ .option('-f, --force', 'Overwrite existing files')
165
+ .action(async (options) => {
166
+ try {
167
+ await syncDatabase(options);
168
+ } catch (error) {
169
+ console.error(error);
170
+ process.exit(1);
171
+ }
172
+ });
173
+
156
174
  // REPL command
157
175
  program
158
176
  .command('repl')