/* Load SQLite3 connector library */
import { DB } from "https://deno.land/x/sqlite/mod.ts";

/* Load SheetJS library */
// @deno-types="https://cdn.sheetjs.com/xlsx-latest/package/types/index.d.ts"
import * as XLSX from "https://cdn.sheetjs.com/xlsx-latest/package/xlsx.mjs";

/* Initialize database */
var db = new DB("chinook.db");

/* Create new workbook */
var wb = XLSX.utils.book_new();

/* Get list of table names */
var sql = db.prepareQuery("SELECT name FROM sqlite_master WHERE type='table'");
var result = sql.all();
/* Loop across each name */
result.forEach(function(row) {
  /* Get first 100K rows */
  var query = db.prepareQuery("SELECT * FROM '" + row[0] + "' LIMIT 100000")
  var aoa = query.all();
  if(aoa.length > 0) {
    /* Create array of arrays */
    var data = [query.columns().map(x => x.name)].concat(aoa);
    /* Create Worksheet from the aoa */
    var ws = XLSX.utils.aoa_to_sheet(data, {dense: true});
    /* Add to Workbook */
    XLSX.utils.book_append_sheet(wb, ws, row[0]);
  }
});

/* Write File */
XLSX.writeFile(wb, "SheetJSQLiteDeno.xlsx");
