Skip to content

Instantly share code, notes, and snippets.

@jakebrinkmann
Forked from mvantellingen/sqla-guid-array.py
Last active November 3, 2020 17:40
Show Gist options
  • Save jakebrinkmann/fb3897feb743239dcbeaa94b97266e7d to your computer and use it in GitHub Desktop.
Save jakebrinkmann/fb3897feb743239dcbeaa94b97266e7d to your computer and use it in GitHub Desktop.
SQLAlchemy INET Array
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()
@jakebrinkmann
Copy link
Author

+  31 class·INET_ARRAY(TypeDecorator):↵          
+  32 ····impl·=·ARRAY(INET,·dimensions=1)↵     
+  33 ↵                                                                
+  34 ····def·bind_expression(self,·bindvalue):↵   
+  35 ········val·=·bindvalue.value↵                        
+  36 ········if·val·is·None:↵                                     
+  37 ············return·bindvalue↵                            
+  38 ········return·array(↵                                      
+  39 ············cast(literal(str(v)),·INET())·for·v·in·val↵
+  40 ········)↵ 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment