-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql.py
More file actions
292 lines (243 loc) · 10.8 KB
/
Copy pathsql.py
File metadata and controls
292 lines (243 loc) · 10.8 KB
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
from datetime import datetime
from enum import Enum
from sqlalchemy import text, RowMapping, bindparam
from sqlalchemy.dialects.mysql import dialect
from connector import DataBase
class DesignCase(Enum):
NEW = 'NEW'
DISABLED = 'DISABLED'
CHANGES = 'CHANGES'
ENABLE = 'ENABLE'
class Conn(DataBase):
local_cache = {}
def get_producttype_info(self, producttype: str) -> dict:
"""Получает информацию о типе продукта по его ключу.
Args:
producttype: Ключ типа продукта (tkey)
Returns:
Словарь с информацией о продукте, содержащий:
- id: идентификатор типа продукта
- tkey: ключ типа продукта
- name_1: название продукта
- price: цена продукта
- sex: половая принадлежность
- model_id: ID основной модели
Если продукт не найден, возвращает пустой словарь.
"""
query = """
SELECT
pt.id,
pt.tkey,
pt.name_1,
pt.price,
pt.sex,
(
SELECT m.model_id
FROM models m
WHERE m.producttype_id = pt.id
AND m.is_active = 1
ORDER BY m.position ASC
LIMIT 1
) AS model_id
FROM producttype pt
WHERE pt.tkey = :producttype
AND pt.active = 'Y'
"""
params = {'producttype': producttype}
if result := self.local_cache.get(producttype):
return result
with self._session() as session:
result = session.execute(text(query), params).mappings().first()
if not result:
return {}
self.local_cache.update({producttype: dict(result)})
return dict(result)
# 14400 секунд = 4 часа
def get_models_list(self, product_type_id: int) -> list[RowMapping]:
"""Возвращает список моделей для указанного типа продукта с информацией о расположении принта.
Args:
product_type_id: Идентификатор типа продукта
Returns:
Список словарей с ключами:
- model_id: идентификатор модели
- printfield_type_id: расположение принта ('front' или 'back')
"""
query = """
SELECT
model_id,
CASE
WHEN printfield_type_id = 1 THEN 'front'
ELSE 'back'
END AS printfield_type_id
FROM models
WHERE producttype_id = :product_type_id
AND is_active = 1
ORDER BY position ASC;
"""
params = {'product_type_id': product_type_id}
if result := self.local_cache.get(product_type_id):
return result
with self._session() as session:
result = session.execute(text(query), params).mappings().all()
if not result:
return []
self.local_cache.update({product_type_id: result})
return result
def get_product_data(self, case: DesignCase, limit: int | None = None, date: datetime = None) -> list[dict]:
"""Получает данные о продуктах из базы данных"""
sub_query = ''
match case:
case DesignCase.NEW:
sub_query = self._case_new(limit=limit, date=date)
case DesignCase.DISABLED:
sub_query = self._case_disabled(limit=limit, date=date)
case DesignCase.CHANGES:
sub_query = self._case_changes(limit=limit, date=date)
case DesignCase.ENABLE:
sub_query = self._case_enable(limit)
print('собираю включенные дизайны')
if sub_query:
query = f"""
SELECT t.theme_id as design_id,
(SELECT pt.tkey
FROM producttype pt
JOIN theme_has_producttype thp ON pt.id = thp.producttype_id
WHERE thp.theme_id = t.theme_id
AND pt.active = 'Y'
LIMIT 1) as product_type,
(SELECT c.tkey
FROM color c
JOIN color_has_producttype chp ON c.id = chp.color_id
JOIN producttype pt ON chp.producttype_id = pt.id
JOIN theme_has_producttype thp ON pt.id = thp.producttype_id
WHERE thp.theme_id = t.theme_id
LIMIT 1) as color_alias
FROM ({sub_query}) t
"""
with self._session() as session:
print(query)
result = session.execute(text(query)).mappings().all()
return [dict(row) for row in result]
return []
@staticmethod
def _case_enable(limit: int | None = None) -> str:
"""Возвращает SQL-запрос для получения всех активных дизайнов, отображаемых на сайте.
Args:
limit: Максимальное количество возвращаемых записей (None - без ограничения)
Returns:
Строка с SQL-запросом
"""
params = [bindparam("limit", value=limit)]
sub_query = f"""
SELECT DISTINCT theme_id
FROM theme_has_producttype
JOIN catalog
ON theme_has_producttype.theme_id = catalog.id
AND catalog.active = 'Y'
AND catalog.show_site = 'Y'
WHERE theme_has_producttype.active = 1
LIMIT :limit
"""
sub_query = text(sub_query).bindparams(*params)
sub_query = sub_query.compile(
dialect=dialect(),
compile_kwargs={"literal_binds": True},
)
return str(sub_query)
@staticmethod
def _case_new(date: datetime, limit: int | None = None) -> str:
"""Возвращает SQL-запрос для получения новых дизайнов, созданных после указанной даты.
Args:
date: Дата, начиная с которой искать новые дизайны
limit: Максимальное количество возвращаемых записей (None - без ограничения)
Returns:
Строка с SQL-запросом
"""
if not date:
return ""
params = [
bindparam("limit", value=limit),
bindparam("date", value=date)
]
sub_query = f"""
SELECT DISTINCT theme_id
FROM theme_has_producttype
JOIN catalog
ON theme_has_producttype.theme_id = catalog.id
AND catalog.active = 'Y'
AND catalog.show_site = 'Y'
AND catalog.moderate_at >= :date
WHERE theme_has_producttype.active = 1
LIMIT :limit
"""
sub_query = text(sub_query).bindparams(*params)
sub_query = sub_query.compile(
dialect=dialect(),
compile_kwargs={"literal_binds": True},
)
return str(sub_query)
@staticmethod
def _case_disabled(date: datetime = datetime.now(), limit: int | None = None) -> str:
"""Возвращает SQL-запрос для получения отключенных дизайнов (active='N'), но показываемых на сайте.
Args:
date: Дата, начиная с которой искать изменения (опционально)
limit: Максимальное количество возвращаемых записей (None - без ограничения)
Returns:
Строка с SQL-запросом
"""
params = [bindparam("limit", value=limit)]
# Базовый запрос
sub_query = """
SELECT DISTINCT theme_id
FROM theme_has_producttype
JOIN catalog
ON theme_has_producttype.theme_id = catalog.id
AND catalog.active = 'N'
AND catalog.show_site = 'Y'
"""
# Добавляем условие по дате, если она указана
if date:
sub_query += "AND catalog.moderate_at >= :date\n"
params.append(bindparam("date", value=date))
# Завершающая часть запроса
sub_query += """
WHERE theme_has_producttype.active = 1
LIMIT :limit
"""
# Компиляция запроса
sub_query = text(sub_query).bindparams(*params)
sub_query = sub_query.compile(
dialect=dialect(),
compile_kwargs={"literal_binds": True},
)
return str(sub_query)
@staticmethod
def _case_changes(date: datetime = datetime.now(), limit: int | None = None) -> str:
"""Возвращает SQL-запрос для получения новых дизайнов, обновлённых после указанной даты.
Args:
date: Дата, начиная с которой искать изменения (по умолчанию текущая дата/время)
limit: Максимальное количество возвращаемых записей (None - без ограничения)
Returns:
Строка с SQL-запросом
"""
if not date:
return ""
params = [bindparam("limit", value=limit),
bindparam("date", value=date)]
sub_query = """
SELECT DISTINCT theme_id
FROM theme_has_producttype
JOIN catalog ON
theme_has_producttype.theme_id = catalog.id
AND catalog.active = 'Y'
AND catalog.show_site = 'Y'
AND catalog.moderate_at >= :date
WHERE theme_has_producttype.active = 1
LIMIT :limit
"""
sub_query = text(sub_query).bindparams(*params)
sub_query = sub_query.compile(
dialect=dialect(),
compile_kwargs={"literal_binds": True},
)
return str(sub_query)