-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusage.py
182 lines (144 loc) · 5.29 KB
/
usage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
173
174
175
176
177
178
179
180
181
182
# -*- coding: UTF-8 -*-
"""
Usage
=====
@ Flask SQLAlchemy Compat - Examples
Author
------
Yuchen Jin (cainmagi)
License
-------
MIT License
Description
-----------
The implementation of services based on Flask SQLAlchemy Lite.
"""
try:
from typing import List
except ImportError:
from builtins import list as List
import sqlalchemy as sa
import sqlalchemy.orm as sa_orm
import flask_sqlalchemy_compat as fsc
class _Base(sa_orm.MappedAsDataclass, sa_orm.DeclarativeBase): ...
engine_options = {
"connect_args": {"check_same_thread": False},
"poolclass": sa.pool.StaticPool,
}
# Use either one of the following options to see the performance.
# Use Flask SQLAlchemy style
#
# db = fsc.get_flask_sqlalchemy(_Base, engine_options=engine_options)
# Base = db.Model
# Use Flask SQLAlchemy Lite style
#
db, Base = fsc.get_flask_sqlalchemy_lite(_Base, engine_options=engine_options)
class NewModel(Base):
__tablename__ = "new_model"
id: sa_orm.Mapped[int] = sa_orm.mapped_column(init=False, primary_key=True)
name: sa_orm.Mapped[str] = sa_orm.mapped_column()
# Test many-to-many mapping.
values: sa_orm.Mapped[List["NumericalModel"]] = sa_orm.relationship(
back_populates="model", default_factory=list
)
def __repr__(self):
return "{0}(id={1}, name={2}, n_vals={3})".format(
self.__class__.__name__, self.id, self.name, len(self.values)
)
class NumericalModel(Base):
__tablename__ = "numerical_model"
id: sa_orm.Mapped[int] = sa_orm.mapped_column(init=False, primary_key=True)
value: sa_orm.Mapped[float] = sa_orm.mapped_column()
model_id: sa_orm.Mapped[int] = sa_orm.mapped_column(
sa.ForeignKey("new_model.id", ondelete="cascade"), nullable=False
)
model: sa_orm.Mapped[NewModel] = sa_orm.relationship(back_populates="values")
def __repr__(self):
return "{0}(id={1}, value={2}, model={3})".format(
self.__class__.__name__, self.id, self.value, self.model.name
)
if __name__ == "__main__":
import os
import flask
import logging
logging.basicConfig(
format="%(asctime)s,%(msecs)03d %(name)s %(levelname)s %(message)s",
datefmt="%H:%M:%S",
level=logging.INFO,
)
logger = logging.getLogger("flask-sqlalchemy-compat").getChild("example")
logger.setLevel(logging.INFO)
app = flask.Flask(
__name__,
instance_path=os.path.abspath(
os.path.join(os.path.dirname(__file__), "instance")
),
)
app.config.update(
{
# Only used by Flask SQLAlchemy Lite
"SQLALCHEMY_ENGINES": {"default": "sqlite://"},
# Only used by Flask SQLAlchemy
"SQLALCHEMY_DATABASE_URI": "sqlite://",
}
)
db.init_app(app)
with app.app_context():
Base.metadata.drop_all(db.engine)
Base.metadata.create_all(db.engine)
logger.info("Start to add testing data.")
model = NewModel(name="only-pos")
NumericalModel(value=1, model_id=model.id, model=model)
NumericalModel(value=1.2, model_id=model.id, model=model)
NumericalModel(value=5.5, model_id=model.id, model=model)
db.session.add(model)
model = NewModel(name="only-neg")
NumericalModel(value=-1, model_id=model.id, model=model)
NumericalModel(value=-1.2, model_id=model.id, model=model)
NumericalModel(value=-5.5, model_id=model.id, model=model)
db.session.add(model)
model = NewModel(name="mixed")
NumericalModel(value=1, model_id=model.id, model=model)
NumericalModel(value=1.2, model_id=model.id, model=model)
NumericalModel(value=-5.5, model_id=model.id, model=model)
db.session.add(model)
db.session.commit()
logger.info("Start to query data.")
logger.info("Query by name.")
model = db.session.scalar(sa.select(NewModel).filter(NewModel.name == "mixed"))
assert model is not None
assert model.name == "mixed"
logger.info("Queried: {0}".format(model))
logger.info("Query all models having positive values.")
models = db.session.scalars(
sa.select(NewModel)
.join(NumericalModel, NewModel.values)
.filter(NumericalModel.value > 0)
.group_by(NewModel.id)
).all()
logger.info("Queried: {0}".format(models))
logger.info("Query all models having negative values.")
models = db.session.scalars(
sa.select(NewModel)
.join(NumericalModel, NewModel.values)
.filter(NumericalModel.value < 0)
.group_by(NewModel.id)
).all()
logger.info("Queried: {0}".format(models))
logger.info("Query all models having both positive and negative values.")
sub_q = (
sa.select(NewModel.id)
.join(NumericalModel, NewModel.values)
.filter(NumericalModel.value < 0)
.group_by(NewModel.id)
.scalar_subquery()
)
models = db.session.scalars(
sa.select(NewModel)
.filter(NewModel.id.in_(sub_q))
.join(NumericalModel, NewModel.values)
.filter(NumericalModel.value > 0)
.group_by(NewModel.id)
).all()
logger.info("Queried: {0}".format(models))