data-integrity

ruby
module EmailNormalization
  extend ActiveSupport::Concern

  included do
    attr_accessor :soft_warnings

Soft Validation: Normalize + Validate Email

rails activerecord validations
by codesnips 4 tabs
ruby
class CreateTags < ActiveRecord::Migration[7.0]
  def change
    create_table :tags do |t|
      t.string :name, null: false
      t.integer :taggings_count, null: false, default: 0
      t.timestamps

Normalize Tags at Write Time

rails activerecord callbacks
by codesnips 3 tabs
ruby
class AtLeastOneOfValidator < ActiveModel::Validator
  def validate(record)
    fields = Array(options[:fields])
    raise ArgumentError, "provide :fields" if fields.empty?

    return if fields.any? { |field| filled?(record.public_send(field)) }

Custom Validator for “At Least One of” Fields

rails activemodel validations
by codesnips 3 tabs
sql
-- Primary key (unique, not null identifier)
CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  username VARCHAR(50) NOT NULL,
  email VARCHAR(100) NOT NULL
);

Database constraints and data validation

database constraints validation
by Maria Garcia 2 tabs
ruby
class CreateSubscriptions < ActiveRecord::Migration[7.1]
  STATUSES = %w[pending active past_due canceled].freeze

  def change
    create_table :subscriptions do |t|
      t.references :account, null: false, foreign_key: true

Schema-Backed Enums (DB Constraint + Rails enum)

rails postgres schema
by codesnips 3 tabs
ruby
class Category < ApplicationRecord
  has_many :products, dependent: :restrict_with_error
  has_many :subcategories,
           class_name: "Category",
           foreign_key: :parent_id,
           dependent: :restrict_with_error

Safer Deletion with dependent: :restrict_with_error

rails activerecord data-integrity
by codesnips 4 tabs
ruby
class Post < ApplicationRecord
  has_many :comments, dependent: :destroy

  # comments_count is maintained by counter_cache on Comment#belongs_to

  scope :stale_comment_counts, lambda {

Counter Cache Repair Job (Consistency Tooling)

rails activerecord counter-cache
by codesnips 3 tabs
ruby
class Order < ApplicationRecord
  has_many :line_items, dependent: :destroy, inverse_of: :order

  accepts_nested_attributes_for :line_items,
    reject_if: :all_blank,
    allow_destroy: true

Transactionally Create Parent + Children with accepts_nested_attributes_for

rails activerecord nested-attributes
by codesnips 3 tabs
python
from django.db import models
from django.utils import timezone


class SoftDeleteQuerySet(models.QuerySet):
    def delete(self):

Soft-Delete in Django with a Custom Manager and QuerySet

django orm soft-delete
by codesnips 3 tabs
ruby
class CreateReservations < ActiveRecord::Migration[7.1]
  def up
    enable_extension "btree_gist" unless extension_enabled?("btree_gist")

    create_table :reservations do |t|
      t.references :room, null: false, foreign_key: true

DB-Level “no overlapping ranges” with exclusion constraint

rails postgres exclusion-constraint
by codesnips 3 tabs
go
package bank

import "errors"

var ErrVersionConflict = errors.New("optimistic lock: version conflict")
var ErrInsufficientFunds = errors.New("insufficient funds")

Optimistic Locking in Go With a Version Column on UPDATE

optimistic-locking concurrency postgres
by codesnips 3 tabs
ruby
class User < ApplicationRecord
  normalizes :phone, with: ->(value) { PhoneNormalizer.call(value) }, apply_to_nil: false

  validates :phone,
            presence: true,
            uniqueness: { case_sensitive: false },

Normalizing Phone Numbers on Assignment with Rails normalizes and a Custom Serializer

rails activerecord normalization
by codesnips 3 tabs