Download all data tables

I want to programmatically download all data tables using a Javascript query and SQL. The SQL code reports an error that my variable is undefined. How can I fix it so it is "defined"?

SQL:
SELECT * FROM {{tableName}}

Javascript:
const selectedTables = checkboxTables.value; // Get selected table names from Checkbox Group

selectedTables.forEach(async (tableName) => {
try {
const queryResult = await fetchTableData.trigger({
additionalScope: { tableName }, // Pass table name dynamically
});

if (!queryResult.data || queryResult.data.length === 0) {
  console.error(`No data returned for table: ${tableName}`);
  return;
}

const csvContent = Papa.unparse(queryResult.data); // Convert query result to CSV
const blob = new Blob([csvContent], { type: "text/csv" });
const url = URL.createObjectURL(blob);

// Create a download link
const a = document.createElement("a");
a.href = url;
a.download = `${tableName}.csv`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);

} catch (error) {
console.error(Error fetching data for table ${tableName}:, error);
}
});

Hey @ADiecidue

Instead of this code use your code for return the data with that checkbox condition and from the query event handler you can download the data in csv format.

For example :


image

3 Likes

Thanks but I'm wanting to export all of my tables at one time and they are all not referenced in the interface.

Hey @ADiecidue,

I think you may achieve this by disabling converting queries to prepared statements (this should be in the settings of your DB resource).

More on this topic here and here

Thanks but that's too risky for me.

Hi @ADiecidue,

Were you able to find a work around to disabling prepared statements?

Also did @WidleStudioLLP's solution not work? You mentioned that not all your tables are "referenced in the interface" and I was curious about what you meant by that.

Are the tables spread across multiple pages of a multiple page app? Or are the DB tables not all being queried and displayed in the app UI?

Another option would be using workflows! You can set up a loop block to query each DB, pass in params such as the table names and iterate through these with the loop. Then, after each query runs, download the file data to a CSV.

Jack_T,

No, I did not find a suitable way to disable prepared statements. The DB tables are not all being queried by the UI. I can try the looping through the tables and returning the names.

1 Like

Ok, I think using workflows would be the best option.

I just added in a link to workflows functions to my comment above :sweat_smile:

You can grab each name, query the DB for the data, then export as a CSV :+1: