scalasbtexecutable-jarsbt-assembly

No suitable driver found for jdbc:postgresql when running from single jar


I have a Scala project which fetches information to a postgress database. I set up the project with sbt, in Intellij. I used the sbt plugin sbt-assembly to create a single jar with all the classes I need from the dependent jars. I can run the program with no problem from Intellij.

But if I run it from the single jar that sbt-assembly builds:

java -jar /opt/service/sample.jar

but it fails with error:

Exception in thread "main" java.sql.SQLException: java.sql.SQLException: No suitable driver found for jdbc:postgresql://

I unzipped the fatty sample.jar, searched postgress jar but I didn't find in it. sbt-assembly might have missed the mysql driver dependency.

Here is my build.sbt assembly code.

ThisBuild / libraryDependencies ++= Seq(
  "com.typesafe.scala-logging" %% "scala-logging" % "3.9.2",
  "org.postgresql" % "postgresql" % "42.2.14"
)

import sbtassembly.MergeStrategy
assemblyMergeStrategy in assembly := {
  case PathList("org", "apache", xs @ _*) => MergeStrategy.first
  case PathList("org", "slf4j", xs @ _*) => MergeStrategy.first
  case PathList("org", "aopalliance", xs @ _*) => MergeStrategy.first
  case PathList("jersey", "repackaged", xs @ _*) => MergeStrategy.first
  case PathList("javax", xs @ _*) => MergeStrategy.first
  case PathList("io", "netty", xs @ _*) => MergeStrategy.first
  case PathList("com", "amazonaws", xs @ _*) => MergeStrategy.first
  case PathList("META-INF", xs @ _*) =>
    (xs map {_.toLowerCase}) match {
      case ("manifest.mf" :: Nil) | ("index.list" :: Nil) | ("dependencies" :: Nil) => MergeStrategy.discard
      case _ => MergeStrategy.first
    }
  case PathList("com", "sun", xs @ _*) => MergeStrategy.first
  case PathList("git.properties", xs @ _*) => MergeStrategy.first
  case PathList("mozilla", xs @ _*) => MergeStrategy.first
  case x =>
    val oldStrategy = (assemblyMergeStrategy in assembly).value
    oldStrategy(x)
}

Is there some other changes I need to do for above code in build.sbt?

Tried running the Jar with command in local and its working.

java -cp sampl.jar:/Users/x/.m2/repository/org/postgresql/postgresql/42.2.7/postgresql-42.2.7.jar com.abc.main

So please suggest the changes in sbt assembly which can run the fatty jar without providing additional jars in run command


Solution

  • ThisBuild / libraryDependencies ++= Seq(
      "com.typesafe.scala-logging" %% "scala-logging" % "3.9.2",
      "org.postgresql" % "postgresql" % "42.2.14"
    )
    

    By any chance, are you using any other DB related dependencies like Oracle or MySQL? If that is the case, you need to update your code to load the Postgres driver while creating a connection.

    Class.forName("org.postgresql.Driver");
    conn = DriverManager.getConnection(url, user, password);
    

    or just remove the unnecessary sql dependencies. This should resolve the issue.