# -*- coding: UTF-8 -*-
#
# Copyright (C) 2007 by Jan Dittberner.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.
#
# Version: $Id$

from sqlalchemy import *
import sys
import migrate.versioning.api
from settings import *

try:
    dbversion = migrate.versioning.api.db_version(
        config.get('database', 'uri'),
        config.get('database', 'repository'))
    if dbversion < required_version:
        print("""Database version is %d but required version is %d, run

 migrate upgrade %s %s

to fix this.""" %
              (dbversion, required_version, config.get('database', 'uri'),
               config.get('database', 'repository')))
        sys.exit(1)
except exceptions.NoSuchTableError, nste:    
    print nste
    sys.exit(1)

meta = BoundMetaData(config.get('database', 'uri'))
#meta.engine.echo = True
client_table = Table(
    'client', meta, schema = dbschema, autoload = True)
sysuser_table = Table(
    'sysuser', meta, ForeignKeyConstraint(['clientid'], ['client.clientid']),
    schema = dbschema, autoload = True)
domain_table = Table(
    'domain', meta, ForeignKeyConstraint(['sysuserid'], ['sysuser.sysuserid']),
    schema = dbschema, autoload = True)
record_table = Table(
    'record', meta, ForeignKeyConstraint(['domainid'], ['domain.domainid']),
    schema = dbschema, autoload = True)
supermaster_table = Table(
    'supermaster', meta,
    ForeignKeyConstraint(['account'], ['sysuser.sysuserid']),
    schema = dbschema, autoload = True)
mailaccount_table = Table(
    'mailaccount', meta,
    ForeignKeyConstraint(['domainid'], ['domain.domainid']),
    schema = dbschema, autoload = True)
mailaddress_table = Table(
    'mailaddress', meta,
    ForeignKeyConstraint(['domainid'], ['domain.domainid']),
    schema = dbschema, autoload = True)
mailtarget_table = Table(
    'mailtarget', meta,
    ForeignKeyConstraint(['mailaddressid'], ['mailaddress.mailaddressid']),
    schema = dbschema, autoload = True)