Тема: data-modelling
-
Проектирование таблицы временных рядов в PostgreSQL только для добавления данных
Храните измерения в таблице с секционированием по диапазонам времени, timestamptz, составным ключом из ряда и времени и индексами под запросы: B-tree для отдельного ряда, BRIN для сканирования времени по всей таблице. Срок хранения обеспечивайте отсоединением и удалением секций вместо DELETE. Такой выбор следует из поступления строк по времени и удаления целых временных интервалов.
-
Медленно меняющиеся измерения: перезаписать значение, добавить строку или столбец
Когда меняется атрибут измерения (клиент переезжает, товар переклассифицируют), тип 1 перезаписывает значение и теряет историю, тип 2 добавляет новую строку с датами начала и окончания действия и признаком текущей строки под новым суррогатным ключом, а тип 3 хранит прежнее значение в дополнительном столбце. Инструменты снимков реализуют тип 2, сравнивая при каждом запуске время обновления или набор столбцов.
-
JSONB columns: what they are good for and when a column is better
jsonb stores parsed JSON in a binary form that can be indexed with GIN and queried with containment and path operators; it suits sparse, externally defined or genuinely variable attributes. Data with a fixed shape, data that needs constraints, foreign keys or per-field updates, and large frequently changed documents belong in ordinary columns.
-
Согласия и предпочтения как данные: что выбрано, когда и через какой интерфейс
Моделируйте выбор человека как события, допускающие только добавление (субъект, цель, выбор, время, источник, версия текста), с производным представлением текущего состояния, которое каждый потребитель читает в момент использования. Булево поле в строке пользователя не объяснит, что было согласовано на момент конкретного действия или каких пользователей затронула ошибка баннера.
-
Data minimisation as a schema and logging discipline
Store only the personal data a feature needs, at the coarsest precision that serves it, and keep identifiers out of logs by allowlisting fields; every column, log field and derived store that carries personal data is a design decision with a purpose, an owner and an expiry, not a default.
-
Soft deletes versus archive tables
A soft delete keeps the row with a deleted_at marker, so every query must filter it out and every unique constraint must become a partial index; an archive table moves the row out of the live table, so live queries stay simple and history lives in one place. Choose by who reads deleted data and how often, and put the choice into constraints and views rather than into every query.
-
Normalising to third normal form and choosing when to denormalise
Normal forms remove repeating groups and facts stored in more than one place; third normal form means every non-key column depends on the key and nothing else. Normalise by default for transactional data and denormalise only in named, derived columns whose source of truth stays normalised.
-
Декларативные ограничения PostgreSQL: CHECK, UNIQUE и внешние ключи с ON DELETE
Ограничения заставляют базу отклонять недопустимые состояния для всех пишущих клиентов, а не только приложения: CHECK для правил строки, NOT NULL для обязательных значений, UNIQUE для уникальности и внешние ключи с явным ON DELETE. Чаще всего упускают выбор ссылочного действия и индексирование ссылающегося столбца.
-
Star schema basics: facts, dimensions and declaring the grain
A star schema stores measurements in fact tables and descriptive context in dimension tables linked by keys; the design starts by declaring the grain, what one fact row represents, because every measure and dimension must be consistent with it. Fully additive measures sum across any dimension, semi-additive ones not across time, and ratios must be stored as their components.
-
Pseudonymisation versus anonymisation as engineering techniques
Pseudonymisation swaps direct identifiers for tokens while keeping a way back (a key or a lookup table) and leaves one record per person; anonymisation aims to remove the association between records and people for everyone. Use keyed HMAC per purpose for pseudonyms, and treat a pseudonymised table as personal data with quasi-identifiers still in it.
-
Столбцы идентификации, последовательности и пропуски в сгенерированных ID
Столбцы идентификации — стандартный способ автоматически нумеровать строки в PostgreSQL. Они получают значения из последовательности вне управления транзакциями, поэтому откаты, сбои, кеширование и вставки ON CONFLICT оставляют пропуски. Это нормально; нумерация без пропусков требует отдельного счётчика с сериализованным доступом.
Машиночитаемо: JSON