Create a SQLAlchemy /Python ORM Model for the following PostgreSQL Tables. Use typedecoartor to create the composite type: CREATE TYPE agreement_content_type AS (
primary_key TEXT,
secondary_key TEXT, #Optional, so it can be NULL
value TEXT
);
Create the main table for agreements
CREATE TABLE Agreement_Templates (
Agreement_Template_id VARCHAR(50) PRIMARY KEY,
title TEXT NOT NULL,
version TEXT NOT NULL DEFAULT '1.0.0', #-- Automatically generated once, so we set a default
html_template_path TEXT,
html_template_name TEXT,
css_template_path TEXT,
css_template_name TEXT,
pdf_output_path TEXT,
pdf_output_name TEXT,
agreement_content agreement_content_type[] NOT NULL DEFAULT '{}',
date_created TIMESTAMPTZ NOT NULL DEFAULT NOW(),
date_updated TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is a compact but fully-working SQLAlchemy model that
• generates the composite type with DDL,
• exposes that composite to Python through a TypeDecorator, and
• stores an ARRAY of that composite in the table exactly like your DDL.
You can copy / paste the whole file and run it (SQLAlchemy ≥ 1.4, Python ≥ 3.8).
python
# models.py
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Optional, List
from sqlalchemy import (
Column,
String,
Text,
DateTime,
func,
text,
event,
DDL,
)
from sqlalchemy.orm import declarative_base
from sqlalchemy.types import TypeDecorator, UserDefinedType
from sqlalchemy.dialects.postgresql import ARRAY
Base = declarative_base()
# ───────────────────────────────────────────────────────────────
# 1. Python representation of one composite element
# ───────────────────────────────────────────────────────────────
@dataclass
class AgreementContent:
primary_key: str
secondary_key: Optional[str]
value: str
# ───────────────────────────────────────────────────────────────
# 2. TypeDecorator that translates <-> PostgreSQL composite
# We will later embed it in an ARRAY.
# ───────────────────────────────────────────────────────────────
class AgreementContentType(TypeDecorator):
"""
SQLAlchemy ⇄ PostgreSQL adapter for `agreement_content_type`.
Uses AgreementContent dataclass instances on the Python side and
native composite values on the PostgreSQL side.
"""
impl = UserDefinedType()
cache_ok = True # SQLAlchemy 1.4+ optimisation
# ---------- Tell SQLAlchemy what the underlying PG type is ----------
def get_col_spec(self, **kw): # called when emitting CREATE TABLE
return "agreement_content_type"
# ---------- How Python → DB happens ----------
def bind_processor(self, dialect):
def process(value: AgreementContent | None):
"""
Accepts a *single* AgreementContent, not the whole ARRAY.
SQLAlchemy / psycopg2 will still wrap this in an array for us.
We return the textual composite representation ( (a,b,c) ).
"""
if value is None:
return None
sec = value.secondary_key or '' # NULL → empty string in composite text
return f"({value.primary_key},{sec},{value.value})"
return process
# ---------- How DB → Python happens ----------
# When inside an ARRAY, psycopg2 gives us the composite as a *string*,
# so we do a tiny regex parse. When used standalone it may be a tuple.
_parse = re.compile(r'^\((.*?),(.*?),(.*?)\)$')
def result_processor(self, dialect, coltype):
def process(value):
if value is None:
return None
# psycopg2 will usually hand us a tuple if not array-nested
if isinstance(value, tuple):
pk, sk, v = value
return AgreementContent(pk, sk or None, v)
# else treat it like raw "text form" of composite
m = self._parse.match(value)
if not m:
return None
pk, sk, v = m.groups()
sk = sk or None
return AgreementContent(pk, sk, v)
return process
# ───────────────────────────────────────────────────────────────
# 3. AgreementTemplate ORM model
# ───────────────────────────────────────────────────────────────
class AgreementTemplate(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=text("'1.0.0'"))
html_template_path = Column(Text)
html_template_name = Column(Text)
css_template_path = Column(Text)
css_template_name = Column(Text)
pdf_output_path = Column(Text)
pdf_output_name = Column(Text)
# <─── HERE: ARRAY of composite values
agreement_content = Column(
ARRAY(AgreementContentType),
nullable=False,
server_default=text("'{}'")
)
date_created = Column(DateTime(timezone=True),
nullable=False, server_default=func.now())
date_updated = Column(DateTime(timezone=True),
nullable=False, server_default=func.now(),
onupdate=func.now())
# helper for Python-side convenience
def add_content(self, primary_key: str, value: str,
secondary_key: Optional[str] = None):
self.agreement_content = (self.agreement_content or []) + [
AgreementContent(primary_key, secondary_key, value)
]
def __repr__(self) -> str: # nice debugging
return (f"<AgreementTemplate id={self.agreement_template_id!r} "
f"title={self.title!r} version={self.version!r}>")
# ───────────────────────────────────────────────────────────────
# 4. Automatically create the composite type BEFORE tables
# ───────────────────────────────────────────────────────────────
_create_composite = DDL("""
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_type WHERE typname = 'agreement_content_type'
) THEN
CREATE TYPE agreement_content_type AS (
primary_key TEXT,
secondary_key TEXT,
value TEXT
);
END IF;
END$$;
""")
# Fire the DDL only for PostgreSQL
event.listen(Base.metadata, "before_create",
_create_composite.execute_if(dialect="postgresql"))
How to use
python
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import Base, AgreementTemplate, AgreementContent
engine = create_engine("postgresql+psycopg2://user:pass@localhost/dbname")
Base.metadata.create_all(engine) # ← runs the composite DDL too
Session = sessionmaker(bind=engine, expire_on_commit=False)
session = Session()
tpl = AgreementTemplate(
agreement_template_id="T-001",
title="NDA Standard v1"
)
tpl.add_content("party1", "ACME Inc.")
tpl.add_content("party2", "John Doe")
tpl.add_content("terms", "These are the terms…", secondary_key=None)
session.add(tpl)
session.commit()