Last active
April 27, 2024 05:41
-
-
Save MartinMuzatko/e3a4fc3b9fc380e74dfdc376da67329d to your computer and use it in GitHub Desktop.
Create SQLITE schema and format it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
})() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
sqlite3 database.sqlite ".output schema.sql" ".schema" ".exit" | |
node beautify-sql-schema.js |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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