การใช้ SQLite/PostgreSQL กับ Node.js

SQLite คือฐานข้อมูลแบบไฟล์ที่ไม่ต้องติดตั้ง Server เหมาะกับ Development และ Prototype ส่วน PostgreSQL คือฐานข้อมูล Production-grade ที่รองรับ transaction, indexing, JSON, extension และ connection pool ได้ดี

Timeline/ประวัติศาสตร์

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart LR
  subgraph Era1["ยุค Local DB / Embedded"]
    A["SQLite
ฐานข้อมูลในไฟล์เดียว"] end subgraph Era2["ยุค Client-Server DB"] B["PostgreSQL
Server Database"] C["Connection Pool
จัดการหลาย connection"] end subgraph Era3["ยุค Cloud Database"] D["Managed DB
Backup/Scaling"] E["pgAdmin/GUI
จัดการฐานข้อมูล"] end A --> B --> C --> D --> E

แนวคิดสำคัญ

ตารางเปรียบเทียบ SQLite และ PostgreSQL

หัวข้อ SQLite PostgreSQL
รูปแบบ ไฟล์เดียว Server
ติดตั้ง ง่ายมาก ต้องมี service
เหมาะกับ Prototype, test, local Production, concurrent users
Feature พื้นฐานครบ Advanced SQL, JSON, Extension
Connection เปิดไฟล์ Connection pool

Mermaid Diagram: Node.js to PostgreSQL

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart LR
  A["Express API
Node.js Server"] --> B["pg Pool
Connection Pool"] B --> C["Parameterized Query
$1 $2"] C --> D["PostgreSQL
Database Server"] D --> E["Rows
ผลลัพธ์"] E --> A

สมการคณิตศาสตร์: Connection Pool Capacity

C=P×Q

Code Example

// db.mjs
// เชื่อมต่อ PostgreSQL ด้วย pg Pool และ parameterized query
import pg from 'pg';

const { Pool } = pg;

const pool = new Pool({
  connectionString: process.env.DATABASE_URL || 'postgres://postgres:postgres@localhost:5432/course'
});

export async function findUsersByAge(minAge) {
  // ใช้ $1 แทนการต่อ string เพื่อป้องกัน SQL Injection
  const result = await pool.query(
    'SELECT id, name, email FROM users WHERE age > $1 ORDER BY name LIMIT 10',
    [minAge]
  );
  return result.rows;
}

export async function createUser(name, email) {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    const result = await client.query(
      'INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *',
      [name, email]
    );
    await client.query('COMMIT');
    return result.rows[0];
  } catch (error) {
    await client.query('ROLLBACK');
    throw error;
  } finally {
    client.release();
  }
}

// ตัวอย่างการใช้งาน:
// npm install pg
// DATABASE_URL=postgres://user:pass@localhost:5432/db node app.mjs

กิจกรรมท้ายบท

กลับสัปดาห์ที่ 11