Skip to content

feat: adds new db package with postgres docker image #661

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions lib/db/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
FROM postgres:16-alpine

# Create a directory for initialization scripts
RUN mkdir -p /docker-entrypoint-initdb.d

# Add any initialization scripts if needed
# COPY ./init-scripts/ /docker-entrypoint-initdb.d/

# Set environment defaults (these can be overridden in docker-compose.yml)
ENV POSTGRES_USER=postgres
ENV POSTGRES_PASSWORD=postgres
ENV POSTGRES_DB=mydb

# Expose the PostgreSQL port
EXPOSE 5432

# Set the data directory
VOLUME ["/var/lib/postgresql/data"]

# Set health check command
HEALTHCHECK --interval=5s --timeout=5s --retries=5 \
CMD pg_isready -U postgres || exit 1
100 changes: 100 additions & 0 deletions lib/db/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# PostgreSQL Docker Setup

This directory contains scripts to easily start and stop a PostgreSQL database using Docker.

## Prerequisites

- [Docker](https://www.docker.com/products/docker-desktop/)
- [Docker Compose](https://docs.docker.com/compose/install/) (included in Docker Desktop)

## Default Configuration

- **PostgreSQL Version**: 16 (latest stable)
- **Port**: 5432
- **Username**: postgres
- **Password**: postgres
- **Database**: mydb
- **Data Volume**: postgres_data (persisted between restarts)

## Getting Started

Make the scripts executable:

```bash
chmod +x start-postgres.sh stop-postgres.sh status-postgres.sh
```

### Starting PostgreSQL

```bash
./start-postgres.sh
```

This script will:
1. Start a PostgreSQL container
2. Wait for it to be ready
3. Display connection information

### Checking Status

```bash
./status-postgres.sh
```

This script will show if PostgreSQL is running and display connection details.

### Stopping PostgreSQL

```bash
./stop-postgres.sh
```

This script stops the PostgreSQL container while preserving your data.

## Connection Information

Once the database is running, you can connect to it using:

- **Host**: localhost
- **Port**: 5432
- **Username**: postgres
- **Password**: postgres
- **Database**: mydb

### Connect with psql client:

```bash
psql -h localhost -U postgres -d mydb
```

### Connect from applications:

Connection string format:
```
postgresql://postgres:postgres@localhost:5432/mydb
```

## Customizing the Setup

You can modify the `docker-compose.yml` file to change:

- Database name, username, and password
- Port mappings
- Volume configuration
- Add initialization scripts

## Data Persistence

The database data is stored in a Docker volume named `postgres_data` which persists between container restarts. To completely reset the data, you would need to remove this volume:

```bash
docker volume rm db_postgres_data
```

## Troubleshooting

If you encounter issues, check the container logs:

```bash
docker-compose logs postgres
```
28 changes: 28 additions & 0 deletions lib/db/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
version: '3.8'

services:
postgres:
build:
context: .
dockerfile: Dockerfile
container_name: 25q1_postgres_db
ports:
- "5432:5432"
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: mydb
volumes:
- postgres_data:/var/lib/postgresql/data
# Uncomment to add init scripts
# - ./init-scripts:/docker-entrypoint-initdb.d/
restart: unless-stopped
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5

volumes:
postgres_data:
driver: local
30 changes: 30 additions & 0 deletions lib/db/init-scripts/01-init-sample.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
-- Sample initialization script
-- This will run when the container first initializes

-- Create a sample table
CREATE TABLE IF NOT EXISTS sample_table (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
description TEXT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Insert some sample data
INSERT INTO sample_table (name, description)
VALUES
('Sample 1', 'This is a sample record'),
('Sample 2', 'Another sample record');

-- Create a sample user (with limited privileges)
-- Uncomment if needed
/*
CREATE USER sampleuser WITH PASSWORD 'samplepass';
GRANT CONNECT ON DATABASE mydb TO sampleuser;
GRANT USAGE ON SCHEMA public TO sampleuser;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO sampleuser;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO sampleuser;
*/

-- Note: This script runs on database creation only. If you modify it,
-- you'll need to remove the postgres_data volume to see the changes:
-- docker volume rm db_postgres_data
21 changes: 21 additions & 0 deletions lib/db/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "postgres-docker-setup",
"version": "1.0.0",
"description": "PostgreSQL Docker setup for development",
"main": "index.js",
"scripts": {
"start": "./start-postgres.sh",
"stop": "./stop-postgres.sh",
"status": "./status-postgres.sh",
"reset": "docker-compose down && docker volume rm db_postgres_data || true && ./start-postgres.sh",
"logs": "docker-compose logs -f postgres"
},
"keywords": [
"postgresql",
"postgres",
"docker",
"database"
],
"author": "",
"license": "ISC"
}
46 changes: 46 additions & 0 deletions lib/db/start-postgres.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#!/bin/bash

# Print colorful message
echo -e "\033[0;32m[INFO] Starting PostgreSQL database...\033[0m"

# Navigate to the script directory
cd "$(dirname "$0")"

# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
echo -e "\033[0;31m[ERROR] Docker is not running. Please start Docker and try again.\033[0m"
exit 1
fi

# Start the PostgreSQL container
docker-compose up -d

# Wait for PostgreSQL to be healthy
echo -e "\033[0;33m[INFO] Waiting for PostgreSQL to be ready...\033[0m"
attempt=0
max_attempts=30

while [ $attempt -lt $max_attempts ]; do
if docker-compose exec postgres pg_isready -U postgres > /dev/null 2>&1; then
echo -e "\033[0;32m[SUCCESS] PostgreSQL is ready!\033[0m"
echo -e "\033[0;34m
Connection Information:
Host: localhost
Port: 5432
Username: postgres
Password: postgres
Database: mydb

Connect with psql: psql -h localhost -U postgres -d mydb
\033[0m"
exit 0
fi

attempt=$((attempt+1))
echo -e "\033[0;33m[INFO] Waiting for database to be ready... ($attempt/$max_attempts)\033[0m"
sleep 1
done

echo -e "\033[0;31m[ERROR] Failed to connect to PostgreSQL after $max_attempts attempts.\033[0m"
echo "Check container logs with: docker-compose logs postgres"
exit 1
50 changes: 50 additions & 0 deletions lib/db/status-postgres.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#!/bin/bash

# Print colorful message
echo -e "\033[0;34m[INFO] Checking PostgreSQL database status...\033[0m"

# Navigate to the script directory
cd "$(dirname "$0")"

# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
echo -e "\033[0;31m[ERROR] Docker is not running. Please start Docker and try again.\033[0m"
exit 1
fi

# Get container status
CONTAINER_ID=$(docker-compose ps -q postgres)

if [ -z "$CONTAINER_ID" ]; then
echo -e "\033[0;33m[INFO] PostgreSQL container is not running.\033[0m"
exit 0
fi

# Check if container is running
if docker ps -q --no-trunc | grep -q "$CONTAINER_ID"; then
echo -e "\033[0;32m[INFO] PostgreSQL container is running.\033[0m"

# Check if PostgreSQL is responsive
if docker-compose exec postgres pg_isready -U postgres > /dev/null 2>&1; then
echo -e "\033[0;32m[SUCCESS] PostgreSQL server is accepting connections.\033[0m"

# Display container info
echo -e "\033[0;34m\nContainer Information:\033[0m"
docker ps --filter "id=$CONTAINER_ID" --format "ID: {{.ID}}\nName: {{.Names}}\nStatus: {{.Status}}\nPorts: {{.Ports}}\n"

echo -e "\033[0;34m\nConnection Information:
Host: localhost
Port: 5432
Username: postgres
Password: postgres
Database: mydb

Connect with psql: psql -h localhost -U postgres -d mydb\033[0m"
else
echo -e "\033[0;31m[WARNING] PostgreSQL container is running but the server is not accepting connections.\033[0m"
fi
else
echo -e "\033[0;31m[ERROR] PostgreSQL container exists but is not running.\033[0m"
echo "Container status:"
docker ps -a --filter "id=$CONTAINER_ID" --format "ID: {{.ID}}\nName: {{.Names}}\nStatus: {{.Status}}\n"
fi
24 changes: 24 additions & 0 deletions lib/db/stop-postgres.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/bin/bash

# Print colorful message
echo -e "\033[0;33m[INFO] Stopping PostgreSQL database...\033[0m"

# Navigate to the script directory
cd "$(dirname "$0")"

# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
echo -e "\033[0;31m[ERROR] Docker is not running. Please start Docker and try again.\033[0m"
exit 1
fi

# Stop the PostgreSQL container
docker-compose down

# Check if the stop was successful
if [ $? -eq 0 ]; then
echo -e "\033[0;32m[SUCCESS] PostgreSQL database stopped successfully.\033[0m"
else
echo -e "\033[0;31m[ERROR] Failed to stop PostgreSQL database.\033[0m"
exit 1
fi
56 changes: 56 additions & 0 deletions lib/javascript/fullstack_demo/docs/database-seeding.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Database Seeding Guide

This guide explains how to use the seed script to populate your database with sample data for development and testing.

## What is Database Seeding?

Database seeding is the process of populating a database with initial data. It's particularly useful for:
- Development environments
- Testing
- Providing sample data for demonstrations
- Setting up initial state for applications

## Seed Data Contents

The seed script populates the database with:

- **Todos**: 12 sample todo items spread across 3 different users
- **Logs**: A single log entry recording the seed script execution

## How to Run the Seed Script

You can run the seed script using npm:

```bash
npm run db:seed
```

Or directly using ts-node:

```bash
npx ts-node prisma/seed.ts
```

## When to Run the Seed Script

You should run the seed script:

1. After setting up a fresh database
2. After clearing your development database
3. When you want to reset your database to a known state

## Modifying Seed Data

If you need to modify the seed data, edit the `/prisma/seed.ts` file. The script is structured as follows:

1. Define sample data in arrays
2. Use Prisma Client to insert the data into the database
3. Log the results

Feel free to add more sample data or modify existing data to suit your development needs.

## Important Notes

- The seed script will delete all existing todos before adding new ones
- The script adds a log entry to record its execution
- User IDs are strings and do not need to exist in an authentication system for development purposes
Loading
Loading