postgres

ruby
class OrderCreationService
  Result = Struct.new(:success?, :order, :error, keyword_init: true)

  def initialize(customer:, line_params:)
    @customer = customer
    @line_params = line_params

Transactional Order Creation With Nested Savepoints in Rails

rails activerecord postgres
by codesnips 3 tabs
ruby
class AddSoftDeleteToDocuments < ActiveRecord::Migration[7.0]
  disable_ddl_transaction!

  def change
    add_column :documents, :marked_for_deletion_at, :datetime, null: true

Safer Time-Based Deletes with “mark then sweep”

rails reliability activerecord
by codesnips 4 tabs
sql
CREATE TABLE idempotency_keys (
    request_key         text        NOT NULL,
    endpoint            text        NOT NULL,
    request_fingerprint text        NOT NULL,
    status              text        NOT NULL DEFAULT 'in_progress'
                                    CHECK (status IN ('in_progress', 'completed')),

Idempotency keys for “create” endpoints

reliability postgres idempotency
by codesnips 3 tabs
java
public record User(Long id, String email, String displayName, boolean active) {

    public static User of(String email, String displayName) {
        return new User(null, email, displayName, true);
    }

Efficient JDBC Batch Inserts With addBatch, executeBatch, and Generated Keys

jdbc batch-insert postgres
by codesnips 3 tabs
python
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models, transaction

from .middleware import get_current_user

Auditing Django Model Field Changes in an Overridden save() Method

django audit-log orm
by codesnips 3 tabs
python
from django.db import models
from django.db.models import Avg, Count, Sum, DecimalField
from django.db.models.functions import Coalesce, TruncDate
from django.utils import timezone

Daily Order Stats Rollup with Django TruncDate Aggregation and a JSON API View

django orm aggregation
by codesnips 3 tabs
ruby
class CreateAccountsAndLedger < ActiveRecord::Migration[7.1]
  def change
    create_table :accounts do |t|
      t.string :name, null: false
      t.string :currency, null: false, default: "USD"
      t.bigint :balance_cents, null: false, default: 0

Atomic Account Transfers in Rails With Row Locks and a Balance Service

rails postgres transactions
by codesnips 4 tabs
ruby
class CreateIdempotencyKeys < ActiveRecord::Migration[7.1]
  def change
    create_table :idempotency_keys do |t|
      t.string :key, null: false
      t.string :request_path, null: false
      t.datetime :locked_at

Idempotent Form Submissions in Rails with an Idempotency-Key Column and before_action Guard

rails idempotency postgres
by codesnips 4 tabs
ruby
module ConnectionHealth
  extend ActiveSupport::Concern

  def with_fresh_connection
    conn = ActiveRecord::Base.connection
    conn.verify! # pings and reconnects if the socket is dead

Keep DB Connections Healthy in Long Jobs

rails activerecord background-jobs
by codesnips 3 tabs
ruby
class Cart < ApplicationRecord
  TTL = 30.minutes

  has_many :line_items, dependent: :destroy

  enum status: { active: 0, expired: 1, checked_out: 2 }

Expiring Idle Shopping Carts with a TTL Check and a Sweeper Job in Rails

rails background-jobs sidekiq
by codesnips 3 tabs
python
import csv


class _LineBuffer:
    def __init__(self):
        self._data = ""

Stream a Large CSV Export in Chunks from a Flask Endpoint

flask streaming csv
by codesnips 3 tabs
ruby
module Keysettable
  extend ActiveSupport::Concern

  included do
    scope :keyset_page, ->(after: nil, limit: 20) do
      relation = order(created_at: :asc, id: :asc).limit(limit + 1)

Keyset (Cursor) Pagination for ActiveRecord in Rails

rails activerecord pagination
by codesnips 4 tabs