import java.util.*;
import java.text.*;
import java.io.*;

import java.sql.*;

////////////////////////////////////////////////////////////
public class DatabaseTest
{
	Connection con = null;
	
	////////////////////////////////////////////////////////////
	public DatabaseTest() 
		throws SQLException, ClassNotFoundException, FileNotFoundException
	{
		Class.forName( "org.postgresql.Driver" );
		con = 
			DriverManager.getConnection( 
				"jdbc:postgresql://localhost/db-test",
				"carlos", "" );
		DatabaseMetaData dbmd = con.getMetaData();
		getKeyInfo( "table_1" );
		getKeyInfo( "table_2" );
	}

	///////////////////////////////////////////////////////////
	public void getKeyInfo( String tableName )
		throws SQLException
	{
		DatabaseMetaData dm = con.getMetaData();
		ResultSet rs = dm.getImportedKeys( "", "", tableName );
		System.out.println( "\n<Database.getKeyInfo> for table: " + tableName );
		System.out.println( ">>> Imported keys\n" );
		while( rs.next() )
		{
			System.out.print( "\n  " + rs.getInt( 9 ) );
			String cName = rs.getString( 12 );
			int idx = cName.indexOf( "\\000" );
			if( idx >= 0 )
				cName = cName.substring( 0, idx );
			System.out.println( ": " + cName );
			System.out.print( "  from " + rs.getString( 3 ) );
			System.out.print( "  to   " + rs.getString( 7 ) );
			System.out.println( "." + rs.getString( 8 ) );
		}
		rs = dm.getExportedKeys( "", "", tableName );
		System.out.println( ">>> Exported keys:\n" );
		while( rs.next() )
		{
			System.out.print( "\n  " + rs.getInt( 9 ) );
			String cName = rs.getString( 12 );
			int idx = cName.indexOf( "\\000" );
			if( idx >= 0 )
				cName = cName.substring( 0, idx );
			System.out.println( ": " + cName );
			System.out.print( "  from " + rs.getString( 3 ) );
			System.out.print( "  to   " + rs.getString( 7 ) );
			System.out.println( "." + rs.getString( 8 ) );
		}
	}
	
	///////////////////////////////////////////////////////////
	public static void main( String[] args )
	{
		try
		{
			new DatabaseTest();
		}
		catch( Exception e )
		{
			System.out.println( e.getMessage() );
			e.printStackTrace();
		}
	}
	
}

