将.sql文件转换为.json或javascript对象或转换模型文件的最佳方法

时间:2020-10-11 14:28:51

标签: javascript sql json sequelize.js

我想从JSON文件中创建可访问的JS-Object.sql。最好的方法是什么,或者有可用的解决方案。

或者有没有很好的解决方案可以从sequelize中创建.sql模型文件

我的.sql文件:

CREATE TABLE `AuthenticationSettings` (
 `AUTSET_Id` int PRIMARY KEY AUTO_INCREMENT, 
 `updated_at` timestamp );

CREATE TABLE `ClinicAuthentiation` (
 `CLINAUT_Id` int PRIMARY KEY AUTO_INCREMENT,
 `updated_at` timestamp );

ALTER TABLE `AuthenticationSettings` ADD FOREIGN KEY (`AUTSET_Id`) REFERENCES `ClinicAuthentiation` (`AUTSET_Id`);

我要创建的示例JSON(仅作为示例,我可以接受任何可以使用的文件):

{
"AuthenticationSettings" : {
"type" : "create",
"fields" : {
 "AUTSET_Id" : "Integer"
...
 }
}

1 个答案:

答案 0 :(得分:0)

如果要将SQL Schema转换为JSON对象,则可以使用sql-ddl-to-json-schema,它的功能不是很完整,但可以满足您的用例。例如

const { Parser } = require('sql-ddl-to-json-schema');
const parser = new Parser('mysql');
 
const sql = `
CREATE TABLE AuthenticationSettings (
    AUTSET_Id int PRIMARY KEY AUTO_INCREMENT, 
    updated_at timestamp
);
`;
 
const options = {};
const jsonSchemaDocuments = parser.feed(sql)
  .toJsonSchemaArray(options);

console.log(jsonSchemaDocuments[0])

将进行转换并将输出显示为

{
  '$schema': 'http://json-schema.org/draft-07/schema',
  '$comment': 'JSON Schema for AuthenticationSettings table',
  '$id': 'AuthenticationSettings',
  title: 'AuthenticationSettings',
  type: 'object',
  required: [ 'AUTSET_Id' ],
  definitions: {
    AUTSET_Id: {
      '$comment': 'primary key',
      type: 'integer',
      minimum: 1,
      maximum: 2147483647
    },
    updated_at: { type: 'string' }
  },
  properties: {
    AUTSET_Id: { '$ref': '#/definitions/AUTSET_Id' },
    updated_at: { '$ref': '#/definitions/updated_at' }
  }
}