Skip to content

Instantly share code, notes, and snippets.

@MartinMuzatko
Last active August 13, 2022 17:41
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MartinMuzatko/e3a4fc3b9fc380e74dfdc376da67329d to your computer and use it in GitHub Desktop.
Save MartinMuzatko/e3a4fc3b9fc380e74dfdc376da67329d 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