Josef Henn
Josef Henn

Reputation: 162

Best way to convert a .sql file to a .json or to a javascript Object or to a sequelize model file

I want ro create a accessible JSON or JS-Object out of a .sql file. What is the best way to do this, or are there any solutions for that available.

Or is there any good solution to create a sequelize model file out of a .sql

my .sql file:

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`);

Example JSON that i want to create (It is just an example, i would accept any file with i can work with):

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

Upvotes: 0

Views: 1232

Answers (1)

KayD
KayD

Reputation: 826

If you want to convert SQL Schema into a JSON Object then you can use sql-ddl-to-json-schema It's not very feature full but can work for your use-case. For example

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])

that will convert and show the output as

{
  '$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' }
  }
}

Upvotes: 1

Related Questions