Skip to content

Commit

Permalink
use sort instead of tosort
Browse files Browse the repository at this point in the history
  • Loading branch information
hans-m-song committed May 27, 2024
1 parent c3c17fc commit c7bcf52
Showing 1 changed file with 18 additions and 30 deletions.
48 changes: 18 additions & 30 deletions bin/generate-queries.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import fs from "fs";
import fs from 'fs';

const [source, destination] = process.argv.slice(2);
console.log({ source, destination });

console.log("reading from source...");
console.log('reading from source...');
const raw = fs.readFileSync(source).toString();
const rawQueries = raw.split(/\n{2,}/g);

console.log("parsing and transforming...");
console.log('parsing and transforming...');
const set = new Set();
const uniques = (inputs?: any[]) => Array.from(new Set(inputs));
const transformed = rawQueries.map((raw, i) => {
const [header, ...lines] = raw.split("\n");
const [header, ...lines] = raw.split('\n');
const name = header
.replace(/^-- name:\s*/, "")
.replace(/:.*$/, "")
.replace(/^-- name:\s*/, '')
.replace(/:.*$/, '')
.trim();
const capitalised = name[0].toUpperCase() + name.slice(1);

Expand All @@ -25,38 +25,26 @@ const transformed = rawQueries.map((raw, i) => {
set.add(name);

const query = lines
.join(" ")
.join(' ')
.trim()
.replace(/\s+/g, " ")
.replace(/;$/, "")
.replace(/\(\s+/g, "(")
.replace(/\s+\)/g, ")");
.replace(/\s+/g, ' ')
.replace(/;$/, '')
.replace(/\(\s+/g, '(')
.replace(/\s+\)/g, ')');

const args = uniques(
query.match(/\$[a-z0-9]+/gi)?.map((arg) => arg.slice(1)),
);
const args = uniques(query.match(/\$[a-z0-9]+/gi)?.map((arg) => arg.slice(1)));
const table = uniques(
query
.match(/(FROM|INTO|UPDATE)\s+([a-z0-9]+)/gi)
?.map((match) => match.replace(/(FROM|INTO|UPDATE)\s+/, "")),
?.map((match) => match.replace(/(FROM|INTO|UPDATE)\s+/, '')),
);
console.log({ name, args, table, query });

const tableComment = `tables: ${table.map((i) => `\`${i}\``).join(", ")}`;
const argComment = `args: ${args.map((i) => `\`${i}\``).join(", ") || "N/A"}`;
const tableComment = `tables: ${table.map((i) => `\`${i}\``).join(', ')}`;
const argComment = `args: ${args.map((i) => `\`${i}\``).join(', ') || 'N/A'}`;
const sqlDeclaration = `export const ${name} = \`${query}\`;`;
return [
"/**",
" * " + tableComment,
" *",
" * " + argComment,
" */",
sqlDeclaration,
].join("\n");
return ['/**', ' * ' + tableComment, ' *', ' * ' + argComment, ' */', sqlDeclaration].join('\n');
});

console.log("writing to destination...");
fs.writeFileSync(
destination,
transformed.toSorted((a, b) => a.localeCompare(b)).join("\n\n") + "\n",
);
console.log('writing to destination...');
fs.writeFileSync(destination, transformed.sort((a, b) => a.localeCompare(b)).join('\n\n') + '\n');

0 comments on commit c7bcf52

Please sign in to comment.