[파이썬] SQLAlchemy Base 및 Declarative Base의 이해

SQLAlchemy는 파이썬으로 구현된 인기 있는 ORM(Object Relational Mapping) 라이브러리입니다. SQLAlchemy를 사용하면 데이터베이스 테이블과 객체 지향 프로그래밍 사이의 매핑을 쉽게 구현할 수 있습니다. SQLAlchemy에서는 BaseDeclarative Base라는 두 가지 기본적인 클래스를 제공합니다. 이번 글에서는 이 두 클래스에 대해 자세히 알아보겠습니다.

SQLAlchemy Base

SQLAlchemy의 Base 클래스는 데이터베이스 스키마의 기본적인 추상화를 담당합니다. Base 클래스를 상속하는 클래스를 통해 테이블을 정의합니다. 예를 들어, 다음과 같이 users 테이블을 정의할 수 있습니다:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(String(50))
    email = Column(String(100))

위의 코드에서 Base 클래스는 declarative_base() 함수를 통해 생성됩니다. Base 클래스를 상속받은 User 클래스는 __tablename__ 속성을 통해 테이블의 이름을 지정하고, Column 클래스를 사용하여 각 열을 정의합니다. 이를 통해 SQLAlchemy는 클래스와 테이블 간의 자동 매핑을 수행합니다.

SQLAlchemy Declarative Base

SQLAlchemy의 Declarative Base 클래스는 Base 클래스를 상속하는 것과 동일한 기능을 제공하지만, 보다 간단한 구문으로 테이블을 정의할 수 있습니다. Declarative Base는 클래스를 정의하는 동시에 테이블 이름 및 열 정보를 기술할 수 있습니다. 위의 예시를 Declarative Base로 다시 작성하면 다음과 같습니다:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(String(50))
    email = Column(String(100))

위의 예시를 보면 Base 클래스는 declarative_base() 함수를 통해 생성되고, User 클래스를 정의하는 동시에 __tablename__과 각 열을 기술합니다. Declarative Base를 사용하면 코드를 좀 더 간결하게 작성할 수 있습니다.

결론

SQLAlchemy의 BaseDeclarative Base 클래스는 ORM을 사용하여 데이터베이스 스키마를 추상화할 때 필수적인 도구입니다. Base 클래스는 보다 직접적인 방법으로 테이블을 정의할 수 있게 해주며, Declarative Base 클래스는 구문을 간소화하여 코드 가독성을 높입니다. SQLAlchemy를 사용하여 데이터베이스와 객체 지향 프로그래밍을 효과적으로 매핑할 수 있습니다.