[파이썬] Peewee 데이터베이스 introspection

Peewee is a simple and lightweight ORM (Object Relational Mapper) for Python, designed to make working with databases easy and efficient. One of the powerful features of Peewee is the ability to perform database introspection, which allows you to gather information about the structure and properties of your database tables.

Introspection in Peewee can be particularly useful when you need to retrieve information about the columns, data types, primary keys, and constraints in your database tables. This information can be used for a variety of purposes, such as generating dynamic SQL queries, building data dictionaries, or performing data validation.

Retrieving Table and Column Information

To retrieve information about the tables and columns in your database using Peewee, you can make use of the get_columns() and get_tables() methods provided by the Database object.

Here’s an example of how you can use these methods to retrieve the column information for a specific table:

from peewee import MySQLDatabase, Model

# Define your database connection
database = MySQLDatabase('my_database', user='my_username', password='my_password', host='localhost')

# Define a base model for all your tables
class BaseModel(Model):
    class Meta:
        database = database

# Define your specific database table model
class MyTable(BaseModel):
    name = CharField()
    age = IntegerField()
    email = CharField(unique=True)

# Connect to the database
database.connect()

# Get the columns for the MyTable table
columns = database.get_columns(MyTable)

# Loop through and print information about each column
for column in columns:
    print(f"Column Name: {column.name}")
    print(f"Data Type: {column.data_type}")
    print(f"Is Primary Key: {column.is_primary_key}")
    print(f"Is Unique: {column.is_unique}")
    print(f"Constraints: {column.constraints}")

The get_columns() method returns a list of ColumnMetadata objects, which contain information about the columns in the specified table. You can access various properties of a ColumnMetadata object, such as the column name, data type, whether it is a primary key, whether it is unique, and any constraints applied to it.

Similarly, the get_tables() method can be used to retrieve a list of table names in the database:

tables = database.get_tables()
for table in tables:
    print(f"Table Name: {table}")

Conclusion

Database introspection is a powerful feature provided by Peewee that allows you to gather information about your database tables and columns. By leveraging this feature, you can dynamically work with your database structure, generate dynamic queries, and perform data validation with ease.

Peewee’s introspection capabilities, combined with its simplicity and efficiency, make it a great choice for working with databases in Python projects.