Skip to content
Back to top
View this page

# pyrate_limiter.buckets.postgres module

A bucket using PostgreSQL as backend

class pyrate_limiter.buckets.postgres.PostgresBucket(pool, table, rates)

  Bases: `AbstractBucket`

  close()

    Release any resources held by the bucket.

    Subclasses may override this method to perform any necessary cleanup (e.g., closing files, network connections, or releasing locks) when the bucket is no longer needed.

  count()

    Count number of items in the bucket

    Return type:

      `int` | `Awaitable`[`int`]

  flush()

    Flush the whole bucket - Must remove failing-rate after flushing

    Return type:

      `None` | `Awaitable`[`None`]

  is_async = False
  leak(current_timestamp=None)

    leaking bucket - removing items that are outdated

    Return type:

      `int` | `Awaitable`[`int`]

  peek(index)

    Peek at the rate-item at a specific index in latest-to-earliest order NOTE: The reason we cannot peek from the start of the queue(earliest-to-latest) is we can’t really tell how many outdated items are still in the queue

    Return type:

      `RateItem` | `None` | `Awaitable`[`RateItem` | `None`]

  pool
  put(item)

    Put an item (typically the current time) in the bucket return true if successful, otherwise false

    Return type:

      `bool` | `Awaitable`[`bool`]

  table

class pyrate_limiter.buckets.postgres.Queries

  Bases: `object`

  SQL templates composed via `psycopg.sql`.

  `{table}` / `{index}` are quoted identifiers filled with `sql.SQL(...).format(...)`; `%s` are bound query parameters supplied at execution time. Neither uses raw string interpolation (issue #233).

  COUNT = '\n SELECT COUNT(*) FROM {table}\n '
  COUNT_WINDOW = "\n SELECT COUNT(*) FROM {table}\n WHERE item_timestamp >= TO_TIMESTAMP(%s) - (%s * INTERVAL '1 milliseconds')\n "
  CREATE_BUCKET_TABLE = '\n CREATE TABLE IF NOT EXISTS {table} (\n name VARCHAR,\n weight SMALLINT,\n item_timestamp TIMESTAMP\n )\n '
  CREATE_INDEX_ON_TIMESTAMP = '\n CREATE INDEX IF NOT EXISTS {index} ON {table} (item_timestamp)\n '
  FLUSH = '\n DELETE FROM {table}\n '
  LEAK = '\n DELETE FROM {table} WHERE item_timestamp < TO_TIMESTAMP(%s)\n '
  LEAK_COUNT = '\n SELECT COUNT(*) FROM {table} WHERE item_timestamp < TO_TIMESTAMP(%s)\n '
  LOCK_TABLE = '\n LOCK TABLE {table} IN EXCLUSIVE MODE NOWAIT\n '
  PEEK = '\n SELECT name, weight, (extract(epoch FROM item_timestamp) * 1000) as item_timestamp\n FROM {table}\n ORDER BY item_timestamp DESC\n LIMIT 1\n OFFSET %s\n '
  PUT = '\n INSERT INTO {table} (name, weight, item_timestamp)\n SELECT %s, %s, TO_TIMESTAMP(%s) FROM generate_series(1, %s)\n '