aboutsummaryrefslogtreecommitdiff
path: root/query-executor.js
blob: 17b3ca502d93f65b6434641cc58440d1b56f2bf7 (plain)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"use strict";

const { remote, ipcRenderer } = require("electron");
const { Pool } = require("pg");

const connectionTestQuery = "SELECT now()";

const executorId = remote.getCurrentWindow().executorId;

const connectionConfig = remote.getCurrentWindow().connectionConfig;

const connectionPool = new Pool({
  user: connectionConfig.username,
  host: connectionConfig.hostname,
  database: connectionConfig.database,
  password: connectionConfig.password,
  port: connectionConfig.port
});

// Test the newly initialised connection
connectionPool.query(connectionTestQuery, (err, res) => {
  setErrorCauseIfExists(err);
  ipcRenderer.send("queryExecutor.initialiseConnectionCallback", {error: err, executorId: executorId});
});

function setErrorCauseIfExists(error) {
  if (error !== undefined) {
    // The IPC payload is serialised to JSON before transmission, so the prototype chain is lost.
    // So store the nicely formatted error message as a property.
    error.cause = error.toString();
  }
}

ipcRenderer.on("queryExecutor.runQuery", (event, payload) => {

  if(payload.queryExecutorId === executorId) {
    connectionPool.query(payload.query, (err, res) => {

      console.log(err, res);
  
      setErrorCauseIfExists(err);

      ipcRenderer.send("queryExecutor.runQueryComplete", {
        "error": err,
        "result": res,
        "editorInstanceId": payload.editorInstanceId
      });
  
    });
  }
  
});

ipcRenderer.on("queryExecutor.queryTableMetadata", (event, payload) => {

  let tableMetadata = {};

  let tableDataQuery = 
    "SELECT c.table_name identifier, c.column_name " +
    "FROM information_schema.columns c " +
    "WHERE c.table_schema = current_schema()";

  connectionPool.query(tableDataQuery, (err, res) => {

    console.log(err, res)

    res.rows.forEach((row) => {
      if(tableMetadata.hasOwnProperty(row.identifier)) {
        tableMetadata[row.identifier].push(row.column_name);
      }
      else {
        tableMetadata[row.identifier] = [row.column_name];
      }
    })

    ipcRenderer.send("queryExecutor.queryTableMetadataComplete", {
      "error": err,
      "result": tableMetadata,
      "editorInstanceId": payload.editorInstanceId
    });

  });

});