Get all tables data from SQLite DB using Node.js

Viewed 811

Having a DB with multiple tables, I managed to get that for one table at a time and also to get the names of the tables.

However, it doesn't work to get the data for all the tables.

This is the code for getting the table names which works fine:

var express = require('express');
var router = express.Router();
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./db/ocs_athletes.db');

router.get('/', function (req, res, next) {
  db.serialize(function () {
    db.all(
      'SELECT name FROM sqlite_master WHERE type="table"',
      function (err, rows) {
        return res.send(rows);
      }
    );
  });
});

module.exports = router;

it returns an array of this form:

[{"name":"Athlete"},{"name":"Game"},{"name":"AthletePhoto"},{"name":"AthleteResult"}]

I don't know how to get the data of these tables, I made a forEach through the elements and create a query for each table and save the data in result but doesn't work how it is.

router.get('/', function (req, res, next) {
  db.serialize(function () {
    db.all(
      'SELECT name FROM sqlite_master WHERE type="table"',
      function (err, rows) {
        const result = [];
        rows.forEach(
          (table) => db.all('SELECT * FROM ' + table.name),
          function (err, innerRows) {
            result.push(innerRows);
          }
        );
        return res.send(result);
      }
    );
  });
});

module.exports = router;

The result is []. I guess it must be written in a way that it waits for the db to be read but I'm not sure.

Any suggestions?

0 Answers
Related