home.social

#psql — Public Fediverse posts

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

fetched live
  1. GIN‑индексы для JSONB в PostgreSQL: jsonb_ops vs jsonb_path_ops

    С JSONB в PostgreSQL есть одна довольно коварная ловушка: GIN‑индекс вроде бы поставили, запросы вроде бы работают, EXPLAIN не пугает — и на этом многие успокаиваются. Но как только данных становится действительно много, выясняется, что выбор между jsonb_ops и jsonb_path_ops — это не нюанс из документации, а вполне ощутимая разница в размере индекса, количестве лишних проверок и времени выполнения запросов. В этой статье разберём, как устроены оба оператор‑класса, почему один считается универсальным, а второй часто оказывается выгоднее на практике, и в каких случаях дефолтный выбор в PostgreSQL оказывается далеко не лучшим.

    habr.com/ru/companies/otus/art

    #psql #GINиндексы #JSONB #postgresql #jsonb_ops #jsonb_path_ops #индексация_JSONB #оптимизация_SQLзапросов #containment_operator

  2. EXPLAIN ANALYZE в PostgreSQL: читаем планы выполнения экспертно

    Привет, Хабр! Запрос работает 30 секунд. Вы смотрите на него, всё вроде ок: JOIN по индексированным полям, WHERE по дате, LIMIT 100. Должен летать, но что-то не летает. Добавляете индекс наугад — не помогает. Переписываете подзапрос в CTE и стало ещё хуже. Проблема не в запросе, а в в том, что вы не смотрели в план выполнения. EXPLAIN ANALYZE показывает не что вы написали, а что PostgreSQL делает: какие индексы использует (и использует ли вообще), в каком порядке соединяет таблицы, где тратит время, сколько строк ожидал и сколько получил. Понять PostgreSQL

    habr.com/ru/companies/otus/art

    #explain #psql #PostgreSQL #план_выполнения #оптимизация_запросов #индексы_PostgreSQL #производительность_БД

  3. Advisory Locks в PostgreSQL: блокировки уровня приложения, о которых мало кто знает

    Привет, Хабр! PostgreSQL умеет блокировать строки ( SELECT ... FOR UPDATE ) и таблицы ( LOCK TABLE ). Об этом знают все. Но есть третий тип блокировок, который решает задачи, с которыми row-level и table-level locks не справляются: advisory locks. Консультативные блокировки — механизм, где PostgreSQL предоставляет инфраструктуру (атомарные блокировки с очередями ожидания), а семантику определяет приложение. Это значит: вы берёте блокировку по произвольному числовому ключу, и PostgreSQL гарантирует, что никто другой не возьмёт блокировку с тем же ключом одновременно. Никаких таблиц, строк или ресурсов БД не блокируется — это чисто логическая блокировка, видимая только тем, кто её проверяет. Звучит как-то абстрактно. Посмотрим на конкретные задачи, где advisory locks незаменимы.

    habr.com/ru/companies/otus/art

    #psql #advisory_locks #PostgreSQL_блокировки #блокировки_в_БД #конкурентный_доступ #идемпотентность #микросервисная_архитектура #распределённые_системы

  4. Had to do a maintenance on Immich, postgres cluster got disconnected from the operator (somehow?) and wouldn't scale past 1 replica anymore...

    And we don't like single points of failure here

    So first, descheduling the Immich pod, to avoid weird writes between last backup and actual DB shutdown

    Triggering a manual backup

    Deleting cluster

    Recovering cluster from last backup

    Woops, the shared library object name got renamed from vectorchord 0.3 to 0.4.3, now it's "vchord.so" instead of "vectors.so"

    Quick fix and boom, everything comes back up

    Restoring Argo auto sync and the cluster is all back up, distributed and shining

    When Backups, DevOps and GitOps come back in a smooth and clear motion ⭐

    #postgresql #postgres #cnpg #psql #selfhosted #selfhosting #homelab #k3s #kubernetes #linux #opensource #immich #vectorchord #backup #devops #argocd #gitops

  5. Had to do a maintenance on Immich, postgres cluster got disconnected from the operator (somehow?) and wouldn't scale past 1 replica anymore...

    And we don't like single points of failure here

    So first, descheduling the Immich pod, to avoid weird writes between last backup and actual DB shutdown

    Triggering a manual backup

    Deleting cluster

    Recovering cluster from last backup

    Woops, the shared library object name got renamed from vectorchord 0.3 to 0.4.3, now it's "vchord.so" instead of "vectors.so"

    Quick fix and boom, everything comes back up

    Restoring Argo auto sync and the cluster is all back up, distributed and shining

    When Backups, DevOps and GitOps come back in a smooth and clear motion ⭐

    #postgresql #postgres #cnpg #psql #selfhosted #selfhosting #homelab #k3s #kubernetes #linux #opensource #immich #vectorchord #backup #devops #argocd #gitops

  6. peertube upgrade done even wrote a nice markdown guide on how to do it, feel free to share :)

    #psql #peertube #sysadmin #postgres #docker
  7. 📋 #psql compatibility with familiar commands like \dt, \d, \dn, \l
    📜 Persistent query history with fuzzy search
    🍺 Easy install via #Homebrew, #Cargo or binary download

    github.com/fcoury/tsql

  8. 📋 #psql compatibility with familiar commands like \dt, \d, \dn, \l
    📜 Persistent query history with fuzzy search
    🍺 Easy install via #Homebrew, #Cargo or binary download

    github.com/fcoury/tsql

  9. So... most gnome apps are failing to open on my debian sid daily driver. So... pgadmin4 won't open to remotely edit my company database. So... I have learned how to add a column to a table in my remote database using psql locally. Yup, I'm a hacker.

    #postgres #postgresql #pgadmin #pgadmin4 #psql #debian #sid #debiansid #hacker

  10. So... most gnome apps are failing to open on my debian sid daily driver. So... pgadmin4 won't open to remotely edit my company database. So... I have learned how to add a column to a table in my remote database using psql locally. Yup, I'm a hacker.

    #postgres #postgresql #pgadmin #pgadmin4 #psql #debian #sid #debiansid #hacker

  11. Tomorrow: @swisspug & @tbussmann invite us to a presentation (Rapperswil + Online) on #psql-chat - ask #PostgreSQL questions in natural language, an SQL query or PSQL command is generated for faster interactive data analysis swisspug.org/#meetup_2025-12

  12. Tomorrow: @swisspug & @tbussmann invite us to a presentation (Rapperswil + Online) on #psql-chat - ask #PostgreSQL questions in natural language, an SQL query or PSQL command is generated for faster interactive data analysis swisspug.org/#meetup_2025-12

  13. Today, trying to get the k3s cluster back to a working and smooth sailing state...

    It has been somewhat unstable since the moving, and with little time to take care of it, outages were around every corner

    Turns out, CNPG wasn't clearing out WAL on local replicas, inflating local disk usage, making them unavailable for scheduling...

    Now that I understand why everything goes down, it is time to setup ntfy and link with with alertmanager+prometheus to get proper insights on the cluster in realtime

    Now, back to rebuilding all Longhorn volumes because of those random outages *sight*

    But underlining the importance of having good backups ! Because no data was lost, despite random downtimes

    #k3s #devops #kubernetes #prometheus #alertmanager #cluster #cnpg #wal #postgres #psql #ntfy #longhorn #volume #backups #homelab #selfhosted

  14. Today, trying to get the k3s cluster back to a working and smooth sailing state...

    It has been somewhat unstable since the moving, and with little time to take care of it, outages were around every corner

    Turns out, CNPG wasn't clearing out WAL on local replicas, inflating local disk usage, making them unavailable for scheduling...

    Now that I understand why everything goes down, it is time to setup ntfy and link with with alertmanager+prometheus to get proper insights on the cluster in realtime

    Now, back to rebuilding all Longhorn volumes because of those random outages *sight*

    But underlining the importance of having good backups ! Because no data was lost, despite random downtimes

    #k3s #devops #kubernetes #prometheus #alertmanager #cluster #cnpg #wal #postgres #psql #ntfy #longhorn #volume #backups #homelab #selfhosted

  15. [Перевод] Как отследить трафик PostgreSQL

    Недавно я изучал детали реализации взаимодействия клиента PostgreSQL с базой данных и был удивлён, насколько легко просматривать трафик PostgreSQL с помощью wireshark. Когда я поделился своим удивлением в социальной сети, меня попросили привести пример того, как это сделать.

    habr.com/ru/companies/gnivc/ar

    #wireshark #sniffer #psql #protocol #бд #базы_данных #постгрес #sql

  16. I was reminded, unfortunately, today that I still despise #psql

    It's like Microsoft Access f🤬d some old 1.0 version of mysql and from that jank, psql squelched out of the conjunction already completely batshit insane

    That's my guess... 🦥

  17. Пять возможностей PostgreSQL, о которых редко вспоминают

    Привет, Хабр! Постгрес – не просто реляционная БД, а настоящий кладезь фич, о которых начинающий разработчик может и не догадываться. Всё началось с того, что PostgreSQL изначально писался на С/C++ и всегда тянуло к расширению стандартного SQL набора возможностей. Так однажды разработчики решили добавить в него JSONB , логику на уровне запросов и многое другое – что в итоге сделало его не хуже NoSQL-систем. Но вернёмся к малоизвестным фичам. Ниже – пять приёмов и возможностей, которые неожиданно полезны в повседневной работе.

    habr.com/ru/companies/otus/art

    #psql #postgresql #базы_данных #оптимизация_запросов #права_доступа #диапазонные_типы #производительность

  18. Great productivity tonight !

    Upgraded Immich from 1.132.1 to 1.135.3
    Migrated its database from pgvector.rs to VectorChord
    Upgraded to VectorChord 0.4.3 from 0.3.0

    That was actually relatively easy once I started taking my time and reading the migration documentation

    Now everything is healthy and up to date, let's see how those performance improvements translate to realworld applications

    #immich #selfhosted #homelab #kubernetes #vectorchord #pgvector #psql #cnpg #rtfm

  19. Great productivity tonight !

    Upgraded Immich from 1.132.1 to 1.135.3
    Migrated its database from pgvector.rs to VectorChord
    Upgraded to VectorChord 0.4.3 from 0.3.0

    That was actually relatively easy once I started taking my time and reading the migration documentation

    Now everything is healthy and up to date, let's see how those performance improvements translate to realworld applications

    #immich #selfhosted #homelab #kubernetes #vectorchord #pgvector #psql #cnpg #rtfm

  20. Migrating all of my CloudNativePG cluster's s3 backup endpoints was... Weirdly easy

    We'll see during the night if everything goes well and only green is to be reported tomorrow morning

    #Homelab #selfhosted #s3 #psql #cloudnativepg #kubernetes #k3s

  21. Migrating all of my CloudNativePG cluster's s3 backup endpoints was... Weirdly easy

    We'll see during the night if everything goes well and only green is to be reported tomorrow morning

    #Homelab #selfhosted #s3 #psql #cloudnativepg #kubernetes #k3s

  22. Заплатки для LAG/LEAD

    Привет, Хабр. Сегодня рассмотрим, как разреженный временной ряд ломает оконные функции ( LAG , LEAD , SUM OVER и др.), посмотрим как находить дыры и заполнять их, чтобы метрики не сыпались и строки не дублировались.

    habr.com/ru/companies/otus/art

    #psql #оконные_функции_SQL #ретеншен_анализ_SQL #кумулятивные_метрики_SQL

  23. pg_partman: автоматизация партиционирования PostgreSQL

    Ситуация: у вас PostgreSQL, в котором копятся гигантские таблицы. Вы попытались их разбить по времени или по ID, но все уперлось в рутинный менеджмент: надо создавать новые партиции, чистить старые, не забыть настроить индексы... Короче, превращается это в сериал на сто сезонов. А может, вы используете встроенное декларативное партиционирование, но хочется чего-то поудобнее? Вот тут хорошо поможет pg_partman . Это расширение — фактически «менеджер по партиционированию», который сделает половину этой рутины за вас. pg_partman — это расширение к PostgreSQL, которое упрощает декларативное партиционирование больших таблиц по времени или по числовым значениям. Не надо вручную создавать новые партиции, ломать голову над датами, выпиливать старые партиции. pg_partman сам создаст нужные секции вперед, поможет с очисткой старых, подскажет, если данные вдруг залетели в дефолтный партишн.

    habr.com/ru/companies/otus/art

    #psql #pg_partman #postgresql #партиционирование

  24. Postgresql version 17 comes out next week. Did anyone try it out with Django already? I wouldn't expect any trouble tbh, even if psycopg (3) supports only version 16 officially.

  25. Postgresql version 17 comes out next week. Did anyone try it out with Django already? I wouldn't expect any trouble tbh, even if psycopg (3) supports only version 16 officially.

    #Django #Postgresql #psql #database

  26. Импортирование csv или json файлов в Heroku Postgres Databases

    Недавно возникла потребность переместить данные из Bubble в Heroku, так как Bubble начал требовать много денег за хранение и доступ к большому кол-ву данных, поэтому было решено переместить данные проекта в Heroku.

    habr.com/ru/articles/830818/

    #bubble #sql #psql #heroku

  27. I freely admit that some problems that aren't easily solvable in relational databases or at scale, but I've developed a kind of instinctive side eye when people start saying that something is "difficult" in a relational database at smaller scales.

    I know that it can seem very know-it-all, especially if you are banging your head against it, but also if I had $100 for every time it turned out to be something like "add an index" or "tweak your settings" I would have a nice side business.

    #psql

  28. If you are stuck dealing with or for modern in , let me turn you on to cloudnative-pg.io

    TL;DR: An operator and CRDs for managing on that actually fulfills the promise of the operator pattern. It just, you know, *operates* the stupid thing for you. And its multi-arch.

    Amusingly, I found out about it because Crunchydata insists that ARM is super hard and reserved for enterprise customers only. (They've since made contrite noises about walking that back, but no actual movement yet.)

    I've been running it for about 15 minutes and so far I am blown away. And weirdly it does not appear to have tried to spy on me! That oversight aside, it comes with full support, base alarms, and a VERY nice dashboard. Handles clustering, failover, scaling, upgrades, all the things.

  29. @hector_sab Oh, it gets even cooler: this functionality is part of readline, and I _think_ also libedit, so anything depending on them potentially has vi mode too! 🙌

    Including other shells like #bash, #dash, #fish, but also tools like #psql and so on 👌

  30. A word to the wise: pressing control-C on a runaway query with doesn’t always cancel its execution on the server. Be sure to also check :show_long or :show_running to be sure it’s really canceled. Yes, I learned this the hard way today. 🤦‍♂️

  31. A few quick thoughts about #PSQL as a database and some things that new administrators running #mastodon instances may not realize

    First, PSQL is _incredibly_ sensitive to the number of connections you have at a given time. The more connections, the worse your system is going to perform. While it can be tempting to just up the number of maximum connections for the purposes of Sidekiq you should almost certainly not do that arbitrarily 1/

    #Postgres #ScalingMastodon