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,711 @@
1
+ require 'sqlite3/constants'
2
+ require 'sqlite3/errors'
3
+ require 'sqlite3/pragmas'
4
+ require 'sqlite3/statement'
5
+ require 'sqlite3/translator'
6
+ require 'sqlite3/value'
7
+
8
+ module SQLite3
9
+
10
+ # The Database class encapsulates a single connection to a SQLite3 database.
11
+ # Its usage is very straightforward:
12
+ #
13
+ # require 'sqlite3'
14
+ #
15
+ # db = SQLite3::Database.new( "data.db" )
16
+ #
17
+ # db.execute( "select * from table" ) do |row|
18
+ # p row
19
+ # end
20
+ #
21
+ # db.close
22
+ #
23
+ # It wraps the lower-level methods provides by the selected driver, and
24
+ # includes the Pragmas module for access to various pragma convenience
25
+ # methods.
26
+ #
27
+ # The Database class provides type translation services as well, by which
28
+ # the SQLite3 data types (which are all represented as strings) may be
29
+ # converted into their corresponding types (as defined in the schemas
30
+ # for their tables). This translation only occurs when querying data from
31
+ # the database--insertions and updates are all still typeless.
32
+ #
33
+ # Furthermore, the Database class has been designed to work well with the
34
+ # ArrayFields module from Ara Howard. If you require the ArrayFields
35
+ # module before performing a query, and if you have not enabled results as
36
+ # hashes, then the results will all be indexible by field name.
37
+ class Database
38
+ include Pragmas
39
+
40
+ class <<self
41
+
42
+ alias :open :new
43
+
44
+ # Quotes the given string, making it safe to use in an SQL statement.
45
+ # It replaces all instances of the single-quote character with two
46
+ # single-quote characters. The modified string is returned.
47
+ def quote( string )
48
+ string.gsub( /'/, "''" )
49
+ end
50
+
51
+ end
52
+
53
+ # The low-level opaque database handle that this object wraps.
54
+ attr_reader :handle
55
+
56
+ # A reference to the underlying SQLite3 driver used by this database.
57
+ attr_reader :driver
58
+
59
+ # A boolean that indicates whether rows in result sets should be returned
60
+ # as hashes or not. By default, rows are returned as arrays.
61
+ attr_accessor :results_as_hash
62
+
63
+ # A boolean indicating whether or not type translation is enabled for this
64
+ # database.
65
+ attr_accessor :type_translation
66
+
67
+ # Create a new Database object that opens the given file. If utf16
68
+ # is +true+, the filename is interpreted as a UTF-16 encoded string.
69
+ #
70
+ # By default, the new database will return result rows as arrays
71
+ # (#results_as_hash) and has type translation disabled (#type_translation=).
72
+ def initialize( file_name, options={} )
73
+ utf16 = options.fetch(:utf16, false)
74
+ load_driver( options[:driver] )
75
+
76
+ @statement_factory = options[:statement_factory] || Statement
77
+
78
+ result, @handle = @driver.open( file_name )
79
+ Error.check( result, self, "could not open database" )
80
+
81
+ @closed = false
82
+ @results_as_hash = options.fetch(:results_as_hash,false)
83
+ @type_translation = options.fetch(:type_translation,false)
84
+ @translator = nil
85
+ @transaction_active = false
86
+ end
87
+
88
+ # Return +true+ if the string is a valid (ie, parsable) SQL statement, and
89
+ # +false+ otherwise. If +utf16+ is +true+, then the string is a UTF-16
90
+ # character string.
91
+ def complete?( string, utf16=false )
92
+ @driver.complete?( string )
93
+ end
94
+
95
+ # Return a string describing the last error to have occurred with this
96
+ # database.
97
+ def errmsg( utf16=false )
98
+ @driver.errmsg( @handle )
99
+ end
100
+
101
+ # Return an integer representing the last error to have occurred with this
102
+ # database.
103
+ def errcode
104
+ @driver.errcode( @handle )
105
+ end
106
+
107
+ # Return the type translator employed by this database instance. Each
108
+ # database instance has its own type translator; this allows for different
109
+ # type handlers to be installed in each instance without affecting other
110
+ # instances. Furthermore, the translators are instantiated lazily, so that
111
+ # if a database does not use type translation, it will not be burdened by
112
+ # the overhead of a useless type translator. (See the Translator class.)
113
+ def translator
114
+ @translator ||= Translator.new
115
+ end
116
+
117
+ # Closes this database.
118
+ def close
119
+ unless @closed
120
+ result = @driver.close( @handle )
121
+ Error.check( result, self )
122
+ end
123
+ @closed = true
124
+ end
125
+
126
+ # Returns +true+ if this database instance has been closed (see #close).
127
+ def closed?
128
+ @closed
129
+ end
130
+
131
+ # Installs (or removes) a block that will be invoked for every SQL
132
+ # statement executed. The block receives a two parameters: the +data+
133
+ # argument, and the SQL statement executed. If the block is +nil+,
134
+ # any existing tracer will be uninstalled.
135
+ #def trace( data=nil, &block )
136
+ # @driver.trace( @handle, data, &block )
137
+ #end
138
+
139
+ # Installs (or removes) a block that will be invoked for every access
140
+ # to the database. If the block returns 0 (or +nil+), the statement
141
+ # is allowed to proceed. Returning 1 causes an authorization error to
142
+ # occur, and returning 2 causes the access to be silently denied.
143
+ #def authorizer( data=nil, &block )
144
+ # result = @driver.set_authorizer( @handle, data, &block )
145
+ # Error.check( result, self )
146
+ #end
147
+
148
+ # Returns a Statement object representing the given SQL. This does not
149
+ # execute the statement; it merely prepares the statement for execution.
150
+ #
151
+ # The Statement can then be executed using Statement#execute.
152
+ #
153
+ def prepare( sql )
154
+ stmt = @statement_factory.new( self, sql )
155
+ if block_given?
156
+ begin
157
+ yield stmt
158
+ ensure
159
+ stmt.close
160
+ end
161
+ else
162
+ return stmt
163
+ end
164
+ end
165
+
166
+ # Executes the given SQL statement. If additional parameters are given,
167
+ # they are treated as bind variables, and are bound to the placeholders in
168
+ # the query.
169
+ #
170
+ # Note that if any of the values passed to this are hashes, then the
171
+ # key/value pairs are each bound separately, with the key being used as
172
+ # the name of the placeholder to bind the value to.
173
+ #
174
+ # The block is optional. If given, it will be invoked for each row returned
175
+ # by the query. Otherwise, any results are accumulated into an array and
176
+ # returned wholesale.
177
+ #
178
+ # See also #execute2, #query, and #execute_batch for additional ways of
179
+ # executing statements.
180
+ def execute( sql, *bind_vars )
181
+ prepare( sql ) do |stmt|
182
+ result = stmt.execute( *bind_vars )
183
+ if block_given?
184
+ result.each { |row| yield row }
185
+ else
186
+ return result.inject( [] ) { |arr,row| arr << row; arr }
187
+ end
188
+ end
189
+ end
190
+
191
+ # Executes the given SQL statement, exactly as with #execute. However, the
192
+ # first row returned (either via the block, or in the returned array) is
193
+ # always the names of the columns. Subsequent rows correspond to the data
194
+ # from the result set.
195
+ #
196
+ # Thus, even if the query itself returns no rows, this method will always
197
+ # return at least one row--the names of the columns.
198
+ #
199
+ # See also #execute, #query, and #execute_batch for additional ways of
200
+ # executing statements.
201
+ def execute2( sql, *bind_vars )
202
+ prepare( sql ) do |stmt|
203
+ result = stmt.execute( *bind_vars )
204
+ if block_given?
205
+ yield result.columns
206
+ result.each { |row| yield row }
207
+ else
208
+ return result.inject( [ result.columns ] ) { |arr,row|
209
+ arr << row; arr }
210
+ end
211
+ end
212
+ end
213
+
214
+ # Executes all SQL statements in the given string. By contrast, the other
215
+ # means of executing queries will only execute the first statement in the
216
+ # string, ignoring all subsequent statements. This will execute each one
217
+ # in turn. The same bind parameters, if given, will be applied to each
218
+ # statement.
219
+ #
220
+ # This always returns +nil+, making it unsuitable for queries that return
221
+ # rows.
222
+ def execute_batch( sql, *bind_vars )
223
+ sql = sql.strip
224
+ until sql.empty? do
225
+ prepare( sql ) do |stmt|
226
+ stmt.execute( *bind_vars )
227
+ sql = stmt.remainder.strip
228
+ end
229
+ end
230
+ nil
231
+ end
232
+
233
+ # This is a convenience method for creating a statement, binding
234
+ # paramters to it, and calling execute:
235
+ #
236
+ # result = db.query( "select * from foo where a=?", 5 )
237
+ # # is the same as
238
+ # result = db.prepare( "select * from foo where a=?" ).execute( 5 )
239
+ #
240
+ # You must be sure to call +close+ on the ResultSet instance that is
241
+ # returned, or you could have problems with locks on the table. If called
242
+ # with a block, +close+ will be invoked implicitly when the block
243
+ # terminates.
244
+ def query( sql, *bind_vars )
245
+ result = prepare( sql ).execute( *bind_vars )
246
+ if block_given?
247
+ begin
248
+ yield result
249
+ ensure
250
+ result.close
251
+ end
252
+ else
253
+ return result
254
+ end
255
+ end
256
+
257
+ # A convenience method for obtaining the first row of a result set, and
258
+ # discarding all others. It is otherwise identical to #execute.
259
+ #
260
+ # See also #get_first_value.
261
+ def get_first_row( sql, *bind_vars )
262
+ execute( sql, *bind_vars ) { |row| return row }
263
+ nil
264
+ end
265
+
266
+ # A convenience method for obtaining the first value of the first row of a
267
+ # result set, and discarding all other values and rows. It is otherwise
268
+ # identical to #execute.
269
+ #
270
+ # See also #get_first_row.
271
+ def get_first_value( sql, *bind_vars )
272
+ execute( sql, *bind_vars ) { |row| return row[0] }
273
+ nil
274
+ end
275
+
276
+ # Obtains the unique row ID of the last row to be inserted by this Database
277
+ # instance.
278
+ def last_insert_row_id
279
+ @driver.last_insert_rowid( @handle )
280
+ end
281
+
282
+ # Returns the number of changes made to this database instance by the last
283
+ # operation performed. Note that a "delete from table" without a where
284
+ # clause will not affect this value.
285
+ def changes
286
+ @driver.changes( @handle )
287
+ end
288
+
289
+ # Returns the total number of changes made to this database instance
290
+ # since it was opened.
291
+ def total_changes
292
+ @driver.total_changes( @handle )
293
+ end
294
+
295
+ # Interrupts the currently executing operation, causing it to abort.
296
+ def interrupt
297
+ @driver.interrupt( @handle )
298
+ end
299
+
300
+ # Register a busy handler with this database instance. When a requested
301
+ # resource is busy, this handler will be invoked. If the handler returns
302
+ # +false+, the operation will be aborted; otherwise, the resource will
303
+ # be requested again.
304
+ #
305
+ # The handler will be invoked with the name of the resource that was
306
+ # busy, and the number of times it has been retried.
307
+ #
308
+ # See also the mutually exclusive #busy_timeout.
309
+ def busy_handler( data=nil, &block ) # :yields: data, retries
310
+ result = @driver.busy_handler( @handle, data, &block )
311
+ Error.check( result, self )
312
+ end
313
+
314
+ # Indicates that if a request for a resource terminates because that
315
+ # resource is busy, SQLite should sleep and retry for up to the indicated
316
+ # number of milliseconds. By default, SQLite does not retry
317
+ # busy resources. To restore the default behavior, send 0 as the
318
+ # +ms+ parameter.
319
+ #
320
+ # See also the mutually exclusive #busy_handler.
321
+ #def busy_timeout( ms )
322
+ # result = @driver.busy_timeout( @handle, ms )
323
+ # Error.check( result, self )
324
+ #end
325
+
326
+ # Creates a new function for use in SQL statements. It will be added as
327
+ # +name+, with the given +arity+. (For variable arity functions, use
328
+ # -1 for the arity.)
329
+ #
330
+ # The block should accept at least one parameter--the FunctionProxy
331
+ # instance that wraps this function invocation--and any other
332
+ # arguments it needs (up to its arity).
333
+ #
334
+ # The block does not return a value directly. Instead, it will invoke
335
+ # the FunctionProxy#set_result method on the +func+ parameter and
336
+ # indicate the return value that way.
337
+ #
338
+ # Example:
339
+ #
340
+ # db.create_function( "maim", 1 ) do |func, value|
341
+ # if value.nil?
342
+ # func.result = nil
343
+ # else
344
+ # func.result = value.split(//).sort.join
345
+ # end
346
+ # end
347
+ #
348
+ # puts db.get_first_value( "select maim(name) from table" )
349
+ def create_function( name, arity, text_rep=Constants::TextRep::ANY, &block ) # :yields: func, *args
350
+ # begin
351
+ callback = proc do |func,*args|
352
+ begin
353
+ block.call( FunctionProxy.new( @driver, func ), *args.map{|v| Value.new(self,v)} )
354
+ rescue StandardError, Exception => e
355
+ @driver.result_error( func, "#{e.message} (#{e.class})", -1 )
356
+ end
357
+ end
358
+
359
+ result = @driver.create_function( @handle, name, arity, text_rep, nil, callback, nil, nil )
360
+ Error.check( result, self )
361
+
362
+ self
363
+ end
364
+
365
+ # Creates a new aggregate function for use in SQL statements. Aggregate
366
+ # functions are functions that apply over every row in the result set,
367
+ # instead of over just a single row. (A very common aggregate function
368
+ # is the "count" function, for determining the number of rows that match
369
+ # a query.)
370
+ #
371
+ # The new function will be added as +name+, with the given +arity+. (For
372
+ # variable arity functions, use -1 for the arity.)
373
+ #
374
+ # The +step+ parameter must be a proc object that accepts as its first
375
+ # parameter a FunctionProxy instance (representing the function
376
+ # invocation), with any subsequent parameters (up to the function's arity).
377
+ # The +step+ callback will be invoked once for each row of the result set.
378
+ #
379
+ # The +finalize+ parameter must be a +proc+ object that accepts only a
380
+ # single parameter, the FunctionProxy instance representing the current
381
+ # function invocation. It should invoke FunctionProxy#set_result to
382
+ # store the result of the function.
383
+ #
384
+ # Example:
385
+ #
386
+ # db.create_aggregate( "lengths", 1 ) do
387
+ # step do |func, value|
388
+ # func[ :total ] ||= 0
389
+ # func[ :total ] += ( value ? value.length : 0 )
390
+ # end
391
+ #
392
+ # finalize do |func|
393
+ # func.set_result( func[ :total ] || 0 )
394
+ # end
395
+ # end
396
+ #
397
+ # puts db.get_first_value( "select lengths(name) from table" )
398
+ #
399
+ # See also #create_aggregate_handler for a more object-oriented approach to
400
+ # aggregate functions.
401
+ def create_aggregate( name, arity, step=nil, finalize=nil,
402
+ text_rep=Constants::TextRep::ANY, &block )
403
+ # begin
404
+ if block
405
+ proxy = AggregateDefinitionProxy.new
406
+ proxy.instance_eval(&block)
407
+ step ||= proxy.step_callback
408
+ finalize ||= proxy.finalize_callback
409
+ end
410
+
411
+ step_callback = proc do |func,*args|
412
+ ctx = @driver.aggregate_context( func )
413
+ unless ctx[:__error]
414
+ begin
415
+ step.call( FunctionProxy.new( @driver, func, ctx ),
416
+ *args.map{|v| Value.new(self,v)} )
417
+ rescue Exception => e
418
+ ctx[:__error] = e
419
+ end
420
+ end
421
+ end
422
+
423
+ finalize_callback = proc do |func|
424
+ ctx = @driver.aggregate_context( func )
425
+ unless ctx[:__error]
426
+ begin
427
+ finalize.call( FunctionProxy.new( @driver, func, ctx ) )
428
+ rescue Exception => e
429
+ @driver.result_error( func,
430
+ "#{e.message} (#{e.class})", -1 )
431
+ end
432
+ else
433
+ e = ctx[:__error]
434
+ @driver.result_error( func,
435
+ "#{e.message} (#{e.class})", -1 )
436
+ end
437
+ end
438
+
439
+ result = @driver.create_function( @handle, name, arity, text_rep, nil,
440
+ nil, step_callback, finalize_callback )
441
+ Error.check( result, self )
442
+
443
+ self
444
+ end
445
+
446
+ # This is another approach to creating an aggregate function (see
447
+ # #create_aggregate). Instead of explicitly specifying the name,
448
+ # callbacks, arity, and type, you specify a factory object
449
+ # (the "handler") that knows how to obtain all of that information. The
450
+ # handler should respond to the following messages:
451
+ #
452
+ # +arity+:: corresponds to the +arity+ parameter of #create_aggregate. This
453
+ # message is optional, and if the handler does not respond to it,
454
+ # the function will have an arity of -1.
455
+ # +name+:: this is the name of the function. The handler _must_ implement
456
+ # this message.
457
+ # +new+:: this must be implemented by the handler. It should return a new
458
+ # instance of the object that will handle a specific invocation of
459
+ # the function.
460
+ #
461
+ # The handler instance (the object returned by the +new+ message, described
462
+ # above), must respond to the following messages:
463
+ #
464
+ # +step+:: this is the method that will be called for each step of the
465
+ # aggregate function's evaluation. It should implement the same
466
+ # signature as the +step+ callback for #create_aggregate.
467
+ # +finalize+:: this is the method that will be called to finalize the
468
+ # aggregate function's evaluation. It should implement the
469
+ # same signature as the +finalize+ callback for
470
+ # #create_aggregate.
471
+ #
472
+ # Example:
473
+ #
474
+ # class LengthsAggregateHandler
475
+ # def self.arity; 1; end
476
+ #
477
+ # def initialize
478
+ # @total = 0
479
+ # end
480
+ #
481
+ # def step( ctx, name )
482
+ # @total += ( name ? name.length : 0 )
483
+ # end
484
+ #
485
+ # def finalize( ctx )
486
+ # ctx.set_result( @total )
487
+ # end
488
+ # end
489
+ #
490
+ # db.create_aggregate_handler( LengthsAggregateHandler )
491
+ # puts db.get_first_value( "select lengths(name) from A" )
492
+ def create_aggregate_handler( handler )
493
+ arity = -1
494
+ text_rep = Constants::TextRep::ANY
495
+
496
+ arity = handler.arity if handler.respond_to?(:arity)
497
+ text_rep = handler.text_rep if handler.respond_to?(:text_rep)
498
+ name = handler.name
499
+
500
+ step = proc do |func,*args|
501
+ ctx = @driver.aggregate_context( func )
502
+ unless ctx[ :__error ]
503
+ ctx[ :handler ] ||= handler.new
504
+ begin
505
+ ctx[ :handler ].step( FunctionProxy.new( @driver, func, ctx ),
506
+ *args.map{|v| Value.new(self,v)} )
507
+ rescue Exception, StandardError => e
508
+ ctx[ :__error ] = e
509
+ end
510
+ end
511
+ end
512
+
513
+ finalize = proc do |func|
514
+ ctx = @driver.aggregate_context( func )
515
+ unless ctx[ :__error ]
516
+ ctx[ :handler ] ||= handler.new
517
+ begin
518
+ ctx[ :handler ].finalize( FunctionProxy.new( @driver, func, ctx ) )
519
+ rescue Exception => e
520
+ ctx[ :__error ] = e
521
+ end
522
+ end
523
+
524
+ if ctx[ :__error ]
525
+ e = ctx[ :__error ]
526
+ @driver.sqlite3_result_error( func, "#{e.message} (#{e.class})", -1 )
527
+ end
528
+ end
529
+
530
+ result = @driver.create_function( @handle, name, arity, text_rep, nil,
531
+ nil, step, finalize )
532
+ Error.check( result, self )
533
+
534
+ self
535
+ end
536
+
537
+ # Begins a new transaction. Note that nested transactions are not allowed
538
+ # by SQLite, so attempting to nest a transaction will result in a runtime
539
+ # exception.
540
+ #
541
+ # The +mode+ parameter may be either <tt>:deferred</tt> (the default),
542
+ # <tt>:immediate</tt>, or <tt>:exclusive</tt>.
543
+ #
544
+ # If a block is given, the database instance is yielded to it, and the
545
+ # transaction is committed when the block terminates. If the block
546
+ # raises an exception, a rollback will be performed instead. Note that if
547
+ # a block is given, #commit and #rollback should never be called
548
+ # explicitly or you'll get an error when the block terminates.
549
+ #
550
+ # If a block is not given, it is the caller's responsibility to end the
551
+ # transaction explicitly, either by calling #commit, or by calling
552
+ # #rollback.
553
+ def transaction( mode = :deferred )
554
+ execute "begin #{mode.to_s} transaction"
555
+ @transaction_active = true
556
+
557
+ if block_given?
558
+ abort = false
559
+ begin
560
+ yield self
561
+ rescue ::Object
562
+ abort = true
563
+ raise
564
+ ensure
565
+ abort and rollback or commit
566
+ end
567
+ end
568
+
569
+ true
570
+ end
571
+
572
+ # Commits the current transaction. If there is no current transaction,
573
+ # this will cause an error to be raised. This returns +true+, in order
574
+ # to allow it to be used in idioms like
575
+ # <tt>abort? and rollback or commit</tt>.
576
+ def commit
577
+ execute "commit transaction"
578
+ @transaction_active = false
579
+ true
580
+ end
581
+
582
+ # Rolls the current transaction back. If there is no current transaction,
583
+ # this will cause an error to be raised. This returns +true+, in order
584
+ # to allow it to be used in idioms like
585
+ # <tt>abort? and rollback or commit</tt>.
586
+ def rollback
587
+ execute "rollback transaction"
588
+ @transaction_active = false
589
+ true
590
+ end
591
+
592
+ # Returns +true+ if there is a transaction active, and +false+ otherwise.
593
+ def transaction_active?
594
+ @transaction_active
595
+ end
596
+
597
+ # Loads the corresponding driver, or if it is nil, attempts to locate a
598
+ # suitable driver.
599
+ def load_driver( driver )
600
+ case driver
601
+ when Class
602
+ # do nothing--use what was given
603
+ when Symbol, String
604
+ require "sqlite3/driver/#{driver.to_s.downcase}/driver"
605
+ driver = SQLite3::Driver.const_get( driver )::Driver
606
+ else
607
+ [ "Native" ].each do |d|
608
+ begin
609
+ require "sqlite3/driver/#{d.downcase}/driver"
610
+ driver = SQLite3::Driver.const_get( d )::Driver
611
+ break
612
+ rescue SyntaxError
613
+ raise
614
+ rescue ScriptError, Exception, NameError
615
+ end
616
+ end
617
+ raise "no driver for sqlite3 found" unless driver
618
+ end
619
+
620
+ @driver = driver.new
621
+ end
622
+ private :load_driver
623
+
624
+ # A helper class for dealing with custom functions (see #create_function,
625
+ # #create_aggregate, and #create_aggregate_handler). It encapsulates the
626
+ # opaque function object that represents the current invocation. It also
627
+ # provides more convenient access to the API functions that operate on
628
+ # the function object.
629
+ #
630
+ # This class will almost _always_ be instantiated indirectly, by working
631
+ # with the create methods mentioned above.
632
+ class FunctionProxy
633
+
634
+ # Create a new FunctionProxy that encapsulates the given +func+ object.
635
+ # If context is non-nil, the functions context will be set to that. If
636
+ # it is non-nil, it must quack like a Hash. If it is nil, then none of
637
+ # the context functions will be available.
638
+ def initialize( driver, func, context=nil )
639
+ @driver = driver
640
+ @func = func
641
+ @context = context
642
+ end
643
+
644
+ # Calls #set_result to set the result of this function.
645
+ def result=( result )
646
+ set_result( result )
647
+ end
648
+
649
+ # Set the result of the function to the given value. The function will
650
+ # then return this value.
651
+ def set_result( result, utf16=false )
652
+ @driver.result_text( @func, result )
653
+ end
654
+
655
+ # Set the result of the function to the given error message.
656
+ # The function will then return that error.
657
+ def set_error( error )
658
+ @driver.result_error( @func, error.to_s, -1 )
659
+ end
660
+
661
+ # (Only available to aggregate functions.) Returns the number of rows
662
+ # that the aggregate has processed so far. This will include the current
663
+ # row, and so will always return at least 1.
664
+ def count
665
+ ensure_aggregate!
666
+ @driver.aggregate_count( @func )
667
+ end
668
+
669
+ # Returns the value with the given key from the context. This is only
670
+ # available to aggregate functions.
671
+ def []( key )
672
+ ensure_aggregate!
673
+ @context[ key ]
674
+ end
675
+
676
+ # Sets the value with the given key in the context. This is only
677
+ # available to aggregate functions.
678
+ def []=( key, value )
679
+ ensure_aggregate!
680
+ @context[ key ] = value
681
+ end
682
+
683
+ # A function for performing a sanity check, to ensure that the function
684
+ # being invoked is an aggregate function. This is implied by the
685
+ # existence of the context variable.
686
+ def ensure_aggregate!
687
+ unless @context
688
+ raise MisuseException, "function is not an aggregate"
689
+ end
690
+ end
691
+ private :ensure_aggregate!
692
+
693
+ end
694
+
695
+ # A proxy used for defining the callbacks to an aggregate function.
696
+ class AggregateDefinitionProxy # :nodoc:
697
+ attr_reader :step_callback, :finalize_callback
698
+
699
+ def step( &block )
700
+ @step_callback = block
701
+ end
702
+
703
+ def finalize( &block )
704
+ @finalize_callback = block
705
+ end
706
+ end
707
+
708
+ end
709
+
710
+ end
711
+