litedbmodel-gen 0.1.0
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.
- package/README.md +204 -0
- package/dist/cli.js +172 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +33 -0
- package/dist/index.js +283 -0
- package/dist/index.js.map +1 -0
- package/package.json +57 -0
- package/templates/model.hbs +10 -0
package/README.md
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
# litedbmodel-gen
|
|
2
|
+
|
|
3
|
+
[embedoc](https://www.npmjs.com/package/embedoc)-based model code generator for [litedbmodel](https://www.npmjs.com/package/litedbmodel). Parses SQL DDL (PostgreSQL / MySQL / SQLite) and generates TypeScript column definitions that stay in sync with your schema.
|
|
4
|
+
|
|
5
|
+
## How It Works
|
|
6
|
+
|
|
7
|
+
litedbmodel-gen provides two embedoc plugins:
|
|
8
|
+
|
|
9
|
+
1. **Custom Datasource** (`sql_schema`) — reads and parses a `schema.sql` file into structured table definitions
|
|
10
|
+
2. **Renderer** (`litedbmodel_columns`) — generates `@column()` decorator code from the datasource
|
|
11
|
+
|
|
12
|
+
Using embedoc's in-place marker system, only the column definitions inside markers are auto-updated. Hand-written code (relations, custom methods, exports) outside the markers is preserved.
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
@model('users')
|
|
16
|
+
class UserModel extends DBModel {
|
|
17
|
+
/*@embedoc:litedbmodel_columns table="users"*/
|
|
18
|
+
@column({ primaryKey: true }) id?: number;
|
|
19
|
+
@column() name?: string;
|
|
20
|
+
@column() email?: string | null;
|
|
21
|
+
@column.boolean() is_active?: boolean | null;
|
|
22
|
+
@column.datetime() created_at?: Date;
|
|
23
|
+
@column.datetime() updated_at?: Date;
|
|
24
|
+
/*@embedoc:end*/
|
|
25
|
+
|
|
26
|
+
// Hand-written — not touched by embedoc
|
|
27
|
+
@hasMany(() => [User.id, Post.user_id])
|
|
28
|
+
declare posts: Promise<Post[]>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const User = UserModel.asModel();
|
|
32
|
+
export type User = InstanceType<typeof User>;
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Quick Start
|
|
36
|
+
|
|
37
|
+
### 1. Initialize embedoc in your project
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
npx embedoc init
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### 2. Install litedbmodel-gen
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
npm install -D litedbmodel-gen
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### 3. Run the init command
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
npx litedbmodel-gen init
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
This automatically:
|
|
56
|
+
- Copies the Handlebars template to `.embedoc/templates/model.hbs`
|
|
57
|
+
- Registers the `sql_schema` datasource in `.embedoc/datasources/index.ts`
|
|
58
|
+
- Registers the `litedbmodel_columns` renderer in `.embedoc/renderers/index.ts`
|
|
59
|
+
- Adds a `schema` datasource config to `embedoc.config.yaml`
|
|
60
|
+
- Adds `./models/**/*.ts` to the build targets
|
|
61
|
+
|
|
62
|
+
If your config file is not at the default `embedoc.config.yaml`:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
npx litedbmodel-gen init path/to/embedoc.config.yaml
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### 4. Edit the config
|
|
69
|
+
|
|
70
|
+
Open `embedoc.config.yaml` and set the schema path and database dialect:
|
|
71
|
+
|
|
72
|
+
```yaml
|
|
73
|
+
datasources:
|
|
74
|
+
schema:
|
|
75
|
+
type: sql_schema
|
|
76
|
+
path: "./db/schema.sql" # your DDL file
|
|
77
|
+
database: PostgreSQL # PostgreSQL | MySQL | SQLite
|
|
78
|
+
generators:
|
|
79
|
+
- output_path: "./models/{model_class}.ts"
|
|
80
|
+
template: model.hbs
|
|
81
|
+
overwrite: false
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### 5. Generate and build
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
# Create model files for each table
|
|
88
|
+
npx embedoc generate --datasource schema
|
|
89
|
+
|
|
90
|
+
# Fill in column definitions
|
|
91
|
+
npx embedoc build
|
|
92
|
+
|
|
93
|
+
# Or use watch mode for ongoing sync
|
|
94
|
+
npx embedoc watch
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Workflow
|
|
98
|
+
|
|
99
|
+
```
|
|
100
|
+
schema.sql changes
|
|
101
|
+
|
|
|
102
|
+
v
|
|
103
|
+
embedoc build / watch
|
|
104
|
+
|
|
|
105
|
+
+-- existing models/*.ts
|
|
106
|
+
| column definitions inside markers are updated
|
|
107
|
+
| relations and exports are preserved
|
|
108
|
+
|
|
|
109
|
+
+-- new tables
|
|
110
|
+
embedoc generate --datasource schema
|
|
111
|
+
creates new model files from template
|
|
112
|
+
embedoc build fills in column definitions
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Supported SQL Types
|
|
116
|
+
|
|
117
|
+
### Common (all dialects)
|
|
118
|
+
|
|
119
|
+
| SQL Type | Decorator | TypeScript Type |
|
|
120
|
+
|----------|-----------|-----------------|
|
|
121
|
+
| `INTEGER`, `INT`, `SMALLINT`, `SERIAL` | `@column()` | `number` |
|
|
122
|
+
| `BIGINT`, `BIGSERIAL` | `@column.bigint()` | `bigint` |
|
|
123
|
+
| `NUMERIC`, `DECIMAL`, `REAL`, `FLOAT`, `DOUBLE PRECISION` | `@column()` | `number` |
|
|
124
|
+
| `VARCHAR`, `TEXT`, `CHAR` | `@column()` | `string` |
|
|
125
|
+
| `BOOLEAN` | `@column.boolean()` | `boolean` |
|
|
126
|
+
| `TIMESTAMP`, `TIMESTAMPTZ`, `DATETIME` | `@column.datetime()` | `Date` |
|
|
127
|
+
| `DATE` | `@column.date()` | `Date` |
|
|
128
|
+
| `JSON`, `JSONB` | `@column.json<Record<string, unknown>>()` | `Record<string, unknown>` |
|
|
129
|
+
| `UUID` | `@column.uuid()` | `string` |
|
|
130
|
+
|
|
131
|
+
### PostgreSQL Arrays
|
|
132
|
+
|
|
133
|
+
| SQL Type | Decorator | TypeScript Type |
|
|
134
|
+
|----------|-----------|-----------------|
|
|
135
|
+
| `TEXT[]` | `@column.stringArray()` | `string[]` |
|
|
136
|
+
| `INTEGER[]` | `@column.intArray()` | `number[]` |
|
|
137
|
+
| `NUMERIC[]` | `@column.numericArray()` | `(number \| null)[]` |
|
|
138
|
+
| `BOOLEAN[]` | `@column.booleanArray()` | `(boolean \| null)[]` |
|
|
139
|
+
| `TIMESTAMP[]` | `@column.datetimeArray()` | `(Date \| null)[]` |
|
|
140
|
+
|
|
141
|
+
### MySQL-specific
|
|
142
|
+
|
|
143
|
+
| SQL Type | Decorator | TypeScript Type |
|
|
144
|
+
|----------|-----------|-----------------|
|
|
145
|
+
| `TINYINT(1)` | `@column.boolean()` | `boolean` |
|
|
146
|
+
|
|
147
|
+
### Primary Keys
|
|
148
|
+
|
|
149
|
+
Columns with `PRIMARY KEY` constraints use `@column({ primaryKey: true })`. For UUID primary keys: `@column.uuid({ primaryKey: true })`. Composite primary keys are supported.
|
|
150
|
+
|
|
151
|
+
## Marker Syntax
|
|
152
|
+
|
|
153
|
+
Inside your model class:
|
|
154
|
+
|
|
155
|
+
```typescript
|
|
156
|
+
/*@embedoc:litedbmodel_columns table="TABLE_NAME"*/
|
|
157
|
+
// auto-generated column definitions
|
|
158
|
+
/*@embedoc:end*/
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
If your datasource is not named `schema`, specify it:
|
|
162
|
+
|
|
163
|
+
```typescript
|
|
164
|
+
/*@embedoc:litedbmodel_columns table="users" datasource="my_schema"*/
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## CLI
|
|
168
|
+
|
|
169
|
+
```bash
|
|
170
|
+
# Initialize litedbmodel-gen in an embedoc project
|
|
171
|
+
npx litedbmodel-gen init [config-path]
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
## API
|
|
175
|
+
|
|
176
|
+
The package also exports lower-level utilities:
|
|
177
|
+
|
|
178
|
+
```typescript
|
|
179
|
+
import {
|
|
180
|
+
sqlSchema, // embedoc custom datasource
|
|
181
|
+
litedbmodelColumns, // embedoc renderer
|
|
182
|
+
parseSchema, // SQL DDL parser
|
|
183
|
+
generateColumnCode, // code generator
|
|
184
|
+
mapColumnType, // single column type mapper
|
|
185
|
+
} from 'litedbmodel-gen';
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
### `parseSchema(sql, options?)`
|
|
189
|
+
|
|
190
|
+
Parses SQL DDL and returns table definitions.
|
|
191
|
+
|
|
192
|
+
```typescript
|
|
193
|
+
const tables = parseSchema(sql, { database: 'PostgreSQL' });
|
|
194
|
+
// Returns: TableDef[] = [{ name: string, columns: ColumnDef[] }]
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
## Requirements
|
|
198
|
+
|
|
199
|
+
- Node.js 18+
|
|
200
|
+
- embedoc >= 0.11.0
|
|
201
|
+
|
|
202
|
+
## License
|
|
203
|
+
|
|
204
|
+
MIT
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { Command } from "commander";
|
|
5
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync, copyFileSync } from "fs";
|
|
6
|
+
import { resolve, dirname, join } from "path";
|
|
7
|
+
import { fileURLToPath } from "url";
|
|
8
|
+
import yaml from "js-yaml";
|
|
9
|
+
var __filename = fileURLToPath(import.meta.url);
|
|
10
|
+
var __dirname = dirname(__filename);
|
|
11
|
+
function resolveEmbedocDirs(configPath) {
|
|
12
|
+
const configDir = dirname(configPath);
|
|
13
|
+
const raw = readFileSync(configPath, "utf-8");
|
|
14
|
+
const config = yaml.load(raw) ?? {};
|
|
15
|
+
const renderersDir = resolve(
|
|
16
|
+
configDir,
|
|
17
|
+
config["renderers_dir"] ?? ".embedoc/renderers"
|
|
18
|
+
);
|
|
19
|
+
const datasourcesDir = resolve(
|
|
20
|
+
configDir,
|
|
21
|
+
config["datasources_dir"] ?? ".embedoc/datasources"
|
|
22
|
+
);
|
|
23
|
+
const templatesDir = resolve(
|
|
24
|
+
configDir,
|
|
25
|
+
config["templates_dir"] ?? ".embedoc/templates"
|
|
26
|
+
);
|
|
27
|
+
return { renderersDir, datasourcesDir, templatesDir };
|
|
28
|
+
}
|
|
29
|
+
var program = new Command();
|
|
30
|
+
program.name("litedbmodel-gen").description("embedoc-based model code generator for litedbmodel").version("0.1.0");
|
|
31
|
+
program.command("init").description("Set up litedbmodel-gen in an embedoc project").argument("[config]", "path to embedoc.config.yaml", "embedoc.config.yaml").action((configPath) => {
|
|
32
|
+
const absConfigPath = resolve(configPath);
|
|
33
|
+
if (!existsSync(absConfigPath)) {
|
|
34
|
+
console.error(`Error: ${configPath} not found. Run "npx embedoc init" first.`);
|
|
35
|
+
process.exit(1);
|
|
36
|
+
}
|
|
37
|
+
const dirs = resolveEmbedocDirs(absConfigPath);
|
|
38
|
+
console.log("Setting up litedbmodel-gen...\n");
|
|
39
|
+
copyTemplate(dirs.templatesDir);
|
|
40
|
+
updateRenderersIndex(dirs.renderersDir);
|
|
41
|
+
updateDatasourcesIndex(dirs.datasourcesDir);
|
|
42
|
+
updateConfig(absConfigPath);
|
|
43
|
+
console.log("\nDone! Next steps:");
|
|
44
|
+
console.log(" 1. Edit embedoc.config.yaml \u2014 set path/database in the schema datasource");
|
|
45
|
+
console.log(" 2. npx embedoc generate --datasource schema (create model files)");
|
|
46
|
+
console.log(" 3. npx embedoc build (fill in column definitions)");
|
|
47
|
+
});
|
|
48
|
+
function copyTemplate(templatesDir) {
|
|
49
|
+
mkdirSync(templatesDir, { recursive: true });
|
|
50
|
+
const destPath = join(templatesDir, "model.hbs");
|
|
51
|
+
if (existsSync(destPath)) {
|
|
52
|
+
console.log(` skip ${destPath} (already exists)`);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const srcPath = resolvePackageTemplate();
|
|
56
|
+
copyFileSync(srcPath, destPath);
|
|
57
|
+
console.log(` create ${destPath}`);
|
|
58
|
+
}
|
|
59
|
+
function resolvePackageTemplate() {
|
|
60
|
+
const candidates = [
|
|
61
|
+
resolve(__dirname, "..", "templates", "model.hbs"),
|
|
62
|
+
resolve(__dirname, "templates", "model.hbs")
|
|
63
|
+
];
|
|
64
|
+
for (const p of candidates) {
|
|
65
|
+
if (existsSync(p)) return p;
|
|
66
|
+
}
|
|
67
|
+
throw new Error("Could not find model.hbs template in package");
|
|
68
|
+
}
|
|
69
|
+
function updateRenderersIndex(renderersDir) {
|
|
70
|
+
const filePath = join(renderersDir, "index.ts");
|
|
71
|
+
if (!existsSync(filePath)) {
|
|
72
|
+
console.error(` warn ${filePath} not found, skipping renderers setup`);
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
let content = readFileSync(filePath, "utf-8");
|
|
76
|
+
if (content.includes("litedbmodel-gen")) {
|
|
77
|
+
console.log(` skip ${filePath} (already configured)`);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const importLine = "import { litedbmodelColumns } from 'litedbmodel-gen';";
|
|
81
|
+
const entry = ` litedbmodel_columns: {
|
|
82
|
+
...litedbmodelColumns,
|
|
83
|
+
dependsOn: ['schema'],
|
|
84
|
+
},`;
|
|
85
|
+
if (content.includes("import ")) {
|
|
86
|
+
const lastImportIdx = content.lastIndexOf("import ");
|
|
87
|
+
const lineEnd = content.indexOf("\n", lastImportIdx);
|
|
88
|
+
content = content.slice(0, lineEnd + 1) + importLine + "\n" + content.slice(lineEnd + 1);
|
|
89
|
+
} else {
|
|
90
|
+
content = importLine + "\n\n" + content;
|
|
91
|
+
}
|
|
92
|
+
content = insertIntoObject(content, "embeds", entry);
|
|
93
|
+
writeFileSync(filePath, content, "utf-8");
|
|
94
|
+
console.log(` update ${filePath}`);
|
|
95
|
+
}
|
|
96
|
+
function updateDatasourcesIndex(datasourcesDir) {
|
|
97
|
+
const filePath = join(datasourcesDir, "index.ts");
|
|
98
|
+
if (!existsSync(filePath)) {
|
|
99
|
+
console.error(` warn ${filePath} not found, skipping datasources setup`);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
let content = readFileSync(filePath, "utf-8");
|
|
103
|
+
if (content.includes("litedbmodel-gen")) {
|
|
104
|
+
console.log(` skip ${filePath} (already configured)`);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
const importLine = "import { sqlSchema } from 'litedbmodel-gen';";
|
|
108
|
+
const entry = " sql_schema: sqlSchema,";
|
|
109
|
+
if (content.includes("import ")) {
|
|
110
|
+
const lastImportIdx = content.lastIndexOf("import ");
|
|
111
|
+
const lineEnd = content.indexOf("\n", lastImportIdx);
|
|
112
|
+
content = content.slice(0, lineEnd + 1) + importLine + "\n" + content.slice(lineEnd + 1);
|
|
113
|
+
} else {
|
|
114
|
+
content = importLine + "\n\n" + content;
|
|
115
|
+
}
|
|
116
|
+
content = insertIntoObject(content, "datasourceTypes", entry);
|
|
117
|
+
writeFileSync(filePath, content, "utf-8");
|
|
118
|
+
console.log(` update ${filePath}`);
|
|
119
|
+
}
|
|
120
|
+
function insertIntoObject(source, objectName, entry) {
|
|
121
|
+
const pattern = new RegExp(`(export\\s+const\\s+${objectName}\\s*=\\s*\\{)([^}]*)(\\})`);
|
|
122
|
+
const match = source.match(pattern);
|
|
123
|
+
if (!match) return source;
|
|
124
|
+
const [, opening, body, closing] = match;
|
|
125
|
+
const trimmedBody = body.replace(/\s+/g, " ").trim();
|
|
126
|
+
let newBody;
|
|
127
|
+
if (trimmedBody === "" || trimmedBody.startsWith("//")) {
|
|
128
|
+
newBody = `
|
|
129
|
+
${entry}
|
|
130
|
+
`;
|
|
131
|
+
} else {
|
|
132
|
+
newBody = body.trimEnd() + "\n" + entry + "\n";
|
|
133
|
+
}
|
|
134
|
+
return source.replace(pattern, `${opening}${newBody}${closing}`);
|
|
135
|
+
}
|
|
136
|
+
function updateConfig(configPath) {
|
|
137
|
+
let content = readFileSync(configPath, "utf-8");
|
|
138
|
+
if (content.includes("sql_schema")) {
|
|
139
|
+
console.log(" skip embedoc.config.yaml (sql_schema already configured)");
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
const datasourceBlock = ` schema:
|
|
143
|
+
type: sql_schema
|
|
144
|
+
path: "./db/schema.sql"
|
|
145
|
+
database: PostgreSQL
|
|
146
|
+
generators:
|
|
147
|
+
- output_path: "./models/{model_class}.ts"
|
|
148
|
+
template: model.hbs
|
|
149
|
+
overwrite: false`;
|
|
150
|
+
if (content.includes("datasources: {}")) {
|
|
151
|
+
content = content.replace("datasources: {}", "datasources:\n" + datasourceBlock);
|
|
152
|
+
} else if (content.includes("datasources:")) {
|
|
153
|
+
const idx = content.indexOf("datasources:");
|
|
154
|
+
const lineEnd = content.indexOf("\n", idx);
|
|
155
|
+
content = content.slice(0, lineEnd + 1) + datasourceBlock + "\n" + content.slice(lineEnd + 1);
|
|
156
|
+
} else {
|
|
157
|
+
content += "\ndatasources:\n" + datasourceBlock + "\n";
|
|
158
|
+
}
|
|
159
|
+
if (!content.includes("models/**/*.ts")) {
|
|
160
|
+
const targetsInsert = ` - pattern: "./models/**/*.ts"
|
|
161
|
+
comment_style: block`;
|
|
162
|
+
if (content.includes("targets:")) {
|
|
163
|
+
const idx = content.indexOf("targets:");
|
|
164
|
+
const lineEnd = content.indexOf("\n", idx);
|
|
165
|
+
content = content.slice(0, lineEnd + 1) + targetsInsert + "\n" + content.slice(lineEnd + 1);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
writeFileSync(configPath, content, "utf-8");
|
|
169
|
+
console.log(" update embedoc.config.yaml");
|
|
170
|
+
}
|
|
171
|
+
program.parse();
|
|
172
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { readFileSync, writeFileSync, existsSync, mkdirSync, copyFileSync } from 'fs';\nimport { resolve, dirname, join } from 'path';\nimport { fileURLToPath } from 'url';\nimport yaml from 'js-yaml';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\ninterface EmbedocDirs {\n renderersDir: string;\n datasourcesDir: string;\n templatesDir: string;\n}\n\nfunction resolveEmbedocDirs(configPath: string): EmbedocDirs {\n const configDir = dirname(configPath);\n const raw = readFileSync(configPath, 'utf-8');\n const config = (yaml.load(raw) ?? {}) as Record<string, unknown>;\n\n const renderersDir = resolve(\n configDir,\n (config['renderers_dir'] as string) ?? '.embedoc/renderers',\n );\n const datasourcesDir = resolve(\n configDir,\n (config['datasources_dir'] as string) ?? '.embedoc/datasources',\n );\n const templatesDir = resolve(\n configDir,\n (config['templates_dir'] as string) ?? '.embedoc/templates',\n );\n\n return { renderersDir, datasourcesDir, templatesDir };\n}\n\nconst program = new Command();\n\nprogram\n .name('litedbmodel-gen')\n .description('embedoc-based model code generator for litedbmodel')\n .version('0.1.0');\n\nprogram\n .command('init')\n .description('Set up litedbmodel-gen in an embedoc project')\n .argument('[config]', 'path to embedoc.config.yaml', 'embedoc.config.yaml')\n .action((configPath: string) => {\n const absConfigPath = resolve(configPath);\n if (!existsSync(absConfigPath)) {\n console.error(`Error: ${configPath} not found. Run \"npx embedoc init\" first.`);\n process.exit(1);\n }\n\n const dirs = resolveEmbedocDirs(absConfigPath);\n\n console.log('Setting up litedbmodel-gen...\\n');\n\n copyTemplate(dirs.templatesDir);\n updateRenderersIndex(dirs.renderersDir);\n updateDatasourcesIndex(dirs.datasourcesDir);\n updateConfig(absConfigPath);\n\n console.log('\\nDone! Next steps:');\n console.log(' 1. Edit embedoc.config.yaml — set path/database in the schema datasource');\n console.log(' 2. npx embedoc generate --datasource schema (create model files)');\n console.log(' 3. npx embedoc build (fill in column definitions)');\n });\n\nfunction copyTemplate(templatesDir: string): void {\n mkdirSync(templatesDir, { recursive: true });\n\n const destPath = join(templatesDir, 'model.hbs');\n if (existsSync(destPath)) {\n console.log(` skip ${destPath} (already exists)`);\n return;\n }\n\n const srcPath = resolvePackageTemplate();\n copyFileSync(srcPath, destPath);\n console.log(` create ${destPath}`);\n}\n\nfunction resolvePackageTemplate(): string {\n const candidates = [\n resolve(__dirname, '..', 'templates', 'model.hbs'),\n resolve(__dirname, 'templates', 'model.hbs'),\n ];\n for (const p of candidates) {\n if (existsSync(p)) return p;\n }\n throw new Error('Could not find model.hbs template in package');\n}\n\nfunction updateRenderersIndex(renderersDir: string): void {\n const filePath = join(renderersDir, 'index.ts');\n if (!existsSync(filePath)) {\n console.error(` warn ${filePath} not found, skipping renderers setup`);\n return;\n }\n\n let content = readFileSync(filePath, 'utf-8');\n if (content.includes('litedbmodel-gen')) {\n console.log(` skip ${filePath} (already configured)`);\n return;\n }\n\n const importLine = \"import { litedbmodelColumns } from 'litedbmodel-gen';\";\n\n const entry = ` litedbmodel_columns: {\n ...litedbmodelColumns,\n dependsOn: ['schema'],\n },`;\n\n if (content.includes('import ')) {\n const lastImportIdx = content.lastIndexOf('import ');\n const lineEnd = content.indexOf('\\n', lastImportIdx);\n content = content.slice(0, lineEnd + 1) + importLine + '\\n' + content.slice(lineEnd + 1);\n } else {\n content = importLine + '\\n\\n' + content;\n }\n\n content = insertIntoObject(content, 'embeds', entry);\n\n writeFileSync(filePath, content, 'utf-8');\n console.log(` update ${filePath}`);\n}\n\nfunction updateDatasourcesIndex(datasourcesDir: string): void {\n const filePath = join(datasourcesDir, 'index.ts');\n if (!existsSync(filePath)) {\n console.error(` warn ${filePath} not found, skipping datasources setup`);\n return;\n }\n\n let content = readFileSync(filePath, 'utf-8');\n if (content.includes('litedbmodel-gen')) {\n console.log(` skip ${filePath} (already configured)`);\n return;\n }\n\n const importLine = \"import { sqlSchema } from 'litedbmodel-gen';\";\n\n const entry = ' sql_schema: sqlSchema,';\n\n if (content.includes('import ')) {\n const lastImportIdx = content.lastIndexOf('import ');\n const lineEnd = content.indexOf('\\n', lastImportIdx);\n content = content.slice(0, lineEnd + 1) + importLine + '\\n' + content.slice(lineEnd + 1);\n } else {\n content = importLine + '\\n\\n' + content;\n }\n\n content = insertIntoObject(content, 'datasourceTypes', entry);\n\n writeFileSync(filePath, content, 'utf-8');\n console.log(` update ${filePath}`);\n}\n\nfunction insertIntoObject(source: string, objectName: string, entry: string): string {\n const pattern = new RegExp(`(export\\\\s+const\\\\s+${objectName}\\\\s*=\\\\s*\\\\{)([^}]*)(\\\\})`);\n const match = source.match(pattern);\n if (!match) return source;\n\n const [, opening, body, closing] = match;\n const trimmedBody = body.replace(/\\s+/g, ' ').trim();\n\n let newBody: string;\n if (trimmedBody === '' || trimmedBody.startsWith('//')) {\n newBody = `\\n${entry}\\n`;\n } else {\n newBody = body.trimEnd() + '\\n' + entry + '\\n';\n }\n\n return source.replace(pattern, `${opening}${newBody}${closing}`);\n}\n\nfunction updateConfig(configPath: string): void {\n let content = readFileSync(configPath, 'utf-8');\n\n if (content.includes('sql_schema')) {\n console.log(' skip embedoc.config.yaml (sql_schema already configured)');\n return;\n }\n\n const datasourceBlock = ` schema:\n type: sql_schema\n path: \"./db/schema.sql\"\n database: PostgreSQL\n generators:\n - output_path: \"./models/{model_class}.ts\"\n template: model.hbs\n overwrite: false`;\n\n if (content.includes('datasources: {}')) {\n content = content.replace('datasources: {}', 'datasources:\\n' + datasourceBlock);\n } else if (content.includes('datasources:')) {\n const idx = content.indexOf('datasources:');\n const lineEnd = content.indexOf('\\n', idx);\n content = content.slice(0, lineEnd + 1) + datasourceBlock + '\\n' + content.slice(lineEnd + 1);\n } else {\n content += '\\ndatasources:\\n' + datasourceBlock + '\\n';\n }\n\n if (!content.includes('models/**/*.ts')) {\n const targetsInsert = ` - pattern: \"./models/**/*.ts\"\n comment_style: block`;\n\n if (content.includes('targets:')) {\n const idx = content.indexOf('targets:');\n const lineEnd = content.indexOf('\\n', idx);\n content = content.slice(0, lineEnd + 1) + targetsInsert + '\\n' + content.slice(lineEnd + 1);\n }\n }\n\n writeFileSync(configPath, content, 'utf-8');\n console.log(' update embedoc.config.yaml');\n}\n\nprogram.parse();\n"],"mappings":";;;AAAA,SAAS,eAAe;AACxB,SAAS,cAAc,eAAe,YAAY,WAAW,oBAAoB;AACjF,SAAS,SAAS,SAAS,YAAY;AACvC,SAAS,qBAAqB;AAC9B,OAAO,UAAU;AAEjB,IAAM,aAAa,cAAc,YAAY,GAAG;AAChD,IAAM,YAAY,QAAQ,UAAU;AAQpC,SAAS,mBAAmB,YAAiC;AAC3D,QAAM,YAAY,QAAQ,UAAU;AACpC,QAAM,MAAM,aAAa,YAAY,OAAO;AAC5C,QAAM,SAAU,KAAK,KAAK,GAAG,KAAK,CAAC;AAEnC,QAAM,eAAe;AAAA,IACnB;AAAA,IACC,OAAO,eAAe,KAAgB;AAAA,EACzC;AACA,QAAM,iBAAiB;AAAA,IACrB;AAAA,IACC,OAAO,iBAAiB,KAAgB;AAAA,EAC3C;AACA,QAAM,eAAe;AAAA,IACnB;AAAA,IACC,OAAO,eAAe,KAAgB;AAAA,EACzC;AAEA,SAAO,EAAE,cAAc,gBAAgB,aAAa;AACtD;AAEA,IAAM,UAAU,IAAI,QAAQ;AAE5B,QACG,KAAK,iBAAiB,EACtB,YAAY,oDAAoD,EAChE,QAAQ,OAAO;AAElB,QACG,QAAQ,MAAM,EACd,YAAY,8CAA8C,EAC1D,SAAS,YAAY,+BAA+B,qBAAqB,EACzE,OAAO,CAAC,eAAuB;AAC9B,QAAM,gBAAgB,QAAQ,UAAU;AACxC,MAAI,CAAC,WAAW,aAAa,GAAG;AAC9B,YAAQ,MAAM,UAAU,UAAU,2CAA2C;AAC7E,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,QAAM,OAAO,mBAAmB,aAAa;AAE7C,UAAQ,IAAI,iCAAiC;AAE7C,eAAa,KAAK,YAAY;AAC9B,uBAAqB,KAAK,YAAY;AACtC,yBAA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
+
import * as embedoc from 'embedoc';
|
|
2
|
+
|
|
3
|
+
declare const sqlSchema: embedoc.CustomDatasourceDefinition;
|
|
4
|
+
|
|
5
|
+
declare const litedbmodelColumns: embedoc.EmbedDefinition;
|
|
6
|
+
|
|
7
|
+
type DatabaseDialect = 'PostgreSQL' | 'MySQL' | 'SQLite';
|
|
8
|
+
interface TableDef {
|
|
9
|
+
name: string;
|
|
10
|
+
columns: ColumnDef[];
|
|
11
|
+
}
|
|
12
|
+
interface ColumnDef {
|
|
13
|
+
name: string;
|
|
14
|
+
sqlType: string;
|
|
15
|
+
isPrimaryKey: boolean;
|
|
16
|
+
isNullable: boolean;
|
|
17
|
+
isArray: boolean;
|
|
18
|
+
}
|
|
19
|
+
interface ColumnMapping {
|
|
20
|
+
decorator: string;
|
|
21
|
+
tsType: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface ParseSchemaOptions {
|
|
25
|
+
database?: DatabaseDialect;
|
|
26
|
+
}
|
|
27
|
+
declare function parseSchema(sql: string, options?: ParseSchemaOptions): TableDef[];
|
|
28
|
+
|
|
29
|
+
declare function generateColumnCode(table: TableDef): string;
|
|
30
|
+
|
|
31
|
+
declare function mapColumnType(col: ColumnDef): ColumnMapping;
|
|
32
|
+
|
|
33
|
+
export { type ColumnDef, type ColumnMapping, type DatabaseDialect, type TableDef, generateColumnCode, litedbmodelColumns, mapColumnType, parseSchema, sqlSchema };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
// src/datasource.ts
|
|
2
|
+
import { defineDatasource } from "embedoc";
|
|
3
|
+
import { readFileSync } from "fs";
|
|
4
|
+
|
|
5
|
+
// src/parser.ts
|
|
6
|
+
import { Parser } from "node-sql-parser";
|
|
7
|
+
function parseSchema(sql, options) {
|
|
8
|
+
const database = options?.database || "PostgreSQL";
|
|
9
|
+
const parser = new Parser();
|
|
10
|
+
let statements;
|
|
11
|
+
try {
|
|
12
|
+
const result = parser.astify(sql, { database });
|
|
13
|
+
statements = Array.isArray(result) ? result : [result];
|
|
14
|
+
} catch {
|
|
15
|
+
return [];
|
|
16
|
+
}
|
|
17
|
+
const tables = [];
|
|
18
|
+
for (const stmt of statements) {
|
|
19
|
+
const s = stmt;
|
|
20
|
+
if (s["type"] !== "create" || s["keyword"] !== "table") continue;
|
|
21
|
+
const tableName = extractTableName(s);
|
|
22
|
+
if (!tableName) continue;
|
|
23
|
+
const createDefs = s["create_definitions"];
|
|
24
|
+
if (!createDefs) continue;
|
|
25
|
+
const pkColumns = extractTableLevelPrimaryKeys(createDefs);
|
|
26
|
+
const columns = extractColumns(createDefs, pkColumns, database);
|
|
27
|
+
tables.push({ name: tableName, columns });
|
|
28
|
+
}
|
|
29
|
+
return tables;
|
|
30
|
+
}
|
|
31
|
+
function extractTableName(stmt) {
|
|
32
|
+
const table = stmt["table"];
|
|
33
|
+
if (!table) return null;
|
|
34
|
+
if (Array.isArray(table)) {
|
|
35
|
+
const first = table[0];
|
|
36
|
+
return first?.["table"] ?? null;
|
|
37
|
+
}
|
|
38
|
+
return table["table"] ?? null;
|
|
39
|
+
}
|
|
40
|
+
function extractTableLevelPrimaryKeys(defs) {
|
|
41
|
+
const pkColumns = /* @__PURE__ */ new Set();
|
|
42
|
+
for (const def of defs) {
|
|
43
|
+
const d = def;
|
|
44
|
+
if (d["resource"] !== "constraint") continue;
|
|
45
|
+
const constraintType = String(d["constraint_type"] || "").toLowerCase();
|
|
46
|
+
if (constraintType !== "primary key") continue;
|
|
47
|
+
const definition = d["definition"];
|
|
48
|
+
if (!definition) continue;
|
|
49
|
+
for (const col of definition) {
|
|
50
|
+
const c = col;
|
|
51
|
+
const colName = extractColumnName(c);
|
|
52
|
+
if (colName) pkColumns.add(colName);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return pkColumns;
|
|
56
|
+
}
|
|
57
|
+
function extractColumnName(ref) {
|
|
58
|
+
const col = ref["column"];
|
|
59
|
+
if (typeof col === "string") return col;
|
|
60
|
+
if (col && typeof col === "object") {
|
|
61
|
+
return col["expr"] ? String(col["expr"]["value"]) : null;
|
|
62
|
+
}
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
function extractColumns(defs, pkColumns, database) {
|
|
66
|
+
const columns = [];
|
|
67
|
+
for (const def of defs) {
|
|
68
|
+
const d = def;
|
|
69
|
+
if (d["resource"] !== "column") continue;
|
|
70
|
+
const colRef = d["column"];
|
|
71
|
+
const name = extractColumnName(colRef);
|
|
72
|
+
if (!name) continue;
|
|
73
|
+
const definition = d["definition"];
|
|
74
|
+
const rawDataType = String(definition?.["dataType"] || "").toUpperCase();
|
|
75
|
+
const length = definition?.["length"];
|
|
76
|
+
const arrayObj = definition?.["array"];
|
|
77
|
+
const isArrayFromSuffix = rawDataType.endsWith("[]");
|
|
78
|
+
const isArrayFromProp = !!arrayObj;
|
|
79
|
+
const isArray = isArrayFromSuffix || isArrayFromProp;
|
|
80
|
+
const dataType = isArrayFromSuffix ? rawDataType.slice(0, -2) : rawDataType;
|
|
81
|
+
const sqlType = normalizeSqlType(dataType, length, isArray, database);
|
|
82
|
+
const isPrimaryKey = pkColumns.has(name) || d["primary_key"] === "primary key" || d["primary"] === "key" || d["primary"] === "primary key";
|
|
83
|
+
const nullable = d["nullable"];
|
|
84
|
+
const isNullable = isPrimaryKey ? false : nullable?.["type"] !== "not null";
|
|
85
|
+
columns.push({ name, sqlType, isPrimaryKey, isNullable, isArray });
|
|
86
|
+
}
|
|
87
|
+
return columns;
|
|
88
|
+
}
|
|
89
|
+
function normalizeSqlType(dataType, length, isArray, database) {
|
|
90
|
+
let base = dataType.toLowerCase();
|
|
91
|
+
if (database === "MySQL" && base === "tinyint" && length === 1) {
|
|
92
|
+
base = "boolean";
|
|
93
|
+
}
|
|
94
|
+
if (isArray) {
|
|
95
|
+
return `${base}[]`;
|
|
96
|
+
}
|
|
97
|
+
return base;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// src/datasource.ts
|
|
101
|
+
function toPascalCase(snakeCase) {
|
|
102
|
+
return snakeCase.split("_").map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join("");
|
|
103
|
+
}
|
|
104
|
+
function singularize(name) {
|
|
105
|
+
if (name.endsWith("ies")) return name.slice(0, -3) + "y";
|
|
106
|
+
if (name.endsWith("ses") || name.endsWith("xes") || name.endsWith("zes")) return name.slice(0, -2);
|
|
107
|
+
if (name.endsWith("s") && !name.endsWith("ss")) return name.slice(0, -1);
|
|
108
|
+
return name;
|
|
109
|
+
}
|
|
110
|
+
var sqlSchema = defineDatasource({
|
|
111
|
+
async create(config) {
|
|
112
|
+
const filePath = config["path"];
|
|
113
|
+
const database = config["database"] || "PostgreSQL";
|
|
114
|
+
const sql = readFileSync(filePath, "utf-8");
|
|
115
|
+
const tables = parseSchema(sql, { database });
|
|
116
|
+
const records = tables.map((t) => ({
|
|
117
|
+
table_name: t.name,
|
|
118
|
+
model_class: toPascalCase(singularize(t.name)),
|
|
119
|
+
columns: t.columns
|
|
120
|
+
}));
|
|
121
|
+
return {
|
|
122
|
+
type: "sql_schema",
|
|
123
|
+
async query(_sql, params) {
|
|
124
|
+
if (params?.[0]) {
|
|
125
|
+
return records.filter((r) => r.table_name === params[0]);
|
|
126
|
+
}
|
|
127
|
+
return records;
|
|
128
|
+
},
|
|
129
|
+
async getAll() {
|
|
130
|
+
return records;
|
|
131
|
+
},
|
|
132
|
+
async close() {
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
// src/renderer.ts
|
|
139
|
+
import { defineEmbed } from "embedoc";
|
|
140
|
+
|
|
141
|
+
// src/type-mapper.ts
|
|
142
|
+
var TYPE_MAP = {
|
|
143
|
+
// Integer types
|
|
144
|
+
"int": { decorator: "@column()", tsType: "number" },
|
|
145
|
+
"int2": { decorator: "@column()", tsType: "number" },
|
|
146
|
+
"int4": { decorator: "@column()", tsType: "number" },
|
|
147
|
+
"int8": { decorator: "@column.bigint()", tsType: "bigint" },
|
|
148
|
+
"integer": { decorator: "@column()", tsType: "number" },
|
|
149
|
+
"smallint": { decorator: "@column()", tsType: "number" },
|
|
150
|
+
"mediumint": { decorator: "@column()", tsType: "number" },
|
|
151
|
+
"bigint": { decorator: "@column.bigint()", tsType: "bigint" },
|
|
152
|
+
"serial": { decorator: "@column()", tsType: "number" },
|
|
153
|
+
"bigserial": { decorator: "@column.bigint()", tsType: "bigint" },
|
|
154
|
+
"smallserial": { decorator: "@column()", tsType: "number" },
|
|
155
|
+
// Floating point / numeric
|
|
156
|
+
"numeric": { decorator: "@column()", tsType: "number" },
|
|
157
|
+
"decimal": { decorator: "@column()", tsType: "number" },
|
|
158
|
+
"real": { decorator: "@column()", tsType: "number" },
|
|
159
|
+
"float": { decorator: "@column()", tsType: "number" },
|
|
160
|
+
"float4": { decorator: "@column()", tsType: "number" },
|
|
161
|
+
"float8": { decorator: "@column()", tsType: "number" },
|
|
162
|
+
"double": { decorator: "@column()", tsType: "number" },
|
|
163
|
+
"double precision": { decorator: "@column()", tsType: "number" },
|
|
164
|
+
"money": { decorator: "@column()", tsType: "number" },
|
|
165
|
+
// String types
|
|
166
|
+
"varchar": { decorator: "@column()", tsType: "string" },
|
|
167
|
+
"character varying": { decorator: "@column()", tsType: "string" },
|
|
168
|
+
"char": { decorator: "@column()", tsType: "string" },
|
|
169
|
+
"character": { decorator: "@column()", tsType: "string" },
|
|
170
|
+
"text": { decorator: "@column()", tsType: "string" },
|
|
171
|
+
"tinytext": { decorator: "@column()", tsType: "string" },
|
|
172
|
+
"mediumtext": { decorator: "@column()", tsType: "string" },
|
|
173
|
+
"longtext": { decorator: "@column()", tsType: "string" },
|
|
174
|
+
"citext": { decorator: "@column()", tsType: "string" },
|
|
175
|
+
"enum": { decorator: "@column()", tsType: "string" },
|
|
176
|
+
// Boolean
|
|
177
|
+
"boolean": { decorator: "@column.boolean()", tsType: "boolean" },
|
|
178
|
+
"bool": { decorator: "@column.boolean()", tsType: "boolean" },
|
|
179
|
+
// Date/time
|
|
180
|
+
"timestamp": { decorator: "@column.datetime()", tsType: "Date" },
|
|
181
|
+
"timestamptz": { decorator: "@column.datetime()", tsType: "Date" },
|
|
182
|
+
"timestamp with time zone": { decorator: "@column.datetime()", tsType: "Date" },
|
|
183
|
+
"timestamp without time zone": { decorator: "@column.datetime()", tsType: "Date" },
|
|
184
|
+
"datetime": { decorator: "@column.datetime()", tsType: "Date" },
|
|
185
|
+
"date": { decorator: "@column.date()", tsType: "Date" },
|
|
186
|
+
// JSON
|
|
187
|
+
"json": { decorator: "@column.json<Record<string, unknown>>()", tsType: "Record<string, unknown>" },
|
|
188
|
+
"jsonb": { decorator: "@column.json<Record<string, unknown>>()", tsType: "Record<string, unknown>" },
|
|
189
|
+
// UUID
|
|
190
|
+
"uuid": { decorator: "@column.uuid()", tsType: "string" },
|
|
191
|
+
// Binary
|
|
192
|
+
"bytea": { decorator: "@column()", tsType: "unknown" },
|
|
193
|
+
"blob": { decorator: "@column()", tsType: "unknown" },
|
|
194
|
+
"tinyblob": { decorator: "@column()", tsType: "unknown" },
|
|
195
|
+
"mediumblob": { decorator: "@column()", tsType: "unknown" },
|
|
196
|
+
"longblob": { decorator: "@column()", tsType: "unknown" }
|
|
197
|
+
};
|
|
198
|
+
var ARRAY_TYPE_MAP = {
|
|
199
|
+
"text": { decorator: "@column.stringArray()", tsType: "string[]" },
|
|
200
|
+
"varchar": { decorator: "@column.stringArray()", tsType: "string[]" },
|
|
201
|
+
"character varying": { decorator: "@column.stringArray()", tsType: "string[]" },
|
|
202
|
+
"char": { decorator: "@column.stringArray()", tsType: "string[]" },
|
|
203
|
+
"int": { decorator: "@column.intArray()", tsType: "number[]" },
|
|
204
|
+
"int4": { decorator: "@column.intArray()", tsType: "number[]" },
|
|
205
|
+
"integer": { decorator: "@column.intArray()", tsType: "number[]" },
|
|
206
|
+
"smallint": { decorator: "@column.intArray()", tsType: "number[]" },
|
|
207
|
+
"numeric": { decorator: "@column.numericArray()", tsType: "(number | null)[]" },
|
|
208
|
+
"decimal": { decorator: "@column.numericArray()", tsType: "(number | null)[]" },
|
|
209
|
+
"real": { decorator: "@column.numericArray()", tsType: "(number | null)[]" },
|
|
210
|
+
"float": { decorator: "@column.numericArray()", tsType: "(number | null)[]" },
|
|
211
|
+
"double precision": { decorator: "@column.numericArray()", tsType: "(number | null)[]" },
|
|
212
|
+
"boolean": { decorator: "@column.booleanArray()", tsType: "(boolean | null)[]" },
|
|
213
|
+
"bool": { decorator: "@column.booleanArray()", tsType: "(boolean | null)[]" },
|
|
214
|
+
"timestamp": { decorator: "@column.datetimeArray()", tsType: "(Date | null)[]" },
|
|
215
|
+
"timestamptz": { decorator: "@column.datetimeArray()", tsType: "(Date | null)[]" }
|
|
216
|
+
};
|
|
217
|
+
function mapColumnType(col) {
|
|
218
|
+
if (col.isArray) {
|
|
219
|
+
const baseType = col.sqlType.replace(/\[\]$/, "");
|
|
220
|
+
const arrayMapping = ARRAY_TYPE_MAP[baseType];
|
|
221
|
+
if (arrayMapping) return arrayMapping;
|
|
222
|
+
return { decorator: "@column()", tsType: "unknown[]" };
|
|
223
|
+
}
|
|
224
|
+
const mapping = TYPE_MAP[col.sqlType];
|
|
225
|
+
if (mapping) return mapping;
|
|
226
|
+
return { decorator: "@column()", tsType: "unknown" };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// src/code-generator.ts
|
|
230
|
+
function generateColumnCode(table) {
|
|
231
|
+
const lines = table.columns.map((col) => formatColumnLine(col));
|
|
232
|
+
return lines.join("\n");
|
|
233
|
+
}
|
|
234
|
+
function formatColumnLine(col) {
|
|
235
|
+
const mapping = mapColumnType(col);
|
|
236
|
+
const decorator = buildDecorator(col, mapping.decorator);
|
|
237
|
+
const nullSuffix = col.isNullable && !col.isPrimaryKey ? " | null" : "";
|
|
238
|
+
return ` ${decorator} ${col.name}?: ${mapping.tsType}${nullSuffix};`;
|
|
239
|
+
}
|
|
240
|
+
function buildDecorator(col, baseDecorator) {
|
|
241
|
+
if (!col.isPrimaryKey) return baseDecorator;
|
|
242
|
+
if (baseDecorator.startsWith("@column.uuid(")) {
|
|
243
|
+
return "@column.uuid({ primaryKey: true })";
|
|
244
|
+
}
|
|
245
|
+
return "@column({ primaryKey: true })";
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// src/renderer.ts
|
|
249
|
+
var litedbmodelColumns = defineEmbed({
|
|
250
|
+
dependsOn: [],
|
|
251
|
+
async render(ctx) {
|
|
252
|
+
const tableName = ctx.params["table"];
|
|
253
|
+
if (!tableName) {
|
|
254
|
+
return { content: "// Error: table parameter is required" };
|
|
255
|
+
}
|
|
256
|
+
const dsName = ctx.params["datasource"] || "schema";
|
|
257
|
+
const ds = ctx.datasources[dsName];
|
|
258
|
+
if (!ds) {
|
|
259
|
+
return { content: `// Error: datasource "${dsName}" not found` };
|
|
260
|
+
}
|
|
261
|
+
const records = await ds.getAll();
|
|
262
|
+
const tableRecord = records.find(
|
|
263
|
+
(r) => r["table_name"] === tableName
|
|
264
|
+
);
|
|
265
|
+
if (!tableRecord) {
|
|
266
|
+
return { content: `// Table "${tableName}" not found in datasource "${dsName}"` };
|
|
267
|
+
}
|
|
268
|
+
return {
|
|
269
|
+
content: generateColumnCode({
|
|
270
|
+
name: tableName,
|
|
271
|
+
columns: tableRecord["columns"]
|
|
272
|
+
})
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
export {
|
|
277
|
+
generateColumnCode,
|
|
278
|
+
litedbmodelColumns,
|
|
279
|
+
mapColumnType,
|
|
280
|
+
parseSchema,
|
|
281
|
+
sqlSchema
|
|
282
|
+
};
|
|
283
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/datasource.ts","../src/parser.ts","../src/renderer.ts","../src/type-mapper.ts","../src/code-generator.ts"],"sourcesContent":["import { defineDatasource } from 'embedoc';\nimport { readFileSync } from 'fs';\nimport { parseSchema } from './parser.js';\nimport type { DatabaseDialect } from './types.js';\n\nfunction toPascalCase(snakeCase: string): string {\n return snakeCase\n .split('_')\n .map(part => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())\n .join('');\n}\n\nfunction singularize(name: string): string {\n if (name.endsWith('ies')) return name.slice(0, -3) + 'y';\n if (name.endsWith('ses') || name.endsWith('xes') || name.endsWith('zes')) return name.slice(0, -2);\n if (name.endsWith('s') && !name.endsWith('ss')) return name.slice(0, -1);\n return name;\n}\n\nexport const sqlSchema = defineDatasource({\n async create(config) {\n const filePath = config['path'] as string;\n const database = (config['database'] as DatabaseDialect) || 'PostgreSQL';\n\n const sql = readFileSync(filePath, 'utf-8');\n const tables = parseSchema(sql, { database });\n\n const records = tables.map(t => ({\n table_name: t.name,\n model_class: toPascalCase(singularize(t.name)),\n columns: t.columns,\n }));\n\n return {\n type: 'sql_schema' as const,\n async query(_sql: string, params?: unknown[]) {\n if (params?.[0]) {\n return records.filter(r => r.table_name === params[0]);\n }\n return records;\n },\n async getAll() {\n return records;\n },\n async close() {},\n };\n },\n});\n","import { Parser } from 'node-sql-parser';\nimport type { DatabaseDialect, TableDef, ColumnDef } from './types.js';\n\ninterface ParseSchemaOptions {\n database?: DatabaseDialect;\n}\n\nexport function parseSchema(\n sql: string,\n options?: ParseSchemaOptions,\n): TableDef[] {\n const database = options?.database || 'PostgreSQL';\n const parser = new Parser();\n\n let statements: unknown[];\n try {\n const result = parser.astify(sql, { database });\n statements = Array.isArray(result) ? result : [result];\n } catch {\n return [];\n }\n\n const tables: TableDef[] = [];\n\n for (const stmt of statements) {\n const s = stmt as Record<string, unknown>;\n if (s['type'] !== 'create' || s['keyword'] !== 'table') continue;\n\n const tableName = extractTableName(s);\n if (!tableName) continue;\n\n const createDefs = s['create_definitions'] as unknown[] | null;\n if (!createDefs) continue;\n\n const pkColumns = extractTableLevelPrimaryKeys(createDefs);\n const columns = extractColumns(createDefs, pkColumns, database);\n\n tables.push({ name: tableName, columns });\n }\n\n return tables;\n}\n\nfunction extractTableName(stmt: Record<string, unknown>): string | null {\n const table = stmt['table'];\n if (!table) return null;\n\n if (Array.isArray(table)) {\n const first = table[0] as Record<string, unknown> | undefined;\n return (first?.['table'] as string) ?? null;\n }\n return (table as Record<string, unknown>)['table'] as string ?? null;\n}\n\nfunction extractTableLevelPrimaryKeys(defs: unknown[]): Set<string> {\n const pkColumns = new Set<string>();\n\n for (const def of defs) {\n const d = def as Record<string, unknown>;\n if (d['resource'] !== 'constraint') continue;\n\n const constraintType = String(d['constraint_type'] || '').toLowerCase();\n if (constraintType !== 'primary key') continue;\n\n const definition = d['definition'] as unknown[];\n if (!definition) continue;\n\n for (const col of definition) {\n const c = col as Record<string, unknown>;\n const colName = extractColumnName(c);\n if (colName) pkColumns.add(colName);\n }\n }\n\n return pkColumns;\n}\n\nfunction extractColumnName(ref: Record<string, unknown>): string | null {\n const col = ref['column'];\n if (typeof col === 'string') return col;\n if (col && typeof col === 'object') {\n return (col as Record<string, unknown>)['expr']\n ? String(((col as Record<string, unknown>)['expr'] as Record<string, unknown>)['value'])\n : null;\n }\n return null;\n}\n\nfunction extractColumns(\n defs: unknown[],\n pkColumns: Set<string>,\n database: DatabaseDialect,\n): ColumnDef[] {\n const columns: ColumnDef[] = [];\n\n for (const def of defs) {\n const d = def as Record<string, unknown>;\n if (d['resource'] !== 'column') continue;\n\n const colRef = d['column'] as Record<string, unknown>;\n const name = extractColumnName(colRef);\n if (!name) continue;\n\n const definition = d['definition'] as Record<string, unknown>;\n const rawDataType = String(definition?.['dataType'] || '').toUpperCase();\n const length = definition?.['length'] as number | undefined;\n const arrayObj = definition?.['array'];\n\n // Arrays are represented in two ways by node-sql-parser:\n // 1. dataType ends with \"[]\" (e.g. \"TEXT[]\")\n // 2. array property is an object with dimension (e.g. INTEGER[])\n const isArrayFromSuffix = rawDataType.endsWith('[]');\n const isArrayFromProp = !!arrayObj;\n const isArray = isArrayFromSuffix || isArrayFromProp;\n\n const dataType = isArrayFromSuffix ? rawDataType.slice(0, -2) : rawDataType;\n const sqlType = normalizeSqlType(dataType, length, isArray, database);\n\n const isPrimaryKey =\n pkColumns.has(name) ||\n d['primary_key'] === 'primary key' ||\n d['primary'] === 'key' ||\n d['primary'] === 'primary key';\n\n const nullable = d['nullable'] as Record<string, unknown> | undefined;\n const isNullable = isPrimaryKey\n ? false\n : nullable?.['type'] !== 'not null';\n\n columns.push({ name, sqlType, isPrimaryKey, isNullable, isArray });\n }\n\n return columns;\n}\n\nfunction normalizeSqlType(\n dataType: string,\n length: number | undefined,\n isArray: boolean,\n database: DatabaseDialect,\n): string {\n let base = dataType.toLowerCase();\n\n if (database === 'MySQL' && base === 'tinyint' && length === 1) {\n base = 'boolean';\n }\n\n if (isArray) {\n return `${base}[]`;\n }\n\n return base;\n}\n","import { defineEmbed } from 'embedoc';\nimport { generateColumnCode } from './code-generator.js';\nimport type { ColumnDef } from './types.js';\n\nexport const litedbmodelColumns = defineEmbed({\n dependsOn: [],\n\n async render(ctx) {\n const tableName = ctx.params['table'];\n if (!tableName) {\n return { content: '// Error: table parameter is required' };\n }\n\n const dsName = ctx.params['datasource'] || 'schema';\n const ds = ctx.datasources[dsName];\n if (!ds) {\n return { content: `// Error: datasource \"${dsName}\" not found` };\n }\n\n const records = await ds.getAll();\n const tableRecord = records.find(\n (r: Record<string, unknown>) => r['table_name'] === tableName,\n );\n\n if (!tableRecord) {\n return { content: `// Table \"${tableName}\" not found in datasource \"${dsName}\"` };\n }\n\n return {\n content: generateColumnCode({\n name: tableName,\n columns: tableRecord['columns'] as ColumnDef[],\n }),\n };\n },\n});\n","import type { ColumnDef, ColumnMapping } from './types.js';\n\nconst TYPE_MAP: Record<string, ColumnMapping> = {\n // Integer types\n 'int': { decorator: '@column()', tsType: 'number' },\n 'int2': { decorator: '@column()', tsType: 'number' },\n 'int4': { decorator: '@column()', tsType: 'number' },\n 'int8': { decorator: '@column.bigint()', tsType: 'bigint' },\n 'integer': { decorator: '@column()', tsType: 'number' },\n 'smallint': { decorator: '@column()', tsType: 'number' },\n 'mediumint': { decorator: '@column()', tsType: 'number' },\n 'bigint': { decorator: '@column.bigint()', tsType: 'bigint' },\n 'serial': { decorator: '@column()', tsType: 'number' },\n 'bigserial': { decorator: '@column.bigint()', tsType: 'bigint' },\n 'smallserial': { decorator: '@column()', tsType: 'number' },\n\n // Floating point / numeric\n 'numeric': { decorator: '@column()', tsType: 'number' },\n 'decimal': { decorator: '@column()', tsType: 'number' },\n 'real': { decorator: '@column()', tsType: 'number' },\n 'float': { decorator: '@column()', tsType: 'number' },\n 'float4': { decorator: '@column()', tsType: 'number' },\n 'float8': { decorator: '@column()', tsType: 'number' },\n 'double': { decorator: '@column()', tsType: 'number' },\n 'double precision': { decorator: '@column()', tsType: 'number' },\n 'money': { decorator: '@column()', tsType: 'number' },\n\n // String types\n 'varchar': { decorator: '@column()', tsType: 'string' },\n 'character varying': { decorator: '@column()', tsType: 'string' },\n 'char': { decorator: '@column()', tsType: 'string' },\n 'character': { decorator: '@column()', tsType: 'string' },\n 'text': { decorator: '@column()', tsType: 'string' },\n 'tinytext': { decorator: '@column()', tsType: 'string' },\n 'mediumtext': { decorator: '@column()', tsType: 'string' },\n 'longtext': { decorator: '@column()', tsType: 'string' },\n 'citext': { decorator: '@column()', tsType: 'string' },\n 'enum': { decorator: '@column()', tsType: 'string' },\n\n // Boolean\n 'boolean': { decorator: '@column.boolean()', tsType: 'boolean' },\n 'bool': { decorator: '@column.boolean()', tsType: 'boolean' },\n\n // Date/time\n 'timestamp': { decorator: '@column.datetime()', tsType: 'Date' },\n 'timestamptz': { decorator: '@column.datetime()', tsType: 'Date' },\n 'timestamp with time zone': { decorator: '@column.datetime()', tsType: 'Date' },\n 'timestamp without time zone': { decorator: '@column.datetime()', tsType: 'Date' },\n 'datetime': { decorator: '@column.datetime()', tsType: 'Date' },\n 'date': { decorator: '@column.date()', tsType: 'Date' },\n\n // JSON\n 'json': { decorator: '@column.json<Record<string, unknown>>()', tsType: 'Record<string, unknown>' },\n 'jsonb': { decorator: '@column.json<Record<string, unknown>>()', tsType: 'Record<string, unknown>' },\n\n // UUID\n 'uuid': { decorator: '@column.uuid()', tsType: 'string' },\n\n // Binary\n 'bytea': { decorator: '@column()', tsType: 'unknown' },\n 'blob': { decorator: '@column()', tsType: 'unknown' },\n 'tinyblob': { decorator: '@column()', tsType: 'unknown' },\n 'mediumblob': { decorator: '@column()', tsType: 'unknown' },\n 'longblob': { decorator: '@column()', tsType: 'unknown' },\n};\n\nconst ARRAY_TYPE_MAP: Record<string, ColumnMapping> = {\n 'text': { decorator: '@column.stringArray()', tsType: 'string[]' },\n 'varchar': { decorator: '@column.stringArray()', tsType: 'string[]' },\n 'character varying': { decorator: '@column.stringArray()', tsType: 'string[]' },\n 'char': { decorator: '@column.stringArray()', tsType: 'string[]' },\n 'int': { decorator: '@column.intArray()', tsType: 'number[]' },\n 'int4': { decorator: '@column.intArray()', tsType: 'number[]' },\n 'integer': { decorator: '@column.intArray()', tsType: 'number[]' },\n 'smallint': { decorator: '@column.intArray()', tsType: 'number[]' },\n 'numeric': { decorator: '@column.numericArray()', tsType: '(number | null)[]' },\n 'decimal': { decorator: '@column.numericArray()', tsType: '(number | null)[]' },\n 'real': { decorator: '@column.numericArray()', tsType: '(number | null)[]' },\n 'float': { decorator: '@column.numericArray()', tsType: '(number | null)[]' },\n 'double precision': { decorator: '@column.numericArray()', tsType: '(number | null)[]' },\n 'boolean': { decorator: '@column.booleanArray()', tsType: '(boolean | null)[]' },\n 'bool': { decorator: '@column.booleanArray()', tsType: '(boolean | null)[]' },\n 'timestamp': { decorator: '@column.datetimeArray()', tsType: '(Date | null)[]' },\n 'timestamptz': { decorator: '@column.datetimeArray()', tsType: '(Date | null)[]' },\n};\n\nexport function mapColumnType(col: ColumnDef): ColumnMapping {\n if (col.isArray) {\n const baseType = col.sqlType.replace(/\\[\\]$/, '');\n const arrayMapping = ARRAY_TYPE_MAP[baseType];\n if (arrayMapping) return arrayMapping;\n return { decorator: '@column()', tsType: 'unknown[]' };\n }\n\n const mapping = TYPE_MAP[col.sqlType];\n if (mapping) return mapping;\n\n return { decorator: '@column()', tsType: 'unknown' };\n}\n","import type { TableDef, ColumnDef } from './types.js';\nimport { mapColumnType } from './type-mapper.js';\n\nexport function generateColumnCode(table: TableDef): string {\n const lines = table.columns.map(col => formatColumnLine(col));\n return lines.join('\\n');\n}\n\nfunction formatColumnLine(col: ColumnDef): string {\n const mapping = mapColumnType(col);\n const decorator = buildDecorator(col, mapping.decorator);\n const nullSuffix = col.isNullable && !col.isPrimaryKey ? ' | null' : '';\n return ` ${decorator} ${col.name}?: ${mapping.tsType}${nullSuffix};`;\n}\n\nfunction buildDecorator(col: ColumnDef, baseDecorator: string): string {\n if (!col.isPrimaryKey) return baseDecorator;\n\n // @column.uuid() supports { primaryKey: true } options\n if (baseDecorator.startsWith('@column.uuid(')) {\n return '@column.uuid({ primaryKey: true })';\n }\n\n // For all other types, use @column({ primaryKey: true })\n // litedbmodel auto-infers number/string/boolean/Date/bigint from TS types\n return '@column({ primaryKey: true })';\n}\n"],"mappings":";AAAA,SAAS,wBAAwB;AACjC,SAAS,oBAAoB;;;ACD7B,SAAS,cAAc;AAOhB,SAAS,YACd,KACA,SACY;AACZ,QAAM,WAAW,SAAS,YAAY;AACtC,QAAM,SAAS,IAAI,OAAO;AAE1B,MAAI;AACJ,MAAI;AACF,UAAM,SAAS,OAAO,OAAO,KAAK,EAAE,SAAS,CAAC;AAC9C,iBAAa,MAAM,QAAQ,MAAM,IAAI,SAAS,CAAC,MAAM;AAAA,EACvD,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,SAAqB,CAAC;AAE5B,aAAW,QAAQ,YAAY;AAC7B,UAAM,IAAI;AACV,QAAI,EAAE,MAAM,MAAM,YAAY,EAAE,SAAS,MAAM,QAAS;AAExD,UAAM,YAAY,iBAAiB,CAAC;AACpC,QAAI,CAAC,UAAW;AAEhB,UAAM,aAAa,EAAE,oBAAoB;AACzC,QAAI,CA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M,QAAQ,MAAM,GAAG,UAAU;AACpE;AAEA,SAAS,eAAe,KAAgB,eAA+B;AACrE,MAAI,CAAC,IAAI,aAAc,QAAO;AAG9B,MAAI,cAAc,WAAW,eAAe,GAAG;AAC7C,WAAO;AAAA,EACT;AAIA,SAAO;AACT;;;AFtBO,IAAM,qBAAqB,YAAY;AAAA,EAC5C,WAAW,CAAC;AAAA,EAEZ,MAAM,OAAO,KAAK;AAChB,UAAM,YAAY,IAAI,OAAO,OAAO;AACpC,QAAI,CAAC,WAAW;AACd,aAAO,EAAE,SAAS,wCAAwC;AAAA,IAC5D;AAEA,UAAM,SAAS,IAAI,OAAO,YAAY,KAAK;AAC3C,UAAM,KAAK,IAAI,YAAY,MAAM;AACjC,QAAI,CAAC,IAAI;AACP,aAAO,EAAE,SAAS,yBAAyB,MAAM,cAAc;AAAA,IACjE;AAEA,UAAM,UAAU,MAAM,GAAG,OAAO;AAChC,UAAM,cAAc,QAAQ;AAAA,MAC1B,CAAC,MAA+B,EAAE,YAAY,MAAM;AAAA,IACtD;AAEA,QAAI,CAAC,aAAa;AAChB,aAAO,EAAE,SAAS,aAAa,SAAS,8BAA8B,MAAM,IAAI;AAAA,IAClF;AAEA,WAAO;AAAA,MACL,SAAS,mBAAmB;AAAA,QAC1B,MAAM;AAAA,QACN,SAAS,YAAY,SAAS;AAAA,MAChC,CAAC;AAAA,IACH;AAAA,EACF;AACF,CAAC;","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "litedbmodel-gen",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "embedoc-based model code generator for litedbmodel — generates TypeScript column definitions from SQL DDL (PostgreSQL/MySQL/SQLite)",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"bin": {
|
|
15
|
+
"litedbmodel-gen": "./dist/cli.js"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist",
|
|
19
|
+
"templates"
|
|
20
|
+
],
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "tsup",
|
|
23
|
+
"dev": "tsup --watch",
|
|
24
|
+
"test": "vitest run",
|
|
25
|
+
"test:watch": "vitest",
|
|
26
|
+
"typecheck": "tsc --noEmit",
|
|
27
|
+
"prepublishOnly": "npm run build"
|
|
28
|
+
},
|
|
29
|
+
"keywords": [
|
|
30
|
+
"litedbmodel",
|
|
31
|
+
"embedoc",
|
|
32
|
+
"code-generator",
|
|
33
|
+
"orm",
|
|
34
|
+
"postgresql",
|
|
35
|
+
"mysql",
|
|
36
|
+
"sqlite",
|
|
37
|
+
"ddl",
|
|
38
|
+
"schema"
|
|
39
|
+
],
|
|
40
|
+
"license": "MIT",
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"commander": "^14.0.3",
|
|
43
|
+
"js-yaml": "^4.1.1",
|
|
44
|
+
"node-sql-parser": "^5.4.0"
|
|
45
|
+
},
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"embedoc": ">=0.11.0"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@types/js-yaml": "^4.0.9",
|
|
51
|
+
"@types/node": "^25.3.3",
|
|
52
|
+
"embedoc": "^0.11.0",
|
|
53
|
+
"tsup": "^8.0.1",
|
|
54
|
+
"typescript": "^5.3.0",
|
|
55
|
+
"vitest": "^1.0.0"
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { DBModel, model, column } from 'litedbmodel';
|
|
2
|
+
|
|
3
|
+
@model('{{table_name}}')
|
|
4
|
+
class {{model_class}}Model extends DBModel {
|
|
5
|
+
/*@embedoc:litedbmodel_columns table="{{table_name}}"*/
|
|
6
|
+
/*@embedoc:end*/
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export const {{model_class}} = {{model_class}}Model.asModel();
|
|
10
|
+
export type {{model_class}} = InstanceType<typeof {{model_class}}>;
|