Database
Database
An organized repository of structured data. Divided into relational (RDBMS) and non-relational (NoSQL), and data is efficiently stored, retrieved, modified, and deleted through a DBMS.
Database
An organized repository of structured data. Divided into relational (RDBMS) and non-relational (NoSQL), and data is efficiently stored, retrieved, modified, and deleted through a DBMS.
A database is a collection of systematically structured data, managed through a DBMS (Database Management System). It provides core functions such as persistent data storage for applications, fast retrieval, concurrency control, and data integrity assurance.
Table-based (rows/columns), uses SQL queries, requires schema definition, guarantees ACID transactions. Suited for structured data and complex JOIN operations.
Flexible schema, easy horizontal scaling, BASE properties. Suited for large volumes of unstructured data and high write throughput.
| Characteristics | ACID (Relational) | BASE (NoSQL) |
|---|---|---|
| Consistency | Strong Consistency | Eventual Consistency |
| Availability | Consistency First | Availability First |
| Scaling | Vertical Scaling (Scale-up) | Horizontal Scaling (Scale-out) |
| Suitable Cases | Finance, order systems | Logs, social, IoT |
-- 테이블 생성 (정규화된 스키마)
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
name VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
total_amount DECIMAL(10, 2) NOT NULL,
status VARCHAR(20) DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 인덱스 생성
CREATE INDEX idx_orders_user_id ON orders(user_id);
CREATE INDEX idx_orders_status ON orders(status);
-- CRUD 작업
INSERT INTO users (email, name) VALUES ('user@example.com', '홍길동');
SELECT u.name, COUNT(o.id) AS order_count, SUM(o.total_amount) AS total_spent
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id
HAVING COUNT(o.id) > 0;
// 컬렉션에 문서 삽입
db.users.insertOne({
email: "user@example.com",
name: "홍길동",
profile: {
age: 30,
interests: ["AI", "Database"]
},
orders: [
{ product: "서버", amount: 1000000, date: new Date() }
],
created_at: new Date()
});
// 집계 파이프라인 - 사용자별 총 주문 금액
db.users.aggregate([
{ $unwind: "$orders" },
{ $group: {
_id: "$email",
total_spent: { $sum: "$orders.amount" },
order_count: { $sum: 1 }
}},
{ $sort: { total_spent: -1 } },
{ $limit: 10 }
]);
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
# 데이터베이스 연결
DATABASE_URL = "postgresql://user:password@localhost:5432/mydb"
engine = create_engine(DATABASE_URL)
Session = sessionmaker(bind=engine)
Base = declarative_base()
# 모델 정의
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
email = Column(String(255), unique=True, nullable=False)
name = Column(String(100), nullable=False)
orders = relationship("Order", back_populates="user", lazy="selectin")
class Order(Base):
__tablename__ = 'orders'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
total_amount = Column(Integer)
user = relationship("User", back_populates="orders")
# CRUD 작업
session = Session()
# Create
new_user = User(email="test@example.com", name="테스트")
session.add(new_user)
session.commit()
# Read with relationship (N+1 방지)
users = session.query(User).options(
selectinload(User.orders)
).filter(User.name.like('%테스트%')).all()
# Transaction
try:
session.begin()
user = session.query(User).filter_by(id=1).first()
user.name = "수정된 이름"
session.commit()
except Exception:
session.rollback()
raise
import redis
import json
r = redis.Redis(host='localhost', port=6379, db=0)
# 캐시 패턴: Cache-Aside
def get_user(user_id: int):
cache_key = f"user:{user_id}"
# 1. 캐시 확인
cached = r.get(cache_key)
if cached:
return json.loads(cached)
# 2. DB 조회 (캐시 미스)
user = db.query(User).get(user_id) # SQLAlchemy
# 3. 캐시 저장 (TTL 1시간)
r.setex(cache_key, 3600, json.dumps(user.to_dict()))
return user
# 세션 저장
r.hset("session:abc123", mapping={
"user_id": "1",
"email": "user@example.com",
"login_at": "2024-01-01T00:00:00"
})
r.expire("session:abc123", 86400) # 24시간 만료
Beware of the N+1 problem, where an ORM issues an additional query on every loop iteration when retrieving related data! Use Eager Loading (selectinload, joinedload) or the DataLoader pattern.
The more indexes you have, the slower INSERT/UPDATE becomes. Analyze actual query patterns, create only the indexes you need, and carefully decide the column order of composite indexes (higher selectivity first).
Database connections are an expensive resource. Configure the Connection Pool appropriately, and always return the connection after a query. Long-running transactions hold on to connections, so they should be avoided.