Created
April 3, 2020 23:48
-
-
Save micimize/7f22759b44f9528ee33229b6095dba5d to your computer and use it in GitHub Desktop.
add comments to sql table definitions
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
function removeUpTo( | |
s: string | undefined, | |
prefix: RegExp | |
){ | |
if (s === undefined){ | |
return undefined | |
} | |
s = s.trim() | |
const i = s.search(prefix) | |
if (i == -1){ | |
return undefined | |
} | |
const found = s.match(prefix) | |
if (!found){ | |
throw Error('Impossible') | |
} | |
return s.substr(i + found[0].length).trim() | |
} | |
function extractDescription(line: string){ | |
return [/--/, /@description\s*:?/].reduce(removeUpTo, line) | |
} | |
function firstWord(text: string){ | |
text = text.trim() | |
return text.substr(0, text.indexOf(" ")) | |
} | |
function extractIdentifier(line: string, currentTable: string | undefined){ | |
var identifier = removeUpTo(line, /create table/) | |
if (identifier){ | |
return `table ${firstWord(identifier)}` | |
} | |
if (currentTable === undefined){ | |
throw Error('Impossible') | |
} | |
return `column ${currentTable}.${firstWord(line)}` | |
} | |
function extractCommentMap(lines: string){ | |
var map: { [identifier: string]: string } = {} | |
var desc: string | undefined = undefined | |
var currentTable: string | undefined = undefined | |
for (var line of lines.split('\n')){ | |
if (desc){ | |
const ident = extractIdentifier(line, currentTable); | |
if (ident.startsWith('table')){ | |
currentTable = ident.substr('table '.length) | |
} | |
map[ident] = desc; | |
desc = undefined | |
} else { | |
desc = extractDescription(line); | |
} | |
} | |
return map | |
} | |
function formatCommentMap(comments: { [identifier: string]: string }){ | |
return Object.keys(comments).map((ident) => `comment on ${ident} is '${comments[ident]}';`).join('\n') | |
} | |
function boltOnComments(sql: string){ | |
return sql + '\n' + formatCommentMap(extractCommentMap(sql)) | |
} | |
console.log(boltOnComments(` | |
-- @description: A feed of \`Post\`s relevant to a particular \`User\`. | |
create table app_public.user_feed_posts ( | |
-- @description: An identifier for this entry in the feed. | |
id serial primary key, | |
user_id int not null references app_public.users on delete cascade, | |
post_id int not null references app_public.posts on delete cascade, | |
-- @description: The time this feed item was added. | |
created_at timestamptz not null default now() | |
); | |
`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment