sqlite3-ironruby 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,175 @@
1
+ require 'sqlite3/driver/native/Community.Data.SQLite'
2
+
3
+ module SQLite3 ; module Driver ; module Native
4
+
5
+ class CallbackData
6
+ attr_accessor :proc, :proc2, :data
7
+ end
8
+
9
+ class Driver
10
+ include CS_SQLite3
11
+
12
+ def initialize
13
+ @callback_data = Hash.new
14
+ @authorizer = Hash.new
15
+ @busy_handler = Hash.new
16
+ @trace = Hash.new
17
+ end
18
+
19
+ def complete?( sql, utf16=false )
20
+ CSSQLite.sqlite3_complete(sql) != 0
21
+ end
22
+
23
+ def open(filename)
24
+ CSSQLite.sqlite3_open( filename, nil )
25
+ end
26
+
27
+ def prepare(db, sql)
28
+ CSSQLite.sqlite3_prepare( db, sql, -1, nil, nil )
29
+ end
30
+
31
+ def bind_text( stmt, index, value, utf16=false )
32
+ CSSQLite.sqlite3_bind_text( stmt, index, value.to_s, -1, nil )
33
+ end
34
+
35
+ #def busy_handler( db, data=nil, &block )
36
+ # if block
37
+ # cb = API::CallbackData.new
38
+ # cb.proc = block
39
+ # cb.data = data
40
+ # result = API.sqlite3_busy_handler( db, API::Sqlite3_ruby_busy_handler, cb )
41
+ # # Reference the Callback object so that
42
+ # # it is not deleted by the GC
43
+ # @busy_handler[db] = cb
44
+ # else
45
+ # # Unreference the callback *after* having removed it
46
+ # # from sqlite
47
+ # result = API.sqlite3_busy_handler( db, nil, nil )
48
+ # @busy_handler.delete(db)
49
+ # end
50
+ #
51
+ # result
52
+ #end
53
+ #
54
+ #def set_authorizer( db, data=nil, &block )
55
+ # if block
56
+ # cb = API::CallbackData.new
57
+ # cb.proc = block
58
+ # cb.data = data
59
+ # result = API.sqlite3_set_authorizer( db, API::Sqlite3_ruby_authorizer, cb )
60
+ # @authorizer[db] = cb # see comments in busy_handler
61
+ # else
62
+ # result = API.sqlite3_set_authorizer( db, nil, nil )
63
+ # @authorizer.delete(db) # see comments in busy_handler
64
+ # end
65
+ #
66
+ # result
67
+ #end
68
+ #
69
+ #def trace( db, data=nil, &block )
70
+ # if block
71
+ # cb = API::CallbackData.new
72
+ # cb.proc = block
73
+ # cb.data = data
74
+ # result = API.sqlite3_trace( db, API::Sqlite3_ruby_trace, cb )
75
+ # @trace[db] = cb # see comments in busy_handler
76
+ # else
77
+ # result = API.sqlite3_trace( db, nil, nil )
78
+ # @trace.delete(db) # see comments in busy_handler
79
+ # end
80
+ #
81
+ # result
82
+ #end
83
+
84
+ def create_function( db, name, args, text, cookie, func, step, final )
85
+ if func || ( step && final )
86
+ cb = CallbackData.new
87
+ cb.proc = cb.proc2 = nil
88
+ cb.data = cookie
89
+ end
90
+
91
+ if func
92
+ cb.proc = func
93
+ step = final = nil
94
+ elsif step && final
95
+ cb.proc = step
96
+ cb.proc2 = final
97
+
98
+ func = nil
99
+ end
100
+
101
+ result = CSSQLite.sqlite3_create_function( db, name, args, text, cb, func, step, final )
102
+
103
+ # see comments in busy_handler
104
+ if cb
105
+ @callback_data[ name ] = cb
106
+ else
107
+ @callback_data.delete( name )
108
+ end
109
+
110
+ return result
111
+ end
112
+
113
+ def aggregate_context( context, n = 0)
114
+ CSSQLite.sqlite3_aggregate_context( context, n ).to_a
115
+ end
116
+
117
+ def result_text( context, result, utf16=false )
118
+ CSSQLite.sqlite3_result_text( context, result.to_s, -1, nil )
119
+ end
120
+
121
+ def self.api_delegate( name )
122
+ eval "def #{name} (*args) ; CSSQLite.sqlite3_#{name}( *args ) ; end"
123
+ end
124
+
125
+ api_delegate :errmsg
126
+ api_delegate :libversion
127
+ api_delegate :close
128
+ api_delegate :last_insert_rowid
129
+ api_delegate :changes
130
+ api_delegate :total_changes
131
+ api_delegate :interrupt
132
+ api_delegate :busy_timeout
133
+ api_delegate :errcode
134
+ api_delegate :bind_blob
135
+ api_delegate :bind_double
136
+ api_delegate :bind_int
137
+ api_delegate :bind_int64
138
+ api_delegate :bind_null
139
+ api_delegate :bind_parameter_count
140
+ api_delegate :bind_parameter_name
141
+ api_delegate :bind_parameter_index
142
+ api_delegate :column_count
143
+ api_delegate :step
144
+ api_delegate :data_count
145
+ api_delegate :column_blob
146
+ api_delegate :column_bytes
147
+ api_delegate :column_bytes16
148
+ api_delegate :column_decltype
149
+ api_delegate :column_double
150
+ api_delegate :column_int
151
+ api_delegate :column_int64
152
+ api_delegate :column_name
153
+ api_delegate :column_text
154
+ api_delegate :column_type
155
+ api_delegate :finalize
156
+ api_delegate :reset
157
+ api_delegate :aggregate_count
158
+ api_delegate :value_blob
159
+ api_delegate :value_bytes
160
+ api_delegate :value_bytes16
161
+ api_delegate :value_double
162
+ api_delegate :value_int
163
+ api_delegate :value_int64
164
+ api_delegate :value_text
165
+ api_delegate :value_type
166
+ api_delegate :result_blob
167
+ api_delegate :result_double
168
+ api_delegate :result_error
169
+ api_delegate :result_int
170
+ api_delegate :result_int64
171
+ api_delegate :result_null
172
+ api_delegate :result_value
173
+ end
174
+
175
+ end ; end ; end
@@ -0,0 +1,68 @@
1
+ require 'sqlite3/constants'
2
+
3
+ module SQLite3
4
+
5
+ class Exception < ::StandardError
6
+ @code = 0
7
+
8
+ # The numeric error code that this exception represents.
9
+ def self.code
10
+ @code
11
+ end
12
+
13
+ # A convenience for accessing the error code for this exception.
14
+ def code
15
+ self.class.code
16
+ end
17
+ end
18
+
19
+ class SQLException < Exception; end
20
+ class InternalException < Exception; end
21
+ class PermissionException < Exception; end
22
+ class AbortException < Exception; end
23
+ class BusyException < Exception; end
24
+ class LockedException < Exception; end
25
+ class MemoryException < Exception; end
26
+ class ReadOnlyException < Exception; end
27
+ class InterruptException < Exception; end
28
+ class IOException < Exception; end
29
+ class CorruptException < Exception; end
30
+ class NotFoundException < Exception; end
31
+ class FullException < Exception; end
32
+ class CantOpenException < Exception; end
33
+ class ProtocolException < Exception; end
34
+ class EmptyException < Exception; end
35
+ class SchemaChangedException < Exception; end
36
+ class TooBigException < Exception; end
37
+ class ConstraintException < Exception; end
38
+ class MismatchException < Exception; end
39
+ class MisuseException < Exception; end
40
+ class UnsupportedException < Exception; end
41
+ class AuthorizationException < Exception; end
42
+ class FormatException < Exception; end
43
+ class RangeException < Exception; end
44
+ class NotADatabaseException < Exception; end
45
+
46
+ EXCEPTIONS = [
47
+ nil,
48
+ SQLException, InternalException, PermissionException,
49
+ AbortException, BusyException, LockedException, MemoryException,
50
+ ReadOnlyException, InterruptException, IOException, CorruptException,
51
+ NotFoundException, FullException, CantOpenException, ProtocolException,
52
+ EmptyException, SchemaChangedException, TooBigException,
53
+ ConstraintException, MismatchException, MisuseException,
54
+ UnsupportedException, AuthorizationException, FormatException,
55
+ RangeException, NotADatabaseException
56
+ ].each_with_index { |e,i| e.instance_variable_set( :@code, i ) if e }
57
+
58
+ module Error
59
+ def check( result, db=nil, msg=nil )
60
+ unless result == Constants::ErrorCode::OK
61
+ msg = ( msg ? msg + ": " : "" ) + db.errmsg if db
62
+ raise(( EXCEPTIONS[result] || SQLite3::Exception ), msg)
63
+ end
64
+ end
65
+ module_function :check
66
+ end
67
+
68
+ end
@@ -0,0 +1,271 @@
1
+ require 'sqlite3/errors'
2
+
3
+ module SQLite3
4
+
5
+ # This module is intended for inclusion solely by the Database class. It
6
+ # defines convenience methods for the various pragmas supported by SQLite3.
7
+ #
8
+ # For a detailed description of these pragmas, see the SQLite3 documentation
9
+ # at http://sqlite.org/pragma.html.
10
+ module Pragmas
11
+
12
+ # Returns +true+ or +false+ depending on the value of the named pragma.
13
+ def get_boolean_pragma( name )
14
+ get_first_value( "PRAGMA #{name}" ) != "0"
15
+ end
16
+ private :get_boolean_pragma
17
+
18
+ # Sets the given pragma to the given boolean value. The value itself
19
+ # may be +true+ or +false+, or any other commonly used string or
20
+ # integer that represents truth.
21
+ def set_boolean_pragma( name, mode )
22
+ case mode
23
+ when String
24
+ case mode.downcase
25
+ when "on", "yes", "true", "y", "t"; mode = "'ON'"
26
+ when "off", "no", "false", "n", "f"; mode = "'OFF'"
27
+ else
28
+ raise Exception,
29
+ "unrecognized pragma parameter #{mode.inspect}"
30
+ end
31
+ when true, 1
32
+ mode = "ON"
33
+ when false, 0, nil
34
+ mode = "OFF"
35
+ else
36
+ raise Exception,
37
+ "unrecognized pragma parameter #{mode.inspect}"
38
+ end
39
+
40
+ execute( "PRAGMA #{name}=#{mode}" )
41
+ end
42
+ private :set_boolean_pragma
43
+
44
+ # Requests the given pragma (and parameters), and if the block is given,
45
+ # each row of the result set will be yielded to it. Otherwise, the results
46
+ # are returned as an array.
47
+ def get_query_pragma( name, *parms, &block ) # :yields: row
48
+ if parms.empty?
49
+ execute( "PRAGMA #{name}", &block )
50
+ else
51
+ args = "'" + parms.join("','") + "'"
52
+ execute( "PRAGMA #{name}( #{args} )", &block )
53
+ end
54
+ end
55
+ private :get_query_pragma
56
+
57
+ # Return the value of the given pragma.
58
+ def get_enum_pragma( name )
59
+ get_first_value( "PRAGMA #{name}" )
60
+ end
61
+ private :get_enum_pragma
62
+
63
+ # Set the value of the given pragma to +mode+. The +mode+ parameter must
64
+ # conform to one of the values in the given +enum+ array. Each entry in
65
+ # the array is another array comprised of elements in the enumeration that
66
+ # have duplicate values. See #synchronous, #default_synchronous,
67
+ # #temp_store, and #default_temp_store for usage examples.
68
+ def set_enum_pragma( name, mode, enums )
69
+ match = enums.find { |p| p.find { |i| i.to_s.downcase == mode.to_s.downcase } }
70
+ raise Exception,
71
+ "unrecognized #{name} #{mode.inspect}" unless match
72
+ execute( "PRAGMA #{name}='#{match.first.upcase}'" )
73
+ end
74
+ private :set_enum_pragma
75
+
76
+ # Returns the value of the given pragma as an integer.
77
+ def get_int_pragma( name )
78
+ get_first_value( "PRAGMA #{name}" ).to_i
79
+ end
80
+ private :get_int_pragma
81
+
82
+ # Set the value of the given pragma to the integer value of the +value+
83
+ # parameter.
84
+ def set_int_pragma( name, value )
85
+ execute( "PRAGMA #{name}=#{value.to_i}" )
86
+ end
87
+ private :set_int_pragma
88
+
89
+ # The enumeration of valid synchronous modes.
90
+ SYNCHRONOUS_MODES = [ [ 'full', 2 ], [ 'normal', 1 ], [ 'off', 0 ] ]
91
+
92
+ # The enumeration of valid temp store modes.
93
+ TEMP_STORE_MODES = [ [ 'default', 0 ], [ 'file', 1 ], [ 'memory', 2 ] ]
94
+
95
+ # Does an integrity check on the database. If the check fails, a
96
+ # SQLite3::Exception will be raised. Otherwise it
97
+ # returns silently.
98
+ def integrity_check
99
+ execute( "PRAGMA integrity_check" ) do |row|
100
+ raise Exception, row[0] if row[0] != "ok"
101
+ end
102
+ end
103
+
104
+ def auto_vacuum
105
+ get_boolean_pragma "auto_vacuum"
106
+ end
107
+
108
+ def auto_vacuum=( mode )
109
+ set_boolean_pragma "auto_vacuum", mode
110
+ end
111
+
112
+ def schema_cookie
113
+ get_int_pragma "schema_cookie"
114
+ end
115
+
116
+ def schema_cookie=( cookie )
117
+ set_int_pragma "schema_cookie", cookie
118
+ end
119
+
120
+ def user_cookie
121
+ get_int_pragma "user_cookie"
122
+ end
123
+
124
+ def user_cookie=( cookie )
125
+ set_int_pragma "user_cookie", cookie
126
+ end
127
+
128
+ def cache_size
129
+ get_int_pragma "cache_size"
130
+ end
131
+
132
+ def cache_size=( size )
133
+ set_int_pragma "cache_size", size
134
+ end
135
+
136
+ def default_cache_size
137
+ get_int_pragma "default_cache_size"
138
+ end
139
+
140
+ def default_cache_size=( size )
141
+ set_int_pragma "default_cache_size", size
142
+ end
143
+
144
+ def default_synchronous
145
+ get_enum_pragma "default_synchronous"
146
+ end
147
+
148
+ def default_synchronous=( mode )
149
+ set_enum_pragma "default_synchronous", mode, SYNCHRONOUS_MODES
150
+ end
151
+
152
+ def synchronous
153
+ get_enum_pragma "synchronous"
154
+ end
155
+
156
+ def synchronous=( mode )
157
+ set_enum_pragma "synchronous", mode, SYNCHRONOUS_MODES
158
+ end
159
+
160
+ def default_temp_store
161
+ get_enum_pragma "default_temp_store"
162
+ end
163
+
164
+ def default_temp_store=( mode )
165
+ set_enum_pragma "default_temp_store", mode, TEMP_STORE_MODES
166
+ end
167
+
168
+ def temp_store
169
+ get_enum_pragma "temp_store"
170
+ end
171
+
172
+ def temp_store=( mode )
173
+ set_enum_pragma "temp_store", mode, TEMP_STORE_MODES
174
+ end
175
+
176
+ def full_column_names
177
+ get_boolean_pragma "full_column_names"
178
+ end
179
+
180
+ def full_column_names=( mode )
181
+ set_boolean_pragma "full_column_names", mode
182
+ end
183
+
184
+ def parser_trace
185
+ get_boolean_pragma "parser_trace"
186
+ end
187
+
188
+ def parser_trace=( mode )
189
+ set_boolean_pragma "parser_trace", mode
190
+ end
191
+
192
+ def vdbe_trace
193
+ get_boolean_pragma "vdbe_trace"
194
+ end
195
+
196
+ def vdbe_trace=( mode )
197
+ set_boolean_pragma "vdbe_trace", mode
198
+ end
199
+
200
+ def database_list( &block ) # :yields: row
201
+ get_query_pragma "database_list", &block
202
+ end
203
+
204
+ def foreign_key_list( table, &block ) # :yields: row
205
+ get_query_pragma "foreign_key_list", table, &block
206
+ end
207
+
208
+ def index_info( index, &block ) # :yields: row
209
+ get_query_pragma "index_info", index, &block
210
+ end
211
+
212
+ def index_list( table, &block ) # :yields: row
213
+ get_query_pragma "index_list", table, &block
214
+ end
215
+
216
+ def table_info( table, &block ) # :yields: row
217
+ columns, *rows = execute2("PRAGMA table_info(#{table})")
218
+
219
+ needs_tweak_default = version_compare(driver.libversion, "3.3.7") > 0
220
+
221
+ result = [] unless block_given?
222
+ rows.each do |row|
223
+ new_row = {}
224
+ columns.each_with_index do |name, index|
225
+ new_row[name] = row[index]
226
+ end
227
+
228
+ tweak_default(new_row) if needs_tweak_default
229
+
230
+ if block_given?
231
+ yield new_row
232
+ else
233
+ result << new_row
234
+ end
235
+ end
236
+
237
+ result
238
+ end
239
+
240
+ private
241
+
242
+ # Compares two version strings
243
+ def version_compare(v1, v2)
244
+ v1 = v1.split(".").map { |i| i.to_i }
245
+ v2 = v2.split(".").map { |i| i.to_i }
246
+ parts = [v1.length, v2.length].max
247
+ v1.push 0 while v1.length < parts
248
+ v2.push 0 while v2.length < parts
249
+ v1.zip(v2).each do |a,b|
250
+ return -1 if a < b
251
+ return 1 if a > b
252
+ end
253
+ return 0
254
+ end
255
+
256
+ # Since SQLite 3.3.8, the table_info pragma has returned the default
257
+ # value of the row as a quoted SQL value. This method essentially
258
+ # unquotes those values.
259
+ def tweak_default(hash)
260
+ case hash["dflt_value"]
261
+ when /^null$/i
262
+ hash["dflt_value"] = nil
263
+ when /^'(.*)'$/
264
+ hash["dflt_value"] = $1.gsub(/''/, "'")
265
+ when /^"(.*)"$/
266
+ hash["dflt_value"] = $1.gsub(/""/, '"')
267
+ end
268
+ end
269
+ end
270
+
271
+ end
@@ -0,0 +1,176 @@
1
+ require 'sqlite3/constants'
2
+ require 'sqlite3/errors'
3
+
4
+ module SQLite3
5
+
6
+ # The ResultSet object encapsulates the enumerability of a query's output.
7
+ # It is a simple cursor over the data that the query returns. It will
8
+ # very rarely (if ever) be instantiated directly. Instead, client's should
9
+ # obtain a ResultSet instance via Statement#execute.
10
+ class ResultSet
11
+ include Enumerable
12
+
13
+ # The class of which we return an object in case we want an Array as
14
+ # result. (ArrayFields is installed.)
15
+ class ArrayWithTypes < Array
16
+ attr_accessor :types
17
+ end
18
+
19
+ # The class of which we return an object in case we want an Array as
20
+ # result. (ArrayFields is not installed.)
21
+ class ArrayWithTypesAndFields < Array
22
+ attr_accessor :types
23
+ attr_accessor :fields
24
+ end
25
+
26
+ # The class of which we return an object in case we want a Hash as
27
+ # result.
28
+ class HashWithTypes < Hash
29
+ attr_accessor :types
30
+ end
31
+
32
+ # Create a new ResultSet attached to the given database, using the
33
+ # given sql text.
34
+ def initialize( db, stmt )
35
+ @db = db
36
+ @driver = @db.driver
37
+ @stmt = stmt
38
+ commence
39
+ end
40
+
41
+ # A convenience method for compiling the virtual machine and stepping
42
+ # to the first row of the result set.
43
+ def commence
44
+ result = @driver.step( @stmt.handle )
45
+ if result == Constants::ErrorCode::ERROR
46
+ @driver.reset( @stmt.handle )
47
+ end
48
+ check result
49
+ @first_row = true
50
+ end
51
+ private :commence
52
+
53
+ def check( result )
54
+ @eof = ( result == Constants::ErrorCode::DONE )
55
+ found = ( result == Constants::ErrorCode::ROW )
56
+ Error.check( result, @db ) unless @eof || found
57
+ end
58
+ private :check
59
+
60
+ # Reset the cursor, so that a result set which has reached end-of-file
61
+ # can be rewound and reiterated.
62
+ def reset( *bind_params )
63
+ @stmt.must_be_open!
64
+ @stmt.reset!(false)
65
+ @driver.reset( @stmt.handle )
66
+ @stmt.bind_params( *bind_params )
67
+ @eof = false
68
+ commence
69
+ end
70
+
71
+ # Query whether the cursor has reached the end of the result set or not.
72
+ def eof?
73
+ @eof
74
+ end
75
+
76
+ # Obtain the next row from the cursor. If there are no more rows to be
77
+ # had, this will return +nil+. If type translation is active on the
78
+ # corresponding database, the values in the row will be translated
79
+ # according to their types.
80
+ #
81
+ # The returned value will be an array, unless Database#results_as_hash has
82
+ # been set to +true+, in which case the returned value will be a hash.
83
+ #
84
+ # For arrays, the column names are accessible via the +fields+ property,
85
+ # and the column types are accessible via the +types+ property.
86
+ #
87
+ # For hashes, the column names are the keys of the hash, and the column
88
+ # types are accessible via the +types+ property.
89
+ def next
90
+ return nil if @eof
91
+
92
+ @stmt.must_be_open!
93
+
94
+ unless @first_row
95
+ result = @driver.step( @stmt.handle )
96
+ check result
97
+ end
98
+
99
+ @first_row = false
100
+
101
+ unless @eof
102
+ row = []
103
+ @driver.data_count( @stmt.handle ).times do |column|
104
+ type = @driver.column_type( @stmt.handle, column )
105
+
106
+ if type == Constants::ColumnType::TEXT
107
+ row << @driver.column_text( @stmt.handle, column )
108
+ elsif type == Constants::ColumnType::NULL
109
+ row << nil
110
+ elsif type == Constants::ColumnType::BLOB
111
+ row << @driver.column_blob( @stmt.handle, column )
112
+ else
113
+ row << @driver.column_text( @stmt.handle, column )
114
+ end
115
+ end
116
+
117
+ if @db.type_translation
118
+ row = @stmt.types.zip( row ).map do |type, value|
119
+ @db.translator.translate( type, value )
120
+ end
121
+ end
122
+
123
+ if @db.results_as_hash
124
+ new_row = HashWithTypes[ *( @stmt.columns.zip( row ).to_a.flatten ) ]
125
+ row.each_with_index { |value,idx| new_row[idx] = value }
126
+ row = new_row
127
+ else
128
+ if row.respond_to?(:fields)
129
+ row = ArrayWithTypes.new(row)
130
+ else
131
+ row = ArrayWithTypesAndFields.new(row)
132
+ end
133
+ row.fields = @stmt.columns
134
+ end
135
+
136
+ row.types = @stmt.types
137
+
138
+ return row
139
+ end
140
+
141
+ nil
142
+ end
143
+
144
+ # Required by the Enumerable mixin. Provides an internal iterator over the
145
+ # rows of the result set.
146
+ def each
147
+ while row=self.next
148
+ yield row
149
+ end
150
+ end
151
+
152
+ # Closes the statement that spawned this result set.
153
+ # <em>Use with caution!</em> Closing a result set will automatically
154
+ # close any other result sets that were spawned from the same statement.
155
+ def close
156
+ @stmt.close
157
+ end
158
+
159
+ # Queries whether the underlying statement has been closed or not.
160
+ def closed?
161
+ @stmt.closed?
162
+ end
163
+
164
+ # Returns the types of the columns returned by this result set.
165
+ def types
166
+ @stmt.types
167
+ end
168
+
169
+ # Returns the names of the columns returned by this result set.
170
+ def columns
171
+ @stmt.columns
172
+ end
173
+
174
+ end
175
+
176
+ end