53 lines
2.0 KiB
Python
53 lines
2.0 KiB
Python
"""create books table
|
|
|
|
Revision ID: 1234567890ab
|
|
Revises:
|
|
Create Date: 2023-05-25 10:00:00.000000
|
|
|
|
"""
|
|
from alembic import op
|
|
import sqlalchemy as sa
|
|
from sqlalchemy.dialects.postgresql import UUID
|
|
|
|
|
|
# revision identifiers, used by Alembic
|
|
revision = '1234567890ab'
|
|
down_revision = None
|
|
branch_labels = None
|
|
depends_on = None
|
|
|
|
|
|
def upgrade():
|
|
op.create_table(
|
|
'books',
|
|
sa.Column('id', UUID(as_uuid=True), primary_key=True, server_default=sa.text("uuid_generate_v4()")),
|
|
sa.Column('title', sa.String, nullable=False, index=True),
|
|
sa.Column('author', sa.String, nullable=False, index=True),
|
|
sa.Column('description', sa.String, nullable=True),
|
|
sa.Column('author_id', UUID(as_uuid=True), nullable=False),
|
|
sa.Column('created_at', sa.TIMESTAMP(timezone=True), nullable=False, server_default=sa.func.now()),
|
|
sa.Column('updated_at', sa.TIMESTAMP(timezone=True), nullable=False, server_default=sa.func.now(), onupdate=sa.func.now()),
|
|
sa.ForeignKeyConstraint(['author_id'], ['authors.id'], ondelete='CASCADE'),
|
|
)
|
|
op.create_index('idx_books_title_author', 'books', ['title', 'author'], unique=True)
|
|
|
|
|
|
def downgrade():
|
|
op.drop_index('idx_books_title_author', 'books')
|
|
op.drop_table('books')
|
|
|
|
```
|
|
|
|
This Alembic migration script creates a new table called `books` with the following columns:
|
|
|
|
- `id` (UUID, primary key, generated using `uuid_generate_v4()`)
|
|
- `title` (String, not nullable, indexed)
|
|
- `author` (String, not nullable, indexed)
|
|
- `description` (String, nullable)
|
|
- `author_id` (UUID, not nullable, foreign key referencing `authors.id` table with `ON DELETE CASCADE`)
|
|
- `created_at` (TIMESTAMP with timezone, not nullable, default to current time)
|
|
- `updated_at` (TIMESTAMP with timezone, not nullable, default to current time, updated on each row update)
|
|
|
|
It also creates a unique index on the `title` and `author` columns combined.
|
|
|
|
The `downgrade()` function removes the index and drops the `books` table. |