Last active
August 29, 2015 14:15
-
-
Save AGhost-7/9d51a53ae6f7b3e8a9f2 to your computer and use it in GitHub Desktop.
SqlConnection.scala
This file contains 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
import java.sql.{Connection, DriverManager} | |
import scala.util.Try | |
import java.net.{URISyntaxException, URI} | |
/** Object abstracts away some of the connection sheneanigans you need to do | |
* if you're trying to use JDBC. This is nice if you're just trying to make | |
* something of very simple with anorm (i.e., without Play! framework). | |
*/ | |
object SqlConnection { | |
private val driverNames = | |
Map("postgresql" -> "org.postgresql.Driver", | |
"mysql" -> "com.mysql.jdbc.Driver") | |
private def findDriver(uri: String): String = { | |
val reg = """^(jdbc:)(.+)(:\/\/.+)""".r | |
val mOpt = reg.findFirstMatchIn(uri) | |
if(!mOpt.isDefined){ | |
throw new URISyntaxException(uri, "JDBC uri not valid. Please enter " + | |
"a driver name instead."); | |
} | |
val dbName = mOpt.get.group(2) | |
val driverNameOpt = driverNames.get(dbName) | |
if(!driverNameOpt.isDefined){ | |
throw new RuntimeException(s"Database $dbName is not automatically handled. " + | |
"You must manually enter the driver name.") | |
} | |
driverNameOpt.get | |
} | |
def defaultUri(baseUri: String): String = | |
if(!baseUri.contains("useOldAliasMetadataBehavior")) | |
if(baseUri.contains("?")) | |
baseUri + "&useOldAliasMetadataBehavior=true" | |
else | |
baseUri + "?useOldAliasMetadataBehavior=true" | |
else | |
baseUri | |
def apply(uri: String, | |
driver: Option[String] = None) | |
(func: Connection => Unit) { | |
val driverStr = driver.getOrElse { findDriver(uri) } | |
Class.forName(driverStr) | |
val uriDefault = defaultUri(uri) | |
val con = DriverManager.getConnection(uriDefault) | |
try { func(con) } | |
finally { con.close() } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment