Created
August 6, 2015 19:05
-
-
Save jrf0110/3ac60d06a9be75ada322 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
dirac.createTables = function(callback){ | |
// Determine order that tables need to be created | |
var ordered = [], column; | |
// Represent the references as a directed acyclic graph | |
var graph = {}; | |
for (var table in dirac.dals){ | |
if (table in dirac.views) continue; | |
graph[table] = { | |
dependencies: [] | |
, incoming: [] | |
}; | |
} | |
for (var table in graph){ | |
for (var col in dirac.dals[table].schema){ | |
column = dirac.dals[table].schema[col]; | |
// Table does not depend on anything | |
if (!column.references) continue; | |
graph[table].dependencies.push(column.references.table); | |
graph[column.references.table].incoming.push(table); | |
} | |
} | |
// Get set of nodes with no edges | |
var notDependedOn = []; | |
for (var table in graph){ | |
if (graph[table].incoming.length == 0) notDependedOn.push(table); | |
} | |
// Perform topological sort on DAG | |
var table, node; | |
while (table = notDependedOn.pop()){ | |
ordered.unshift( table ); | |
// Table has no dependencies, so it doesn't matter where it is | |
if (graph[table].dependencies.length == 0) continue; | |
// Remove edges from table to dependencies | |
while ( graph[table].dependencies.length > 0 ){ | |
node = graph[table].dependencies.pop(); | |
graph[node].incoming = graph[node].incoming.filter(function(t){ | |
return t != table; | |
}); | |
if ( graph[node].incoming.length == 0 ){ | |
notDependedOn.push( node ); | |
} | |
} | |
} | |
// Ensure solution was found | |
if ( Object.keys( graph ).filter( function( table ){ | |
return graph[ tabqle ].incoming.length > 0 || graph[ table ].dependencies.length > 0; | |
}).length > 0 ) return callback( new Error( 'Dependency tree is cyclic' )); | |
utils.series( | |
ordered.map( function( table ){ | |
return function( done ){ | |
dirac.dals[table].createIfNotExists( done ); | |
} | |
}) | |
, function( error ){ | |
if ( error ) return callback( error ); | |
dirac.createViews( callback ); | |
} | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment