Class: AlRdbwMysql2

Inherits:
AlRdbw show all
Defined in:
lib/al_rdbw_mysql2.rb,
lib/al_persist_mysql2.rb

Overview

リレーショナルデータベースラッパー MySQL2版

Instance Attribute Summary

Attributes inherited from AlRdbw

#fields, #flag_transaction, #handle, #select_data_type, #select_fetch_mode

Instance Method Summary collapse

Methods inherited from AlRdbw

#close, connect, #get_handle, inherited, #initialize, #transaction_active?

Constructor Details

This class inherits a constructor from AlRdbw

Instance Method Details

#[](tname) ⇒ AlPersistMysql2

tableを指定して、Persistオブジェクトを生成 syntax sugar

Parameters:

  • tname (String)

    テーブル名

Returns:



52
53
54
# File 'lib/al_persist_mysql2.rb', line 52

def []( tname )
  return AlPersistMysql2.new( self, tname )
end

#commitBoolean

TODO:

トランザクションコミット

実装中。トランザクションがSQLレベルで失敗する条件をテストして返り値に反映する

Returns:

  • (Boolean)

    成否



252
253
254
255
256
257
# File 'lib/al_rdbw_mysql2.rb', line 252

def commit()
  return false  if ! @flag_transaction
  get_handle().query("commit;")
  @flag_transaction = false
  return true
end

#delete(table, where_cond) ⇒ Hash

delete文の発行ヘルパー

Parameters:

  • table (String)

    テーブル名

  • where_cond (Hash)

    where条件

Returns:

  • (Hash)

    結果のHash



221
222
223
224
225
226
227
228
229
230
# File 'lib/al_rdbw_mysql2.rb', line 221

def delete( table, where_cond )
  (where, wval) = make_where_condition( where_cond )
  sql = "delete from #{table} where #{where};"

  stmt = get_handle().prepare( sql )
  stmt.execute( *wval )
  ret = { :cmdtuples=>stmt.affected_rows() }
  stmt.close()
  return ret
end

#execute(sql, values = []) ⇒ Hash Also known as: exec

Note:

任意SQLの実行

アクションクエリの実行用。selectは、select()メソッドを使う。

Parameters:

  • sql (String)

    SQL文

  • values (Array) (defaults to: [])

    パラメータクエリ用変数

Returns:

  • (Hash)

    結果



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/al_rdbw_mysql2.rb', line 42

def execute( sql, values = [] )
  # MySQLでは、"lock tables" 等は、query()でしか実行できない。
  begin
    stmt = get_handle().prepare( sql )
  rescue Mysql2::Error => ex
    raise ex  if ex.errno != 1295 # ER_UNSUPPORTED_PS
    raise ex  if ! values.empty?
    get_handle().query( sql )
    return {}
  end

  stmt.execute( *values )
  ret = { :cmdtuples=>stmt.affected_rows(), :insert_id=>stmt.last_id() }
  stmt.close()
  return ret
end

#insert(table, values) ⇒ Hash

insert文の発行ヘルパー

Parameters:

  • table (String)

    テーブル名

  • values (Hash)

    insertする値のhash

Returns:

  • (Hash)

    結果のHash



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/al_rdbw_mysql2.rb', line 156

def insert( table, values )
  col = ""
  plh = ""
  val = []
  values.each do |k,v|
    col << "#{k},"
    plh << "?,"
    if v.class == Array
      val << v.join(",")
    else
      val << v
    end
  end
  col.chop!
  plh.chop!

  sql = "insert into #{table} (#{col}) values (#{plh});"
  stmt = get_handle().prepare( sql )
  stmt.execute( *val )
  ret = { :cmdtuples=>stmt.affected_rows(), :insert_id=>stmt.last_id() }
  stmt.close()
  return ret
end

#open_connectionObject

RDBサーバとのコネクションを開始する



25
26
27
28
29
30
# File 'lib/al_rdbw_mysql2.rb', line 25

def open_connection()
  return false  if ! @dsn

  @handle = Mysql2::Client.new(@dsn)
  @dsn = nil
end

#rollbackBoolean

トランザクションロールバック

