public List getInsertOrder()

in rdb/src/main/java/org/apache/tuscany/das/rdb/config/wrapper/MappingWrapper.java [667:728]


	public List getInsertOrder() {
		if (this.logger.isDebugEnabled()) {
			this.logger.debug("Getting insert order");
		}
		if (insertOrder == null) {
			insertOrder = new ArrayList();
			if (config == null) return insertOrder;
			// correct insert order: tables sorted by ascending depth
			// parse all relationships
			Set allParents = new HashSet();
			Set allChildren = new HashSet();
			Map parentToChild = new HashMap();
			Iterator i = getConfig().getRelationship().iterator();
			while (i.hasNext()) {
				Relationship r = (Relationship) i.next();
				String parent = r.getPrimaryKeyTable();
				String child = r.getForeignKeyTable();
				if (parent.equals(child)) {
					// self-relationship
					// do not add to all children list to allow root detection
					allParents.add(parent);
					Set children = (Set) parentToChild.get(parent);
					if (children == null) {
						children = new HashSet();
						parentToChild.put(parent, children);
					}
					children.add(child);
				} else {
					allParents.add(parent);
					allChildren.add(child);
					Set children = (Set) parentToChild.get(parent);
					if (children == null) {
						children = new HashSet();
						parentToChild.put(parent, children);
					}
					children.add(child);
				}
			}
			// build list of tables ordered by depth
			List depthList = new ArrayList();
			// find roots (depth 0)
			// roots are tables that are present in the parents set, but not in the children set
			Set roots = new HashSet();
			for (Iterator itParents = allParents.iterator(); itParents.hasNext(); ) {
				String parent = (String) itParents.next();
				if (!allChildren.contains(parent)) {
					roots.add(parent);
				}
			}
			// traverse table graph to populate depth list
			traverseTableGraph(roots, 0, parentToChild, depthList, new ArrayList());
			// build insert order from depth list
			for (Iterator itDepths = depthList.iterator(); itDepths.hasNext(); ) {
				Set tables = (Set) itDepths.next();
				insertOrder.addAll(tables);
			}
		}
		if (this.logger.isDebugEnabled()) {
			this.logger.debug(insertOrder);
		}
		return insertOrder;
	}