Class: Syntropy::Storage::ConnectionPool

Inherits:
Object
  • Object
show all
Defined in:
lib/syntropy/storage/connection_pool.rb

Overview

ConnectionPool implements concurrent access to an SQLite database.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(machine, fn, max_conn) ⇒ void

Initializes the connection pool.

Parameters:

  • machine (UringMachine)

    machine instance

  • fn (String)

    database filename

  • max_conn (Integer)

    maximum number of connections



17
18
19
20
21
22
23
24
# File 'lib/syntropy/storage/connection_pool.rb', line 17

def initialize(machine, fn, max_conn)
  @machine = machine
  @fn = fn
  @count = 0
  @max_conn = max_conn
  @queue = UM::Queue.new
  @key = :"connection_pool_#{object_id}"
end

Instance Attribute Details

#countObject (readonly)

Returns the value of attribute count.



9
10
11
# File 'lib/syntropy/storage/connection_pool.rb', line 9

def count
  @count
end

Instance Method Details

#closevoid

This method returns an undefined value.

Closes the connection pool by removing all connections.



68
69
70
71
72
73
74
# File 'lib/syntropy/storage/connection_pool.rb', line 68

def close
  while @queue.count > 0
    db = @machine.shift(@queue)
    db.close
    @count -= 1
  end
end

#execute(sql) ⇒ Integer

Executes the given query by acquiring a database connection and running the query.

Parameters:

  • sql (String)

    SQL query

Returns:

  • (Integer)

    number of changed rows



61
62
63
# File 'lib/syntropy/storage/connection_pool.rb', line 61

def execute(sql, *, **)
  with_db { it.execute(sql, *, **) }
end

#query(sql) ⇒ Array<Hash>

Performs the given query by acquiring a database connection and running the query.

Parameters:

  • sql (String)

    SQL query

Returns:

  • (Array<Hash>)

    result rows



52
53
54
# File 'lib/syntropy/storage/connection_pool.rb', line 52

def query(sql, *, **, &)
  with_db { it.query(sql, *, **, &) }
end

#with_dbExtralite::Database

Checks out a database connection, passing it to the given block. This method is reentrant - called from the same fiber, it will yield the same database connection.

Returns:

  • (Extralite::Database)

    database connection



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/syntropy/storage/connection_pool.rb', line 31

def with_db
  if (db = Thread.current[@key])
    @machine.snooze
    return yield(db)
  end

  db = checkout
  begin
    Thread.current[@key] = db
    yield(db)
  ensure
    Thread.current[@key] = nil
    checkin(db)
  end
end