Skip to content

Instantly share code, notes, and snippets.

@johnsage25
Forked from MartinMuzatko/beautify-sql-schema.js
Created August 13, 2022 17:41
Show Gist options
  • Save johnsage25/d02a32dd7cef21cb8dd243658a4ba17b to your computer and use it in GitHub Desktop.
Save johnsage25/d02a32dd7cef21cb8dd243658a4ba17b to your computer and use it in GitHub Desktop.
Create SQLITE schema and format it
const sqlFormatter = require('sql-formatter')
const promisify = require('promisify-node')
const fs = promisify('fs')
const path = require('path')
const INDENT = '\t'
const SCHEMAFILE = path.resolve(__dirname, 'schema.sql')
(async () => {
try {
const schema = await fs.readFile(SCHEMAFILE);
let beautifiedSchema = await sqlFormatter.format(
schema.toString(),
{
indent: INDENT
}
)
beautifiedSchema = beautifiedSchema
.replace(/[\"\`]/g, '') // remove quotes and backticks
.replace(/[;]/g, ';\n') // add newline to semicolons
.split(';') // split all create table statements
.filter(line => line != '\n') // remove any lines only containing of linefeeds
.map(line => line.charAt(0) != '\n' ? '\n' + line : line) // if there is no linefeed before the line, add one
.sort() // order them naturally
.join(';') + ';' // concatenate them again and add the last ; again
await fs.writeFile(SCHEMAFILE, beautifiedSchema)
} catch (error) {
console.log(error)
}
})()
#!/bin/bash
sqlite3 database.sqlite ".output schema.sql" ".schema" ".exit"
node beautify-sql-schema.js
{
"devDependencies": {
"husky": "^0.14.3",
"sql-formatter": "^2.1.0",
"promisify-node": "^0.4.0"
},
"scripts": {
"precommit": "export-sql-schema.sh"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment