Class: AlRdbwMysql

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

Overview

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

Constant Summary

@@suitable_dbms =

Returns connectメソッドが生成するオブジェクトのためのクラス (継承アトリビュート)

Returns:

  • (Object)

    connectメソッドが生成するオブジェクトのためのクラス (継承アトリビュート)

self

Instance Attribute Summary

Attributes inherited from AlRdbw

#conn_info, #flag_transaction, #handle

Instance Method Summary (collapse)

Methods inherited from AlRdbw

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

Constructor Details

This class inherits a constructor from AlRdbw

Instance Method Details

- (AlPersistMysql) [](tname)

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

Parameters:

  • tname (String)

    テーブル名

Returns:



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

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

- (Boolean) commit

TODO:

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

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

Returns:

  • (Boolean)

    成否



253
254
255
256
257
258
# File 'lib/al_rdbw_mysql.rb', line 253

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

- (Hash) delete(table, where_cond)

delete文の発行ヘルパー

Parameters:

  • table (String)

    テーブル名

  • where_cond (Hash)

    where条件

Returns:

  • (Hash)

    結果のHash



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

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

- (Hash) execute(sql, var = []) Also known as: exec

Note:

任意SQLの実行

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

Parameters:

  • sql (String)

    SQL文

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

    パラメータクエリ用変数

Returns:

  • (Hash)

    結果



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/al_rdbw_mysql.rb', line 53

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

- (Hash) insert(table, values)

insert文の発行ヘルパー

Parameters:

  • table (String)

    テーブル名

  • values (Hash)

    insertする値のhash

Returns:

  • (Hash)

    結果のHash



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

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

- (Object) open_connection

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



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/al_rdbw_mysql.rb', line 28

def open_connection()
  return false  if ! @conn_info

#    @handle = Mysql::init()
#    @handle.options( Mysql::SET_CHARSET_NAME, "utf8" )  # can't use  AL_CHARSET. what to do?
#    @handle.connect( @conn_info[:host], @conn_info[:user],
#       @conn_info[:passwd], @conn_info[:db], @conn_info[:port], 
#       @conn_info[:sock], @conn_info[:flag] )

  @handle = Mysql::connect( @conn_info[:host], @conn_info[:user], 
      @conn_info[:passwd], @conn_info[:db], @conn_info[:port], 
      @conn_info[:sock], @conn_info[:flag] )
  @conn_info = nil
end

- (Boolean) rollback

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

Returns:

  • (Boolean)

    成否



266
267
268
269
270
271
# File 'lib/al_rdbw_mysql.rb', line 266

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

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

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

    結果の配列



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
138
139
140
141
142
143
144
145
146
147
# File 'lib/al_rdbw_mysql.rb', line 86

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 select()"
  end

  #
  # データの取り出しとデータタイプの変換
  #  TODO: if type is bool?
  #
  ret = []
  fields = stmt.().fetch_fields()

  stmt.each do |datas|
    r = {}
    datas.each_with_index do |d,i|
      case d
      when Mysql::Time
        case fields[i].type
        when Mysql::Field::TYPE_TIME
          r[ fields[i].name.to_sym ] = Time.local( 1, 1, 1, d.hour, d.minute, d.second )

        when Mysql::Field::TYPE_DATE
          r[ fields[i].name.to_sym ] = (d.year == 0) ? nil : Time.local( d.year, d.month, d.day, 0, 0, 0 )

        when Mysql::Field::TYPE_TIMESTAMP, Mysql::Field::TYPE_DATETIME
          r[ fields[i].name.to_sym ] = (d.year == 0) ? nil : Time.local( d.year, d.month, d.day, d.hour, d.minute, d.second )
        end

      when String
        d.force_encoding( AL_CHARSET )
        r[ fields[i].name.to_sym ] = d
      else
        r[ fields[i].name.to_sym ] = d
      end
    end
    ret << r
  end

  stmt.close()
  return ret
end

- (AlPersistMysql) table(tname, pkey = nil)

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

Parameters:

  • tname (String)

    テーブル名

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

    プライマリキー

Returns:



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

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

- (Boolean) transaction

トランザクション開始

Returns:

  • (Boolean)

    成否



239
240
241
242
243
# File 'lib/al_rdbw_mysql.rb', line 239

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

- (Hash) update(table, values, where_cond)

update文の発行ヘルパー

Parameters:

  • table (String)

    テーブル名

  • values (Hash)

    updateする値のhash

  • where_cond (Hash)

    where条件

Returns:

  • (Hash)

    結果のHash



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

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