Use Groovy to Find Database Size
>> Wednesday, March 16, 2011
Last week I found a SQL statement to find the size of rows in a database. That was helpful but I wanted to be able to run this from the command line. Sounds like a good job for the Groovy database features.
import groovy.sql.Sql
//connect to the database
def sql = Sql.newInstance('jdbc:oracle:thin:user/pass@host:1521:database')
//define the statement to run
def sizeStatement = """select table_name, num_rows, avg_row_len,
ROUND((num_rows * avg_row_len / 1048576),2) "mb_used"
from user_tables
where num_rows > 0"""
//create a date to output (not needed for SQL, just for reporting purposes
def formattedDate = String.format('%tD %
//output the results
sql.eachRow(sizeStatement) { row ->
println "${formattedDate},${row.table_name},${row.mb_used}"
}
A nice little script. The only catch is that my database is Oracle so I need to pass in the driver jar when I run the script from the command line like this
groovy -classpath OracleThinDrivers.jar CheckSize.groovy
9 comments:
Matt,
Would you care to summarize the steps at a high level for a non java dev to use this? Do we need some particular something installed in order to run groovy on java or...?
You will need both Groovy and Java installed.
First install Java:
http://www.java.com/en/download/index.jsp
Then install Groovy:
http://groovy.codehaus.org/Installing+Groovy
There are some environment variables you may need to set up that are detailed on this page.
Then create a folder and copy your OracleThinDrivers.jar into there (or whatever jar is appropriate for you database). Create a new file in that folder (named CheckSize.groovy) and copy/paste the script contents from above. You don't really need these in the same folder, but it makes running the command easier.
Finally you should be able to run the command above from a command line (in Windows Shell or Terminal on linux, etc).
I hope that helps. Feel free to add more comments or email me directly (address on the blog) if you have more questions.
Matt,
You have a few options for dealing with the "catch" you mentioned (and I agree that it is a catch):
http://marxsoftware.blogspot.com/2011/02/groovy-scripts-master-their-own.html
Dustin
Thanks for the link Dustin. I thought about using the .groovy/lib for that driver but I didn't know about the RootLoader. I'll have to try that out.
It's an opportunity to practice Ruby, I guess. But sqlplus would've done the job faster and better.
Eh, I mean Groovy. I guess my brain refuses to acknowledge Groovy.
Matt, if you put the oracle driver jar in your ~/.groovy/lib directory, you won't have to include it in your class path anymore.
Not sure why a is showing up in the script on this page. That shouldn't be there
If you are really interested, be sure to understand the user_tables and how often it is updated
Post a Comment