Class: Tina4::Drivers::MongodbDriver

Inherits:
Object
  • Object
show all
Includes:
Tina4::DatabaseAdapter
Defined in:
lib/tina4/drivers/mongodb_driver.rb

Constant Summary

Constants included from Tina4::DatabaseAdapter

Tina4::DatabaseAdapter::CONNECT_TIMEOUT_SLACK_SECONDS, Tina4::DatabaseAdapter::CONNECT_TIMEOUT_VAR, Tina4::DatabaseAdapter::CONTRACT, Tina4::DatabaseAdapter::DEFAULT_CONNECT_TIMEOUT_SECONDS

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Tina4::DatabaseAdapter

bounding_connect, connect_timed_out!, connect_timeout_seconds, connect_timeout_whole_seconds, implemented_by?

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



7
8
9
# File 'lib/tina4/drivers/mongodb_driver.rb', line 7

def connection
  @connection
end

#dbObject (readonly)

Returns the value of attribute db.



7
8
9
# File 'lib/tina4/drivers/mongodb_driver.rb', line 7

def db
  @db
end

Instance Method Details

#apply_limit(sql, limit, offset = 0) ⇒ Object

MongoDB has no LIMIT clause — ignore; already handled in execute_query Uses the SAME detector as Database#fetch (scrubbed + anchored to the end) instead of its own naive sql.upcase.include?("LIMIT"), which mistook a column named rate_limit or a 'LIMIT' literal for a real clause and returned the statement uncapped. Appends on a NEW LINE so a trailing -- comment cannot swallow the clause.



108
109
110
111
112
113
114
# File 'lib/tina4/drivers/mongodb_driver.rb', line 108

def apply_limit(sql, limit, offset = 0)
  return sql if Tina4::Database.has_trailing_limit?(sql)
  modified = sql.dup
  modified += "\nLIMIT #{limit}" if limit && limit > 0
  modified += " OFFSET #{offset}" if offset && offset > 0
  modified
end

#begin_transactionObject

MongoDB transactions require a replica set — wrap in session if available



117
118
119
# File 'lib/tina4/drivers/mongodb_driver.rb', line 117

def begin_transaction
  # no-op for standalone; transaction support via session handled externally
end

#closeObject



37
38
39
40
41
42
# File 'lib/tina4/drivers/mongodb_driver.rb', line 37

def close
  @client&.close
  @client = nil
  @db = nil
  @connection = nil
end

#columns(table_name) ⇒ Object



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/tina4/drivers/mongodb_driver.rb', line 133

def columns(table_name)
  collection = @db[table_name.to_s]
  sample = collection.find.limit(1).first
  return [] unless sample

  sample.keys.map do |key|
    {
      name: key,
      type: sample[key].class.name,
      nullable: true,
      default: nil,
      primary_key: key == "_id"
    }
  end
end

#commitObject



121
122
123
# File 'lib/tina4/drivers/mongodb_driver.rb', line 121

def commit
  # no-op
end

#connect(connection_string, username: nil, password: nil) ⇒ Object



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
# File 'lib/tina4/drivers/mongodb_driver.rb', line 9

def connect(connection_string, username: nil, password: nil)
  begin
    require "mongo"
  rescue LoadError
    raise LoadError,
          "The 'mongo' gem is required for MongoDB connections. Install one of:\n" \
          "    bundle add mongo     # if your project uses Bundler\n" \
          "    gem install mongo    # bare driver"
  end

  uri = build_uri(connection_string, username, password)
  @db_name = extract_db_name(connection_string)
  # The mongo driver's OWN connect_timeout, in seconds. It already bounds
  # itself - MEASURED: Mongo::Client.new against a TCPServer that accepts
  # and never replies returns after 10.02s, the gem's hard-coded default -
  # so this makes it honour the Tina4 variable instead. A URI that spells
  # connectTimeoutMS itself keeps that value. No bounding_connect wrapper:
  # Client.new does NOT raise on an unreachable server (server selection
  # happens later, on the first operation), so there is no expiry to name.
  seconds = Tina4::DatabaseAdapter.connect_timeout_seconds
  options = {}
  options[:connect_timeout] = seconds if seconds && !uri.include?("connectTimeoutMS")
  @client = Mongo::Client.new(uri, options)
  @db = @client.use(@db_name)
  @connection = @db
  @last_insert_id = nil
end

#execute(sql, params = []) ⇒ Object

Execute a DML statement (INSERT, UPDATE, DELETE, CREATE)



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/tina4/drivers/mongodb_driver.rb', line 63

def execute(sql, params = [])
  parsed = parse_sql(sql, params)
  collection = @db[parsed[:collection]]

  case parsed[:operation]
  when :insert
    result = collection.insert_one(parsed[:document])
    @last_insert_id = result.inserted_id.to_s
    result
  when :update
    collection.update_many(parsed[:filter] || {}, { "$set" => parsed[:updates] })
  when :delete
    collection.delete_many(parsed[:filter] || {})
  when :create_collection
    begin
      @db.command(create: parsed[:collection].to_s)
    rescue Mongo::Error::OperationFailure
      # Collection already exists — ignore
    end
    nil
  when :find
    execute_query(sql, params)
  else
    nil
  end
end

#execute_query(sql, params = []) ⇒ Object

Execute a query (SELECT-like) and return array of symbol-keyed hashes



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/tina4/drivers/mongodb_driver.rb', line 45

def execute_query(sql, params = [])
  parsed = parse_sql(sql, params)
  collection = @db[parsed[:collection]]

  case parsed[:operation]
  when :find
    cursor = collection.find(parsed[:filter] || {})
    cursor = cursor.projection(parsed[:projection]) if parsed[:projection] && !parsed[:projection].empty?
    cursor = cursor.sort(parsed[:sort]) if parsed[:sort] && !parsed[:sort].empty?
    cursor = cursor.skip(parsed[:skip]) if parsed[:skip] && parsed[:skip] > 0
    cursor = cursor.limit(parsed[:limit]) if parsed[:limit] && parsed[:limit] > 0
    cursor.map { |doc| mongo_doc_to_hash(doc) }
  else
    []
  end
end

#last_insert_idObject



90
91
92
# File 'lib/tina4/drivers/mongodb_driver.rb', line 90

def last_insert_id
  @last_insert_id
end

#placeholderObject



94
95
96
# File 'lib/tina4/drivers/mongodb_driver.rb', line 94

def placeholder
  "?"
end

#placeholders(count) ⇒ Object



98
99
100
# File 'lib/tina4/drivers/mongodb_driver.rb', line 98

def placeholders(count)
  (["?"] * count).join(", ")
end

#rollbackObject



125
126
127
# File 'lib/tina4/drivers/mongodb_driver.rb', line 125

def rollback
  # no-op
end

#tablesObject



129
130
131
# File 'lib/tina4/drivers/mongodb_driver.rb', line 129

def tables
  @db.collection_names.reject { |n| n.start_with?("system.") }
end