Database View
A view in SQL is like a virtual table that you create using a SQL query. It doesn't store data itself but pulls it from one or more actual tables whenever you use it. Here’s why you might use a view:
- Simplify Complex Queries: Instead of writing the same complicated joins or filters every time, you define them once in a view and just select from the view.
- Improve Security: You can restrict what data users see by only exposing certain columns or rows through the view, keeping sensitive information hidden.
- Enhance Maintainability: If the underlying table structure changes, you can update the view without having to change all the queries that use it.
- Consistency: Ensure that everyone is using the same logic to access data, reducing errors and inconsistencies.
In short, views make your SQL work cleaner, safer, and easier to manage.
CreateView ¶
Bases: DDLElement
A CREATE VIEW statement, usually useful when using in migrations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name |
str
|
The name of the view. |
required |
selectable |
Select
|
The select statement to be used as the view. |
required |
Example
Source code in naked_sqla/view.py
DropView ¶
Bases: DDLElement
A DROP VIEW statement, usually useful when using in migrations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name |
The name of the view. |
required | |
cascade |
Whether to drop the view with cascade or not. |
False
|
|
if_exists |
Whether to drop the view if it exists or not. |
False
|
Example
Source code in naked_sqla/view.py
init_view_in_base ¶
Calling this function is required to allow a declarative base to have views as tables. Look at the example below to see how to use it.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cls |
Type[DeclarativeBase]
|
The declarative base class to be initialized. |
required |
Example
Source code in naked_sqla/view.py
view_table ¶
Create a view table.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name |
The name of the view. |
required | |
metadata |
The metadata object to bind the view to. |
required | |
selectable |
The select statement to be used as the view. |
required | |
cascade |
Whether to drop the view with cascade or not. |
True
|
Example
from datetime import datetime
from uuid import uuid4
import sqlalchemy as sa
from sqlalchemy.orm import DeclarativeBase, Mapped, MappedAsDataclass, mapped_column
from naked_sqla.view import init_view_in_base, view_table
class BaseSQL(MappedAsDataclass, DeclarativeBase):
def __init_subclass__(
cls,
*args,
**kw,
) -> None:
init_view_in_base(cls)
super().__init_subclass__(*args, **kw)
class Event(BaseSQL):
__tablename__ = "Events"
event: Mapped[str] = mapped_column(sa.String())
created_at: Mapped[datetime] = mapped_column(sa.DateTime(timezone=True))
id: Mapped[str] = mapped_column(
primary_key=True, default_factory=lambda: str(uuid4())
)
author_id: Mapped[str] = mapped_column(
primary_key=True, default_factory=lambda: str(uuid4())
)
def event_period_view_query():
event_transitions = sa.select(
Event.author_id,
Event.event,
Event.created_at,
sa.func.lead(Event.created_at)
.over(
partition_by=Event.author_id,
order_by=Event.created_at,
)
.label("next_created_at"),
).subquery()
event_periods = sa.select(
event_transitions.c.author_id,
event_transitions.c.event,
event_transitions.c.created_at.label("start_datetime"),
sa.func.coalesce(event_transitions.c.next_created_at, sa.func.now()).label(
"end_datetime"
),
).select_from(event_transitions)
return event_periods
class EventPeriod(BaseSQL):
__tablename__ = "EventPeriods"
__table__ = view_table(__tablename__, BaseSQL.metadata, event_period_view_query())
author_id: Mapped[str]
event: Mapped[str]
start_datetime: Mapped[datetime]
end_datetime: Mapped[datetime]
Source code in naked_sqla/view.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
|