/*-----------------------------------------------------------------------------
 -   I n Q u i r a   Copyright (c) 2000-2002 InQuira. All rights reserved.    -
 -   ^^^^^^^^^^^^^   Unauthorized use or distribution is prohibited by law.   -
 -----------------------------------------------------------------------------*/

import java.sql.*;
import java.util.*;
import org.hsqldb.*;


public class test_gen_id
    implements Trigger {

    private static final String DB_URL   = "jdbc:hsqldb:c:/temp/hsqldb/test";
    private static final String DB_CLASS = "org.hsqldb.jdbcDriver";

    public void fire(String triggerName, String tableName, Object row[]) {

        PreparedStatement nextIdStatement = null;
        Connection        conn            = null;
        Statement         stmt            = null;
        ResultSet         results         = null;
        int               newId;

        System.out.println( "Trigger fired" );

        try {

            //Create the connection
            Class.forName( DB_CLASS );

            Properties props;

            props = new Properties();

            props.put( "user", "sa" );

            conn = DriverManager.getConnection( DB_URL, props );
        }catch ( Exception sqlex ) {
            sqlex.printStackTrace();

            return;
        }

        try {

            //get the new id
            stmt    = conn.createStatement();
            results = stmt.executeQuery( "SELECT MAX(gen_id) FROM PARENT" );

            if ( results.next() ) {
                newId = results.getInt( 1 );

                if ( results.wasNull() ) {
                    newId = 0;
                }else {
                    newId++;
                }
            }else {
                newId = 0;
            }

            System.out.println( "Setting row[1]=" + newId );

            row[1] = new Integer( newId );
        }catch ( Exception cex ) {
            cex.printStackTrace();
        }finally {
            try {
                if ( conn != null ) {
                    conn.commit();
                    conn.close();
                }

                if ( results != null ) {
                    results.close();
                }

                if ( stmt != null ) {
                    stmt.close();
                }
            }catch ( Exception ex ) {
                ex.printStackTrace();
            }
        }
    }
}

