Class: Taupe::Database::MysqlDriver

Inherits:
Object
  • Object
show all
Defined in:
lib/taupe/database/mysql.rb

Overview

Mysql database driver

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dsn) ⇒ MysqlDriver

Constructor

Parameters:

  • dsn (Hash)

    The data source name



15
16
17
18
19
# File 'lib/taupe/database/mysql.rb', line 15

def initialize(dsn)
  dsn[:host] = '127.0.0.1' if dsn[:host].to_s == 'localhost'
  @connection = Mysql2::Client.new dsn
  @connection.query_options.merge! symbolize_keys: true
end

Instance Attribute Details

#connectionObject

Accessors



11
12
13
# File 'lib/taupe/database/mysql.rb', line 11

def connection
  @connection
end

Instance Method Details

#escape(str) ⇒ String

Escape a string

Parameters:

  • str (String)

Returns:

  • (String)


65
66
67
# File 'lib/taupe/database/mysql.rb', line 65

def escape(str)
  @connection.escape str
end

#exec(query) ⇒ Object

Execute a single query

Parameters:

  • query (String)

    The query to execute

Returns:

  • (Object)


24
25
26
# File 'lib/taupe/database/mysql.rb', line 24

def exec(query)
  @connection.query query
end

#fetch(query) ⇒ Array, Object

Fetch objects from database

Parameters:

  • query (String)

    The query to fetch

Returns:

  • (Array, Object)


31
32
33
# File 'lib/taupe/database/mysql.rb', line 31

def fetch(query)
  exec(query).to_a
end

#guess_schema(table) ⇒ Hash

Guess schema of a table

Parameters:

  • table (String)

    The table name

Returns:



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/taupe/database/mysql.rb', line 44

def guess_schema(table)
  results = {}

  query = format('SHOW COLUMNS FROM %s', table)

  fetch(query).each do |values|
    type = Taupe::Validate.standardize_sql_type values[:Type]

    results[values[:Field].to_sym] = {
      type: type,
      null: values[:Null] != 'NO',
      primary_key: values[:Key] == 'PRI'
    }
  end

  results
end

#last_idInteger

Get last inserted id

Returns:

  • (Integer)


37
38
39
# File 'lib/taupe/database/mysql.rb', line 37

def last_id
  @connection.last_id.to_i
end