home.social

#sqlc — Public Fediverse posts

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

fetched live
  1. Используем sqlc в Го: нужно ли делать отдельный слой «репозиторий», или достаточно сгенерированного?

    Всем привет! Эта статья является выжимкой моего опыта. Возможно для кого-то это очевидные вещи, тем не менее, считаю, что она может мыть полезна начинающим и не только. Для работы с базами данных в го есть несколько подходов от стандартного "ручного", до удобных, таких как sqlx, GORM, sqlc... Список можно продолжать дальше. При разработке очередного ПО я познакомился с sqlc ( sqlc.dev/ ) и его подход мне понравился: на основе sql запросов создается полноценная обертка над бд - чем не песня, но как ее грамотно использовать в соответствии с принципами SOLID и Го подходом?

    habr.com/ru/articles/1057118/

    #sqlc #golang #solid

  2. sqlc в Go: нужен ли ручной слой репозиториев? Разбор по SOLID, DDD и Go‑прагматизму

    Давайте честно — и да, и нет. Этот вопрос возникает у каждого Go‑разработчика, который начинает использовать sqlc . Генератор кода создаёт отличные типизированные запросы, но как правильно интегрировать их в архитектуру приложения? Стоит ли оборачивать сгенерированный Querier в ручной слой репозиториев, чтобы соблюсти «букву» чистой архитектуры, или использовать его напрямую в сервисах (use cases), следуя принципу KISS? Мы разберём эту дилемму через призму пяти ключевых перспектив: SOLID (все 5 принципов), идиомы Go, DDD , тестирование и скорость разработки.

    habr.com/ru/articles/1056302/

    #sqlc #SOLID #go #ddd

  3. Query‑first подход или как из SQL запросов или MongoDB контрактов получить готовое REST API

    Я давно хотел убрать из backend‑разработки одну особенно липкую рутину: когда для каждой новой сущности снова и снова приходится собирать одни и те же слои REST API — repository, service, handlers, request/response модели, OpenAPI, auth, тесты, curl‑примеры, Docker и прочую инфраструктуру. В этой статье рассказываю про query‑first подход и open‑source Go CLI rest , который позволяет реализовать эту идею. Смысл простой: если SQL‑запросы или MongoDB‑контракты уже описывают, какие операции нужны приложению, то из них можно сгенерировать согласованный каркас REST‑сервиса. В статье показано, как это работает для PostgreSQL и MongoDB, что именно генерируется, что такое rest doctor и почему цель инструмента — не заменить бизнес‑логику, а снять первые 80–90% повторяющейся ручной работы.

    habr.com/ru/articles/1056034/

    #Go #REST_API #backend #генерация_кода #SQLC #PostgreSQL #MongoDB #OpenAPI #queryfirst #CLI

  4. [Перевод] Unit of Work в Go: практический гайд по транзакциям между репозиториями

    Когда у каждого репозитория есть свой Tx , код может выглядеть чисто, но атомарность всё равно сломается: один Store откатится, другой уже успеет закоммитить изменения. В статье показан более надёжный вариант для Go-кода: репозитории остаются небольшими интерфейсами, транзакционная логика уезжает в Unit of Work , а сервис работает с готовым набором хранилищ, построенных поверх одного sql.Tx . Разобраться в Go

    habr.com/ru/companies/otus/art

    #golang #go #репозиторий #транзакции #Unit_of_Work #интерфейсы #сервисный_слой #sqlc

  5. This is pretty sweet. , a library for which lets you write your queries directly in SQL. Think , but for lua. 😎

    git.sr.ht/~technomancy/litehug

  6. This is pretty sweet. #litehug, a #SQL library for #lua which lets you write your queries directly in SQL. Think #SQLc, but for lua. 😎

    git.sr.ht/~technomancy/litehug

  7. When building CRUD apps with capability for partial updates in #Go & #PostgreSQL with #sqlc , how do you tell the difference between "field omitted" and "field was set explicitly to zero-value"?

    Go pointers solve that issue but carrying it all the way to the database requires bridging three type systems.

    I explored reflection, generics, and code generation as possible solutions.

    Here's the write-up:
    laelapa.dev/blog/001-the-three

    ---

    Replies to this thread show up in the article's comment section.

  8. When building CRUD apps with capability for partial updates in #Go & #PostgreSQL with #sqlc , how do you tell the difference between "field omitted" and "field was set explicitly to zero-value"?

    Go pointers solve that issue but carrying it all the way to the database requires bridging three type systems.

    I explored reflection, generics, and code generation as possible solutions.

    Here's the write-up:
    laelapa.dev/blog/001-the-three

    ---

    Replies to this thread show up in the article's comment section.

  9. En ce début de vacances, mes parents m'ont demandé de faire une application qui les notifierait lorsqu'il faisait trop chaud dans la serre et qu'il fallait l'ouvrir (mon petit frère électronicien a déjà fait le capteur)
    Je me suis dit que ce serait l'occasion d'apprendre le #golang et d'autres technologies ( #templ #sqlc #alpineJS etc... )
    Maintenant je termine gentiment le backend, et la partie la plus dure m'attend: faire un appli Android (j'ai pas hâte) 💀

  10. En ce début de vacances, mes parents m'ont demandé de faire une application qui les notifierait lorsqu'il faisait trop chaud dans la serre et qu'il fallait l'ouvrir (mon petit frère électronicien a déjà fait le capteur)
    Je me suis dit que ce serait l'occasion d'apprendre le #golang et d'autres technologies ( #templ #sqlc #alpineJS etc... )
    Maintenant je termine gentiment le backend, et la partie la plus dure m'attend: faire un appli Android (j'ai pas hâte) 💀

  11. Меньше кода, больше результата: применяем sqlc для работы с БД

    Привет, Хабр! Инструмент, который генерирует производительный и безопасный код для работы с базой данных — миф или реальность? В этой статье обсудим, что такое sqlc, откуда он появился и какие идеи в него заложены. Разберём его возможности и ограничения, а также кейсы, когда он подходит лучше всего.

    habr.com/ru/companies/uzum/art

    #go #sqlc #golang #postgresql #uzum #uzumtech

  12. Here's an sqlc + postgres query, used to fetch a list of posts to be displayed on a user's profile:

    -- name: GetPostsByAuthor :many
    SELECT * FROM posts WHERE author = $1;

    Can you spot the problem with this query? ;)

    #SQL #PostgreSQL #Postgres #SQLC #Go #GoLang

  13. Here's an sqlc + postgres query, used to fetch a list of posts to be displayed on a user's profile:

    -- name: GetPostsByAuthor :many
    SELECT * FROM posts WHERE author = $1;

    Can you spot the problem with this query? ;)

    #SQL #PostgreSQL #Postgres #SQLC #Go #GoLang

  14. I am generating db use with , api with , and page renders with .

    The last thing I'm actually writing is my test with . Which dictate how everything else is built.

    Feels like my workflow has gotten pretty productive. Once I stopped trying to bikeshed. 😅

  15. I am generating db use with #sqlc, api with #gqlgen, and page renders with #templ.

    The last thing I'm actually writing is my test with #ginkgo. Which dictate how everything else is built.

    Feels like my #golang workflow has gotten pretty productive. Once I stopped trying to bikeshed. 😅

  16. I started to play a little with . Think code generator for queries you write in .

    You still need to do migrations. But certainly makes the whole "service is the data" considerably more apparent. 😎

    sqlc.dev/

  17. I started to play a little with #sqlc. Think code generator for queries you write in #SQL.

    You still need to do migrations. But certainly makes the whole "service is the data" considerably more apparent. 😎

    sqlc.dev/

  18. I've been playing with #sqlc for database access (in this case #sqlite) in #Go. It does a great job with static queries but falls down hard on dynamic queries. Really needs to be a better answer there. I love the idea, but dynamic queries need a solution.

  19. I've been playing with #sqlc for database access (in this case #sqlite) in #Go. It does a great job with static queries but falls down hard on dynamic queries. Really needs to be a better answer there. I love the idea, but dynamic queries need a solution.

  20. @sybren I’m using goose as my migration tool, embeds all migrations and auto migrates during startup.

    in turn reads each migration and generates models.

    github.com/pressly/goose

  21. @sybren I’m using goose as my migration tool, embeds all migrations and auto migrates during startup.

    #sqlc in turn reads each migration and generates models.

    github.com/pressly/goose

    #sql #golang #mysql

  22. This is simply brilliant!

    > ORMs also have the problem of being an impedance mismatch compared to the raw SQL most people are used to, meaning you’ve got the reference documentation open all day looking up how to do accomplish things when the equivalent SQL would’ve been automatic.

    From brandur.org/sqlc

    #golang #orm #sqlc

  23. This is simply brilliant!

    > ORMs also have the problem of being an impedance mismatch compared to the raw SQL most people are used to, meaning you’ve got the reference documentation open all day looking up how to do accomplish things when the equivalent SQL would’ve been automatic.

    From brandur.org/sqlc

    #golang #orm #sqlc

  24. I wanted to share a couple of points of why I am not a particular fan of #sqlc, but as usually, those turned into a full-blown blog post: preslav.me/2023/03/07/reasons-

    #prgramming #golang #sql

  25. I wanted to share a couple of points of why I am not a particular fan of #sqlc, but as usually, those turned into a full-blown blog post: preslav.me/2023/03/07/reasons-

    #prgramming #golang #sql