Ant-contrib

foreach with Ant

I’ve been building a cool little ANT Compiler script, and found I could really use the ability to loop through a set of files. Namely sql files and then execute each file. I ended up finding a cool little add-on to ant. Ant-Contrib Adds in a bunch of functionality. The piece I used was the foreach task. Check it out below.

The Code (build.xml)

<!-- ===================================== -->
<!-- = Include The Ant-Contrib Functions = -->
<!-- ===================================== -->
<taskdef resource="net/sf/antcontrib/antcontrib.properties"/>

<!-- ====================================== -->
<!-- = Function to exececute foreach file = -->
<!-- ====================================== -->
<target name="DB.SQL">
	<sql driver="${JDBC.Driver}"
		url="${JDBC.URL}"
		userid="postgres"
		password="">
		<transaction src="${SQLFile}"/>
	</sql>
</target>

<!-- ================================ -->
<!-- = Scans Folder for *.sql Files = -->
<!-- ================================ -->
<target name="runSQLScripts">
	<foreach target="DB.SQL"
		param="SQLFile">
		<path>
			<fileset dir="." casesensitive="yes">
				<include name="Scripts/*.sql"/>
			</fileset>
		</path>
	</foreach>
</target>

It loops through every .sql file in the Scripts folder and executes it with the DB.SQL task. 😉