Represent a PostgreSQL bit string in python. This object is used by the :class:`_postgresql.BIT` type when returning values. :class:`_postgresql.BitString` values may also be constructed directly and used with :class:`_postgresql.BIT` columns:: from sqlalchemy.dialects.postgr
| 14 | |
| 15 | |
| 16 | class BitString(str): |
| 17 | """Represent a PostgreSQL bit string in python. |
| 18 | |
| 19 | This object is used by the :class:`_postgresql.BIT` type when returning |
| 20 | values. :class:`_postgresql.BitString` values may also be constructed |
| 21 | directly and used with :class:`_postgresql.BIT` columns:: |
| 22 | |
| 23 | from sqlalchemy.dialects.postgresql import BitString |
| 24 | |
| 25 | with engine.connect() as conn: |
| 26 | conn.execute(table.insert(), {"data": BitString("011001101")}) |
| 27 | |
| 28 | .. versionadded:: 2.1 |
| 29 | |
| 30 | """ |
| 31 | |
| 32 | _DIGITS = frozenset("01") |
| 33 | |
| 34 | def __new__(cls, _value: str, _check: bool = True) -> BitString: |
| 35 | if isinstance(_value, BitString): |
| 36 | return _value |
| 37 | elif _check and cls._DIGITS.union(_value) > cls._DIGITS: |
| 38 | raise ValueError("BitString must only contain '0' and '1' chars") |
| 39 | else: |
| 40 | return super().__new__(cls, _value) |
| 41 | |
| 42 | @classmethod |
| 43 | def from_int(cls, value: int, length: int) -> BitString: |
| 44 | """Returns a BitString consisting of the bits in the integer ``value``. |
| 45 | A ``ValueError`` is raised if ``value`` is not a non-negative integer. |
| 46 | |
| 47 | If the provided ``value`` can not be represented in a bit string |
| 48 | of at most ``length``, a ``ValueError`` will be raised. The bitstring |
| 49 | will be padded on the left by ``'0'`` to bits to produce a |
| 50 | bitstring of the desired length. |
| 51 | """ |
| 52 | if value < 0: |
| 53 | raise ValueError("value must be non-negative") |
| 54 | if length < 0: |
| 55 | raise ValueError("length must be non-negative") |
| 56 | |
| 57 | template_str = f"{{0:0{length}b}}" if length > 0 else "" |
| 58 | r = template_str.format(value) |
| 59 | |
| 60 | if (length == 0 and value > 0) or len(r) > length: |
| 61 | raise ValueError( |
| 62 | f"Cannot encode {value} as a BitString of length {length}" |
| 63 | ) |
| 64 | |
| 65 | return cls(r) |
| 66 | |
| 67 | @classmethod |
| 68 | def from_bytes(cls, value: bytes, length: int = -1) -> BitString: |
| 69 | """Returns a ``BitString`` consisting of the bits in the given |
| 70 | ``value`` bytes. |
| 71 | |
| 72 | If ``length`` is provided, then the length of the provided string |
| 73 | will be exactly ``length``, with ``'0'`` bits inserted at the left of |
no outgoing calls