-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimulation.js
68 lines (56 loc) · 2.4 KB
/
simulation.js
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
const { Pool } = require('pg');
require('dotenv').config();
async function runSimulation() {
// Create a new Pool object to handle connections to Postgres
const pool = new Pool({
user: process.env.POSTGRES_USER,
host: process.env.POSTGRES_HOST,
database: process.env.POSTGRES_DB,
password: process.env.POSTGRES_PW,
port: process.env.POSTGRES_PORT,
});
try {
// Create the "mytable" table if it doesn't already exist
const createTableQuery = `CREATE TABLE IF NOT EXISTS mytable (
id BIGINT PRIMARY KEY,
mystring VARCHAR(255) NOT NULL,
datetime TIMESTAMP NOT NULL
)`;
await pool.query(createTableQuery);
// Get the number of rows in the "mytable" table before inserting a new row
const countBeforeQuery = 'SELECT COUNT(*) FROM mytable';
const { rows: rowsBefore } = await pool.query(countBeforeQuery);
console.log(`Number of rows before: ${rowsBefore[0].count}`);
// Generate a unique identifier using the current timestamp
const id = parseInt(Date.now());
const mystring = `mykey_${new Date().getTime()}`;
// Get the current datetime in ISO format
const datetime = new Date().toISOString();
// Insert a new row into the "mytable" table with the generated id and current datetime
const insertQuery = `INSERT INTO mytable (id, mystring, datetime) VALUES ($1, $2, $3)`;
const values = [id, mystring, datetime];
await pool.query(insertQuery, values);
// Retrieve the value of the inserted row and print it to the console
const selectQuery = `SELECT * FROM mytable WHERE id = $1`;
const { rows: insertedRow } = await pool.query(selectQuery, [id]);
console.log(insertedRow[0]);
// Get the number of rows in the "mytable" table after inserting a new row
const countAfterQuery = 'SELECT COUNT(*) FROM mytable';
const { rows: rowsAfter } = await pool.query(countAfterQuery);
console.log(`Number of rows after: ${rowsAfter[0].count}`);
// Retrieve all rows in the "mytable" table
const selectAllQuery = 'SELECT * FROM mytable';
const { rows: allRows } = await pool.query(selectAllQuery);
// Create an array of objects representing each row
const rows = allRows.map(row => {
return { id: row.id, datetime: row.datetime };
});
console.log(rows);
} catch (error) {
console.error(error);
} finally {
// End the connection pool
await pool.end();
}
}
runSimulation();