PostgreSQL UPSERT
Example SQL Syntax:
INSERT INTO student (id, name)
VALUES (5, 'Nasohi Ciptandani')
ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name;
Example Node.js code
queries.js file:
const Pool = require('pg').Pool
const pool = new Pool({
user: 'monitoring',
host: 'localhost',
database: 'monitoring',
password: 'p4ssw0rd',
port: 5432,
})
pool.query("DELETE FROM linux_server_status", (error, results) => {
console.log(error, results);
});
const createLinux = (request, response) => {
const {hostname, ip, os, hdd_total, hdd_used, hdd_free, mem_total, mem_free, mem_used, core } = request.body
const now = new Date();
pool.query('INSERT INTO linux_server_status (hostname, ip, os, hdd_total, hdd_used, hdd_free, mem_total, mem_free, mem_used, core, last_update) VALUES ($1, $2, $3, $4 , $5, $6, $7, $8, $9, $10, $11) ON CONFLICT (HOSTNAME) DO UPDATE SET ip = $2, os = $3, hdd_total = $4, hdd_used = $5, hdd_free = $6, mem_total = $7, mem_free = $8, mem_used = $9, core = $10, last_update = $11 ', [hostname, ip, os, hdd_total, hdd_used, hdd_free, mem_total, mem_free, mem_used, core, now], (error, results) => {
console.log(error, results);
response.send("OK");
});
}
module.exports = {
createLinux,
}
https://www.postgresql.org/docs/9.5/sql-insert.html
https://www.alibabacloud.com/help/doc-detail/52951.htm
INSERT INTO student (id, name)
VALUES (5, 'Nasohi Ciptandani')
ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name;
Example Node.js code
queries.js file:
const Pool = require('pg').Pool
const pool = new Pool({
user: 'monitoring',
host: 'localhost',
database: 'monitoring',
password: 'p4ssw0rd',
port: 5432,
})
pool.query("DELETE FROM linux_server_status", (error, results) => {
console.log(error, results);
});
const createLinux = (request, response) => {
const {hostname, ip, os, hdd_total, hdd_used, hdd_free, mem_total, mem_free, mem_used, core } = request.body
const now = new Date();
pool.query('INSERT INTO linux_server_status (hostname, ip, os, hdd_total, hdd_used, hdd_free, mem_total, mem_free, mem_used, core, last_update) VALUES ($1, $2, $3, $4 , $5, $6, $7, $8, $9, $10, $11) ON CONFLICT (HOSTNAME) DO UPDATE SET ip = $2, os = $3, hdd_total = $4, hdd_used = $5, hdd_free = $6, mem_total = $7, mem_free = $8, mem_used = $9, core = $10, last_update = $11 ', [hostname, ip, os, hdd_total, hdd_used, hdd_free, mem_total, mem_free, mem_used, core, now], (error, results) => {
console.log(error, results);
response.send("OK");
});
}
module.exports = {
createLinux,
}
index.js file:
var express = require("express");
var myParser = require("body-parser");
const db = require('./queries');
var app = express();
app.use(myParser.urlencoded({extended : true}));
app.use(myParser.json());
app.post("/form", db.createLinux);
app.listen(3000);
https://www.postgresql.org/docs/9.5/sql-insert.html
https://www.alibabacloud.com/help/doc-detail/52951.htm
Komentar