Postgre SQL
Postgre SQL
Akash Pundir
System Programming
School of Computer Science and Engineering
What is a Database?
A database is a structured collection of data
organized for efficient retrieval, storage, and
manipulation. It serves as a central repository for
storing and managing information in a structured
manner.
DBMS (Database Management System)
It is a software system that facilitates the
creation, organization, manipulation, and
administration of databases. DBMS serves as an
interface between users or applications and the
database itself, providing a set of tools and
functionalities for managing data efficiently
PostgresSQL
\l
Connecting to a Specific Database
• To connect to a specific database, use the \c command
\c database_name
Let’s try creating a table
\dt
Describing a Table
• To describe the structure of a specific table, use the \d command:
\d table_name
Viewing Data
• To view data from a table, use a simple SQL query
npm init -y
Install necessary libraries
npm i express pg
Make a new index.js file in the same folder
const express = require('express');
const { Pool } = require('pg');
app.use(express.json());
// GET all todos
app.get('/todos', (req, res) => {
pool.query('SELECT * FROM todos', (error, result) =>
{
if (error) {
console.error('Error fetching todos', error);
res.status(500).json({ error: 'Internal server
error' });
} else {
res.json(result.rows);
}
});
});
// POST a new todo
app.post('/todos', (req, res) => {
const { title, completed } = req.body;
pool.query('INSERT INTO todos (title, completed) VALUES ($1, $2)', [title,
completed], (error) => {
if (error) {
console.error('Error creating todo', error);
res.status(500).json({ error: 'Internal server error' });
} else {
res.status(201).json({ message: 'Todo created successfully' });
}
});
});
// PUT update todo
app.put('/todos/:id', (req, res) => {
const { id } = req.params;
const { title, completed } = req.body;
pool.query('UPDATE todos SET title = $1, completed = $2 WHERE id = $3', [title,
completed, id], (error) => {
if (error) {
console.error('Error updating todo', error);
res.status(500).json({ error: 'Internal server error' });
} else {
res.json({ message: 'Todo updated successfully' });
}
});
});
// DELETE todo
app.delete('/todos/:id', (req, res) => {
const { id } = req.params;
pool.query('DELETE FROM todos WHERE id = $1', [id], (error) => {
if (error) {
console.error('Error deleting todo', error);
res.status(500).json({ error: 'Internal server error' });
} else {
res.json({ message: 'Todo deleted successfully' });
}
});
});
Object Relational Mapping
mkdir sequelize-postgres
cd sequelize-postgres
Initialize a new Node.js project:
npm init -y
Install Sequelize, PostgreSQL, and the pg
driver:
• pg: This is the PostgreSQL client for Node.js. Sequelize uses this
package to communicate with PostgreSQL databases.
module.exports = sequelize;
Define a model:
Create a folder named models in your project directory, and within it,
create a file named Todo.js:
const { DataTypes } = require('sequelize');
const sequelize = require('../sequelize');
module.exports = Todo;
Create an index.js file in your project directory to initialize
Sequelize and synchronize the models with the database:
app.use(express.json());
// Define endpoints
app.get('/todos', (req, res) => {
Todo.findAll()
.then((todos) => {
res.json(todos);
})
.catch((error) => {
res.status(500).json({ error: 'Internal
server error' });
});
});
app.post('/todos', (req, res) => {
const { title, completed } = req.body;
Todo.create({ title, completed })
.then((todo) => {
res.status(201).json(todo);
})
.catch((error) => {
res.status(400).json({ error: 'Bad request' });
});
});
// PUT endpoint to update a todo item
Todo.findByPk(todoId)
.then(todo => {
if (!todo) {
todo.title = title;
todo.completed = completed;
return todo.save();
})
.then(updatedTodo => {
res.json(updatedTodo);
})
.catch(error => {
});
});
// DELETE endpoint to delete a todo item
app.delete('/todos/:id', (req, res) => {
const todoId = req.params.id;
Todo.findByPk(todoId)
.then(todo => {
if (!todo) {
return res.status(404).json({ error: 'Todo not found' });
}