Skip to content

Commit

Permalink
feat: implemented jdbc driver methods
Browse files Browse the repository at this point in the history
  • Loading branch information
QuadStingray committed Apr 26, 2024
1 parent 0c8861a commit 0408c7e
Showing 1 changed file with 24 additions and 25 deletions.
Original file line number Diff line number Diff line change
@@ -1,46 +1,45 @@
package dev.mongocamp.driver.mongodb.jdbc

import com.mongodb.MongoCredential.createCredential
import com.vdurmont.semver4j.Semver
import dev.mongocamp.driver.mongodb.BuildInfo
import org.mongodb.scala.MongoClient.DEFAULT_CODEC_REGISTRY
import org.mongodb.scala.{ConnectionString, MongoClient, MongoClientSettings, MongoCredential}
import dev.mongocamp.driver.mongodb.database.{ DatabaseProvider, MongoConfig }
import org.mongodb.scala.{ ConnectionString, ServerAddress }

import java.sql.{Connection, DriverPropertyInfo}
import java.sql.{ Connection, DriverPropertyInfo }
import java.util.Properties
import java.util.logging.Logger
import scala.jdk.CollectionConverters.CollectionHasAsScala

class MongoJdbcDriver extends java.sql.Driver {

private lazy val semVer = new Semver(BuildInfo.version)


/**
* Connect to the database using a URL like :
* jdbc:mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
* The URL excepting the jdbc: prefix is passed as it is to the MongoDb native Java driver.
*/
/** Connect to the database using a URL like : jdbc:mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] The
* URL excepting the jdbc: prefix is passed as it is to the MongoDb native Java driver.
*/
override def connect(url: String, info: Properties): Connection = {
if (url == null || !acceptsURL(url)) {
return null
}

val connectionUrl = url.replaceFirst("^jdbc:", "")
val username = info.getProperty("user")
val password = info.getProperty("password")

val builder = MongoClientSettings
.builder()
.applyConnectionString(new ConnectionString(connectionUrl))
.codecRegistry(DEFAULT_CODEC_REGISTRY)

if (!username.equalsIgnoreCase("") && !password.equalsIgnoreCase("")) {
val credential: MongoCredential = createCredential(username, "admin", password.toCharArray)
builder.credential(credential).build()
}

val client: MongoClient = MongoClient(builder.build())
new MongoJdbcConnection(client)
val username = Option(info.getProperty("user")).filter(_.trim.nonEmpty)
val password = Option(info.getProperty("password")).filter(_.trim.nonEmpty)

val string = new ConnectionString(connectionUrl)
val provider = DatabaseProvider(
MongoConfig(
string.getDatabase,
MongoConfig.DefaultHost,
MongoConfig.DefaultPort,
string.getApplicationName,
username,
password,
string.getDatabase,
serverAddressList = string.getHosts.asScala.toList.map(h => new ServerAddress(h))
)
)
new MongoJdbcConnection(provider)
}

override def acceptsURL(url: String): Boolean = {
Expand Down

0 comments on commit 0408c7e

Please sign in to comment.