-
-
Save jakebrinkmann/fb3897feb743239dcbeaa94b97266e7d to your computer and use it in GitHub Desktop.
SQLAlchemy INET Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
import uuid | |
import psycopg2.extras | |
from sqlalchemy import Column, MetaData, Table | |
from sqlalchemy.types import Integer, DateTime, TypeDecorator | |
from sqlalchemy.dialects.postgresql import ARRAY, array | |
from sqlalchemy.dialects.postgresql import UUID | |
from sqlalchemy.sql.expression import cast, literal, select | |
psycopg2.extras.register_uuid() | |
metadata = MetaData() | |
class UUID_ARRAY(TypeDecorator): | |
impl = ARRAY(UUID, dimensions=1) | |
def bind_expression(self, bindvalue): | |
val = bindvalue.value | |
if val is None: | |
val = [] | |
return array( | |
cast(literal(str(uuid_val)), UUID()) | |
for uuid_val in val | |
) | |
table = Table('example_2', metadata, | |
Column('timestamp', DateTime(timezone=False), primary_key=True), | |
Column('num', Integer), | |
Column('guids', UUID_ARRAY) | |
) | |
class INET_ARRAY(TypeDecorator): | |
impl = ARRAY(INET, dimensions=1) | |
def bind_expression(self, bindvalue): | |
val = bindvalue.value | |
if val is None: | |
return bindvalue | |
return array( | |
cast(literal(str(v)), INET()) for v in val | |
) | |
iptv_networks = Table( | |
"networks", | |
MetaData(), | |
Column("netmasks", INET_ARRAY), | |
schema="schema", | |
) | |
if __name__ == '__main__': | |
from sqlalchemy import create_engine | |
engine = create_engine('postgresql://localhost:5432/test') | |
metadata.bind = engine | |
metadata.create_all() | |
stmt = table.insert().values( | |
timestamp=datetime.datetime.utcnow(), | |
num=2, | |
guids=[uuid.uuid4(), uuid.uuid4()]) | |
engine.execute(stmt) | |
stmt = select([table.c.guids]) | |
print engine.execute(stmt).fetchall() |
Author
jakebrinkmann
commented
Sep 25, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment