Reputation: 5115
I have this function for comparing version numbers:
def version_gt(left, right):
"""
Compare two version numbers telling which is greater
Returns True if left is greater, False if right is greater.
"""
left = map(int, filter(None, str(left).split('.')))
right = map(int, filter(None, str(right).split('.')))
for i in range(max([len(left), len(right)])):
if i > len(left)-1:
# left ran out of version numbers, therefore right is greater
return False
elif i > len(right)-1:
# right ran out of version numbers therefore left is greater
return True
else:
# compare versions only if the version number is different
if left[i] != right[i]:
return left[i] > right[i]
return False # if all is equal, return False since left is not greater
How can I use this in SQLAlchemy to compare version numbers in a select statement?
I couldn't figure out the online documentation. Thanks for your help. -Sunjay03
[EDIT] Here is how I have defined the columns:
Table("updates", metadata,
Column("u_id", Integer, primary_key=True),
Column("appname", String, nullable=False),
Column("version", String, nullable=False),
Column("uploaded", DateTime, default=func.now()),
)
The answer has something to do with this: http://www.sqlalchemy.org/docs/orm/mapper_config.html#custom-comparators
I couldn't understand it very well, maybe you can.
Upvotes: 1
Views: 710
Reputation: 156238
The sqlite database engine is not quite expressive enough to do that kind of comparison on a single column, even in raw SQL. The best option will be to split out the version
column into several, or to simply accept a simple string comparison (something to the effect of updates1.version > updates2.version
. If none of those are an option, you will need to extend the sqlite engine (via sqlite_create_function()
) with the function you need.
Upvotes: 1