home.social

#sqlalchemy — Public Fediverse posts

Live and recent posts from across the Fediverse tagged #sqlalchemy, aggregated by home.social.

fetched live
  1. Предзагрузил пачкой — получил N² запросов. Как expire_on_commit превращает оптимизацию в квадрат

    Бывают ошибки, которые не видит ни ревью, ни тесты: код отрабатывает правильно, прогон зелёный, а запросов к базе он делает в сто раз больше прежнего. Я убрал из фонового планировщика классический N+1 — самым что ни на есть учебным способом — и чуть не выкатил в прод версию, где нагрузка росла как квадрат числа пользователей. Разбираемся с замерами в руках: при чём тут expire_on_commit, почему предзагрузка пачкой сама по себе ни в чём не виновата и как одна строка превращает цикл в N².

    habr.com/ru/articles/1065546/

    #sqlalchemy #orm #postgresql #python #n+1 #оптимизация #производительность #expire_on_commit #профилирование

  2. Товароучёт + Честный Знак: как написать свое ПО для работы с маркировкой настольных игр

    «Честный Знак» накрывает всех: как не платить по несколько тысяч рублей в месяц за готовые облачные решения, если у вас небольшие тиражи. Рассказываю, как я написал (а точнее навайбкодил) собственное веб-приложение на Python/Flask для учета товаров и автоматизации работы с КМ (кодами маркировки), чтобы упростить складской учет и не сойти с ума от бюрократии.

    habr.com/ru/articles/1058282/

    #Честный_Знак #API #Python #Flask #SQLAlchemy #SQLite #Маркировка_товаров #Автоматизация_склада #настольные_игры

  3. DTO, schema, model, entity: почему в коде всё называется User

    Один User сначала кажется удобным: его можно принять в запросе, вернуть из API, сохранить в базу и передать дальше. Но со временем такой класс смешивает разные границы и перестаёт защищать код. Разбираю на Python-примерах, чем отличаются DTO, schema, model и entity — и когда отдельные классы действительно нужны.

    habr.com/ru/articles/1054614/

    #python #backend #api #dto #pydantic #sqlalchemy #архитектура #orm #naming #django

  4. Django-style фильтры поверх SQLAlchemy: зачем я написал python пакет sqlalchemy-query-manager

    TL;DR: я сделал sqlalchemy-query-manager — небольшой слой поверх SQLAlchemy для типовых backend-запросов. Он не заменяет SQLAlchemy, а добавляет более компактную запись для частых операций: фильтры в стиле number__gte=100 , условия через Q , фильтрацию по связанным моделям, eager loading, CRUD helpers, агрегаты и просмотр итогового SQL. Идея в том, чтобы оставить SQLAlchemy в основе, но убрать повторяющийся код там, где запросы становятся слишком большими.

    habr.com/ru/articles/1052518/

    #sqlalchemy #python #orm #sql #djangostyle_filters #crud #flask #fastapi #open_source #sqlalchemyquerymanager

  5. Browser Policy Manager: распаковка

    В предыдущих публикациях я уже рассказывал, зачем вообще появился Browser Policy Manager, почему я начал с Firefox Enterprise Policies и почему не стал делать «просто генератор policies.json ». Эта статья — более техническая. Здесь я хочу разобрать, как Browser Policy Manager устроен внутри на версии 0.8.8. Версия 0.8.8 для проекта важна тем, что в ней фактически сложилась основная архитектура продукта:

    habr.com/ru/articles/1051206/

    #firefox #browser_policy_manager #корпоративные_политики #policiesjson #fastapi #sqlalchemy #json_schema #системное_администрирование #информационная_безопасность #open_source

  6. Чтобы ваши тесты работали быстрее, нужен простой советский… xdist. Я измерил. Часть 2

    В первой части я ускорил большой интеграционный pytest-сьют с получаса до полутора минут за счёт инфраструктурных правок. Во второй проверяю следующий очевидный слой оптимизации — pytest-xdist. Результат оказался не магическим, но полезным: -n auto дал ещё ×3.4 локально и около ×2.7 в CI. В статье показываю, почему xdist не заменяет дешёвый setup, а только домножает его; как разводить БД и Redis по воркерам; где упираются соединения Postgres; и почему память Docker VM и тюнинг Postgres не сдвинули потолок.

    habr.com/ru/articles/1047134/

    #pytest #pytestxdist #python #xdist #интеграционные_тесты #ускорение_тестов #параллельное_тестирование #postgresql #sqlalchemy #redis

  7. Ваши тесты медленные не из-за базы данных. Я измерил

    Есть устойчивое поверье: интеграционные тесты медленные, потому что ходят в настоящую базу. «Подними SQLite в памяти», «замокай репозитории», «не гоняй Postgres в CI» — стандартный набор советов. Мокать я не люблю, но крыть упрёк «настоящая база — это медленно» было нечем. Поэтому я сел, спрофилировал и померил: 3316 интеграционных тестов, прогон 30 минут. После трёх правок инфраструктуры — 109 секунд. База оказалась ни при чём, а совет «чисти базу через TRUNCATE, это быстрее DELETE» у меня работал ровно наоборот — обидно вдвойне, потому что эта рекомендация уже лежала в черновике моей следующей статьи.

    habr.com/ru/articles/1045923/

    #pytest #pytestasyncio #интеграционные_тесты #Python #sqlalchemy #postgresql #fixtures #asyncio #cprofile #event_loop

  8. nORM — ORM, но есть одно «no»

    Если вы работаете с базами данных и используете ORM, вы, вероятно, сталкивались с той же проблемой, что и я. ORM отлично подходят для отображения таблиц на объекты. Но они начинают мешать, когда запрос становится сложным: агрегации, тщательно продуманные JOIN’ы, формы отчетов, которые не соответствуют одной модели на таблицу. Вы боретесь с ORM, переходите на сырой SQL, а затем вручную пишете связующий код (маппинг). Не каждый SELECT возвращает то, что подходит под одну ORM-модель. SQL - это лучший язык для доступа к данным. Лучшие ORM, которые я использовал, такие как Drizzle , побеждают, потому что они остаются близки к SQL. Я хотел пойти дальше: хранить SQL в системе контроля версий и генерировать из него типизированный Python. Именно поэтому я создал nORM (no ORM - не ORM) и выпустил версию v0.1.0 на этой неделе (мой первый опенсорс проект).

    habr.com/ru/articles/1044020/

    #ОРМ #sql #sqlalchemy #кодогенерация

  9. novo post no blog: suas queries do sqlalchemy podem ser cacheadas sem redis manual

    pool configurado, índices no lugar, mas o endpoint de relatório ainda é caro demais pra rodar a cada requisição. o lru_cache não resolve porque os argumentos variam. o redis resolve, mas você acaba escrevendo código de infraestrutura no meio da lógica de negócio.

    o dogpile.cache é a abstração que faltava: regiões configuráveis, invalidação por chave, e um mecanismo de lock que evita o dogpile effect quando o cache expira sob carga.

    riverfount.dev.br/posts/dogpil

    #python #sqlalchemy #cache #performance

  10. novo post no blog: suas queries do sqlalchemy podem ser cacheadas sem redis manual

    pool configurado, índices no lugar, mas o endpoint de relatório ainda é caro demais pra rodar a cada requisição. o lru_cache não resolve porque os argumentos variam. o redis resolve, mas você acaba escrevendo código de infraestrutura no meio da lógica de negócio.

    o dogpile.cache é a abstração que faltava: regiões configuráveis, invalidação por chave, e um mecanismo de lock que evita o dogpile effect quando o cache expira sob carga.

    riverfount.dev.br/posts/dogpil

    #python #sqlalchemy #cache #performance

  11. GigaIDE Pro для FastAPI, Flask и SQLAlchemy

    Наш предыдущий обзор касался поддержки в GigaIDE — возможно, самого популярного фреймворка Python, который, однако, восходит к эпохе шаблонизаторов, когда веб-страницы формировались на бэке. Кстати, обзор, как реализована поддержка идеологических братьев Django в Java, есть здесь . Сегодня мы рассмотрим поддержку других популярных Python-фреймворков: FastAPI, Flask, SQLAlchemy и немного Pydantic. В отличие от Django, все из них стали популярны благодаря своей легковесности и узкой специализации. Первые два — это веб-фреймворки, третий — ORM-фреймворк.

    habr.com/ru/companies/sberbank

    #gigaide #python #fastapi #flask #sqlalchemy #pydantic

  12. Как за один вечер я написал сервис инвентаризации оргтехники для филиальной сети из 16 локаций

    Знакомая работает в IT-департаменте организации с 16 филиалами и ~5000 единиц оргтехники на балансе. Попросила: “Сделай сервис, чтобы загрузить фотку шильдика, и он сказал, у кого эта железка стоит”. Звучит просто. На практике это вылилось в production-сервис с распознаванием по фото через Claude vision, ETL из бухгалтерских .xls (привет, xlrd 1.2), нормализацией грязных инвентарных номеров и автопушем в Google Sheets. Рассказываю про все грабли — от deadlock pandas vs xlrd до бага, который считал две разные железки одной

    habr.com/ru/articles/1039940/

    #Python #FastAPI #SQLite #ETL #pandas #инвентаризация #Claude_vision #OpenRouter #SQLAlchemy

  13. "Wait… SQLAlchemy Core Support?", I hear you ask. Yes, #DBXS supports #SQLAlchemy Core, and has done so for quite some time. This was previously undocumented so I can certainly forgive you for not knowing.

    So the *real* story of this release is not so much any big code changes, but rather updated dependency testing as well as *comprehensive documentation* for the SQLAlchemy feature. This may teach you a few things you didn't know about #Python database support. dbxs.readthedocs.io/en/latest/

  14. "Wait… SQLAlchemy Core Support?", I hear you ask. Yes, #DBXS supports #SQLAlchemy Core, and has done so for quite some time. This was previously undocumented so I can certainly forgive you for not knowing.

    So the *real* story of this release is not so much any big code changes, but rather updated dependency testing as well as *comprehensive documentation* for the SQLAlchemy feature. This may teach you a few things you didn't know about #Python database support. dbxs.readthedocs.io/en/latest/

  15. I think #SQLAlchemy is a magnificent software project, worthy of great respect. But oh my god is it sapping my energy on a hobby project.

    The biggest point of friction is that for various reasons, I want my domain objects to be driven by attrs plus cattrs. It's a combination I know well, and it lends itself perfectly to some of the things I'm doing.

    But of course, the SQLAlchemy ORM wants to be the source of truth for my object graph. There being multiple layers at which you can do any given thing is also pretty exhausting.

    I'm considering my alternatives. Do I keep SA but not use the ORM? Fall back to executing SQL statements directly via a lower-level, simpler library? Use a completely different type of datastore?

    #python #programming

  16. I think #SQLAlchemy is a magnificent software project, worthy of great respect. But oh my god is it sapping my energy on a hobby project.

    The biggest point of friction is that for various reasons, I want my domain objects to be driven by attrs plus cattrs. It's a combination I know well, and it lends itself perfectly to some of the things I'm doing.

    But of course, the SQLAlchemy ORM wants to be the source of truth for my object graph. There being multiple layers at which you can do any given thing is also pretty exhausting.

    I'm considering my alternatives. Do I keep SA but not use the ORM? Fall back to executing SQL statements directly via a lower-level, simpler library? Use a completely different type of datastore?

    #python #programming

  17. Три архитектурных решения для multi-tenant B2B SaaS, о которых я пожалел, что не узнал раньше

    Самая дорогая ошибка моего B2B SaaS имела ровно одну строчку Самая дорогая ошибка моего B2B SaaS имела ровно одну строчку: TENANT_ID = “tenant-1” в config.py . Полтора дня поиска бага показали, почему multi-tenant архитектуру нужно закладывать с первого коммита. Разбор трёх архитектурных решений для multi-tenant SaaS в регулируемой отрасли — tenant_id helper, PostgreSQL EXCLUDE USING gist против double-booking, 152-ФЗ как код на FastAPI и SQLAlchemy.

    habr.com/ru/articles/1033488/

    #multitenant #fastapi #postgresql #sqlalchemy #exclude_using_gist #argon2id #pbkdf2 #152фз #audit_log #b2b_saas

  18. novo artigo: sua aplicação pode estar travando sob carga mesmo com queries rápidas e banco saudável.

    o culpado quase sempre é o pool de conexões que ninguém configurou.

    cobre pool_size, max_overflow, pool_recycle, pool_pre_ping, NullPool e PgBouncer — com critérios claros para cada escolha.

    riverfount.dev.br/posts/connec

    #python #sqlalchemy #performance #produção

  19. novo artigo: sua aplicação pode estar travando sob carga mesmo com queries rápidas e banco saudável.

    o culpado quase sempre é o pool de conexões que ninguém configurou.

    cobre pool_size, max_overflow, pool_recycle, pool_pre_ping, NullPool e PgBouncer — com critérios claros para cada escolha.

    riverfount.dev.br/posts/connec

    #python #sqlalchemy #performance #produção

  20. I'm sure I'm doing something stupid, but I'm seeing SQLAlchemy+sqlite return a row that doesn't match the select condition. It is likely that SQLAlchemy is caching something, even though the session is fresh,

    But the query is:
    stmt = select(orm.Files).where(orm.Files.user == user and orm.Files.ontape == False).limit(1)

    and it's returning:
    Files(user='someuser', uuid='1b9f0805-6587-46ba-a44d-df0e2a1654bb', name='filename', size=3181952, ontape=True)

    NEVER EVER should database software cache data at the start of a session. That's just wrong.

    #Python #SQLAlchemy

  21. I'm sure I'm doing something stupid, but I'm seeing SQLAlchemy+sqlite return a row that doesn't match the select condition. It is likely that SQLAlchemy is caching something, even though the session is fresh,

    But the query is:
    stmt = select(orm.Files).where(orm.Files.user == user and orm.Files.ontape == False).limit(1)

    and it's returning:
    Files(user='someuser', uuid='1b9f0805-6587-46ba-a44d-df0e2a1654bb', name='filename', size=3181952, ontape=True)

    NEVER EVER should database software cache data at the start of a session. That's just wrong.

    #Python #SQLAlchemy

  22. Ich versacke im #python Universum. Nachdem ich einen Griff an #fastapi @FastAPI bekommen und @pydantic ein wenig verstanden habe, habe ich mir #sqlalchemy angesehen und mir ist am Donnerstag #typer über den Weg gelaufen. Auth kommt dann auch noch.
    Mit einem eigenen Skill führt mich @claudeai Stück für Stück zu einer umfangreichen Anwendung

  23. Ich versacke im #python Universum. Nachdem ich einen Griff an #fastapi @FastAPI bekommen und @pydantic ein wenig verstanden habe, habe ich mir #sqlalchemy angesehen und mir ist am Donnerstag #typer über den Weg gelaufen. Auth kommt dann auch noch.
    Mit einem eigenen Skill führt mich @claudeai Stück für Stück zu einer umfangreichen Anwendung

  24. Как я за выходные собрала сервис озвучки книг на FastAPI + Edge TTS + Telegram Mini App

    Привет, Хабр! Я люблю слушать книги, но не все есть на Литрес и Storytel. Особенно это касается профессиональной литературы, фанфиков, статей и документов — всего того, что вряд ли когда-нибудь озвучат профессиональные дикторы. Я поняла, что нейросетевые голоса уже достаточно хороши для комфортного прослушивания. И подумала: а что если сделать Telegram-бота, которому можно просто скинуть файл — а через пару минут слушать аудиокнигу в удобном плеере прямо в Telegram? Так родился VoiceBooks — open-source сервис для озвучки книг, который работает полностью бесплатно. В этой статье я разберу архитектуру open-source проекта: как организован парсинг 6 форматов в единый пайплайн, как работает фоновая генерация аудио без Celery и RabbitMQ, и как элегантно обойти лимиты Telegram Bot API на загрузку файлов. Стек: Python 3.12, FastAPI, aiogram 3, Edge TTS, SQLAlchemy 2.0 + PostgreSQL. Деплой — Railway. Читать разбор архитектуры

    habr.com/ru/articles/1010306/

    #python #fastapi #telegram_bot #aiogram #edge_tts #sqlalchemy #postgresql #архитектура #petпроект #аудиокниги

  25. Векторный поиск в PostgreSQL: PGVector, SQLAlchemy и FastAPI

    Реализуем сервис семантического поиска на базе PostgreSQL с расширением PGVector. В статье: настройка БД через Docker, миграции Alembic, асинхронный слой на SQLAlchemy и API на FastAPI. Иллюстрация на обложке - нейрослоп для привлечения внимания

    habr.com/ru/articles/1006364/

    #PGVector #SQLAlchemy #FastAPI

  26. I tweaked a little bit SQLAlchemy documentation CSS to be more readable (close to python documentation):
    userstyles.world/style/26409/r
    #python #sqlalchemy

  27. I tweaked a little bit SQLAlchemy documentation CSS to be more readable (close to python documentation):
    userstyles.world/style/26409/r
    #python #sqlalchemy

  28. #GutenMorgen #GoodMorning aus dem regnerischen #Naxos. Der (diesen Winter etwas regelmässigere) Regen tut der Insel gut, die ganze #Insel ist grün -- ganz anders als es unsere Sommerbesucher kennen. Unsere Wasserspeicher sind allerdings noch bei weitem nicht voll.

    Ich werde ein paar Stunden investieren, um die #SQLAlchemy -Dokumentation zu lesen, wenigstens kann ich dabei zwischendurch durchs Fenster auf die grün-graue Landschaft schauen. Nachmittags will ich dann wieder etwas zeichnen.

  29. New blog post is up! How I added search functionality to Rack Root, a FastAPI app.

    I cover just about all the Python code I wish I had examples for when I was figuring this out. I go over the database class design, indexes/vectors a little bit, and the API design I ended up implementing.

    #blogging #writing #development #search #rackroot #python #backend #fastapi #homelab #learning #databases #sqlalchemy

    medium.com/@a.j.longchamps/how

  30. New blog post is up! How I added search functionality to Rack Root, a FastAPI app.

    I cover just about all the Python code I wish I had examples for when I was figuring this out. I go over the database class design, indexes/vectors a little bit, and the API design I ended up implementing.

    #blogging #writing #development #search #rackroot #python #backend #fastapi #homelab #learning #databases #sqlalchemy

    medium.com/@a.j.longchamps/how

  31. Cложные запросы через паттерн Repository. Large Repository

    После негодования по поводу реализации паттерна Repository в обучающих материалах, а именно скудность функционала, я решил, что нужно расширяться и это привело к тому, что появился ORM Query Builder, о котором подробно расскажет вам эта статья.

    habr.com/ru/articles/991494/

    #sqlalchemy #repository #patterns #python #api

  32. Компромиссы

    До того как я начал кодить, я думал, что у разработчиков на любую задачу есть какое-то одно решение — бест-практика. Достаточно почитать SO или, вот теперь, пообщаться с нейронкой и — вуаля — задача сделана. Но, начав погружаться в литературу по дизайну систем, я стал чаще встречать тему про компромиссы. У задач нет единственных способов решения. Сейчас я рад, что на практике стали попадаться ситуации, где нет одного решения, но есть цели и ограничения.

    habr.com/ru/articles/988846/

    #sql #sqlalchemy #проектирование #компромисс

  33. Модуль Python для обновления данных в БД — DBMerge

    Хочу рассказать о своей разработке и поделиться ей с сообществом habr в виде готового модуля для Python. Этот модуль решает задачу обновления данных в базе данных. Он выполняет insert/update/delete в одном действии. Модуль DBMerge проектировался для упрощения ETL процессов по загрузке данных из множества внешних источников в SQL базу. Для взаимодействия с базой данных используется SQLAlchemy и ее универсальные механизмы, таким образом, разработка не имеет привязки к конкретной БД. (На момент написания статьи, детальные тесты проводились для PostgreSQL, MariaDB, SQLite, MS SQL) Принцип действия Принцип действия следующий: модуль создает временную таблицу в базе и записывает в нее весь входящий датасет через операцию массового insert. Далее он выполняет инструкции UPDATE, INSERT, DELETE для целевой таблицы.

    habr.com/ru/articles/985306/

    #sql #sqlalchemy #python #etl #postgresql #pandas

  34. FastAPI: 5 практичных архитектурных решений, о которых я пожалел, что не узнал раньше

    Привет, Хабр! Когда начинаешь новый проект на FastAPI, всё кажется простым: пара моделей Pydantic, несколько эндпоинтов — и готово. Но через полгода и 20 000 строк кода оказывается, что базовая валидация размазана по всему приложению, бизнес-логика перемешана с обращениями к БД, а тесты пишутся со скрипом. Сегодня я хочу поделиться конкретными архитектурными паттернами и приёмами , которые я неоднократно использовал в своих проектах. Они не усложняют простые задачи, но делают жизнь в долгосрочной перспективе несоизмеримо легче.

    habr.com/ru/articles/983254/

    #backend #python #FastAPI #sqlalchemy #Redis

  35. Хроники тестирования Data Quality

    В современных data-процессах ключевую роль играет обеспечение качества данных. Рассмотрим четыре популярных подхода: DBT, SQL, Python (Pandas/SQLAlchemy) и Great Expectations, оценив их эффективность для различных сценариев проверки данных. Эта статья будет интересна и полезна Data-инженерам, аналитикам данных и специалистам Data Quality для выбора оптимального метода валидации данных в зависимости от стека технологий и сложности бизнес-логики. Материал ориентирован на начинающий уровень подготовки: тем, кто еще не сталкивался системно с инструментами управления качеством данных. Привет, Хабр! Меня зовут Мария, я Data-инженер в SimbirSoft, и предлагаю для начала немного познакомиться с каждым из вышеперечисленных инструментов. Читать далее ⚡

    habr.com/ru/companies/simbirso

    #data_engineering #data_quality #dbt #sql #python #pandas #great_expectations #sqlalchemy #greenplum

  36. Just released Flask-Alembic 3.2.0. Added `check` and `current --check-heads` CLI commands to match the commands from Alembic. This was the second library I ever wrote, first published in 2014, and I still use it in every project. github.com/pallets-eco/flask-a #Python #Flask #SQLAlchemy

  37. Released Flask-SQLAlchemy-Lite 0.2.0 a few days ago! It has new methods `get_or_abort` and `one_or_abort` to help for querying for a row or 404 in a detail view. And a `test_isolation` helper to keep database changes isolated between tests. github.com/pallets-eco/flask-s #Python #Flask #SQLAlchemy

  38. Как использовать ИИ для модернизации архитектуры программного обеспечения

    ИИ может ускорить разработку, но без руководства он рискует усугубить архитектурный долг. При наличии четкого контекста и подсказок он может помочь укрепить архитектуру.

    Сегодня корпоративные команды отправляют больше кода и чаще...

    #DST #DSTGlobal #ДСТ #ДСТГлобал #архитектура #искусственныйинтеллект #программноеобеспечение #ии #RESTAPI #Flask #SQLAlchemy #AmazonQ #GitHub #Copilot

    Источник: dstglobal.ru/club/1128-kak-isp

  39. @dashdsrdash Oh yeah, I'm not a fan of directly emitting SQL (hi, injection vectors!). Totally willing to wrap the creation of the SQL in a language-specific well-typed abstract syntax tree.

    What's biting me in the ORM I'm using is that the ORM has a lot of implicit behavior around class construction but that abstraction is leaky. Among the leaks:

    • alembic auto-builds migration steps based on the shape of a sqlalchemy model. It can build migration scripts that don't run (for example, if you don't name your foreign keys it builds them with None names in the alembic script and aelmbic can't roll back an unnamed key).

    • we have a binding layer between sqlalchemy and strawberry (GraphQL API generation) that treats fields that are mapped columns and fields that are relationships differently. Knowing which fields are relationships and which are mapped columns is just something you go look up in the model.

    At this point, I'd like to throw out about half of this magic and just have alembic migration files and a GraphQL binding layer that just builds SQL queries to populate GraphQL fields.

    Part of me also wonders how much of my irritation is ORMs in general and how much is sqlalchemy in particular. The docs for sqlalchemy include examples for making one-to-one, one-to-many, and many-to-many mappings between model ORM constructs. Those three terms aren't keywords in the API, they're patterns you have to hold your mouth a specific way to make them happen in the model bindings. All this magic and they didn't provide a macro for the three most common patterns in relational database association? "But why though?"

    #sqlalchemy #alembic #strawberry

  40. I'm starting to think the real problem I see with most ORM architectures is that SQL is, honestly, a really terse but expressive language in a way.

    So when you go trying to wrap it in language-specific helpers, you end up with something remarkably more complex than SQL that your developers now need to understand on top of SQL.

    #sql #sqlalchemy

  41. The problem with magic is that it both requires deep reading to comprehend it and it fails you when you least expect it to.

    We have reflection logic to reflect fields in sqlalchemy models into GraphQL types.

    This reflects individual fields but not backfilled relations. Why? Because fuck you is why.

    But from a sqlalchemy standpoint, those relation fields are fields too; nothing special about them. You just have to know the reflector won't pick them up and you'll have to write your own access logic. Most importantly, you have to know that the reason is all that magic is at the sqlalchemy-reflected-to-strawberry-graphql layer, even though the fact that backfilled relationships exist at all is already sqlalchemy magic.

    Magic on magic.

    #sqlalchemy #strawberry #graphql

  42. Gripe:

    Shit like this.

    It really feels like I average about one "Oh, that's a weird corner case regarding your specific combination of database and feature that we don't auto-support" per change.

    My compatriots in code: if the abstraction is this leaky, maybe it's bad actually?

    (And while we're on the subject: if it's an error to try and drop_constraint on a constraint with no name, why is Alembic willing to generate op.drop_constraint(None,... ) in the first place?)

    #sqlalchemy #gripe

  43. Here I will document my sqlalchemy gripes so I can blog about them later.

    Gripe:

    Because MappedAsDataclass turns your model into a dataclass, you have to care about whether individual entries in the model do or do not have default values because Python doesn't allow a dataclass to have defaults before non-defaults (because dataclasses can have positional constructors). That's simple enough for fields with obvious default-ness.

    ... does a relationship field have a default? Effed if I know.

    #sqlalchemy #gripe

  44. Search results are working now, all the way through to the front end!

    I was curious if I needed to worry about HTTP encoding/decoding of things like spaces/%20, but it looks like everything from the frontend to the backend is helping me with all of that. Search results are coming back as expected, though notably not partial string matches. To find the string DS414 for example, you need the whole DS414 and not just 'DS', which isn't the behavior I want. That'll be the next thing to fix.

    I am also going to need to fix how the backend is talking to the database, which may mean fixing all of the fields to be lowercase/snake_case instead of camelCase. I discovered that when I was working on the triggers for finding these search results. My preference would be to name the database field somewhere in the Column(...) definition instead of refactoring most of my API calls, but we'll see what SQLAlchemy has for me there.

    Then I'll add search support for networking/DHCP and I can get past this hurdle.

    #http #programming #vuetify #fastapi #postgres #sqlalchemy #rackroot #homelab

  45. Tests are passing?! I can go to bed. Yay.

    Mini Rack Root update: I've been working on search functionality, because I don't have enough in the backlog already for Rack Root, and I've discovered just how little I know about database searches. After MANY iterations back and forth on all the ways not to do it, I've finally found a working piece of code.

    I even used ChatGPT, which I almost never do and it was mostly helpful. Sometimes a search engine won't quite get you there and that's how ChatGPT helped. Here's an example with code, help me fix it.

    I've also had oh-so-much fun with database schemas being case sensitive (camel case is out, snake case is in), triggers going...somewhere unknown, calling make_searchable() in the right places, and making sure my test environment was _really_ doing what it should have when I dropped the tables to recreate everything. Testing is close to, but not the same as, day to day use when an app is running, of course.

    That's a really good stopping point for tonight and I will take it. 55 tests, all green.

    #homelab #programming #rackroot #opensource #sqlalchemy #python #postgresql #alwayslearning

  46. Hi folks. I started with a #cli tool that should manage db migrations for different #data projects on different db types. How do you manage your databases and migrations that are not bound to an application let's say? #sqlalchemy #python #typer #alembic? What features would you like to have?

  47. I think I finally have my SQLModel to SQLAlchemy refactor completed for Rack Root. As of now, I at least have all of my tests passing and typos worked out. I know I need to add some more join statements, but I'll do those as I come across them.

    I still have a little bit of cleanup to do in removing commented code, fixing comments, organizing imports, and syncing this back to the main branch, but the hard part is done.

    Then I can finally get back to the front end work. I've been on the backend side of things for what feels like months.

    #sqlalchemy #fastapi #webdev #backend #databases #opensource #rackroot

  48. ⚙️Are you looking for an #online #database #modeling #tool with #SQL generation?

    With the latest updates (e.g. modeling of #association #classes), BESSER is your ideal tool to #design and #generate your databases in many different "flavours" :

    ☑️ #SQLLite

    ☑️ #PostgresQL

    ☑️ #MySQL

    ☑️ #MariaDB

    ☑️ #MSSQLServer

    ☑️ and even #SQLAlchemy

    Ready to give it a try? No installation required! ➡️ editor.besser-pearl.org/

    Did I already mention is completely 🆓 and #opensource?