Avg. Reading Time 5 minutes

Setting up PostgreSQL in Linux

PostgreSQL, often referred to as "Postgres," is a powerful, open-source object-relational database management system (RDBMS). It is widely used for handling large-scale data, supporting advanced data types, and ensuring data integrity. Postgres is a popular choice in industries like finance, web development, and data analysis due to its reliability, robust feature set, and active community. With features like transactional integrity, concurrency, and support for modern applications, PostgreSQL is highly regarded for building scalable, secure, and high-performance database systems.


Installing and Setting Up PostgreSQL on Manjaro

Step 1: Install PostgreSQL

First, install PostgreSQL using pacman. Open your terminal and execute the following command:

sudo pacman -S postgresql

Step 2: Initialize the PostgreSQL Database Cluster

After installation, you must initialize the PostgreSQL database cluster. This prepares the system for PostgreSQL to manage its databases. Run:

sudo -iu postgres initdb -D /var/lib/postgres/data

Step 3: Start and Enable PostgreSQL Service

To start the PostgreSQL service and ensure it starts automatically on boot, use the following commands:

sudo systemctl start postgresql
sudo systemctl enable postgresql

Step 4: Verify Installation

To verify that PostgreSQL is running correctly, switch to the postgres user:

sudo -iu postgres

Then, connect to the default PostgreSQL environment using the psql command-line tool:

psql

This should open the PostgreSQL interactive terminal. If successful, you’ll see something like this:

psql (13.4)
Type "help" for help.

postgres=#

To exit, simply type:

\q

At this point, PostgreSQL is installed, running, and confirmed on your Manjaro system.

Creating a PostgreSQL User and Database on Manjaro

Step 1: Access PostgreSQL as the postgres User

To create a new user and database, first switch to the postgres user and open the PostgreSQL interactive terminal:

sudo -u postgres psql

Step 2: Create a New User

Inside the PostgreSQL prompt, create a new user with a password using the following SQL command:

CREATE USER your_username WITH PASSWORD 'your_password';

Step 3: Create a New Database

Now, create a database and assign ownership to the newly created user:

CREATE DATABASE your_database_name OWNER your_username;

Step 4: Verify the User and Database

To verify that the user and database have been created, you can list all databases:

\l

You should see your new database in the list. Additionally, you can list users and roles with:

\du

Step 5: Exit the PostgreSQL Terminal

To exit the PostgreSQL prompt, type:

\q

Local PostgreSQL Connection String

After creating a user and database, you’ll need to know how to connect to your PostgreSQL instance. The connection string provides the details for connecting to the database from an application or the psql terminal.

Here’s what a typical local PostgreSQL connection string looks like:

postgres://your_username:your_password@localhost:5432/your_database_name

Breakdown of the Connection String

  • postgres:// – The protocol used to connect to the PostgreSQL database.
  • your_username – The username you created for accessing the database.
  • your_password – The password for the user.
  • localhost – The server where PostgreSQL is running. Since it's a local setup, localhost points to your machine.
  • 5432 – The default port PostgreSQL listens on. Unless you’ve changed it, this is the standard.
  • your_database_name – The name of the database you created.

Example

If you created a user named kushagra with the password mypassword and a database named mydb, the connection string would be:

postgres://kushagra:mypassword@localhost:5432/mydb

Using the Connection String in psql

You can connect to your PostgreSQL database using psql and the connection string as follows:

psql postgres://your_username:your_password@localhost:5432/your_database_name

Example:

psql postgres://kushagra:mypassword@localhost:5432/mydb

This command will directly connect you to the specified database using the provided user credentials.


Tips:

  1. Store connection strings in environment variables for security purposes.
  2. Use PGPASSWORD in scripts to avoid exposing passwords in connection strings.
  3. For remote connections, replace localhost with the server's IP address.

Setting Up PostgreSQL in Various Frameworks

Now that we have a PostgreSQL database set up locally, let's see how to connect and configure it in different frameworks and environments like Django, Next.js (React), and Express with Node.js.

1. Setting Up PostgreSQL in Django

Django provides built-in support for PostgreSQL through its ORM. Follow these steps to configure your local PostgreSQL database.

Step 1: Install PostgreSQL Driver for Python

Install psycopg2 for PostgreSQL connectivity in Django:

pip install psycopg2

Step 2: Configure settings.py

In your Django project, open settings.py and modify the DATABASES section:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'your_database_name',
        'USER': 'your_username',
        'PASSWORD': 'your_password',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

Replace your_database_name, your_username, and your_password with your actual PostgreSQL credentials.

Step 3: Apply Migrations

Run the migrations to create the required tables:

python manage.py migrate

Your Django project is now connected to PostgreSQL.


2. Setting Up PostgreSQL in Next.js (React)

Next.js does not natively include a backend for database interaction, so you’ll typically use a Node.js backend or an ORM like Prisma.

Step 1: Install pg and prisma Packages

First, install the PostgreSQL package (pg) and Prisma ORM in your Next.js project:

npm install pg @prisma/client

Step 2: Configure prisma/schema.prisma

Create a prisma/schema.prisma file and configure it with the PostgreSQL connection string:

datasource db {
  provider = "postgresql"
  url      = "postgresql://your_username:your_password@localhost:5432/your_database_name"
}

Replace with your actual PostgreSQL details.

Step 3: Generate Prisma Client

Run the following commands to generate the Prisma client:

npx prisma generate

Now you can use Prisma to interact with your PostgreSQL database in your Next.js application.


3. Setting Up PostgreSQL in Express (Node.js)

Express, a Node.js framework, allows seamless integration with PostgreSQL using the pg library.

Step 1: Install pg Package

Install the pg package in your Node.js project:

npm install pg

Step 2: Set Up PostgreSQL Connection

In your Express app, create a connection to the PostgreSQL database:

const { Pool } = require('pg');

const pool = new Pool({
  user: 'your_username',
  host: 'localhost',
  database: 'your_database_name',
  password: 'your_password',
  port: 5432,
});

pool.connect((err) => {
  if (err) {
    console.error('Error connecting to PostgreSQL', err);
  } else {
    console.log('Connected to PostgreSQL');
  }
});

This sets up a connection pool that allows your Express app to interact with PostgreSQL.


4. Setting Up PostgreSQL in Node.js (without Express)

In a simple Node.js application, you can directly use the pg package without any framework.

Step 1: Install pg

Like before, install the pg package:

npm install pg

Step 2: Connect to PostgreSQL

Use the following code to set up a connection in Node.js:

const { Client } = require('pg');

const client = new Client({
  user: 'your_username',
  host: 'localhost',
  database: 'your_database_name',
  password: 'your_password',
  port: 5432,
});

client.connect((err) => {
  if (err) {
    console.error('Error connecting to PostgreSQL', err);
  } else {
    console.log('Connected to PostgreSQL');
  }
});

This code establishes a direct connection to the PostgreSQL database and can be used in your Node.js application.


Tips:

  1. Always store sensitive data like credentials in environment variables using tools like dotenv.
  2. For ORM solutions, explore Prisma (Next.js), Sequelize (Node.js), and Django's ORM for abstracted database management.
  3. Use connection pooling (like with pg.Pool) for efficient database connections in Node.js and Express apps.