-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsdk-connection-scala.scala
More file actions
78 lines (67 loc) · 2.41 KB
/
sdk-connection-scala.scala
File metadata and controls
78 lines (67 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Couchbase SDK connection singleton — Scala
// Copy and adapt for your application.
//
// Dependencies (build.sbt):
// libraryDependencies += "com.couchbase.client" %% "scala-client" % "1.7.0"
import com.couchbase.client.scala._
import com.couchbase.client.scala.json.JsonObject
import com.couchbase.client.scala.query.QueryOptions
import scala.concurrent.duration._
import scala.util.{Failure, Success, Try}
// --- Configuration ---
object CouchbaseConfig {
val host: String = "localhost" // or "cb.xxxxx.cloud.couchbase.com" for Capella
val user: String = "app-service-user"
val password: String = "AppSecret123!"
val bucket: String = "myapp"
val scope: String = "_default"
val collection: String = "_default"
// Use "couchbases://" for TLS (required for Capella, recommended for production)
val scheme: String = "couchbase"
}
object CouchbaseConnection {
// Lazy val — initialized once on first access, thread-safe by the JVM
lazy val cluster: Cluster = {
val c = Cluster.connect(
s"${CouchbaseConfig.scheme}://${CouchbaseConfig.host}",
CouchbaseConfig.user,
CouchbaseConfig.password
).get // throws on failure — handle in production with match/recover
c.bucket(CouchbaseConfig.bucket).waitUntilReady(10.seconds)
c
}
lazy val collection: Collection =
cluster
.bucket(CouchbaseConfig.bucket)
.scope(CouchbaseConfig.scope)
.collection(CouchbaseConfig.collection)
/** Call on application shutdown to release resources. */
def close(): Unit = cluster.disconnect()
}
// --- Usage example ---
object Main extends App {
import CouchbaseConnection._
// KV upsert
collection.upsert("doc_1", JsonObject("type" -> "example", "value" -> 42)) match {
case Success(_) => println("Upserted")
case Failure(err) => println(s"Upsert failed: $err")
}
// KV get
collection.get("doc_1") match {
case Success(result) => println(result.contentAs[JsonObject].get)
case Failure(err) => println(s"Get failed: $err")
}
// SQL++ query
cluster.query(
"SELECT * FROM `myapp`._default._default WHERE type = $type LIMIT 5",
QueryOptions().parameters(
com.couchbase.client.scala.query.QueryParameters.Named("type" -> "example")
)
) match {
case Success(result) =>
result.rowsAs[JsonObject].get.foreach(println)
case Failure(err) =>
println(s"Query failed: $err")
}
close()
}