# Path: invenio_pidstore/models.py
# class RecordIdentifier(db.Model):
#     """Sequence generator for integer record identifiers.
# 
#     The sole purpose of this model is to generate integer record identifiers in
#     sequence using the underlying database's auto increment features in a
#     transaction friendly manner. The feature is primarily provided to support
#     legacy Invenio instances to continue their current record identifier
#     scheme. For new instances we strong encourage to not use auto incrementing
#     record identifiers, but instead use e.g. UUIDs as record identifiers.
#     """
# 
#     __tablename__ = 'pidstore_recid'
# 
#     recid = db.Column(
#         db.BigInteger().with_variant(db.Integer, "sqlite"),
#         primary_key=True, autoincrement=True)
# 
#     @classmethod
#     def next(cls):
#         """Return next available record identifier."""
#         try:
#             with db.session.begin_nested():
#                 obj = cls()
#                 db.session.add(obj)
#         except IntegrityError:  # pragma: no cover
#             with db.session.begin_nested():
#                 # Someone has likely modified the table without using the
#                 # models API. Let's fix the problem.
#                 cls._set_sequence(cls.max())
#                 obj = cls()
#                 db.session.add(obj)
#         return obj.recid
# 
#     @classmethod
#     def max(cls):
#         """Get max record identifier."""
#         max_recid = db.session.query(func.max(cls.recid)).scalar()
#         return max_recid if max_recid else 0
# 
#     @classmethod
#     def _set_sequence(cls, val):
#         """Internal function to reset sequence to specific value.
# 
#         Note: this function is for PostgreSQL compatibility.
# 
#         :param val: The value to be set.
#         """
#         if db.engine.dialect.name == 'postgresql':  # pragma: no cover
#             db.session.execute(
#                 "SELECT setval(pg_get_serial_sequence("
#                 "'{0}', 'recid'), :newval)".format(
#                     cls.__tablename__), dict(newval=val))
# 
#     @classmethod
#     def insert(cls, val):
#         """Insert a record identifier.
# 
#         :param val: The `recid` column value to insert.
#         """
#         with db.session.begin_nested():
#             obj = cls(recid=val)
#             db.session.add(obj)
#             cls._set_sequence(cls.max())


from invenio_pidstore.models import RecordIdentifier
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.

"""Record identifier model tests."""

from __future__ import absolute_import, print_function



def test_record_identifier(app, db):
    """Test base provider."""
    with app.app_context():
        assert RecordIdentifier.next() == 1
        assert RecordIdentifier.next() == 2
        assert RecordIdentifier.max() == 2

        # Mess up the sequence
        with db.session.begin_nested():
            obj = RecordIdentifier(recid=3)
            db.session.add(obj)

        assert RecordIdentifier.max() == 3

        # This tests a particular problem on PostgreSQL which is using
        # sequences to generate auto incrementing columns and doesn't deal
        # nicely with having values inserted in the table.

# Path: invenio_pidstore/models.py
# class RecordIdentifier(db.Model):
#     """Sequence generator for integer record identifiers.
# 
#     The sole purpose of this model is to generate integer record identifiers in
#     sequence using the underlying database's auto increment features in a
#     transaction friendly manner. The feature is primarily provided to support
#     legacy Invenio instances to continue their current record identifier
#     scheme. For new instances we strong encourage to not use auto incrementing
#     record identifiers, but instead use e.g. UUIDs as record identifiers.
#     """
# 
#     __tablename__ = 'pidstore_recid'
# 
#     recid = db.Column(
#         db.BigInteger().with_variant(db.Integer, "sqlite"),
#         primary_key=True, autoincrement=True)
# 
#     @classmethod
#     def next(cls):
#         """Return next available record identifier."""
#         try:
#             with db.session.begin_nested():
#                 obj = cls()
#                 db.session.add(obj)
#         except IntegrityError:  # pragma: no cover
#             with db.session.begin_nested():
#                 # Someone has likely modified the table without using the
#                 # models API. Let's fix the problem.
#                 cls._set_sequence(cls.max())
#                 obj = cls()
#                 db.session.add(obj)
#         return obj.recid
# 
#     @classmethod
#     def max(cls):
#         """Get max record identifier."""
#         max_recid = db.session.query(func.max(cls.recid)).scalar()
#         return max_recid if max_recid else 0
# 
#     @classmethod
#     def _set_sequence(cls, val):
#         """Internal function to reset sequence to specific value.
# 
#         Note: this function is for PostgreSQL compatibility.
# 
#         :param val: The value to be set.
#         """
#         if db.engine.dialect.name == 'postgresql':  # pragma: no cover
#             db.session.execute(
#                 "SELECT setval(pg_get_serial_sequence("
#                 "'{0}', 'recid'), :newval)".format(
#                     cls.__tablename__), dict(newval=val))
# 
#     @classmethod
#     def insert(cls, val):
#         """Insert a record identifier.
# 
#         :param val: The `recid` column value to insert.
#         """
#         with db.session.begin_nested():
#             obj = cls(recid=val)
#             db.session.add(obj)
#             cls._set_sequence(cls.max())


# Path: tests/test_recordidentifier.py
from invenio_pidstore.models import RecordIdentifier

#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.

"""Record identifier model tests."""

from __future__ import absolute_import, print_function



def test_record_identifier(app, db):
    """Test base provider."""
    with app.app_context():
        assert RecordIdentifier.next() == 1
        assert RecordIdentifier.next() == 2
        assert RecordIdentifier.max() == 2

        # Mess up the sequence
        with db.session.begin_nested():
            obj = RecordIdentifier(recid=3)
            db.session.add(obj)

        assert RecordIdentifier.max() == 3

        # This tests a particular problem on PostgreSQL which is using
        # sequences to generate auto incrementing columns and doesn't deal
        # nicely with having values inserted in the table.

        assert RecordIdentifier.next() == 4