-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsdk-connection-ruby.rb
More file actions
72 lines (59 loc) · 1.97 KB
/
sdk-connection-ruby.rb
File metadata and controls
72 lines (59 loc) · 1.97 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
# Couchbase SDK connection singleton — Ruby
# Copy and adapt for your application.
#
# Dependencies:
# gem install couchbase
require 'couchbase'
# --- Configuration ---
CB_HOST = 'localhost' # or 'cb.xxxxx.cloud.couchbase.com' for Capella
CB_USER = 'app-service-user'
CB_PASSWORD = 'AppSecret123!'
CB_BUCKET = 'myapp'
CB_SCOPE = '_default'
CB_COLLECTION = '_default'
# Use 'couchbases://' for TLS (required for Capella, recommended for production)
CB_SCHEME = 'couchbase'
module CouchbaseConnection
@cluster = nil
@collection = nil
@mutex = Mutex.new
# Returns the singleton Collection, initializing the cluster on first call.
def self.collection
return @collection unless @collection.nil?
@mutex.synchronize do
return @collection unless @collection.nil?
options = Couchbase::Options::Cluster.new
options.authenticate(CB_USER, CB_PASSWORD)
options.connect_timeout = 10_000 # ms
options.key_value_timeout = 2_500 # ms
options.query_timeout = 75_000 # ms
options.search_timeout = 75_000 # ms
@cluster = Couchbase::Cluster.connect("#{CB_SCHEME}://#{CB_HOST}", options)
@collection = @cluster.bucket(CB_BUCKET).scope(CB_SCOPE).collection(CB_COLLECTION)
end
@collection
end
# Returns the singleton Cluster (needed for queries).
def self.cluster
collection # ensures cluster is initialized
@cluster
end
end
# --- Usage example ---
col = CouchbaseConnection.collection
cluster = CouchbaseConnection.cluster
# KV upsert
col.upsert('doc_1', { type: 'example', value: 42 })
# KV get
begin
result = col.get('doc_1')
puts result.content.inspect
rescue Couchbase::Error::DocumentNotFound
puts 'Document not found'
end
# SQL++ query
result = cluster.query(
'SELECT * FROM `myapp`._default._default WHERE type = $type LIMIT 5',
Couchbase::Options::Query.new(named_parameters: { type: 'example' })
)
result.rows.each { |row| puts row.inspect }