Class: AlRdbwMysql

Inherits:
AlRdbw show all
Defined in:
lib/al_rdbw_mysql.rb,
lib/al_persist_mysql.rb

Overview

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

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) ⇒ AlPersistMysql

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

Parameters:

  • tname (String)

    テーブル名

Returns:



53
54
55
# File 'lib/al_persist_mysql.rb', line 53

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

#commitBoolean

TODO:

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

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

Returns:

  • (Boolean)

    成否



300
301
302
303
304
305
# File 'lib/al_rdbw_mysql.rb', line 300

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



269
270
271
272
273
274
275
276
277
278
# File 'lib/al_rdbw_mysql.rb', line 269

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, var = []) ⇒ Hash Also known as: exec

Note:

任意SQLの実行

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

Parameters:

  • sql (String)

    SQL文

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

    パラメータクエリ用変数

Returns:

  • (Hash)

    結果



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/al_rdbw_mysql.rb', line 47

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

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

#insert(table, values) ⇒ Hash

insert文の発行ヘルパー

Parameters:

  • table (String)

    テーブル名

  • values (Hash)

    insertする値のhash

Returns:

  • (Hash)

    結果のHash



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/al_rdbw_mysql.rb', line 204

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.insert_id() }
  stmt.close()
  return ret
end

#normalize_data_type(f, d) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/al_rdbw_mysql.rb', line 177

def normalize_data_type( f, d )
  case d
  when String
    d.force_encoding( AL_CHARSET )

  when Mysql::Time
    case f.type
    when Mysql::Field::TYPE_TIME
      d = Time.new( 1, 1, 1, d.hour, d.minute, d.second )
    when Mysql::Field::TYPE_DATE
      d = (d.year == 0) ? nil : Time.new( d.year, d.month, d.day, 0, 0, 0 )
    when Mysql::Field::TYPE_TIMESTAMP, Mysql::Field::TYPE_DATETIME
      d = (d.year == 0) ? nil : Time.new( d.year, d.month, d.day, d.hour, d.minute, d.second )
    end
  end

  return d
end

#open_connectionObject

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



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/al_rdbw_mysql.rb', line 23

def open_connection()
  return false  if ! @dsn

  @handle = Mysql::init()
  @handle.options( Mysql::SET_CHARSET_NAME, "utf8" )  # can't use  AL_CHARSET. what to do?
  @handle.options( Mysql::OPT_CONNECT_TIMEOUT, 10 )

  @handle.connect( @dsn[:host], @dsn[:user],
     @dsn[:passwd], @dsn[:db], @dsn[:port],
     @dsn[:sock], @dsn[:flag] )

  @dsn = nil
end

#rollbackBoolean

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

Returns:

  • (Boolean)

    成否



313
314
315
316
317
318
# File 'lib/al_rdbw_mysql.rb', line 313

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>)

    結果の配列



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
128
129
130
131
132
133
134
135
136
137
# File 'lib/al_rdbw_mysql.rb', line 80

def select( sql, where_cond = nil )
  case where_cond
  when NilClass
    @stmt = get_handle().prepare( sql )
    @stmt.execute()

  when Array
    @stmt = get_handle().prepare( sql )
    @stmt.execute( *where_cond )

  when Hash
    s = sql.split( '_WHERE_' )
    raise "SQL error in select()"  if s.size != 2
    (where, val) = make_where_condition( where_cond )
    @stmt = get_handle().prepare( "#{s[0]} where #{where} #{s[1]}" )
    @stmt.execute( *val )

  when String
    sql.sub!( '_WHERE_', "where #{where_cond}" )
    @stmt = get_handle().prepare( sql )
    @stmt.execute()

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

  # get field name
  @fields_m = @stmt.().fetch_fields()
  @fields = @fields_m.map {|field| field.name.to_sym }

  # get data (row mode)
  return select_next()  if @select_fetch_mode == :ROW

  # get data all
  ret = []
  case @select_data_type
  when :ARRAY         # Array<Array>で返す
    @stmt.each {|row|
      row.size.times {|i|
        row[i] = normalize_data_type( @fields_m[i], row[i] )
      }
      ret << row
    }

  else                # Array<Hash>で返す(標準)
    @stmt.each {|row|
      r = {}
      row.each_with_index {|d,i|
        r[ @fields[i] ] = normalize_data_type( @fields_m[i], d )
      }
      ret << r
    }
  end

  @stmt.close()
  @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)

    結果



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/al_rdbw_mysql.rb', line 151

def select_next()
  return nil  if !@stmt
  row = @stmt.fetch()
  if !row
    @stmt.close()
    @stmt = nil
    @fields_m = nil
    return nil
  end

  case @select_data_type
  when :ARRAY
    row.size.times {|i|
      row[i] = normalize_data_type( @fields_m[i], row[i] )
    }
    return row

  else
    ret = {}
    row.each_with_index {|d,i|
      ret[ @fields[i] ] = normalize_data_type( @fields_m[i], d )
    }
    return ret
  end
end

#table(tname, pkey = nil) ⇒ AlPersistMysql

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

Parameters:

  • tname (String)

    テーブル名

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

    プライマリキー

Returns:



43
44
45
# File 'lib/al_persist_mysql.rb', line 43

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

#transactionBoolean

トランザクション開始

Returns:

  • (Boolean)

    成否



286
287
288
289
290
# File 'lib/al_rdbw_mysql.rb', line 286

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



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/al_rdbw_mysql.rb', line 237

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