def get_max_id(cls, session):
"""Get the current max value of the ``id`` column.
When creating and storing ORM objects in bulk, :mod:`sqlalchemy` does not automatically
generate an incrementing primary key ``id``. To do this manually, one needs to know the
current max ``id``. For ORM object classes that are derived from other ORM object classes,
the max ``id`` of the lowest base class is returned. This is designed to be used with
inheritance by joining, in which derived and base class objects have identical ``id`` values.
Args:
session: database session to operate in
"""
# sqlalchemy allows only one level of inheritance, so just check this class and all its bases
id_base = None
for c in [cls] + list(cls.__bases__):
for base_class in c.__bases__:
if base_class.__name__ == 'Base':
if id_base is None:
# we found our base class for determining the ID
id_base = c
else:
raise RuntimeError("Multiple base object classes for class " + cls.__name__)
# this should never happen
if id_base is None:
raise RuntimeError("Error searching for base class of " + cls.__name__)
# get its max ID
max_id = session.query(func.max(id_base.id)).scalar()
# if no object is present, None is returned
if max_id is None:
max_id = 0
return max_id
评论列表
文章目录