Returns:

  • (Boolean)

    成否



265
266
267
268
269
270
# File 'lib/al_rdbw_mysql2.rb', line 265

def rollback()
  return false  if ! @flag_transaction
  get_handle().query("rollback;")
  @flag_transaction = false
  return true
end

#select(sql, where_cond = nil) ⇒ Array<Hash>

select文の発行ヘルパー

Examples:

where condition
use Array
 select( "select * from t1 where id=?;", [2] )
use Hash
 select( "select * from t1 _WHERE_;",
   { :id=>2, :age=>nil, "name like"=>"a%" } )

Parameters:

  • sql (String)

    SQL文

  • where_cond (Array, Hash) (defaults to: nil)

    where条件

Returns:

  • (Array<Hash>)

    結果の配列



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/al_rdbw_mysql2.rb', line 75

def select( sql, where_cond = nil )
  case where_cond
  when NilClass
    args = []

  when Array
    args = where_cond

  when Hash
    s = sql.split("_WHERE_")
    raise "SQL error in select()"  if s.size != 2
    (where, args) = make_where_condition( where_cond )
    sql = "#{s[0]} where #{where} #{s[1]}"

  when String
    args = []
    sql = sql.sub("_WHERE_", "where #{where_cond}")

  else
    raise "where_cond error in AlRdbwMysql#select()"
  end

  @stmt = get_handle().prepare( sql )
  if @select_data_type == :ARRAY
    @exec_result = @stmt.execute( *args, :as=>:array )
  else
    @exec_result = @stmt.execute( *args )
  end

  # get field name
  @fields = @stmt.fields.map {|field| field.to_sym }

  # get data (row mode)
  if @select_fetch_mode == :ROW
    @fiber = Fiber.new {
      @exec_result.each {|row| Fiber.yield( row ) }

      @exec_result.free()
      @stmt.close()
      @exec_result = @stmt = nil
    }
    return select_next()
  end

  # get data all
  ret = @exec_result.each {}

  # return
  @exec_result.free()
  @stmt.close()
  @exec_result = @stmt = nil
  return ret
end

#select_nextArray, ...

シングル行モード(select_fetch_mode = :ROW)の場合の次行取得

res = @db.select( sql ) p @db.fields while res

p res
res = db.select_next()

end

Returns:

  • (Array, Hash, Nil)

    結果



142
143
144
145
146
# File 'lib/al_rdbw_mysql2.rb', line 142

def select_next()
  return nil  if !@stmt

  return @fiber.resume
end

#table(tname, pkey = nil) ⇒ AlPersistMysql2

tableを指定して、Persistオブジェクトを生成

Parameters:

  • tname (String)

    テーブル名

  • pkey (Array<String,Symbol>, String, Symbol) (defaults to: nil)

    プライマリキー

Returns:



42
43
44
# File 'lib/al_persist_mysql2.rb', line 42

def table( tname, pkey = nil )
  return AlPersistMysql2.new( self, tname, pkey )
end

#transactionBoolean

トランザクション開始

Returns:

  • (Boolean)

    成否



238
239
240
241
242
# File 'lib/al_rdbw_mysql2.rb', line 238

def transaction()
  return false  if @flag_transaction
  get_handle().query("begin;")
  return @flag_transaction = true
end

#update(table, values, where_cond) ⇒ Hash

update文の発行ヘルパー

Parameters:

  • table (String)

    テーブル名

  • values (Hash)

    updateする値のhash

  • where_cond (Hash)

    where条件

Returns:

  • (Hash)

    結果のHash



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/al_rdbw_mysql2.rb', line 189

def update( table, values, where_cond )
  columns = ""
  val = []
  values.each do |k,v|
    columns << "#{k}=?,"
    if v.class == Array
      val << v.join(",")
    else
      val << v
    end
  end
  columns.chop!

  (where, wval) = make_where_condition( where_cond )
  sql = "update #{table} set #{columns} where #{where};"
  val += wval

  stmt = get_handle().prepare( sql )
  stmt.execute( *val )
  ret = { :cmdtuples=>stmt.affected_rows() }
  stmt.close()
  return ret
end