src/main/scala/fis/base/model/SeqIdPostgreSqlAdapter.scala
author Tomas Zeman <tzeman@volny.cz>
Fri, 10 Feb 2012 09:53:04 +0100
changeset 7 8ef5e77ad79e
parent 6 98d9c92a726f
permissions -rw-r--r--
base entity addons: entityTable()

/*
 * Copyright 2011 Tomas Zeman <tzeman@volny.cz>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package fis.base.model

import org.squeryl.{Session, Table}
import org.squeryl.adapters.PostgreSqlAdapter
import org.squeryl.internals.StatementWriter
import scala.collection.mutable.HashSet

/**
 * Postgres adapter which enables multiple entities to share the same
 * sequence. 
 *
 * The implementation is based on Postgres adapter which is
 *
 *    Copyright 2010 Maxime Lévesque
 *
 * and licensed under the same license (Apache 2).
 */
class SeqIdPostgreSqlAdapter extends PostgreSqlAdapter {
  private val seqs = new HashSet[String]

  override def postCreateTable(t: Table[_],
    printSinkWhenWriteOnlyMode: Option[String => Unit]) = {

    val autoIncrementedFields = t.posoMetaData.fieldsMetaData.
      filter(_.isAutoIncremented).
      filter(f => !seqs.contains(f.sequenceName))

    for(fmd <-autoIncrementedFields) {
      val sw = new StatementWriter(false, this)
      sw.write("create sequence ", quoteName(fmd.sequenceName))
      seqs += fmd.sequenceName

      if(printSinkWhenWriteOnlyMode == None) {
        val st = Session.currentSession.connection.createStatement
        st.execute(sw.statement)
      }
      else
        printSinkWhenWriteOnlyMode.get.apply(sw.statement + ";")
    }
  }
}

// vim: set ts=2 sw=2 et: