-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschema-sql.js
182 lines (152 loc) · 5.56 KB
/
schema-sql.js
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
const sqlSchemaRegistry = {};
function registerJsonSchema(id, schema) {
sqlSchemaRegistry[id] = schema;
}
function resolveJsonSchemaRef(ref) {
const parts = ref.split('#');
const id = parts[0];
const path = parts[1] ? parts[1].split('/').slice(1) : [];
if (!sqlSchemaRegistry[id]) {
console.error(`Schema with id ${id} not found in registry`);
return null;
}
let schema = sqlSchemaRegistry[id];
for (let part of path) {
if (!schema[part]) {
console.error(`Property ${part} not found in schema ${id}`);
return null;
}
schema = schema[part];
}
return schema;
}
function getColumnType(property) {
if (property.$ref) {
return "REFERENCE";
} else {
switch (property.type) {
case "integer":
return property.format === "id" ? "INT AUTO_INCREMENT PRIMARY KEY" :
property.format === "int64" ? "BIGINT" : "INT";
case "number": return property.format === "float" ? "FLOAT" : "DECIMAL";
case "boolean": return "BOOLEAN";
case "array": return "JSON -- Consider normalization";
case "object": return "JSON -- Consider normalization";
case "string":
if (property.format === "date") return "DATE";
if (property.format === "date-time") return "TIMESTAMP";
if (property.maxLength) return `VARCHAR(${property.maxLength})`;
return "TEXT";
default: return "VARCHAR(255)";
}
}
}
function jsonSchemaToCreateTable(jsonSchema, tableName) {
const schema = typeof jsonSchema === 'string' ? JSON.parse(jsonSchema) : jsonSchema;
const properties = schema.properties || {};
const required = schema.required || [];
const foreignKeys = [];
const columns = [];
const indices = [];
const uniques = [];
let primaryKey = null;
for (const [prop, propertySchema] of Object.entries(properties)) {
const columnName = camelToSnake(prop);
let columnType = getColumnType(propertySchema);
let columnDef = `${columnName} ${columnType}`;
if (required.includes(prop)) {
columnDef += ' NOT NULL';
}
if (propertySchema.default !== undefined) {
columnDef += ` DEFAULT ${JSON.stringify(propertySchema.default)}`;
}
if (columnType.includes("PRIMARY KEY")) {
primaryKey = columnName;
}
if (columnType === "REFERENCE") {
const refSchema = resolveJsonSchemaRef(propertySchema.$ref);
const refTableName = propertySchema.$ref.split('.')[0];
const refColumnName = Object.keys(refSchema.properties).find(key =>
refSchema.properties[key].type === "integer" && refSchema.properties[key].format === "id"
) || 'id';
foreignKeys.push(`FOREIGN KEY (${columnName}_id) REFERENCES ${refTableName}(${camelToSnake(refColumnName)})`);
columns.push(`${columnName}_id INT${required.includes(prop) ? ' NOT NULL' : ''}`);
indices.push(`CREATE INDEX idx_${tableName}_${columnName}_id ON ${tableName}(${columnName}_id);`);
} else {
columns.push(columnDef);
}
if (propertySchema.pattern === "UNIQUE") {
uniques.push(`UNIQUE (${columnName})`);
}
}
if (!primaryKey) {
columns.unshift('id INT AUTO_INCREMENT PRIMARY KEY');
primaryKey = 'id';
}
if (foreignKeys.length > 0) {
columns.push(...foreignKeys);
}
if (uniques.length > 0) {
columns.push(...uniques);
}
let createTableStatement = `CREATE TABLE ${tableName} (\n ${columns.join(',\n ')}\n);`;
if (indices.length > 0) {
createTableStatement += '\n\n' + indices.join('\n');
}
return createTableStatement;
}
function extractJsonSchemas(text) {
const jsonSchemas = [];
let stack = [];
let startIndex = null;
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (char === '{') {
if (stack.length === 0) {
startIndex = i;
}
stack.push(char);
} else if (char === '}') {
if (stack.length === 1) {
jsonSchemas.push(text.slice(startIndex, i + 1));
}
stack.pop();
}
}
return jsonSchemas;
}
function convertJsonSchemasToCreateTables(jsonSchemasText) {
const jsonSchemas = extractJsonSchemas(jsonSchemasText);
const createStatements = [];
jsonSchemas.forEach(schemaText => {
const schema = JSON.parse(schemaText.trim());
registerJsonSchema(schema.$id, schema);
});
jsonSchemas.forEach(schemaText => {
const schema = JSON.parse(schemaText.trim());
const tableName = schema.$id.replace('.json', '');
createStatements.push(jsonSchemaToCreateTable(schema, tableName));
});
return createStatements.join('\n\n');
}
function camelToSnake(camelStr) {
return camelStr.replace(/([A-Z])/g, '_$1').toLowerCase();
}
// グローバル変数として公開(ブラウザ環境)
if (typeof window !== 'undefined') {
window.sqlSchema = {
registerJsonSchema,
jsonSchemaToCreateTable,
extractJsonSchemas,
convertJsonSchemasToCreateTables
};
}
// モジュールエクスポート(Node.js環境)
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
registerJsonSchema,
jsonSchemaToCreateTable,
extractJsonSchemas,
convertJsonSchemasToCreateTables
};
}