# $Id: sequence_spec.py 164 2007-11-22 23:29:30Z jaraco $

"""
Support for non-standard sequence names in autoloaded tables.

For some reason, in PostgreSQL databases as well as possibly others, sequence
names aren't accurately deduced when Entities are autoloaded from existing
tables.  This prevents the creation of new objects because PKs can't be
generated if the sequences aren't properly known.

This statement designates the sequence name for an autoloaded column and
adds it to the column definition.
"""

__all__ = ['specify_sequence']
__doc_all__ = []

from elixir.statements import Statement
from sqlalchemy import Sequence

import logging
log = logging.getLogger( __name__ )

#
# the specify_sequence statement
#

class SpecifiedSequenceBuilder(object):

        def __init__(self, entity, column, sequence):
                """column is the column name of the column that uses the sequence.
                sequence is the name of the sequence relation."""
                self.entity = entity
                self.column = column
                self.sequence = sequence

        def after_table(self):
                entity = self.entity

                col = entity.table.c[ self.column ]
                sequence_name = self.sequence
                # TODO - allow the sequence name to be derived from other parameters
                # such as the column name or table name
                sequence = Sequence( sequence_name )
                sequence._set_parent( col )

specify_sequence = Statement(SpecifiedSequenceBuilder)