Featured
PostgreSQL Basics
Pre-shell
Check if installed: psql --version
Check if it is running: sudo service postgresql status
Switch to the postgres user that comes by default on postgres installation (by default no password):
sudo -u postgres -i
Enter the shell: psql
In the shell
Here you can now write RAW SQL queries and do stuff to your dbs.
List out the current databases under postgres user: \l (\q to leave the view)
Create new database: CREATE DATABASE "database_name";
Switch to specified database: \c database_name
Create a new table for authors:
CREATE TABLE authors (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL
);
Create a new table for posts:
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
summary VARCHAR(255) NOT NULL,
body TEXT NOT NULL,
date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
author_id INT NOT NULL
);
Insert into the authors table:
INSERT INTO authors (name, email)
VALUES ('Jane Doe', 'ranchrobe23@gmail.com');
d
Change or add password to account (replace postgres with username used to login to psql): \password postgres
Express + Postgres
pnpm i pg
pnpm i --save @types/pg
create src/data/database.ts and insert:
Make an authors table in your db with: id (int, pk, nn, ai), name (varchar255, nn), email (varchar255, nn)
Now go to src/index.ts and add:
when there is a GET request on localhost:3333/authors, the data will be returned as a json
To see how to set up an Express server with TS, see: https://frontend-lord.blogspot.com/2023/07/typescript-express-setup.html
Comments
Post a Comment