Last active
December 21, 2022 11:35
-
-
Save CharlesNepote/14ad6382a7b61826497f2023fcb15b77 to your computer and use it in GitHub Desktop.
Datasette: button to count rows
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
// Add "count" button aside the "Custom SQL query returning XX rows" title | |
// Clicking on the button counts and displays total number of rows | |
// Probably does not play well with complex queries (eg. sub-queries) | |
// Test if we're located in a query's page | |
const hide = document.getElementsByClassName('show-hide-sql')[0] || false; | |
if (hide) { | |
var sql_request = document.getElementById('sql-editor').value; | |
// Remove request's comments | |
var sql_req_wo_comments = sql_request.replace(/(\/\*[^*]*\*\/)|(--[^.].*)/gm, ''); | |
// Test if sql query does contain LIMIT X | |
// select * from table limit 1 => display button | |
// select count(*) from table group by f limit 5 => display button | |
// select count(*) from table group by f => don't | |
// select count(*) from table => don't | |
// select count(*) from table limit 5 -- doesn't make sense | |
if (/(\slimit \d)/i.test(sql_req_wo_comments) === true) { | |
hide.insertAdjacentHTML( 'beforeBegin', | |
'<sup><span id="count" title="count the results without LIMIT">count</span></sup> ' ); | |
document.head.insertAdjacentHTML('beforeend', | |
`<style> | |
#count { font-size: 60%; vertical-align: top; | |
cursor: pointer; border-radius: 4px; border: none; | |
padding: 3px 8px; background-color: #0000000d; } | |
#count:hover { background-color: #0000001a; } | |
</style>`); | |
const count = document.getElementById('count'); | |
count.addEventListener("click", displayCount); | |
} | |
} | |
function displayCount() { | |
// Delete limit X | |
var sql_request_wo_limit = sql_req_wo_comments.replace(/limit \d+/gi, ""); | |
sql_request_wo_limit = sql_request_wo_limit.replace(/\n$/gi, ""); | |
// build query | |
const count_request = "select count(*) from (" + sql_request_wo_limit + "\n);"; | |
var url = document.URL.replace(/\?.*$/gi, ""); // https://example.org/database?sql=.......... | |
fetch(encodeURI(url + ".json?sql=") + encodeURIComponent(count_request) + "&_shape=arrayfirst") | |
.then(function(response) { | |
return response.json(); | |
}) | |
.then(function(data) { | |
console.log('JSON', JSON.stringify(data)); | |
count.innerHTML = data[0]; | |
}) | |
.catch(error => console.error('Error!', error.message)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment