public final class SqlSchemaConnectionService extends StandardConnectionService
{
@Override
public DiagramConnectionPart connect( final DiagramNodePart node1, final DiagramNodePart node2, final String connectionType )
{
final DiagramConnectionPart fkConnectionPart = super.connect( node1, node2, connectionType );
final ForeignKey fk = (ForeignKey) fkConnectionPart.getLocalModelElement();
final Table referencedTable = fk.getReferencedTable().target();
if( referencedTable != null )
{
for( final Column column : referencedTable.getColumns() )
{
if( column.isPartOfPrimaryKey().content() )
{
fk.getColumnAssociations().insert().setReferencedColumn( column.getName().content() );
}
}
}
if( ! fk.getColumnAssociations().isEmpty() )
{
// Make an intelligent guess on local columns by looking for a prefix naming pattern.
final Table table = (Table) fk.parent().element();
final List<String> prefixes = new ArrayList<String>();
final String firstReferencedColumnName = fk.getColumnAssociations().get( 0 ).getReferencedColumn().content();
for( final Column column : table.getColumns() )
{
final String localColumnName = column.getName().content();
if( localColumnName != null && localColumnName.endsWith( firstReferencedColumnName ) )
{
prefixes.add( localColumnName.substring( 0, localColumnName.length() - firstReferencedColumnName.length() ) );
}
}
for( final String prefix : prefixes )
{
boolean match = true;
for( final ForeignKey.ColumnAssociation association : fk.getColumnAssociations() )
{
final Column candidateLocalColumn = find( table.getColumns(), prefix + association.getReferencedColumn().content() );
if( candidateLocalColumn == null || ! equal( candidateLocalColumn.getType().content(), association.getReferencedColumn().target().getType().content() ) )
{
match = false;
break;
}
}
if( match )
{
for( final ForeignKey.ColumnAssociation association : fk.getColumnAssociations() )
{
association.setLocalColumn( prefix + association.getReferencedColumn().content() );
}
break;
}
}
}
final SapphireWizard<ForeignKey> wizard = new SapphireWizard<ForeignKey>( fk, DefinitionLoader.sdef( SqlSchemaEditor.class ).wizard( "DefineForeignKeyWizard" ) )
{
@Override
public boolean performCancel()
{
fkConnectionPart.remove();
return true;
}
};
final WizardDialog dialog = new WizardDialog( Display.getDefault().getActiveShell(), wizard );