-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql-generator.js
54 lines (48 loc) · 1.52 KB
/
sql-generator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
export function setup(element) {
element.addEventListener("click", updateCode);
}
export function updateCode() {
const tryParseJson = () => {
try {
const config = document.querySelector("#config").value;
return JSON.parse(config);
} catch (error) {
console.error(error);
}
};
const getCTEFromSources = (sources, limitPerSource = 10) => {
return sources.map((source) => {
return `${source.column}_matches AS (
SELECT DISTINCT ${source.column} AS hit,
similarity(${source.column}, :query_string) AS similarity_score,
'${source.column}' AS match_column
FROM ${source.table}
WHERE ${source.column} % :query_string
ORDER BY similarity_score DESC
LIMIT ${limitPerSource}
)`;
});
};
const getSelectAllSqlFromSources = (sources) => {
return sources.map((source) => {
return `SELECT * FROM ${source.column}_matches`;
});
};
const { sources, pgTrgmSimilarityThreshold, limitPerSource, totalLimit } =
tryParseJson();
console.log(sources);
const output = document.querySelector("#output");
output.innerHTML = `
SET pg_trgm.similarity_threshold = ${pgTrgmSimilarityThreshold};
WITH ${getCTEFromSources(sources, limitPerSource).join(", ")}
SELECT hit,
similarity_score,
match_column
FROM (
${getSelectAllSqlFromSources(sources).join(" UNION ALL ")}
) AS all_matches
ORDER BY similarity_score DESC
LIMIT ${totalLimit};
RESET pg_trgm.similarity_threshold;
`;
}