Wednesday 5 June 2013

Highlight empty tables in PowerDesigner model with VB Script

The wonderful thing about PowerDesigner automation is that you can actually connect to database from VB Script to get some crucial information that is unavailable (or was not captured) at a reverse engineering phase.
The following script queries Oracle ALL_TABLES system view to find out if table in the model stores any data. Then those tables that are empty are highlighted with thick maroon frame.


On Error Resume Next 

function ConnectToOra( ByRef aConnection )
  Const adUseClient = 3 
  aConnection.CursorLocation = adUseClient 
  aConnection.ConnectionTimeout = 300 
  Dim strConnection
  strConnection = "Provider=OraOLEDB.Oracle;Data Source=your_tns_name;User ID=your_id;Password=your_pass" 
  output "Connecting to Oracle"
  aConnection.Open strConnection
  if ( 0 <> err ) then 
    output "An error occurred trying to open Oracle System DSN: " & _ 
      err.number & " " & err.description & " " & err.Source  
    ConnectToOra = vbFalse
    exit function
  End if 
  
  ConnectToOra = vbTrue
  Exit Function 
End Function

const GET_ROW_COUNT_ERROR = -1
const GET_ROW_COUNT_NOT_FOUND = -2

function GetRowCount( ByRef aConnection, ByRef aRecordSet, aTableName )
  Dim SQLSelect 
  SQLSelect = "select num_rows from all_tables where owner like 'SHOPS_MOD' and table_name like '" & aTableName & "'"
  Set aRecordSet = aConnection.Execute( SQLSelect )  
  if ( 0 <> err ) then 
    output "An error occurred trying to execute query " & _
      SQLSelect & ": " & err.number & " " & err.description & " " & err.Source  
    GetRowCount = GET_ROW_COUNT_ERROR
    exit function
  End if 
  if ( aRecordSet.BOF and aRecordSet.EOF ) then 
    GetRowCount = GET_ROW_COUNT_NOT_FOUND
    Exit Function 
  end if
  GetRowCount = aRecordSet.Fields(0).Value
  Exit Function 
end function


sub main( ByRef aModel )
  Dim ADODBConnection: Set ADODBConnection = CreateObject("ADODB.Connection") 
  Dim connected: connected = ConnectToOra( ADODBConnection )

  if ( not connected ) then
    output "Not connected. Terminating"
    Set ADODBConnection = Nothing 
    exit sub
  end if
  output "Successfully connected to Oracle"

  Dim ADODBRecordSet
  Set ADODBRecordSet = CreateObject("ADODB.Recordset")
  
  Dim rowCount
  Dim tableName
  Dim strRowCount
  For each table in aModel.Tables
    tableName = Trim( table.Name )
    rowCount = GetRowCount( ADODBConnection, ADODBRecordSet, tableName )
    strRowCount = "" & rowCount
    output tableName & "->" & rowCount
    if ( "0" = strRowCount ) then
      For each symbol in table.Symbols
        symbol.LineWidth = 75 ' double
        symbol.LineColor = RGB( 138, 0, 21 )
      Next
    end if   
  Next

  ADODBConnection.Close  
  Set ADODBRecordSet = Nothing 
  Set ADODBConnection = Nothing
  exit sub 
end sub

Dim model
Set model = ActiveModel
main model

No comments:

Post a Comment