Below is a complete SQLAlchemy ORM model for the provided PostgreSQL tables. I'll first explain the key points, then provide the Python code.
Key Points:
-
Custom Composite Type (agreement_content_type):
- This is a PostgreSQL composite type with three fields:
primary_key (TEXT), secondary_key (TEXT, nullable), and value (TEXT).
- In SQLAlchemy, we use the
COMPOSITE type from sqlalchemy.dialects.postgresql to represent this. This allows us to define the structure of the composite type and use it in an array.
-
Table (Agreement_Templates):
- This table has various columns, including an array of the composite type (
agreement_content).
- We'll use SQLAlchemy's
declarative_base to define the model class.
- For defaults:
- Use
server_default for database-level defaults (e.g., NOW() for timestamps and '1.0.0' for version).
- For the array column (
agreement_content), we'll set a server default to an empty array ('{}'), which is PostgreSQL-specific.
- Data types:
VARCHAR(50) maps to String(50).
TEXT maps to Text.
TIMESTAMPTZ maps to DateTime(timezone=True).
-
Dependencies:
- You'll need to install SQLAlchemy and a PostgreSQL driver like
psycopg2 or psycopg2-binary. You can do this via pip: pip install SQLAlchemy psycopg2-binary.
- Ensure your PostgreSQL database is set up with the custom type and table already created, as SQLAlchemy doesn't handle schema creation for custom types out of the box.
-
How to Use:
- Create a database engine and session (e.g., using
create_engine from SQLAlchemy).
- You can query, insert, and update records using this model. For example, when accessing
agreement_content, it will be a list of composite objects, each with attributes like primary_key, secondary_key, and value.
Now, here's the Python code:
import sqlalchemy as sa
from sqlalchemy import Column, String, Text, DateTime, func
from sqlalchemy.dialects.postgresql import COMPOSITE, ARRAY as PG_ARRAY
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql import text
# Create the base class for declarative models
Base = declarative_base()
# Define the composite type for agreement_content_type
# This matches the PostgreSQL composite type structure
AgreementContentType = COMPOSITE(
'agreement_content_type', # The name of the PostgreSQL type
[
Column('primary_key', String), # TEXT in PostgreSQL
Column('secondary_key', String, nullable=True), # TEXT, optional (can be NULL)
Column('value', String) # TEXT in PostgreSQL
]
)
# Define the ORM model for the Agreement_Templates table
class AgreementTemplates(Base):
__tablename__ = 'Agreement_Templates'
Agreement_Template_id = Column(String(50), primary_key=True)
title = Column(Text, nullable=False)
version = Column(Text, nullable=False, server_default='1.0.0') # Default as per table
html_template_path = Column(Text) # Nullable by default
html_template_name = Column(Text) # Nullable by default
css_template_path = Column(Text) # Nullable by default
css_template_name = Column(Text) # Nullable by default
pdf_output_path = Column(Text) # Nullable by default
pdf_output_name = Column(Text) # Nullable by default
agreement_content = Column(
PG_ARRAY(AgreementContentType), # Array of the composite type
nullable=False,
server_default=text("'{}'") # Default to an empty array
)
date_created = Column(
DateTime(timezone=True), # TIMESTAMPTZ
nullable=False,
server_default=func.now() # Default to NOW()
)
date_updated = Column(
DateTime(timezone=True), # TIMESTAMPTZ
nullable=False,
server_default=func.now() # Default to NOW()
)
# Optional: Add a __repr__ method for better debugging
def __repr__(self):
return f"<AgreementTemplates(Agreement_Template_id={self.Agreement_Template_id}, title={self.title})>"
Explanation of the Code:
Example Usage:
Here's a quick example of how to use this model:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# Create an engine (replace with your database URL)
engine = create_engine('postgresql://user:password@localhost/dbname')
# Create the tables if they don't exist (this will create the ORM tables, but not the custom type)
Base.metadata.create_all(engine)
# Create a session
Session = sessionmaker(bind=engine)
session = Session()
# Example: Insert a new record
new_agreement = AgreementTemplates(
Agreement_Template_id='template1',
title='Sample Agreement',
# agreement_content will default to an empty array if not provided
agreement_content=[ # This is a list of composite objects
AgreementContentType(primary_key='key1', secondary_key='subkey1', value='value1'),
AgreementContentType(primary_key='key2', value='value2') # secondary_key can be omitted/None
]
)
session.add(new_agreement)
session.commit()
# Example: Query a record
agreement = session.query(AgreementTemplates).filter_by(Agreement_Template_id='template1').first()
print(agreement.title) # Output: Sample Agreement
print(agreement.agreement_content[0].primary_key) # Output: key1
Notes:
- Custom Type Handling: If you're using an ORM session, SQLAlchemy will handle the composite type automatically when inserting or querying. However, ensure the PostgreSQL type is already created in your database schema.
- Error Handling: In a production environment, add try-except blocks for database operations.
- Updates to
date_updated: The table defines date_updated with only a default (set on insert). If you want it to update automatically on each record update, you'll need to handle that in your application code (e.g., set it manually before committing) or use a PostgreSQL trigger.
- Limitations: SQLAlchemy's support for composite types is robust but requires the PostgreSQL dialect. If you encounter issues, ensure your SQLAlchemy version is up-to-date (e.g., 1.4+).
This should give you a fully functional ORM model. Let me know if you need any modifications!