Checkout of Instiki Trunk 1/21/2007.

This commit is contained in:
Jacques Distler 2007-01-22 07:43:50 -06:00
commit 69b62b6f33
1138 changed files with 139586 additions and 0 deletions

35
vendor/plugins/dnsbl_check/README vendored Normal file
View file

@ -0,0 +1,35 @@
This plugin checks if the client is listed in RBLs (Real-time Blackhole Lists).
These are lists of IP addresses misbehaving. There are many RBLs, some are more
aggressive than others. More information at http://en.wikipedia.org/wiki/DNSBL
This filter will result in one DNS request for every blocklist that you have
configured. This might be problematic for sites under heavy load, although this
plugin has been used on high-traffic sites without any problem. One DNS
request takes a few miliseconds to complete, after all.
INSTALLATION
1. Download dnsbl_check-(version).tar.gz. You agree to the license.
2. Go to your application's 'vendor/plugins' directory
3. Untar (un-winzip) the above file: tar xvfz dnsbl_check.tar.gz
4. Restart your application.
VERSION HISTORY
0.1 18 June 2006 Initial release
0.2 10 June 2006 Renamed to dnsbl_check, bugfix
0.3 20 June 2006 Removed sorbs from distribution, was not supposed to be included (too aggressive)
0.4 18 July 2006 Explicit return false added, moved to a per-controller basis (not global anymore)
1.0 16 August 2006 Renamed 0.4 to 1.0. I have been using the plugin very succesfully for months now.
1.1 17 October 2006 Multithreaded version
1.2 23 October 2006 Using the native Ruby resolver library for better multithreaded support
1.2.1 25 October 2006 Accepts a wider range of dns responses
1.2.2 11 December 2006 dnsbls are seemingly under attack, added code to cope with failing service
MORE INFORMATION
http://spacebabies.nl/dnsbl_check/
joost@spacebabies.nl

1
vendor/plugins/dnsbl_check/init.rb vendored Normal file
View file

@ -0,0 +1 @@
ActionController::Base.send :include, DNSBL_Check

View file

@ -0,0 +1,58 @@
# This plugin checks if the client is listed in DNSBLs (DNS Blackhole Lists).
# These are lists of IP addresses misbehaving. There are many DNSBLs, some are more
# aggressive than others. More information at http://en.wikipedia.org/wiki/DNSBL
#
# This plugin will perform one DNS request per client per blocklist.
# This plugin will deny service to clients those blocklists have listed.
# Whether any of this is acceptable is up to you.
#
# mailto:joost@spacebabies.nl
# License: MIT License, like Rails.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Version 1.2
# http://www.spacebabies.nl/dnsbl_check
require 'resolv'
module DNSBL_Check
$dnsbl_passed ||= []
DNSBLS = %w{list.dsbl.org bl.spamcop.net sbl-xbl.spamhaus.org}
private
# Filter to check if the client is listed. This will be run before all requests.
def dnsbl_check
return true if $dnsbl_passed.include? request.remote_addr
passed = true
threads = []
request.remote_addr =~ /(\d+).(\d+).(\d+).(\d+)/
# Check the remote address against each dnsbl in a separate thread
DNSBLS.each do |dnsbl|
threads << Thread.new("#$4.#$3.#$2.#$1.#{dnsbl}") do |host|
logger.warn("Checking DNSBL #{host}")
addr = Resolv.getaddress("#{host}") rescue ''
if addr[0,7]=="127.0.0"
logger.info("#{request.remote_addr} found using DNSBL #{host}")
passed = false
end
end
end
threads.each {|thread| thread.join(2)} # join threads, but use timeout to kill blocked ones
# Add client ip to global passed cache if no dnsbls objected. else deny service.
if passed
$dnsbl_passed = $dnsbl_passed[0,49].unshift request.remote_addr
logger.warn("#{request.remote_addr} added to DNSBL passed cache")
else
render :text => 'Access denied', :status => 403
return false
end
end
end

1081
vendor/plugins/rubyzip-0.9.1/ChangeLog vendored Normal file

File diff suppressed because it is too large Load diff

144
vendor/plugins/rubyzip-0.9.1/NEWS vendored Normal file
View file

@ -0,0 +1,144 @@
= Version 0.9.1
Added symlink support and support for unix file permissions. Reduced
memory usage during decompression.
New methods ZipFile::[follow_symlinks, restore_times, restore_permissions, restore_ownership].
New methods ZipEntry::unix_perms, ZipInputStream::eof?.
Added documentation and test for new ZipFile::extract.
Added some of the API suggestions from sf.net #1281314.
Applied patch for sf.net bug #1446926.
Applied patch for sf.net bug #1459902.
Rework ZipEntry and delegate classes.
= Version 0.5.12
Fixed problem with writing binary content to a ZipFile in MS Windows.
= Version 0.5.11
Fixed name clash file method copy_stream from fileutils.rb. Fixed
problem with references to constant CHUNK_SIZE.
ZipInputStream/AbstractInputStream read is now buffered like ruby IO's
read method, which means that read and gets etc can be mixed. The
unbuffered read method has been renamed to sysread.
= Version 0.5.10
Fixed method name resolution problem with FileUtils::copy_stream and
IOExtras::copy_stream.
= Version 0.5.9
Fixed serious memory consumption issue
= Version 0.5.8
Fixed install script.
= Version 0.5.7
install.rb no longer assumes it is being run from the toplevel source
dir. Directory structure changed to reflect common ruby library
project structure. Migrated from RubyUnit to Test::Unit format. Now
uses Rake to build source packages and gems and run unit tests.
= Version 0.5.6
Fix for FreeBSD 4.9 which returns Errno::EFBIG instead of
Errno::EINVAL for some invalid seeks. Fixed 'version needed to
extract'-field incorrect in local headers.
= Version 0.5.5
Fix for a problem with writing zip files that concerns only ruby 1.8.1.
= Version 0.5.4
Significantly reduced memory footprint when modifying zip files.
= Version 0.5.3
Added optimization to avoid decompressing and recompressing individual
entries when modifying a zip archive.
= Version 0.5.2
Fixed ZipFile corruption bug in ZipFile class. Added basic unix
extra-field support.
= Version 0.5.1
Fixed ZipFile.get_output_stream bug.
= Version 0.5.0
List of changes:
* Ruby 1.8.0 and ruby-zlib 0.6.0 compatibility
* Changed method names from camelCase to rubys underscore style.
* Installs to zip/ subdir instead of directly to site_ruby
* Added ZipFile.directory and ZipFile.file - each method return an
object that can be used like Dir and File only for the contents of the
zip file.
* Added sample application zipfind which works like Find.find, only
Zip::ZipFind.find traverses into zip archives too.
Bug fixes:
* AbstractInputStream.each_line with non-default separator
= Version 0.5.0a
Source reorganized. Added ziprequire, which can be used to load ruby
modules from a zip file, in a fashion similar to jar files in
Java. Added gtkRubyzip, another sample application. Implemented
ZipInputStream.lineno and ZipInputStream.rewind
Bug fixes:
* Read and write date and time information correctly for zip entries.
* Fixed read() using separate buffer, causing mix of gets/readline/read to
cause problems.
= Version 0.4.2
Performance optimizations. Test suite runs in half the time.
= Version 0.4.1
Windows compatibility fixes.
= Version 0.4.0
Zip::ZipFile is now mutable and provides a more convenient way of
modifying zip archives than Zip::ZipOutputStream. Operations for
adding, extracting, renaming, replacing and removing entries to zip
archives are now available.
Runs without warnings with -w switch.
Install script install.rb added.
= Version 0.3.1
Rudimentary support for writing zip archives.
= Version 0.2.2
Fixed and extended unit test suite. Updated to work with ruby/zlib
0.5. It doesn't work with earlier versions of ruby/zlib.
= Version 0.2.0
Class ZipFile added. Where ZipInputStream is used to read the
individual entries in a zip file, ZipFile reads the central directory
in the zip archive, so you can get to any entry in the zip archive
without having to skipping through all the preceeding entries.
= Version 0.1.0
First working version of ZipInputStream.

72
vendor/plugins/rubyzip-0.9.1/README vendored Normal file
View file

@ -0,0 +1,72 @@
= rubyzip
rubyzip is a ruby library for reading and writing zip files.
= Install
If you have rubygems you can install rubyzip directly from the gem
repository
gem install rubyzip
Otherwise obtain the source (see below) and run
ruby install.rb
To run the unit tests you need to have test::unit installed
rake test
= Documentation
There is more than one way to access or create a zip archive with
rubyzip. The basic API is modeled after the classes in
java.util.zip from the Java SDK. This means there are classes such
as Zip::ZipInputStream, Zip::ZipOutputStream and
Zip::ZipFile. Zip::ZipInputStream provides a basic interface for
iterating through the entries in a zip archive and reading from the
entries in the same way as from a regular File or IO
object. ZipOutputStream is the corresponding basic output
facility. Zip::ZipFile provides a mean for accessing the archives
central directory and provides means for accessing any entry without
having to iterate through the archive. Unlike Java's
java.util.zip.ZipFile rubyzip's Zip::ZipFile is mutable, which means
it can be used to change zip files as well.
Another way to access a zip archive with rubyzip is to use rubyzip's
Zip::ZipFileSystem API. Using this API files can be read from and
written to the archive in much the same manner as ruby's builtin
classes allows files to be read from and written to the file system.
rubyzip also features the
zip/ziprequire.rb[link:files/lib/zip/ziprequire_rb.html] module which
allows ruby to load ruby modules from zip archives.
For details about the specific behaviour of classes and methods refer
to the test suite. Finally you can generate the rdoc documentation or
visit http://rubyzip.sourceforge.net.
= License
rubyzip is distributed under the same license as ruby. See
http://www.ruby-lang.org/en/LICENSE.txt
= Website and Project Home
http://rubyzip.sourceforge.net
http://sourceforge.net/projects/rubyzip
== Download (tarballs and gems)
http://sourceforge.net/project/showfiles.php?group_id=43107&package_id=35377
= Authors
Thomas Sondergaard (thomas at sondergaard.cc)
Technorama Ltd. (oss-ruby-zip at technorama.net)
extra-field support contributed by Tatsuki Sugiura (sugi at nemui.org)

110
vendor/plugins/rubyzip-0.9.1/Rakefile vendored Executable file
View file

@ -0,0 +1,110 @@
# Rakefile for RubyGems -*- ruby -*-
require 'rubygems'
require 'rake/clean'
require 'rake/testtask'
require 'rake/packagetask'
require 'rake/gempackagetask'
require 'rake/rdoctask'
require 'rake/contrib/sshpublisher'
require 'net/ftp'
PKG_NAME = 'rubyzip'
PKG_VERSION = File.read('lib/zip/zip.rb').match(/\s+VERSION\s*=\s*'(.*)'/)[1]
PKG_FILES = FileList.new
PKG_FILES.add %w{ README NEWS TODO ChangeLog install.rb Rakefile }
PKG_FILES.add %w{ samples/*.rb }
PKG_FILES.add %w{ test/*.rb }
PKG_FILES.add %w{ test/data/* }
PKG_FILES.exclude "test/data/generated"
PKG_FILES.add %w{ lib/**/*.rb }
def clobberFromCvsIgnore(path)
CLOBBER.add File.readlines(path+'/.cvsignore').map {
|f| File.join(path, f.chomp)
} rescue StandardError
end
clobberFromCvsIgnore '.'
clobberFromCvsIgnore 'samples'
clobberFromCvsIgnore 'test'
clobberFromCvsIgnore 'test/data'
task :default => [:test]
desc "Run unit tests"
task :test do
ruby %{-C test alltests.rb}
end
# Shortcuts for test targets
task :ut => [:test]
spec = Gem::Specification.new do |s|
s.name = PKG_NAME
s.version = PKG_VERSION
s.author = "Thomas Sondergaard"
s.email = "thomas(at)sondergaard.cc"
s.homepage = "http://rubyzip.sourceforge.net/"
s.platform = Gem::Platform::RUBY
s.summary = "rubyzip is a ruby module for reading and writing zip files"
s.files = PKG_FILES.to_a
s.require_path = 'lib'
end
Rake::GemPackageTask.new(spec) do |pkg|
pkg.need_zip = true
pkg.need_tar = true
end
Rake::RDocTask.new do |rd|
rd.main = "README"
rd.rdoc_files.add %W{ lib/zip/*.rb README NEWS TODO ChangeLog }
rd.options << "--title 'rubyzip documentation' --webcvs http://cvs.sourceforge.net/viewcvs.py/rubyzip/rubyzip/"
# rd.options << "--all"
end
desc "Publish documentation"
task :pdoc => [:rdoc] do
Rake::SshFreshDirPublisher.
new("thomas@rubyzip.sourceforge.net", "/home/groups/r/ru/rubyzip/htdocs", "html").upload
end
desc "Publish package"
task :ppackage => [:package] do
Net::FTP.open("upload.sourceforge.net",
"ftp",
ENV['USER']+"@"+ENV['HOSTNAME']) {
|ftpclient|
ftpclient.passive = true
ftpclient.chdir "incoming"
Dir['pkg/*.{tgz,zip,gem}'].each {
|e|
ftpclient.putbinaryfile(e, File.basename(e))
}
}
end
desc "Generate the ChangeLog file"
task :ChangeLog do
puts "Updating ChangeLog"
system %{cvs2cl}
end
desc "Make a release"
task :release => [:tag_release, :pdoc, :ppackage] do
end
desc "Make a release tag"
task :tag_release do
tag = "release-#{PKG_VERSION.gsub('.','-')}"
puts "Checking for tag '#{tag}'"
if (Regexp.new("^\\s+#{tag}") =~ `cvs log README`)
abort "Tag '#{tag}' already exists"
end
puts "Tagging module with '#{tag}'"
system("cvs tag #{tag}")
end

16
vendor/plugins/rubyzip-0.9.1/TODO vendored Normal file
View file

@ -0,0 +1,16 @@
* ZipInputStream: Support zip-files with trailing data descriptors
* Adjust rdoc stylesheet to advertise inherited methods if possible
* Suggestion: Add ZipFile/ZipInputStream example that demonstrates extracting all entries.
* Suggestion: ZipFile#extract destination should default to "."
* Suggestion: ZipEntry should have extract(), get_input_stream() methods etc
* SUggestion: ZipInputStream/ZipOutputStream should accept an IO object in addition to a filename.
* (is buffering used anywhere with write?)
* Inflater.sysread should pass the buffer to produce_input.
* Implement ZipFsDir.glob
* ZipFile.checkIntegrity method
* non-MSDOS permission attributes
** See mail from Ned Konz to ruby-talk subj. "Re: SV: [ANN] Archive 0.2"
* Packager version, required unpacker version in zip headers
** See mail from Ned Konz to ruby-talk subj. "Re: SV: [ANN] Archive 0.2"
* implement storing attributes and ownership information

22
vendor/plugins/rubyzip-0.9.1/install.rb vendored Executable file
View file

@ -0,0 +1,22 @@
#!/usr/bin/env ruby
$VERBOSE = true
require 'rbconfig'
require 'find'
require 'ftools'
include Config
files = %w{ stdrubyext.rb ioextras.rb zip.rb zipfilesystem.rb ziprequire.rb tempfile_bugfixed.rb }
INSTALL_DIR = File.join(CONFIG["sitelibdir"], "zip")
File.makedirs(INSTALL_DIR)
SOURCE_DIR = File.join(File.dirname($0), "lib/zip")
files.each {
|filename|
installPath = File.join(INSTALL_DIR, filename)
File::install(File.join(SOURCE_DIR, filename), installPath, 0644, true)
}

View file

@ -0,0 +1,155 @@
module IOExtras #:nodoc:
CHUNK_SIZE = 32768
RANGE_ALL = 0..-1
def self.copy_stream(ostream, istream)
s = ''
ostream.write(istream.read(CHUNK_SIZE, s)) until istream.eof?
end
# Implements kind_of? in order to pretend to be an IO object
module FakeIO
def kind_of?(object)
object == IO || super
end
end
# Implements many of the convenience methods of IO
# such as gets, getc, readline and readlines
# depends on: input_finished?, produce_input and read
module AbstractInputStream
include Enumerable
include FakeIO
def initialize
super
@lineno = 0
@outputBuffer = ""
end
attr_accessor :lineno
def read(numberOfBytes = nil, buf = nil)
tbuf = nil
if @outputBuffer.length > 0
if numberOfBytes <= @outputBuffer.length
tbuf = @outputBuffer.slice!(0, numberOfBytes)
else
numberOfBytes -= @outputBuffer.length if (numberOfBytes)
rbuf = sysread(numberOfBytes, buf)
tbuf = @outputBuffer
tbuf << rbuf if (rbuf)
@outputBuffer = ""
end
else
tbuf = sysread(numberOfBytes, buf)
end
return nil unless (tbuf)
if buf
buf.replace(tbuf)
else
buf = tbuf
end
buf
end
def readlines(aSepString = $/)
retVal = []
each_line(aSepString) { |line| retVal << line }
return retVal
end
def gets(aSepString=$/)
@lineno = @lineno.next
return read if aSepString == nil
aSepString="#{$/}#{$/}" if aSepString == ""
bufferIndex=0
while ((matchIndex = @outputBuffer.index(aSepString, bufferIndex)) == nil)
bufferIndex=@outputBuffer.length
if input_finished?
return @outputBuffer.empty? ? nil : flush
end
@outputBuffer << produce_input
end
sepIndex=matchIndex + aSepString.length
return @outputBuffer.slice!(0...sepIndex)
end
def flush
retVal=@outputBuffer
@outputBuffer=""
return retVal
end
def readline(aSepString = $/)
retVal = gets(aSepString)
raise EOFError if retVal == nil
return retVal
end
def each_line(aSepString = $/)
while true
yield readline(aSepString)
end
rescue EOFError
end
alias_method :each, :each_line
end
# Implements many of the output convenience methods of IO.
# relies on <<
module AbstractOutputStream
include FakeIO
def write(data)
self << data
data.to_s.length
end
def print(*params)
self << params.to_s << $\.to_s
end
def printf(aFormatString, *params)
self << sprintf(aFormatString, *params)
end
def putc(anObject)
self << case anObject
when Fixnum then anObject.chr
when String then anObject
else raise TypeError, "putc: Only Fixnum and String supported"
end
anObject
end
def puts(*params)
params << "\n" if params.empty?
params.flatten.each {
|element|
val = element.to_s
self << val
self << "\n" unless val[-1,1] == "\n"
}
end
end
end # IOExtras namespace module
# Copyright (C) 2002-2004 Thomas Sondergaard
# rubyzip is free software; you can redistribute it and/or
# modify it under the terms of the ruby license.

View file

@ -0,0 +1,111 @@
unless Enumerable.method_defined?(:inject)
module Enumerable #:nodoc:all
def inject(n = 0)
each { |value| n = yield(n, value) }
n
end
end
end
module Enumerable #:nodoc:all
# returns a new array of all the return values not equal to nil
# This implementation could be faster
def select_map(&aProc)
map(&aProc).reject { |e| e.nil? }
end
end
unless Object.method_defined?(:object_id)
class Object #:nodoc:all
# Using object_id which is the new thing, so we need
# to make that work in versions prior to 1.8.0
alias object_id id
end
end
unless File.respond_to?(:read)
class File # :nodoc:all
# singleton method read does not exist in 1.6.x
def self.read(fileName)
open(fileName) { |f| f.read }
end
end
end
class String #:nodoc:all
def starts_with(aString)
rindex(aString, 0) == 0
end
def ends_with(aString)
index(aString, -aString.size)
end
def ensure_end(aString)
ends_with(aString) ? self : self + aString
end
def lchop
slice(1, length)
end
end
class Time #:nodoc:all
#MS-DOS File Date and Time format as used in Interrupt 21H Function 57H:
#
# Register CX, the Time:
# Bits 0-4 2 second increments (0-29)
# Bits 5-10 minutes (0-59)
# bits 11-15 hours (0-24)
#
# Register DX, the Date:
# Bits 0-4 day (1-31)
# bits 5-8 month (1-12)
# bits 9-15 year (four digit year minus 1980)
def to_binary_dos_time
(sec/2) +
(min << 5) +
(hour << 11)
end
def to_binary_dos_date
(day) +
(month << 5) +
((year - 1980) << 9)
end
# Dos time is only stored with two seconds accuracy
def dos_equals(other)
to_i/2 == other.to_i/2
end
def self.parse_binary_dos_format(binaryDosDate, binaryDosTime)
second = 2 * ( 0b11111 & binaryDosTime)
minute = ( 0b11111100000 & binaryDosTime) >> 5
hour = (0b1111100000000000 & binaryDosTime) >> 11
day = ( 0b11111 & binaryDosDate)
month = ( 0b111100000 & binaryDosDate) >> 5
year = ((0b1111111000000000 & binaryDosDate) >> 9) + 1980
begin
return Time.local(year, month, day, hour, minute, second)
end
end
end
class Module #:nodoc:all
def forward_message(forwarder, *messagesToForward)
methodDefs = messagesToForward.map {
|msg|
"def #{msg}; #{forwarder}(:#{msg}); end"
}
module_eval(methodDefs.join("\n"))
end
end
# Copyright (C) 2002, 2003 Thomas Sondergaard
# rubyzip is free software; you can redistribute it and/or
# modify it under the terms of the ruby license.

View file

@ -0,0 +1,195 @@
#
# tempfile - manipulates temporary files
#
# $Id: tempfile_bugfixed.rb,v 1.2 2005/02/19 20:30:33 thomas Exp $
#
require 'delegate'
require 'tmpdir'
module BugFix #:nodoc:all
# A class for managing temporary files. This library is written to be
# thread safe.
class Tempfile < DelegateClass(File)
MAX_TRY = 10
@@cleanlist = []
# Creates a temporary file of mode 0600 in the temporary directory
# whose name is basename.pid.n and opens with mode "w+". A Tempfile
# object works just like a File object.
#
# If tmpdir is omitted, the temporary directory is determined by
# Dir::tmpdir provided by 'tmpdir.rb'.
# When $SAFE > 0 and the given tmpdir is tainted, it uses
# /tmp. (Note that ENV values are tainted by default)
def initialize(basename, tmpdir=Dir::tmpdir)
if $SAFE > 0 and tmpdir.tainted?
tmpdir = '/tmp'
end
lock = nil
n = failure = 0
begin
Thread.critical = true
begin
tmpname = sprintf('%s/%s%d.%d', tmpdir, basename, $$, n)
lock = tmpname + '.lock'
n += 1
end while @@cleanlist.include?(tmpname) or
File.exist?(lock) or File.exist?(tmpname)
Dir.mkdir(lock)
rescue
failure += 1
retry if failure < MAX_TRY
raise "cannot generate tempfile `%s'" % tmpname
ensure
Thread.critical = false
end
@data = [tmpname]
@clean_proc = Tempfile.callback(@data)
ObjectSpace.define_finalizer(self, @clean_proc)
@tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600)
@tmpname = tmpname
@@cleanlist << @tmpname
@data[1] = @tmpfile
@data[2] = @@cleanlist
super(@tmpfile)
# Now we have all the File/IO methods defined, you must not
# carelessly put bare puts(), etc. after this.
Dir.rmdir(lock)
end
# Opens or reopens the file with mode "r+".
def open
@tmpfile.close if @tmpfile
@tmpfile = File.open(@tmpname, 'r+')
@data[1] = @tmpfile
__setobj__(@tmpfile)
end
def _close # :nodoc:
@tmpfile.close if @tmpfile
@data[1] = @tmpfile = nil
end
protected :_close
# Closes the file. If the optional flag is true, unlinks the file
# after closing.
#
# If you don't explicitly unlink the temporary file, the removal
# will be delayed until the object is finalized.
def close(unlink_now=false)
if unlink_now
close!
else
_close
end
end
# Closes and unlinks the file.
def close!
_close
@clean_proc.call
ObjectSpace.undefine_finalizer(self)
end
# Unlinks the file. On UNIX-like systems, it is often a good idea
# to unlink a temporary file immediately after creating and opening
# it, because it leaves other programs zero chance to access the
# file.
def unlink
# keep this order for thread safeness
File.unlink(@tmpname) if File.exist?(@tmpname)
@@cleanlist.delete(@tmpname) if @@cleanlist
end
alias delete unlink
if RUBY_VERSION > '1.8.0'
def __setobj__(obj)
@_dc_obj = obj
end
else
def __setobj__(obj)
@obj = obj
end
end
# Returns the full path name of the temporary file.
def path
@tmpname
end
# Returns the size of the temporary file. As a side effect, the IO
# buffer is flushed before determining the size.
def size
if @tmpfile
@tmpfile.flush
@tmpfile.stat.size
else
0
end
end
alias length size
class << self
def callback(data) # :nodoc:
pid = $$
lambda{
if pid == $$
path, tmpfile, cleanlist = *data
print "removing ", path, "..." if $DEBUG
tmpfile.close if tmpfile
# keep this order for thread safeness
File.unlink(path) if File.exist?(path)
cleanlist.delete(path) if cleanlist
print "done\n" if $DEBUG
end
}
end
# If no block is given, this is a synonym for new().
#
# If a block is given, it will be passed tempfile as an argument,
# and the tempfile will automatically be closed when the block
# terminates. In this case, open() returns nil.
def open(*args)
tempfile = new(*args)
if block_given?
begin
yield(tempfile)
ensure
tempfile.close
end
nil
else
tempfile
end
end
end
end
end # module BugFix
if __FILE__ == $0
# $DEBUG = true
f = Tempfile.new("foo")
f.print("foo\n")
f.close
f.open
p f.gets # => "foo\n"
f.close!
end

1847
vendor/plugins/rubyzip-0.9.1/lib/zip/zip.rb vendored Executable file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,609 @@
require 'zip/zip'
module Zip
# The ZipFileSystem API provides an API for accessing entries in
# a zip archive that is similar to ruby's builtin File and Dir
# classes.
#
# Requiring 'zip/zipfilesystem' includes this module in ZipFile
# making the methods in this module available on ZipFile objects.
#
# Using this API the following example creates a new zip file
# <code>my.zip</code> containing a normal entry with the name
# <code>first.txt</code>, a directory entry named <code>mydir</code>
# and finally another normal entry named <code>second.txt</code>
#
# require 'zip/zipfilesystem'
#
# Zip::ZipFile.open("my.zip", Zip::ZipFile::CREATE) {
# |zipfile|
# zipfile.file.open("first.txt", "w") { |f| f.puts "Hello world" }
# zipfile.dir.mkdir("mydir")
# zipfile.file.open("mydir/second.txt", "w") { |f| f.puts "Hello again" }
# }
#
# Reading is as easy as writing, as the following example shows. The
# example writes the contents of <code>first.txt</code> from zip archive
# <code>my.zip</code> to standard out.
#
# require 'zip/zipfilesystem'
#
# Zip::ZipFile.open("my.zip") {
# |zipfile|
# puts zipfile.file.read("first.txt")
# }
module ZipFileSystem
def initialize # :nodoc:
mappedZip = ZipFileNameMapper.new(self)
@zipFsDir = ZipFsDir.new(mappedZip)
@zipFsFile = ZipFsFile.new(mappedZip)
@zipFsDir.file = @zipFsFile
@zipFsFile.dir = @zipFsDir
end
# Returns a ZipFsDir which is much like ruby's builtin Dir (class)
# object, except it works on the ZipFile on which this method is
# invoked
def dir
@zipFsDir
end
# Returns a ZipFsFile which is much like ruby's builtin File (class)
# object, except it works on the ZipFile on which this method is
# invoked
def file
@zipFsFile
end
# Instances of this class are normally accessed via the accessor
# ZipFile::file. An instance of ZipFsFile behaves like ruby's
# builtin File (class) object, except it works on ZipFile entries.
#
# The individual methods are not documented due to their
# similarity with the methods in File
class ZipFsFile
attr_writer :dir
# protected :dir
class ZipFsStat
def initialize(zipFsFile, entryName)
@zipFsFile = zipFsFile
@entryName = entryName
end
def forward_invoke(msg)
@zipFsFile.send(msg, @entryName)
end
def kind_of?(t)
super || t == ::File::Stat
end
forward_message :forward_invoke, :file?, :directory?, :pipe?, :chardev?
forward_message :forward_invoke, :symlink?, :socket?, :blockdev?
forward_message :forward_invoke, :readable?, :readable_real?
forward_message :forward_invoke, :writable?, :writable_real?
forward_message :forward_invoke, :executable?, :executable_real?
forward_message :forward_invoke, :sticky?, :owned?, :grpowned?
forward_message :forward_invoke, :setuid?, :setgid?
forward_message :forward_invoke, :zero?
forward_message :forward_invoke, :size, :size?
forward_message :forward_invoke, :mtime, :atime, :ctime
def blocks; nil; end
def get_entry
@zipFsFile.__send__(:get_entry, @entryName)
end
private :get_entry
def gid
e = get_entry
if e.extra.member? "IUnix"
e.extra["IUnix"].gid || 0
else
0
end
end
def uid
e = get_entry
if e.extra.member? "IUnix"
e.extra["IUnix"].uid || 0
else
0
end
end
def ino; 0; end
def dev; 0; end
def rdev; 0; end
def rdev_major; 0; end
def rdev_minor; 0; end
def ftype
if file?
return "file"
elsif directory?
return "directory"
else
raise StandardError, "Unknown file type"
end
end
def nlink; 1; end
def blksize; nil; end
def mode
e = get_entry
if e.fstype == 3
e.externalFileAttributes >> 16
else
33206 # 33206 is equivalent to -rw-rw-rw-
end
end
end
def initialize(mappedZip)
@mappedZip = mappedZip
end
def get_entry(fileName)
if ! exists?(fileName)
raise Errno::ENOENT, "No such file or directory - #{fileName}"
end
@mappedZip.find_entry(fileName)
end
private :get_entry
def unix_mode_cmp(fileName, mode)
begin
e = get_entry(fileName)
e.fstype == 3 && ((e.externalFileAttributes >> 16) & mode ) != 0
rescue Errno::ENOENT
false
end
end
private :unix_mode_cmp
def exists?(fileName)
expand_path(fileName) == "/" || @mappedZip.find_entry(fileName) != nil
end
alias :exist? :exists?
# Permissions not implemented, so if the file exists it is accessible
alias owned? exists?
alias grpowned? exists?
def readable?(fileName)
unix_mode_cmp(fileName, 0444)
end
alias readable_real? readable?
def writable?(fileName)
unix_mode_cmp(fileName, 0222)
end
alias writable_real? writable?
def executable?(fileName)
unix_mode_cmp(fileName, 0111)
end
alias executable_real? executable?
def setuid?(fileName)
unix_mode_cmp(fileName, 04000)
end
def setgid?(fileName)
unix_mode_cmp(fileName, 02000)
end
def sticky?(fileName)
unix_mode_cmp(fileName, 01000)
end
def umask(*args)
::File.umask(*args)
end
def truncate(fileName, len)
raise StandardError, "truncate not supported"
end
def directory?(fileName)
entry = @mappedZip.find_entry(fileName)
expand_path(fileName) == "/" || (entry != nil && entry.directory?)
end
def open(fileName, openMode = "r", &block)
case openMode
when "r"
@mappedZip.get_input_stream(fileName, &block)
when "w"
@mappedZip.get_output_stream(fileName, &block)
else
raise StandardError, "openmode '#{openMode} not supported" unless openMode == "r"
end
end
def new(fileName, openMode = "r")
open(fileName, openMode)
end
def size(fileName)
@mappedZip.get_entry(fileName).size
end
# Returns nil for not found and nil for directories
def size?(fileName)
entry = @mappedZip.find_entry(fileName)
return (entry == nil || entry.directory?) ? nil : entry.size
end
def chown(ownerInt, groupInt, *filenames)
filenames.each { |fileName|
e = get_entry(fileName)
unless e.extra.member?("IUnix")
e.extra.create("IUnix")
end
e.extra["IUnix"].uid = ownerInt
e.extra["IUnix"].gid = groupInt
}
filenames.size
end
def chmod (modeInt, *filenames)
filenames.each { |fileName|
e = get_entry(fileName)
e.fstype = 3 # force convertion filesystem type to unix
e.externalFileAttributes = modeInt << 16
}
filenames.size
end
def zero?(fileName)
sz = size(fileName)
sz == nil || sz == 0
rescue Errno::ENOENT
false
end
def file?(fileName)
entry = @mappedZip.find_entry(fileName)
entry != nil && entry.file?
end
def dirname(fileName)
::File.dirname(fileName)
end
def basename(fileName)
::File.basename(fileName)
end
def split(fileName)
::File.split(fileName)
end
def join(*fragments)
::File.join(*fragments)
end
def utime(modifiedTime, *fileNames)
fileNames.each { |fileName|
get_entry(fileName).time = modifiedTime
}
end
def mtime(fileName)
@mappedZip.get_entry(fileName).mtime
end
def atime(fileName)
e = get_entry(fileName)
if e.extra.member? "UniversalTime"
e.extra["UniversalTime"].atime
else
nil
end
end
def ctime(fileName)
e = get_entry(fileName)
if e.extra.member? "UniversalTime"
e.extra["UniversalTime"].ctime
else
nil
end
end
def pipe?(filename)
false
end
def blockdev?(filename)
false
end
def chardev?(filename)
false
end
def symlink?(fileName)
false
end
def socket?(fileName)
false
end
def ftype(fileName)
@mappedZip.get_entry(fileName).directory? ? "directory" : "file"
end
def readlink(fileName)
raise NotImplementedError, "The readlink() function is not implemented"
end
def symlink(fileName, symlinkName)
raise NotImplementedError, "The symlink() function is not implemented"
end
def link(fileName, symlinkName)
raise NotImplementedError, "The link() function is not implemented"
end
def pipe
raise NotImplementedError, "The pipe() function is not implemented"
end
def stat(fileName)
if ! exists?(fileName)
raise Errno::ENOENT, fileName
end
ZipFsStat.new(self, fileName)
end
alias lstat stat
def readlines(fileName)
open(fileName) { |is| is.readlines }
end
def read(fileName)
@mappedZip.read(fileName)
end
def popen(*args, &aProc)
File.popen(*args, &aProc)
end
def foreach(fileName, aSep = $/, &aProc)
open(fileName) { |is| is.each_line(aSep, &aProc) }
end
def delete(*args)
args.each {
|fileName|
if directory?(fileName)
raise Errno::EISDIR, "Is a directory - \"#{fileName}\""
end
@mappedZip.remove(fileName)
}
end
def rename(fileToRename, newName)
@mappedZip.rename(fileToRename, newName) { true }
end
alias :unlink :delete
def expand_path(aPath)
@mappedZip.expand_path(aPath)
end
end
# Instances of this class are normally accessed via the accessor
# ZipFile::dir. An instance of ZipFsDir behaves like ruby's
# builtin Dir (class) object, except it works on ZipFile entries.
#
# The individual methods are not documented due to their
# similarity with the methods in Dir
class ZipFsDir
def initialize(mappedZip)
@mappedZip = mappedZip
end
attr_writer :file
def new(aDirectoryName)
ZipFsDirIterator.new(entries(aDirectoryName))
end
def open(aDirectoryName)
dirIt = new(aDirectoryName)
if block_given?
begin
yield(dirIt)
return nil
ensure
dirIt.close
end
end
dirIt
end
def pwd; @mappedZip.pwd; end
alias getwd pwd
def chdir(aDirectoryName)
unless @file.stat(aDirectoryName).directory?
raise Errno::EINVAL, "Invalid argument - #{aDirectoryName}"
end
@mappedZip.pwd = @file.expand_path(aDirectoryName)
end
def entries(aDirectoryName)
entries = []
foreach(aDirectoryName) { |e| entries << e }
entries
end
def foreach(aDirectoryName)
unless @file.stat(aDirectoryName).directory?
raise Errno::ENOTDIR, aDirectoryName
end
path = @file.expand_path(aDirectoryName).ensure_end("/")
subDirEntriesRegex = Regexp.new("^#{path}([^/]+)$")
@mappedZip.each {
|fileName|
match = subDirEntriesRegex.match(fileName)
yield(match[1]) unless match == nil
}
end
def delete(entryName)
unless @file.stat(entryName).directory?
raise Errno::EINVAL, "Invalid argument - #{entryName}"
end
@mappedZip.remove(entryName)
end
alias rmdir delete
alias unlink delete
def mkdir(entryName, permissionInt = 0755)
@mappedZip.mkdir(entryName, permissionInt)
end
def chroot(*args)
raise NotImplementedError, "The chroot() function is not implemented"
end
end
class ZipFsDirIterator # :nodoc:all
include Enumerable
def initialize(arrayOfFileNames)
@fileNames = arrayOfFileNames
@index = 0
end
def close
@fileNames = nil
end
def each(&aProc)
raise IOError, "closed directory" if @fileNames == nil
@fileNames.each(&aProc)
end
def read
raise IOError, "closed directory" if @fileNames == nil
@fileNames[(@index+=1)-1]
end
def rewind
raise IOError, "closed directory" if @fileNames == nil
@index = 0
end
def seek(anIntegerPosition)
raise IOError, "closed directory" if @fileNames == nil
@index = anIntegerPosition
end
def tell
raise IOError, "closed directory" if @fileNames == nil
@index
end
end
# All access to ZipFile from ZipFsFile and ZipFsDir goes through a
# ZipFileNameMapper, which has one responsibility: ensure
class ZipFileNameMapper # :nodoc:all
include Enumerable
def initialize(zipFile)
@zipFile = zipFile
@pwd = "/"
end
attr_accessor :pwd
def find_entry(fileName)
@zipFile.find_entry(expand_to_entry(fileName))
end
def get_entry(fileName)
@zipFile.get_entry(expand_to_entry(fileName))
end
def get_input_stream(fileName, &aProc)
@zipFile.get_input_stream(expand_to_entry(fileName), &aProc)
end
def get_output_stream(fileName, &aProc)
@zipFile.get_output_stream(expand_to_entry(fileName), &aProc)
end
def read(fileName)
@zipFile.read(expand_to_entry(fileName))
end
def remove(fileName)
@zipFile.remove(expand_to_entry(fileName))
end
def rename(fileName, newName, &continueOnExistsProc)
@zipFile.rename(expand_to_entry(fileName), expand_to_entry(newName),
&continueOnExistsProc)
end
def mkdir(fileName, permissionInt = 0755)
@zipFile.mkdir(expand_to_entry(fileName), permissionInt)
end
# Turns entries into strings and adds leading /
# and removes trailing slash on directories
def each
@zipFile.each {
|e|
yield("/"+e.to_s.chomp("/"))
}
end
def expand_path(aPath)
expanded = aPath.starts_with("/") ? aPath : @pwd.ensure_end("/") + aPath
expanded.gsub!(/\/\.(\/|$)/, "")
expanded.gsub!(/[^\/]+\/\.\.(\/|$)/, "")
expanded.empty? ? "/" : expanded
end
private
def expand_to_entry(aPath)
expand_path(aPath).lchop
end
end
end
class ZipFile
include ZipFileSystem
end
end
# Copyright (C) 2002, 2003 Thomas Sondergaard
# rubyzip is free software; you can redistribute it and/or
# modify it under the terms of the ruby license.

View file

@ -0,0 +1,90 @@
# With ziprequire you can load ruby modules from a zip file. This means
# ruby's module include path can include zip-files.
#
# The following example creates a zip file with a single entry
# <code>log/simplelog.rb</code> that contains a single function
# <code>simpleLog</code>:
#
# require 'zip/zipfilesystem'
#
# Zip::ZipFile.open("my.zip", true) {
# |zf|
# zf.file.open("log/simplelog.rb", "w") {
# |f|
# f.puts "def simpleLog(v)"
# f.puts ' Kernel.puts "INFO: #{v}"'
# f.puts "end"
# }
# }
#
# To use the ruby module stored in the zip archive simply require
# <code>zip/ziprequire</code> and include the <code>my.zip</code> zip
# file in the module search path. The following command shows one
# way to do this:
#
# ruby -rzip/ziprequire -Imy.zip -e " require 'log/simplelog'; simpleLog 'Hello world' "
#$: << 'data/rubycode.zip' << 'data/rubycode2.zip'
require 'zip/zip'
class ZipList #:nodoc:all
def initialize(zipFileList)
@zipFileList = zipFileList
end
def get_input_stream(entry, &aProc)
@zipFileList.each {
|zfName|
Zip::ZipFile.open(zfName) {
|zf|
begin
return zf.get_input_stream(entry, &aProc)
rescue Errno::ENOENT
end
}
}
raise Errno::ENOENT,
"No matching entry found in zip files '#{@zipFileList.join(', ')}' "+
" for '#{entry}'"
end
end
module Kernel #:nodoc:all
alias :oldRequire :require
def require(moduleName)
zip_require(moduleName) || oldRequire(moduleName)
end
def zip_require(moduleName)
return false if already_loaded?(moduleName)
get_resource(ensure_rb_extension(moduleName)) {
|zis|
eval(zis.read); $" << moduleName
}
return true
rescue Errno::ENOENT => ex
return false
end
def get_resource(resourceName, &aProc)
zl = ZipList.new($:.grep(/\.zip$/))
zl.get_input_stream(resourceName, &aProc)
end
def already_loaded?(moduleName)
moduleRE = Regexp.new("^"+moduleName+"(\.rb|\.so|\.dll|\.o)?$")
$".detect { |e| e =~ moduleRE } != nil
end
def ensure_rb_extension(aString)
aString.sub(/(\.rb)?$/i, ".rb")
end
end
# Copyright (C) 2002 Thomas Sondergaard
# rubyzip is free software; you can redistribute it and/or
# modify it under the terms of the ruby license.

View file

@ -0,0 +1,69 @@
#!/usr/bin/env ruby
$: << "../lib"
system("zip example.zip example.rb gtkRubyzip.rb")
require 'zip/zip'
####### Using ZipInputStream alone: #######
Zip::ZipInputStream.open("example.zip") {
|zis|
entry = zis.get_next_entry
print "First line of '#{entry.name} (#{entry.size} bytes): "
puts "'#{zis.gets.chomp}'"
entry = zis.get_next_entry
print "First line of '#{entry.name} (#{entry.size} bytes): "
puts "'#{zis.gets.chomp}'"
}
####### Using ZipFile to read the directory of a zip file: #######
zf = Zip::ZipFile.new("example.zip")
zf.each_with_index {
|entry, index|
puts "entry #{index} is #{entry.name}, size = #{entry.size}, compressed size = #{entry.compressed_size}"
# use zf.get_input_stream(entry) to get a ZipInputStream for the entry
# entry can be the ZipEntry object or any object which has a to_s method that
# returns the name of the entry.
}
####### Using ZipOutputStream to write a zip file: #######
Zip::ZipOutputStream.open("exampleout.zip") {
|zos|
zos.put_next_entry("the first little entry")
zos.puts "Hello hello hello hello hello hello hello hello hello"
zos.put_next_entry("the second little entry")
zos.puts "Hello again"
# Use rubyzip or your zip client of choice to verify
# the contents of exampleout.zip
}
####### Using ZipFile to change a zip file: #######
Zip::ZipFile.open("exampleout.zip") {
|zf|
zf.add("thisFile.rb", "example.rb")
zf.rename("thisFile.rb", "ILikeThisName.rb")
zf.add("Again", "example.rb")
}
# Lets check
Zip::ZipFile.open("exampleout.zip") {
|zf|
puts "Changed zip file contains: #{zf.entries.join(', ')}"
zf.remove("Again")
puts "Without 'Again': #{zf.entries.join(', ')}"
}
# For other examples, look at zip.rb and ziptest.rb
# Copyright (C) 2002 Thomas Sondergaard
# rubyzip is free software; you can redistribute it and/or
# modify it under the terms of the ruby license.

View file

@ -0,0 +1,34 @@
#!/usr/bin/env ruby
$: << "../lib"
require 'zip/zipfilesystem'
require 'ftools'
EXAMPLE_ZIP = "filesystem.zip"
File.delete(EXAMPLE_ZIP) if File.exists?(EXAMPLE_ZIP)
Zip::ZipFile.open(EXAMPLE_ZIP, Zip::ZipFile::CREATE) {
|zf|
zf.file.open("file1.txt", "w") { |os| os.write "first file1.txt" }
zf.dir.mkdir("dir1")
zf.dir.chdir("dir1")
zf.file.open("file1.txt", "w") { |os| os.write "second file1.txt" }
puts zf.file.read("file1.txt")
puts zf.file.read("../file1.txt")
zf.dir.chdir("..")
zf.file.open("file2.txt", "w") { |os| os.write "first file2.txt" }
puts "Entries: #{zf.entries.join(', ')}"
}
Zip::ZipFile.open(EXAMPLE_ZIP) {
|zf|
puts "Entries from reloaded zip: #{zf.entries.join(', ')}"
}
# For other examples, look at zip.rb and ziptest.rb
# Copyright (C) 2003 Thomas Sondergaard
# rubyzip is free software; you can redistribute it and/or
# modify it under the terms of the ruby license.

View file

@ -0,0 +1,86 @@
#!/usr/bin/env ruby
$: << "../lib"
$VERBOSE = true
require 'gtk'
require 'zip/zip'
class MainApp < Gtk::Window
def initialize
super()
set_usize(400, 256)
set_title("rubyzip")
signal_connect(Gtk::Window::SIGNAL_DESTROY) { Gtk.main_quit }
box = Gtk::VBox.new(false, 0)
add(box)
@zipfile = nil
@buttonPanel = ButtonPanel.new
@buttonPanel.openButton.signal_connect(Gtk::Button::SIGNAL_CLICKED) {
show_file_selector
}
@buttonPanel.extractButton.signal_connect(Gtk::Button::SIGNAL_CLICKED) {
puts "Not implemented!"
}
box.pack_start(@buttonPanel, false, false, 0)
sw = Gtk::ScrolledWindow.new
sw.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC)
box.pack_start(sw, true, true, 0)
@clist = Gtk::CList.new(["Name", "Size", "Compression"])
@clist.set_selection_mode(Gtk::SELECTION_BROWSE)
@clist.set_column_width(0, 120)
@clist.set_column_width(1, 120)
@clist.signal_connect(Gtk::CList::SIGNAL_SELECT_ROW) {
|w, row, column, event|
@selected_row = row
}
sw.add(@clist)
end
class ButtonPanel < Gtk::HButtonBox
attr_reader :openButton, :extractButton
def initialize
super
set_layout(Gtk::BUTTONBOX_START)
set_spacing(0)
@openButton = Gtk::Button.new("Open archive")
@extractButton = Gtk::Button.new("Extract entry")
pack_start(@openButton)
pack_start(@extractButton)
end
end
def show_file_selector
@fileSelector = Gtk::FileSelection.new("Open zip file")
@fileSelector.show
@fileSelector.ok_button.signal_connect(Gtk::Button::SIGNAL_CLICKED) {
open_zip(@fileSelector.filename)
@fileSelector.destroy
}
@fileSelector.cancel_button.signal_connect(Gtk::Button::SIGNAL_CLICKED) {
@fileSelector.destroy
}
end
def open_zip(filename)
@zipfile = Zip::ZipFile.open(filename)
@clist.clear
@zipfile.each {
|entry|
@clist.append([ entry.name,
entry.size.to_s,
(100.0*entry.compressedSize/entry.size).to_s+"%" ])
}
end
end
mainApp = MainApp.new()
mainApp.show_all
Gtk.main

101
vendor/plugins/rubyzip-0.9.1/samples/qtzip.rb vendored Executable file
View file

@ -0,0 +1,101 @@
#!/usr/bin/env ruby
$VERBOSE=true
$: << "../lib"
require 'Qt'
system('rbuic -o zipdialogui.rb zipdialogui.ui')
require 'zipdialogui.rb'
require 'zip/zip'
a = Qt::Application.new(ARGV)
class ZipDialog < ZipDialogUI
def initialize()
super()
connect(child('add_button'), SIGNAL('clicked()'),
self, SLOT('add_files()'))
connect(child('extract_button'), SIGNAL('clicked()'),
self, SLOT('extract_files()'))
end
def zipfile(&proc)
Zip::ZipFile.open(@zip_filename, &proc)
end
def each(&proc)
Zip::ZipFile.foreach(@zip_filename, &proc)
end
def refresh()
lv = child("entry_list_view")
lv.clear
each {
|e|
lv.insert_item(Qt::ListViewItem.new(lv, e.name, e.size.to_s))
}
end
def load(zipfile)
@zip_filename = zipfile
refresh
end
def add_files
l = Qt::FileDialog.getOpenFileNames(nil, nil, self)
zipfile {
|zf|
l.each {
|path|
zf.add(File.basename(path), path)
}
}
refresh
end
def extract_files
selected_items = []
unselected_items = []
lv_item = entry_list_view.first_child
while (lv_item)
if entry_list_view.is_selected(lv_item)
selected_items << lv_item.text(0)
else
unselected_items << lv_item.text(0)
end
lv_item = lv_item.next_sibling
end
puts "selected_items.size = #{selected_items.size}"
puts "unselected_items.size = #{unselected_items.size}"
items = selected_items.size > 0 ? selected_items : unselected_items
puts "items.size = #{items.size}"
d = Qt::FileDialog.get_existing_directory(nil, self)
if (!d)
puts "No directory chosen"
else
zipfile { |zf| items.each { |e| zf.extract(e, File.join(d, e)) } }
end
end
slots 'add_files()', 'extract_files()'
end
if !ARGV[0]
puts "usage: #{$0} zipname"
exit
end
zd = ZipDialog.new
zd.load(ARGV[0])
a.mainWidget = zd
zd.show()
a.exec()

View file

@ -0,0 +1,13 @@
#!/usr/bin/env ruby
$: << "../lib"
require 'zip/zip'
include Zip
ZipOutputStream.open('simple.zip') {
|zos|
ze = zos.put_next_entry 'entry.txt'
zos.puts "Hello world"
}

View file

@ -0,0 +1,74 @@
#!/usr/bin/env ruby
$VERBOSE = true
$: << "../lib"
require 'zip/zip'
require 'find'
module Zip
module ZipFind
def self.find(path, zipFilePattern = /\.zip$/i)
Find.find(path) {
|fileName|
yield(fileName)
if zipFilePattern.match(fileName) && File.file?(fileName)
begin
Zip::ZipFile.foreach(fileName) {
|zipEntry|
yield(fileName + File::SEPARATOR + zipEntry.to_s)
}
rescue Errno::EACCES => ex
puts ex
end
end
}
end
def self.find_file(path, fileNamePattern, zipFilePattern = /\.zip$/i)
self.find(path, zipFilePattern) {
|fileName|
yield(fileName) if fileNamePattern.match(fileName)
}
end
end
end
if __FILE__ == $0
module ZipFindConsoleRunner
PATH_ARG_INDEX = 0;
FILENAME_PATTERN_ARG_INDEX = 1;
ZIPFILE_PATTERN_ARG_INDEX = 2;
def self.run(args)
check_args(args)
Zip::ZipFind.find_file(args[PATH_ARG_INDEX],
args[FILENAME_PATTERN_ARG_INDEX],
args[ZIPFILE_PATTERN_ARG_INDEX]) {
|fileName|
report_entry_found fileName
}
end
def self.check_args(args)
if (args.size != 3)
usage
exit
end
end
def self.usage
puts "Usage: #{$0} PATH ZIPFILENAME_PATTERN FILNAME_PATTERN"
end
def self.report_entry_found(fileName)
puts fileName
end
end
ZipFindConsoleRunner.run(ARGV)
end

View file

@ -0,0 +1,9 @@
#!/usr/bin/env ruby
$VERBOSE = true
require 'stdrubyexttest'
require 'ioextrastest'
require 'ziptest'
require 'zipfilesystemtest'
require 'ziprequiretest'

View file

@ -0,0 +1,46 @@
AUTOMAKE_OPTIONS = gnu
EXTRA_DIST = test.zip
CXXFLAGS= -g
noinst_LIBRARIES = libzipios.a
bin_PROGRAMS = test_zip test_izipfilt test_izipstream
# test_flist
libzipios_a_SOURCES = backbuffer.h fcol.cpp fcol.h \
fcol_common.h fcolexceptions.cpp fcolexceptions.h \
fileentry.cpp fileentry.h flist.cpp \
flist.h flistentry.cpp flistentry.h \
flistscanner.h ifiltstreambuf.cpp ifiltstreambuf.h \
inflatefilt.cpp inflatefilt.h izipfilt.cpp \
izipfilt.h izipstream.cpp izipstream.h \
zipfile.cpp zipfile.h ziphead.cpp \
ziphead.h flistscanner.ll
# test_flist_SOURCES = test_flist.cpp
test_izipfilt_SOURCES = test_izipfilt.cpp
test_izipstream_SOURCES = test_izipstream.cpp
test_zip_SOURCES = test_zip.cpp
# Notice that libzipios.a is not specified as -L. -lzipios
# If it was, automake would not include it as a dependency.
# test_flist_LDADD = libzipios.a
test_izipfilt_LDADD = libzipios.a -lz
test_zip_LDADD = libzipios.a -lz
test_izipstream_LDADD = libzipios.a -lz
flistscanner.cc : flistscanner.ll
$(LEX) -+ -PFListScanner -o$@ $^

Binary file not shown.

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,7 @@
#!/usr/bin/env ruby
class NotZippedRuby
def returnTrue
true
end
end

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,157 @@
#!/usr/bin/env ruby
$VERBOSE = true
class TestFiles
RANDOM_ASCII_FILE1 = "data/generated/randomAscii1.txt"
RANDOM_ASCII_FILE2 = "data/generated/randomAscii2.txt"
RANDOM_ASCII_FILE3 = "data/generated/randomAscii3.txt"
RANDOM_BINARY_FILE1 = "data/generated/randomBinary1.bin"
RANDOM_BINARY_FILE2 = "data/generated/randomBinary2.bin"
EMPTY_TEST_DIR = "data/generated/emptytestdir"
ASCII_TEST_FILES = [ RANDOM_ASCII_FILE1, RANDOM_ASCII_FILE2, RANDOM_ASCII_FILE3 ]
BINARY_TEST_FILES = [ RANDOM_BINARY_FILE1, RANDOM_BINARY_FILE2 ]
TEST_DIRECTORIES = [ EMPTY_TEST_DIR ]
TEST_FILES = [ ASCII_TEST_FILES, BINARY_TEST_FILES, EMPTY_TEST_DIR ].flatten!
def TestFiles.create_test_files(recreate)
if (recreate ||
! (TEST_FILES.inject(true) { |accum, element| accum && File.exists?(element) }))
Dir.mkdir "data/generated" rescue Errno::EEXIST
ASCII_TEST_FILES.each_with_index {
|filename, index|
create_random_ascii(filename, 1E4 * (index+1))
}
BINARY_TEST_FILES.each_with_index {
|filename, index|
create_random_binary(filename, 1E4 * (index+1))
}
ensure_dir(EMPTY_TEST_DIR)
end
end
private
def TestFiles.create_random_ascii(filename, size)
File.open(filename, "wb") {
|file|
while (file.tell < size)
file << rand
end
}
end
def TestFiles.create_random_binary(filename, size)
File.open(filename, "wb") {
|file|
while (file.tell < size)
file << [rand].pack("V")
end
}
end
def TestFiles.ensure_dir(name)
if File.exists?(name)
return if File.stat(name).directory?
File.delete(name)
end
Dir.mkdir(name)
end
end
# For representation and creation of
# test data
class TestZipFile
attr_accessor :zip_name, :entry_names, :comment
def initialize(zip_name, entry_names, comment = "")
@zip_name=zip_name
@entry_names=entry_names
@comment = comment
end
def TestZipFile.create_test_zips(recreate)
files = Dir.entries("data/generated")
if (recreate ||
! (files.index(File.basename(TEST_ZIP1.zip_name)) &&
files.index(File.basename(TEST_ZIP2.zip_name)) &&
files.index(File.basename(TEST_ZIP3.zip_name)) &&
files.index(File.basename(TEST_ZIP4.zip_name)) &&
files.index("empty.txt") &&
files.index("empty_chmod640.txt") &&
files.index("short.txt") &&
files.index("longAscii.txt") &&
files.index("longBinary.bin") ))
raise "failed to create test zip '#{TEST_ZIP1.zip_name}'" unless
system("zip #{TEST_ZIP1.zip_name} data/file2.txt")
raise "failed to remove entry from '#{TEST_ZIP1.zip_name}'" unless
system("zip #{TEST_ZIP1.zip_name} -d data/file2.txt")
File.open("data/generated/empty.txt", "w") {}
File.open("data/generated/empty_chmod640.txt", "w") { |f| f.chmod(0640) }
File.open("data/generated/short.txt", "w") { |file| file << "ABCDEF" }
ziptestTxt=""
File.open("data/file2.txt") { |file| ziptestTxt=file.read }
File.open("data/generated/longAscii.txt", "w") {
|file|
while (file.tell < 1E5)
file << ziptestTxt
end
}
testBinaryPattern=""
File.open("data/generated/empty.zip") { |file| testBinaryPattern=file.read }
testBinaryPattern *= 4
File.open("data/generated/longBinary.bin", "wb") {
|file|
while (file.tell < 3E5)
file << testBinaryPattern << rand << "\0"
end
}
raise "failed to create test zip '#{TEST_ZIP2.zip_name}'" unless
system("zip #{TEST_ZIP2.zip_name} #{TEST_ZIP2.entry_names.join(' ')}")
# without bash system interprets everything after echo as parameters to
# echo including | zip -z ...
raise "failed to add comment to test zip '#{TEST_ZIP2.zip_name}'" unless
system("bash -c \"echo #{TEST_ZIP2.comment} | zip -z #{TEST_ZIP2.zip_name}\"")
raise "failed to create test zip '#{TEST_ZIP3.zip_name}'" unless
system("zip #{TEST_ZIP3.zip_name} #{TEST_ZIP3.entry_names.join(' ')}")
raise "failed to create test zip '#{TEST_ZIP4.zip_name}'" unless
system("zip #{TEST_ZIP4.zip_name} #{TEST_ZIP4.entry_names.join(' ')}")
end
rescue
raise $!.to_s +
"\n\nziptest.rb requires the Info-ZIP program 'zip' in the path\n" +
"to create test data. If you don't have it you can download\n" +
"the necessary test files at http://sf.net/projects/rubyzip."
end
TEST_ZIP1 = TestZipFile.new("data/generated/empty.zip", [])
TEST_ZIP2 = TestZipFile.new("data/generated/5entry.zip", %w{ data/generated/longAscii.txt data/generated/empty.txt data/generated/empty_chmod640.txt data/generated/short.txt data/generated/longBinary.bin},
"my zip comment")
TEST_ZIP3 = TestZipFile.new("data/generated/test1.zip", %w{ data/file1.txt })
TEST_ZIP4 = TestZipFile.new("data/generated/zipWithDir.zip", [ "data/file1.txt",
TestFiles::EMPTY_TEST_DIR])
end
END {
TestFiles::create_test_files(ARGV.index("recreate") != nil ||
ARGV.index("recreateonly") != nil)
TestZipFile::create_test_zips(ARGV.index("recreate") != nil ||
ARGV.index("recreateonly") != nil)
exit if ARGV.index("recreateonly") != nil
}

View file

@ -0,0 +1,208 @@
#!/usr/bin/env ruby
$VERBOSE = true
$: << "../lib"
require 'test/unit'
require 'zip/ioextras'
include IOExtras
class FakeIOTest < Test::Unit::TestCase
class FakeIOUsingClass
include FakeIO
end
def test_kind_of?
obj = FakeIOUsingClass.new
assert(obj.kind_of?(Object))
assert(obj.kind_of?(FakeIOUsingClass))
assert(obj.kind_of?(IO))
assert(!obj.kind_of?(Fixnum))
assert(!obj.kind_of?(String))
end
end
class AbstractInputStreamTest < Test::Unit::TestCase
# AbstractInputStream subclass that provides a read method
TEST_LINES = [ "Hello world#{$/}",
"this is the second line#{$/}",
"this is the last line"]
TEST_STRING = TEST_LINES.join
class TestAbstractInputStream
include AbstractInputStream
def initialize(aString)
super()
@contents = aString
@readPointer = 0
end
def read(charsToRead)
retVal=@contents[@readPointer, charsToRead]
@readPointer+=charsToRead
return retVal
end
def produce_input
read(100)
end
def input_finished?
@contents[@readPointer] == nil
end
end
def setup
@io = TestAbstractInputStream.new(TEST_STRING)
end
def test_gets
assert_equal(TEST_LINES[0], @io.gets)
assert_equal(1, @io.lineno)
assert_equal(TEST_LINES[1], @io.gets)
assert_equal(2, @io.lineno)
assert_equal(TEST_LINES[2], @io.gets)
assert_equal(3, @io.lineno)
assert_equal(nil, @io.gets)
assert_equal(4, @io.lineno)
end
def test_getsMultiCharSeperator
assert_equal("Hell", @io.gets("ll"))
assert_equal("o world#{$/}this is the second l", @io.gets("d l"))
end
def test_each_line
lineNumber=0
@io.each_line {
|line|
assert_equal(TEST_LINES[lineNumber], line)
lineNumber+=1
}
end
def test_readlines
assert_equal(TEST_LINES, @io.readlines)
end
def test_readline
test_gets
begin
@io.readline
fail "EOFError expected"
rescue EOFError
end
end
end
class AbstractOutputStreamTest < Test::Unit::TestCase
class TestOutputStream
include AbstractOutputStream
attr_accessor :buffer
def initialize
@buffer = ""
end
def << (data)
@buffer << data
self
end
end
def setup
@outputStream = TestOutputStream.new
@origCommaSep = $,
@origOutputSep = $\
end
def teardown
$, = @origCommaSep
$\ = @origOutputSep
end
def test_write
count = @outputStream.write("a little string")
assert_equal("a little string", @outputStream.buffer)
assert_equal("a little string".length, count)
count = @outputStream.write(". a little more")
assert_equal("a little string. a little more", @outputStream.buffer)
assert_equal(". a little more".length, count)
end
def test_print
$\ = nil # record separator set to nil
@outputStream.print("hello")
assert_equal("hello", @outputStream.buffer)
@outputStream.print(" world.")
assert_equal("hello world.", @outputStream.buffer)
@outputStream.print(" You ok ", "out ", "there?")
assert_equal("hello world. You ok out there?", @outputStream.buffer)
$\ = "\n"
@outputStream.print
assert_equal("hello world. You ok out there?\n", @outputStream.buffer)
@outputStream.print("I sure hope so!")
assert_equal("hello world. You ok out there?\nI sure hope so!\n", @outputStream.buffer)
$, = "X"
@outputStream.buffer = ""
@outputStream.print("monkey", "duck", "zebra")
assert_equal("monkeyXduckXzebra\n", @outputStream.buffer)
$\ = nil
@outputStream.buffer = ""
@outputStream.print(20)
assert_equal("20", @outputStream.buffer)
end
def test_printf
@outputStream.printf("%d %04x", 123, 123)
assert_equal("123 007b", @outputStream.buffer)
end
def test_putc
@outputStream.putc("A")
assert_equal("A", @outputStream.buffer)
@outputStream.putc(65)
assert_equal("AA", @outputStream.buffer)
end
def test_puts
@outputStream.puts
assert_equal("\n", @outputStream.buffer)
@outputStream.puts("hello", "world")
assert_equal("\nhello\nworld\n", @outputStream.buffer)
@outputStream.buffer = ""
@outputStream.puts("hello\n", "world\n")
assert_equal("hello\nworld\n", @outputStream.buffer)
@outputStream.buffer = ""
@outputStream.puts(["hello\n", "world\n"])
assert_equal("hello\nworld\n", @outputStream.buffer)
@outputStream.buffer = ""
@outputStream.puts(["hello\n", "world\n"], "bingo")
assert_equal("hello\nworld\nbingo\n", @outputStream.buffer)
@outputStream.buffer = ""
@outputStream.puts(16, 20, 50, "hello")
assert_equal("16\n20\n50\nhello\n", @outputStream.buffer)
end
end
# Copyright (C) 2002-2004 Thomas Sondergaard
# rubyzip is free software; you can redistribute it and/or
# modify it under the terms of the ruby license.

View file

@ -0,0 +1,52 @@
#!/usr/bin/env ruby
$VERBOSE = true
$: << "../lib"
require 'test/unit'
require 'zip/stdrubyext'
class ModuleTest < Test::Unit::TestCase
def test_select_map
assert_equal([2, 4, 8, 10], [1, 2, 3, 4, 5].select_map { |e| e == 3 ? nil : 2*e })
end
end
class StringExtensionsTest < Test::Unit::TestCase
def test_starts_with
assert("hello".starts_with(""))
assert("hello".starts_with("h"))
assert("hello".starts_with("he"))
assert(! "hello".starts_with("hello there"))
assert(! "hello".starts_with(" he"))
assert_raise(TypeError, "type mismatch: NilClass given") {
"hello".starts_with(nil)
}
end
def test_ends_with
assert("hello".ends_with("o"))
assert("hello".ends_with("lo"))
assert("hello".ends_with("hello"))
assert(!"howdy".ends_with("o"))
assert(!"howdy".ends_with("oy"))
assert(!"howdy".ends_with("howdy doody"))
assert(!"howdy".ends_with("doody howdy"))
end
def test_ensure_end
assert_equal("hello!", "hello!".ensure_end("!"))
assert_equal("hello!", "hello!".ensure_end("o!"))
assert_equal("hello!", "hello".ensure_end("!"))
assert_equal("hello!", "hel".ensure_end("lo!"))
end
end
# Copyright (C) 2002, 2003 Thomas Sondergaard
# rubyzip is free software; you can redistribute it and/or
# modify it under the terms of the ruby license.

View file

@ -0,0 +1,831 @@
#!/usr/bin/env ruby
$VERBOSE = true
$: << "../lib"
require 'zip/zipfilesystem'
require 'test/unit'
module ExtraAssertions
def assert_forwarded(anObject, method, retVal, *expectedArgs)
callArgs = nil
setCallArgsProc = proc { |args| callArgs = args }
anObject.instance_eval <<-"end_eval"
alias #{method}_org #{method}
def #{method}(*args)
ObjectSpace._id2ref(#{setCallArgsProc.object_id}).call(args)
ObjectSpace._id2ref(#{retVal.object_id})
end
end_eval
assert_equal(retVal, yield) # Invoke test
assert_equal(expectedArgs, callArgs)
ensure
anObject.instance_eval "alias #{method} #{method}_org"
end
end
include Zip
class ZipFsFileNonmutatingTest < Test::Unit::TestCase
def setup
@zipFile = ZipFile.new("data/zipWithDirs.zip")
end
def teardown
@zipFile.close if @zipFile
end
def test_umask
assert_equal(File.umask, @zipFile.file.umask)
@zipFile.file.umask(0006)
end
def test_exists?
assert(! @zipFile.file.exists?("notAFile"))
assert(@zipFile.file.exists?("file1"))
assert(@zipFile.file.exists?("dir1"))
assert(@zipFile.file.exists?("dir1/"))
assert(@zipFile.file.exists?("dir1/file12"))
assert(@zipFile.file.exist?("dir1/file12")) # notice, tests exist? alias of exists? !
@zipFile.dir.chdir "dir1/"
assert(!@zipFile.file.exists?("file1"))
assert(@zipFile.file.exists?("file12"))
end
def test_open_read
blockCalled = false
@zipFile.file.open("file1", "r") {
|f|
blockCalled = true
assert_equal("this is the entry 'file1' in my test archive!",
f.readline.chomp)
}
assert(blockCalled)
blockCalled = false
@zipFile.dir.chdir "dir2"
@zipFile.file.open("file21", "r") {
|f|
blockCalled = true
assert_equal("this is the entry 'dir2/file21' in my test archive!",
f.readline.chomp)
}
assert(blockCalled)
@zipFile.dir.chdir "/"
assert_raise(Errno::ENOENT) {
@zipFile.file.open("noSuchEntry")
}
begin
is = @zipFile.file.open("file1")
assert_equal("this is the entry 'file1' in my test archive!",
is.readline.chomp)
ensure
is.close if is
end
end
def test_new
begin
is = @zipFile.file.new("file1")
assert_equal("this is the entry 'file1' in my test archive!",
is.readline.chomp)
ensure
is.close if is
end
begin
is = @zipFile.file.new("file1") {
fail "should not call block"
}
ensure
is.close if is
end
end
def test_symlink
assert_raise(NotImplementedError) {
@zipFile.file.symlink("file1", "aSymlink")
}
end
def test_size
assert_raise(Errno::ENOENT) { @zipFile.file.size("notAFile") }
assert_equal(72, @zipFile.file.size("file1"))
assert_equal(0, @zipFile.file.size("dir2/dir21"))
assert_equal(72, @zipFile.file.stat("file1").size)
assert_equal(0, @zipFile.file.stat("dir2/dir21").size)
end
def test_size?
assert_equal(nil, @zipFile.file.size?("notAFile"))
assert_equal(72, @zipFile.file.size?("file1"))
assert_equal(nil, @zipFile.file.size?("dir2/dir21"))
assert_equal(72, @zipFile.file.stat("file1").size?)
assert_equal(nil, @zipFile.file.stat("dir2/dir21").size?)
end
def test_file?
assert(@zipFile.file.file?("file1"))
assert(@zipFile.file.file?("dir2/file21"))
assert(! @zipFile.file.file?("dir1"))
assert(! @zipFile.file.file?("dir1/dir11"))
assert(@zipFile.file.stat("file1").file?)
assert(@zipFile.file.stat("dir2/file21").file?)
assert(! @zipFile.file.stat("dir1").file?)
assert(! @zipFile.file.stat("dir1/dir11").file?)
end
include ExtraAssertions
def test_dirname
assert_forwarded(File, :dirname, "retVal", "a/b/c/d") {
@zipFile.file.dirname("a/b/c/d")
}
end
def test_basename
assert_forwarded(File, :basename, "retVal", "a/b/c/d") {
@zipFile.file.basename("a/b/c/d")
}
end
def test_split
assert_forwarded(File, :split, "retVal", "a/b/c/d") {
@zipFile.file.split("a/b/c/d")
}
end
def test_join
assert_equal("a/b/c", @zipFile.file.join("a/b", "c"))
assert_equal("a/b/c/d", @zipFile.file.join("a/b", "c/d"))
assert_equal("/c/d", @zipFile.file.join("", "c/d"))
assert_equal("a/b/c/d", @zipFile.file.join("a", "b", "c", "d"))
end
def test_utime
t_now = Time.now
t_bak = @zipFile.file.mtime("file1")
@zipFile.file.utime(t_now, "file1")
assert_equal(t_now, @zipFile.file.mtime("file1"))
@zipFile.file.utime(t_bak, "file1")
assert_equal(t_bak, @zipFile.file.mtime("file1"))
end
def assert_always_false(operation)
assert(! @zipFile.file.send(operation, "noSuchFile"))
assert(! @zipFile.file.send(operation, "file1"))
assert(! @zipFile.file.send(operation, "dir1"))
assert(! @zipFile.file.stat("file1").send(operation))
assert(! @zipFile.file.stat("dir1").send(operation))
end
def assert_true_if_entry_exists(operation)
assert(! @zipFile.file.send(operation, "noSuchFile"))
assert(@zipFile.file.send(operation, "file1"))
assert(@zipFile.file.send(operation, "dir1"))
assert(@zipFile.file.stat("file1").send(operation))
assert(@zipFile.file.stat("dir1").send(operation))
end
def test_pipe?
assert_always_false(:pipe?)
end
def test_blockdev?
assert_always_false(:blockdev?)
end
def test_symlink?
assert_always_false(:symlink?)
end
def test_socket?
assert_always_false(:socket?)
end
def test_chardev?
assert_always_false(:chardev?)
end
def test_truncate
assert_raise(StandardError, "truncate not supported") {
@zipFile.file.truncate("file1", 100)
}
end
def assert_e_n_o_e_n_t(operation, args = ["NoSuchFile"])
assert_raise(Errno::ENOENT) {
@zipFile.file.send(operation, *args)
}
end
def test_ftype
assert_e_n_o_e_n_t(:ftype)
assert_equal("file", @zipFile.file.ftype("file1"))
assert_equal("directory", @zipFile.file.ftype("dir1/dir11"))
assert_equal("directory", @zipFile.file.ftype("dir1/dir11/"))
end
def test_link
assert_raise(NotImplementedError) {
@zipFile.file.link("file1", "someOtherString")
}
end
def test_directory?
assert(! @zipFile.file.directory?("notAFile"))
assert(! @zipFile.file.directory?("file1"))
assert(! @zipFile.file.directory?("dir1/file11"))
assert(@zipFile.file.directory?("dir1"))
assert(@zipFile.file.directory?("dir1/"))
assert(@zipFile.file.directory?("dir2/dir21"))
assert(! @zipFile.file.stat("file1").directory?)
assert(! @zipFile.file.stat("dir1/file11").directory?)
assert(@zipFile.file.stat("dir1").directory?)
assert(@zipFile.file.stat("dir1/").directory?)
assert(@zipFile.file.stat("dir2/dir21").directory?)
end
def test_chown
assert_equal(2, @zipFile.file.chown(1,2, "dir1", "file1"))
assert_equal(1, @zipFile.file.stat("dir1").uid)
assert_equal(2, @zipFile.file.stat("dir1").gid)
assert_equal(2, @zipFile.file.chown(nil, nil, "dir1", "file1"))
end
def test_zero?
assert(! @zipFile.file.zero?("notAFile"))
assert(! @zipFile.file.zero?("file1"))
assert(@zipFile.file.zero?("dir1"))
blockCalled = false
ZipFile.open("data/generated/5entry.zip") {
|zf|
blockCalled = true
assert(zf.file.zero?("data/generated/empty.txt"))
}
assert(blockCalled)
assert(! @zipFile.file.stat("file1").zero?)
assert(@zipFile.file.stat("dir1").zero?)
blockCalled = false
ZipFile.open("data/generated/5entry.zip") {
|zf|
blockCalled = true
assert(zf.file.stat("data/generated/empty.txt").zero?)
}
assert(blockCalled)
end
def test_expand_path
ZipFile.open("data/zipWithDirs.zip") {
|zf|
assert_equal("/", zf.file.expand_path("."))
zf.dir.chdir "dir1"
assert_equal("/dir1", zf.file.expand_path("."))
assert_equal("/dir1/file12", zf.file.expand_path("file12"))
assert_equal("/", zf.file.expand_path(".."))
assert_equal("/dir2/dir21", zf.file.expand_path("../dir2/dir21"))
}
end
def test_mtime
assert_equal(Time.at(1027694306),
@zipFile.file.mtime("dir2/file21"))
assert_equal(Time.at(1027690863),
@zipFile.file.mtime("dir2/dir21"))
assert_raise(Errno::ENOENT) {
@zipFile.file.mtime("noSuchEntry")
}
assert_equal(Time.at(1027694306),
@zipFile.file.stat("dir2/file21").mtime)
assert_equal(Time.at(1027690863),
@zipFile.file.stat("dir2/dir21").mtime)
end
def test_ctime
assert_nil(@zipFile.file.ctime("file1"))
assert_nil(@zipFile.file.stat("file1").ctime)
end
def test_atime
assert_nil(@zipFile.file.atime("file1"))
assert_nil(@zipFile.file.stat("file1").atime)
end
def test_readable?
assert(! @zipFile.file.readable?("noSuchFile"))
assert(@zipFile.file.readable?("file1"))
assert(@zipFile.file.readable?("dir1"))
assert(@zipFile.file.stat("file1").readable?)
assert(@zipFile.file.stat("dir1").readable?)
end
def test_readable_real?
assert(! @zipFile.file.readable_real?("noSuchFile"))
assert(@zipFile.file.readable_real?("file1"))
assert(@zipFile.file.readable_real?("dir1"))
assert(@zipFile.file.stat("file1").readable_real?)
assert(@zipFile.file.stat("dir1").readable_real?)
end
def test_writable?
assert(! @zipFile.file.writable?("noSuchFile"))
assert(@zipFile.file.writable?("file1"))
assert(@zipFile.file.writable?("dir1"))
assert(@zipFile.file.stat("file1").writable?)
assert(@zipFile.file.stat("dir1").writable?)
end
def test_writable_real?
assert(! @zipFile.file.writable_real?("noSuchFile"))
assert(@zipFile.file.writable_real?("file1"))
assert(@zipFile.file.writable_real?("dir1"))
assert(@zipFile.file.stat("file1").writable_real?)
assert(@zipFile.file.stat("dir1").writable_real?)
end
def test_executable?
assert(! @zipFile.file.executable?("noSuchFile"))
assert(! @zipFile.file.executable?("file1"))
assert(@zipFile.file.executable?("dir1"))
assert(! @zipFile.file.stat("file1").executable?)
assert(@zipFile.file.stat("dir1").executable?)
end
def test_executable_real?
assert(! @zipFile.file.executable_real?("noSuchFile"))
assert(! @zipFile.file.executable_real?("file1"))
assert(@zipFile.file.executable_real?("dir1"))
assert(! @zipFile.file.stat("file1").executable_real?)
assert(@zipFile.file.stat("dir1").executable_real?)
end
def test_owned?
assert_true_if_entry_exists(:owned?)
end
def test_grpowned?
assert_true_if_entry_exists(:grpowned?)
end
def test_setgid?
assert_always_false(:setgid?)
end
def test_setuid?
assert_always_false(:setgid?)
end
def test_sticky?
assert_always_false(:sticky?)
end
def test_readlink
assert_raise(NotImplementedError) {
@zipFile.file.readlink("someString")
}
end
def test_stat
s = @zipFile.file.stat("file1")
assert(s.kind_of?(File::Stat)) # It pretends
assert_raise(Errno::ENOENT, "No such file or directory - noSuchFile") {
@zipFile.file.stat("noSuchFile")
}
end
def test_lstat
assert(@zipFile.file.lstat("file1").file?)
end
def test_chmod
assert_raise(Errno::ENOENT, "No such file or directory - noSuchFile") {
@zipFile.file.chmod(0644, "file1", "NoSuchFile")
}
assert_equal(2, @zipFile.file.chmod(0644, "file1", "dir1"))
end
def test_pipe
assert_raise(NotImplementedError) {
@zipFile.file.pipe
}
end
def test_foreach
ZipFile.open("data/generated/zipWithDir.zip") {
|zf|
ref = []
File.foreach("data/file1.txt") { |e| ref << e }
index = 0
zf.file.foreach("data/file1.txt") {
|l|
assert_equal(ref[index], l)
index = index.next
}
assert_equal(ref.size, index)
}
ZipFile.open("data/generated/zipWithDir.zip") {
|zf|
ref = []
File.foreach("data/file1.txt", " ") { |e| ref << e }
index = 0
zf.file.foreach("data/file1.txt", " ") {
|l|
assert_equal(ref[index], l)
index = index.next
}
assert_equal(ref.size, index)
}
end
def test_popen
cmd = /mswin/i =~ RUBY_PLATFORM ? 'dir' : 'ls'
assert_equal(File.popen(cmd) { |f| f.read },
@zipFile.file.popen(cmd) { |f| f.read })
end
# Can be added later
# def test_select
# fail "implement test"
# end
def test_readlines
ZipFile.open("data/generated/zipWithDir.zip") {
|zf|
assert_equal(File.readlines("data/file1.txt"),
zf.file.readlines("data/file1.txt"))
}
end
def test_read
ZipFile.open("data/generated/zipWithDir.zip") {
|zf|
assert_equal(File.read("data/file1.txt"),
zf.file.read("data/file1.txt"))
}
end
end
class ZipFsFileStatTest < Test::Unit::TestCase
def setup
@zipFile = ZipFile.new("data/zipWithDirs.zip")
end
def teardown
@zipFile.close if @zipFile
end
def test_blocks
assert_equal(nil, @zipFile.file.stat("file1").blocks)
end
def test_ino
assert_equal(0, @zipFile.file.stat("file1").ino)
end
def test_uid
assert_equal(0, @zipFile.file.stat("file1").uid)
end
def test_gid
assert_equal(0, @zipFile.file.stat("file1").gid)
end
def test_ftype
assert_equal("file", @zipFile.file.stat("file1").ftype)
assert_equal("directory", @zipFile.file.stat("dir1").ftype)
end
def test_mode
assert_equal(0600, @zipFile.file.stat("file1").mode & 0777)
assert_equal(0600, @zipFile.file.stat("file1").mode & 0777)
assert_equal(0755, @zipFile.file.stat("dir1").mode & 0777)
assert_equal(0755, @zipFile.file.stat("dir1").mode & 0777)
end
def test_dev
assert_equal(0, @zipFile.file.stat("file1").dev)
end
def test_rdev
assert_equal(0, @zipFile.file.stat("file1").rdev)
end
def test_rdev_major
assert_equal(0, @zipFile.file.stat("file1").rdev_major)
end
def test_rdev_minor
assert_equal(0, @zipFile.file.stat("file1").rdev_minor)
end
def test_nlink
assert_equal(1, @zipFile.file.stat("file1").nlink)
end
def test_blksize
assert_nil(@zipFile.file.stat("file1").blksize)
end
end
class ZipFsFileMutatingTest < Test::Unit::TestCase
TEST_ZIP = "zipWithDirs_copy.zip"
def setup
File.copy("data/zipWithDirs.zip", TEST_ZIP)
end
def teardown
end
def test_delete
do_test_delete_or_unlink(:delete)
end
def test_unlink
do_test_delete_or_unlink(:unlink)
end
def test_open_write
ZipFile.open(TEST_ZIP) {
|zf|
zf.file.open("test_open_write_entry", "w") {
|f|
blockCalled = true
f.write "This is what I'm writing"
}
assert_equal("This is what I'm writing",
zf.file.read("test_open_write_entry"))
# Test with existing entry
zf.file.open("file1", "w") {
|f|
blockCalled = true
f.write "This is what I'm writing too"
}
assert_equal("This is what I'm writing too",
zf.file.read("file1"))
}
end
def test_rename
ZipFile.open(TEST_ZIP) {
|zf|
assert_raise(Errno::ENOENT, "") {
zf.file.rename("NoSuchFile", "bimse")
}
zf.file.rename("file1", "newNameForFile1")
}
ZipFile.open(TEST_ZIP) {
|zf|
assert(! zf.file.exists?("file1"))
assert(zf.file.exists?("newNameForFile1"))
}
end
def do_test_delete_or_unlink(symbol)
ZipFile.open(TEST_ZIP) {
|zf|
assert(zf.file.exists?("dir2/dir21/dir221/file2221"))
zf.file.send(symbol, "dir2/dir21/dir221/file2221")
assert(! zf.file.exists?("dir2/dir21/dir221/file2221"))
assert(zf.file.exists?("dir1/file11"))
assert(zf.file.exists?("dir1/file12"))
zf.file.send(symbol, "dir1/file11", "dir1/file12")
assert(! zf.file.exists?("dir1/file11"))
assert(! zf.file.exists?("dir1/file12"))
assert_raise(Errno::ENOENT) { zf.file.send(symbol, "noSuchFile") }
assert_raise(Errno::EISDIR) { zf.file.send(symbol, "dir1/dir11") }
assert_raise(Errno::EISDIR) { zf.file.send(symbol, "dir1/dir11/") }
}
ZipFile.open(TEST_ZIP) {
|zf|
assert(! zf.file.exists?("dir2/dir21/dir221/file2221"))
assert(! zf.file.exists?("dir1/file11"))
assert(! zf.file.exists?("dir1/file12"))
assert(zf.file.exists?("dir1/dir11"))
assert(zf.file.exists?("dir1/dir11/"))
}
end
end
class ZipFsDirectoryTest < Test::Unit::TestCase
TEST_ZIP = "zipWithDirs_copy.zip"
def setup
File.copy("data/zipWithDirs.zip", TEST_ZIP)
end
def test_delete
ZipFile.open(TEST_ZIP) {
|zf|
assert_raise(Errno::ENOENT, "No such file or directory - NoSuchFile.txt") {
zf.dir.delete("NoSuchFile.txt")
}
assert_raise(Errno::EINVAL, "Invalid argument - file1") {
zf.dir.delete("file1")
}
assert(zf.file.exists?("dir1"))
zf.dir.delete("dir1")
assert(! zf.file.exists?("dir1"))
}
end
def test_mkdir
ZipFile.open(TEST_ZIP) {
|zf|
assert_raise(Errno::EEXIST, "File exists - dir1") {
zf.dir.mkdir("file1")
}
assert_raise(Errno::EEXIST, "File exists - dir1") {
zf.dir.mkdir("dir1")
}
assert(!zf.file.exists?("newDir"))
zf.dir.mkdir("newDir")
assert(zf.file.directory?("newDir"))
assert(!zf.file.exists?("newDir2"))
zf.dir.mkdir("newDir2", 3485)
assert(zf.file.directory?("newDir2"))
}
end
def test_pwd_chdir_entries
ZipFile.open(TEST_ZIP) {
|zf|
assert_equal("/", zf.dir.pwd)
assert_raise(Errno::ENOENT, "No such file or directory - no such dir") {
zf.dir.chdir "no such dir"
}
assert_raise(Errno::EINVAL, "Invalid argument - file1") {
zf.dir.chdir "file1"
}
assert_equal(["dir1", "dir2", "file1"].sort, zf.dir.entries(".").sort)
zf.dir.chdir "dir1"
assert_equal("/dir1", zf.dir.pwd)
assert_equal(["dir11", "file11", "file12"], zf.dir.entries(".").sort)
zf.dir.chdir "../dir2/dir21"
assert_equal("/dir2/dir21", zf.dir.pwd)
assert_equal(["dir221"].sort, zf.dir.entries(".").sort)
}
end
def test_foreach
ZipFile.open(TEST_ZIP) {
|zf|
blockCalled = false
assert_raise(Errno::ENOENT, "No such file or directory - noSuchDir") {
zf.dir.foreach("noSuchDir") { |e| blockCalled = true }
}
assert(! blockCalled)
assert_raise(Errno::ENOTDIR, "Not a directory - file1") {
zf.dir.foreach("file1") { |e| blockCalled = true }
}
assert(! blockCalled)
entries = []
zf.dir.foreach(".") { |e| entries << e }
assert_equal(["dir1", "dir2", "file1"].sort, entries.sort)
entries = []
zf.dir.foreach("dir1") { |e| entries << e }
assert_equal(["dir11", "file11", "file12"], entries.sort)
}
end
def test_chroot
ZipFile.open(TEST_ZIP) {
|zf|
assert_raise(NotImplementedError) {
zf.dir.chroot
}
}
end
# Globbing not supported yet
#def test_glob
# # test alias []-operator too
# fail "implement test"
#end
def test_open_new
ZipFile.open(TEST_ZIP) {
|zf|
assert_raise(Errno::ENOTDIR, "Not a directory - file1") {
zf.dir.new("file1")
}
assert_raise(Errno::ENOENT, "No such file or directory - noSuchFile") {
zf.dir.new("noSuchFile")
}
d = zf.dir.new(".")
assert_equal(["file1", "dir1", "dir2"].sort, d.entries.sort)
d.close
zf.dir.open("dir1") {
|d|
assert_equal(["dir11", "file11", "file12"].sort, d.entries.sort)
}
}
end
end
class ZipFsDirIteratorTest < Test::Unit::TestCase
FILENAME_ARRAY = [ "f1", "f2", "f3", "f4", "f5", "f6" ]
def setup
@dirIt = ZipFileSystem::ZipFsDirIterator.new(FILENAME_ARRAY)
end
def test_close
@dirIt.close
assert_raise(IOError, "closed directory") {
@dirIt.each { |e| p e }
}
assert_raise(IOError, "closed directory") {
@dirIt.read
}
assert_raise(IOError, "closed directory") {
@dirIt.rewind
}
assert_raise(IOError, "closed directory") {
@dirIt.seek(0)
}
assert_raise(IOError, "closed directory") {
@dirIt.tell
}
end
def test_each
# Tested through Enumerable.entries
assert_equal(FILENAME_ARRAY, @dirIt.entries)
end
def test_read
FILENAME_ARRAY.size.times {
|i|
assert_equal(FILENAME_ARRAY[i], @dirIt.read)
}
end
def test_rewind
@dirIt.read
@dirIt.read
assert_equal(FILENAME_ARRAY[2], @dirIt.read)
@dirIt.rewind
assert_equal(FILENAME_ARRAY[0], @dirIt.read)
end
def test_tell_seek
@dirIt.read
@dirIt.read
pos = @dirIt.tell
valAtPos = @dirIt.read
@dirIt.read
@dirIt.seek(pos)
assert_equal(valAtPos, @dirIt.read)
end
end
# Copyright (C) 2002, 2003 Thomas Sondergaard
# rubyzip is free software; you can redistribute it and/or
# modify it under the terms of the ruby license.

View file

@ -0,0 +1,43 @@
#!/usr/bin/env ruby
$VERBOSE = true
$: << "../lib"
require 'test/unit'
require 'zip/ziprequire'
$: << 'data/rubycode.zip' << 'data/rubycode2.zip'
class ZipRequireTest < Test::Unit::TestCase
def test_require
assert(require('data/notzippedruby'))
assert(!require('data/notzippedruby'))
assert(require('zippedruby1'))
assert(!require('zippedruby1'))
assert(require('zippedruby2'))
assert(!require('zippedruby2'))
assert(require('zippedruby3'))
assert(!require('zippedruby3'))
c1 = NotZippedRuby.new
assert(c1.returnTrue)
assert(ZippedRuby1.returnTrue)
assert(!ZippedRuby2.returnFalse)
assert_equal(4, ZippedRuby3.multiplyValues(2, 2))
end
def test_get_resource
get_resource("aResource.txt") {
|f|
assert_equal("Nothing exciting in this file!", f.read)
}
end
end
# Copyright (C) 2002 Thomas Sondergaard
# rubyzip is free software; you can redistribute it and/or
# modify it under the terms of the ruby license.

1599
vendor/plugins/rubyzip-0.9.1/test/ziptest.rb vendored Executable file

File diff suppressed because it is too large Load diff

33
vendor/plugins/sqlite3-ruby/sqlite3.rb vendored Normal file
View file

@ -0,0 +1,33 @@
#--
# =============================================================================
# Copyright (c) 2004, Jamis Buck (jgb3@email.byu.edu)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * The names of its contributors may not be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# =============================================================================
#++
require 'sqlite3/database'

View file

@ -0,0 +1,81 @@
#--
# =============================================================================
# Copyright (c) 2004, Jamis Buck (jgb3@email.byu.edu)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * The names of its contributors may not be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# =============================================================================
#++
module SQLite3 ; module Constants
module TextRep
UTF8 = 1
UTF16LE = 2
UTF16BE = 3
UTF16 = 4
ANY = 5
end
module ColumnType
INTEGER = 1
FLOAT = 2
TEXT = 3
BLOB = 4
NULL = 5
end
module ErrorCode
OK = 0 # Successful result
ERROR = 1 # SQL error or missing database
INTERNAL = 2 # An internal logic error in SQLite
PERM = 3 # Access permission denied
ABORT = 4 # Callback routine requested an abort
BUSY = 5 # The database file is locked
LOCKED = 6 # A table in the database is locked
NOMEM = 7 # A malloc() failed
READONLY = 8 # Attempt to write a readonly database
INTERRUPT = 9 # Operation terminated by sqlite_interrupt()
IOERR = 10 # Some kind of disk I/O error occurred
CORRUPT = 11 # The database disk image is malformed
NOTFOUND = 12 # (Internal Only) Table or record not found
FULL = 13 # Insertion failed because database is full
CANTOPEN = 14 # Unable to open the database file
PROTOCOL = 15 # Database lock protocol error
EMPTY = 16 # (Internal Only) Database table is empty
SCHEMA = 17 # The database schema changed
TOOBIG = 18 # Too much data for one row of a table
CONSTRAINT = 19 # Abort due to contraint violation
MISMATCH = 20 # Data type mismatch
MISUSE = 21 # Library used incorrectly
NOLFS = 22 # Uses OS features not supported on host
AUTH = 23 # Authorization denied
ROW = 100 # sqlite_step() has another row ready
DONE = 101 # sqlite_step() has finished executing
end
end ; end

View file

@ -0,0 +1,745 @@
#--
# =============================================================================
# Copyright (c) 2004, Jamis Buck (jgb3@email.byu.edu)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * The names of its contributors may not be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# =============================================================================
#++
require 'base64'
require 'sqlite3/constants'
require 'sqlite3/errors'
require 'sqlite3/pragmas'
require 'sqlite3/statement'
require 'sqlite3/translator'
require 'sqlite3/value'
module SQLite3
# The Database class encapsulates a single connection to a SQLite3 database.
# Its usage is very straightforward:
#
# require 'sqlite3'
#
# db = SQLite3::Database.new( "data.db" )
#
# db.execute( "select * from table" ) do |row|
# p row
# end
#
# db.close
#
# It wraps the lower-level methods provides by the selected driver, and
# includes the Pragmas module for access to various pragma convenience
# methods.
#
# The Database class provides type translation services as well, by which
# the SQLite3 data types (which are all represented as strings) may be
# converted into their corresponding types (as defined in the schemas
# for their tables). This translation only occurs when querying data from
# the database--insertions and updates are all still typeless.
#
# Furthermore, the Database class has been designed to work well with the
# ArrayFields module from Ara Howard. If you require the ArrayFields
# module before performing a query, and if you have not enabled results as
# hashes, then the results will all be indexible by field name.
class Database
include Pragmas
class <<self
alias :open :new
# Quotes the given string, making it safe to use in an SQL statement.
# It replaces all instances of the single-quote character with two
# single-quote characters. The modified string is returned.
def quote( string )
string.gsub( /'/, "''" )
end
end
# The low-level opaque database handle that this object wraps.
attr_reader :handle
# A reference to the underlying SQLite3 driver used by this database.
attr_reader :driver
# A boolean that indicates whether rows in result sets should be returned
# as hashes or not. By default, rows are returned as arrays.
attr_accessor :results_as_hash
# A boolean indicating whether or not type translation is enabled for this
# database.
attr_accessor :type_translation
# Create a new Database object that opens the given file. If utf16
# is +true+, the filename is interpreted as a UTF-16 encoded string.
#
# By default, the new database will return result rows as arrays
# (#results_as_hash) and has type translation disabled (#type_translation=).
def initialize( file_name, options={} )
utf16 = options.fetch(:utf16, false)
load_driver( options[:driver] )
@statement_factory = options[:statement_factory] || Statement
result, @handle = @driver.open( file_name, utf16 )
Error.check( result, self, "could not open database" )
@closed = false
@results_as_hash = options.fetch(:results_as_hash,false)
@type_translation = options.fetch(:type_translation,false)
@translator = nil
@transaction_active = false
end
# Return +true+ if the string is a valid (ie, parsable) SQL statement, and
# +false+ otherwise. If +utf16+ is +true+, then the string is a UTF-16
# character string.
def complete?( string, utf16=false )
@driver.complete?( string, utf16 )
end
# Return a string describing the last error to have occurred with this
# database.
def errmsg( utf16=false )
@driver.errmsg( @handle, utf16 )
end
# Return an integer representing the last error to have occurred with this
# database.
def errcode
@driver.errcode( @handle )
end
# Return the type translator employed by this database instance. Each
# database instance has its own type translator; this allows for different
# type handlers to be installed in each instance without affecting other
# instances. Furthermore, the translators are instantiated lazily, so that
# if a database does not use type translation, it will not be burdened by
# the overhead of a useless type translator. (See the Translator class.)
def translator
@translator ||= Translator.new
end
# Closes this database.
def close
unless @closed
result = @driver.close( @handle )
Error.check( result, self )
end
@closed = true
end
# Returns +true+ if this database instance has been closed (see #close).
def closed?
@closed
end
# Installs (or removes) a block that will be invoked for every SQL
# statement executed. The block receives a two parameters: the +data+
# argument, and the SQL statement executed. If the block is +nil+,
# any existing tracer will be uninstalled.
def trace( data=nil, &block )
@driver.trace( @handle, data, &block )
end
# Installs (or removes) a block that will be invoked for every access
# to the database. If the block returns 0 (or +nil+), the statement
# is allowed to proceed. Returning 1 causes an authorization error to
# occur, and returning 2 causes the access to be silently denied.
def authorizer( data=nil, &block )
result = @driver.set_authorizer( @handle, data, &block )
Error.check( result, self )
end
# Returns a Statement object representing the given SQL. This does not
# execute the statement; it merely prepares the statement for execution.
def prepare( sql )
stmt = @statement_factory.new( self, sql )
if block_given?
begin
yield stmt
ensure
stmt.close
end
else
return stmt
end
end
# Executes the given SQL statement. If additional parameters are given,
# they are treated as bind variables, and are bound to the placeholders in
# the query.
#
# Note that if any of the values passed to this are hashes, then the
# key/value pairs are each bound separately, with the key being used as
# the name of the placeholder to bind the value to.
#
# The block is optional. If given, it will be invoked for each row returned
# by the query. Otherwise, any results are accumulated into an array and
# returned wholesale.
#
# See also #execute2, #query, and #execute_batch for additional ways of
# executing statements.
def execute( sql, *bind_vars )
prepare( sql ) do |stmt|
result = stmt.execute( *bind_vars )
if block_given?
result.each { |row| yield row }
else
return result.inject( [] ) { |arr,row| arr << row; arr }
end
end
end
# Executes the given SQL statement, exactly as with #execute. However, the
# first row returned (either via the block, or in the returned array) is
# always the names of the columns. Subsequent rows correspond to the data
# from the result set.
#
# Thus, even if the query itself returns no rows, this method will always
# return at least one row--the names of the columns.
#
# See also #execute, #query, and #execute_batch for additional ways of
# executing statements.
def execute2( sql, *bind_vars )
prepare( sql ) do |stmt|
result = stmt.execute( *bind_vars )
if block_given?
yield result.columns
result.each { |row| yield row }
else
return result.inject( [ result.columns ] ) { |arr,row|
arr << row; arr }
end
end
end
# Executes all SQL statements in the given string. By contrast, the other
# means of executing queries will only execute the first statement in the
# string, ignoring all subsequent statements. This will execute each one
# in turn. The same bind parameters, if given, will be applied to each
# statement.
#
# This always returns +nil+, making it unsuitable for queries that return
# rows.
def execute_batch( sql, *bind_vars )
sql = sql.strip
until sql.empty? do
prepare( sql ) do |stmt|
stmt.execute( *bind_vars )
sql = stmt.remainder.strip
end
end
nil
end
# This is a convenience method for creating a statement, binding
# paramters to it, and calling execute:
#
# result = db.query( "select * from foo where a=?", 5 )
# # is the same as
# result = db.prepare( "select * from foo where a=?" ).execute( 5 )
#
# You must be sure to call +close+ on the ResultSet instance that is
# returned, or you could have problems with locks on the table. If called
# with a block, +close+ will be invoked implicitly when the block
# terminates.
def query( sql, *bind_vars )
result = prepare( sql ).execute( *bind_vars )
if block_given?
begin
yield result
ensure
result.close
end
else
return result
end
end
# A convenience method for obtaining the first row of a result set, and
# discarding all others. It is otherwise identical to #execute.
#
# See also #get_first_value.
def get_first_row( sql, *bind_vars )
execute( sql, *bind_vars ) { |row| return row }
nil
end
# A convenience method for obtaining the first value of the first row of a
# result set, and discarding all other values and rows. It is otherwise
# identical to #execute.
#
# See also #get_first_row.
def get_first_value( sql, *bind_vars )
execute( sql, *bind_vars ) { |row| return row[0] }
nil
end
# Obtains the unique row ID of the last row to be inserted by this Database
# instance.
def last_insert_row_id
@driver.last_insert_rowid( @handle )
end
# Returns the number of changes made to this database instance by the last
# operation performed. Note that a "delete from table" without a where
# clause will not affect this value.
def changes
@driver.changes( @handle )
end
# Returns the total number of changes made to this database instance
# since it was opened.
def total_changes
@driver.total_changes( @handle )
end
# Interrupts the currently executing operation, causing it to abort.
def interrupt
@driver.interrupt( @handle )
end
# Register a busy handler with this database instance. When a requested
# resource is busy, this handler will be invoked. If the handler returns
# +false+, the operation will be aborted; otherwise, the resource will
# be requested again.
#
# The handler will be invoked with the name of the resource that was
# busy, and the number of times it has been retried.
#
# See also #busy_timeout.
def busy_handler( data=nil, &block ) # :yields: data, retries
result = @driver.busy_handler( @handle, data, &block )
Error.check( result, self )
end
# Indicates that if a request for a resource terminates because that
# resource is busy, SQLite should wait for the indicated number of
# milliseconds before trying again. By default, SQLite does not retry
# busy resources. To restore the default behavior, send 0 as the
# +ms+ parameter.
#
# See also #busy_handler.
def busy_timeout( ms )
result = @driver.busy_timeout( @handle, ms )
Error.check( result, self )
end
# Creates a new function for use in SQL statements. It will be added as
# +name+, with the given +arity+. (For variable arity functions, use
# -1 for the arity.)
#
# The block should accept at least one parameter--the FunctionProxy
# instance that wraps this function invocation--and any other
# arguments it needs (up to its arity).
#
# The block does not return a value directly. Instead, it will invoke
# the FunctionProxy#set_result method on the +func+ parameter and
# indicate the return value that way.
#
# Example:
#
# db.create_function( "maim", 1 ) do |func, value|
# if value.nil?
# func.result = nil
# else
# func.result = value.split(//).sort.join
# end
# end
#
# puts db.get_first_value( "select maim(name) from table" )
def create_function( name, arity, text_rep=Constants::TextRep::ANY,
&block ) # :yields: func, *args
# begin
callback = proc do |func,*args|
begin
block.call( FunctionProxy.new( @driver, func ),
*args.map{|v| Value.new(self,v)} )
rescue StandardError, Exception => e
@driver.result_error( func,
"#{e.message} (#{e.class})", -1 )
end
end
result = @driver.create_function( @handle, name, arity, text_rep, nil,
callback, nil, nil )
Error.check( result, self )
self
end
# Creates a new aggregate function for use in SQL statements. Aggregate
# functions are functions that apply over every row in the result set,
# instead of over just a single row. (A very common aggregate function
# is the "count" function, for determining the number of rows that match
# a query.)
#
# The new function will be added as +name+, with the given +arity+. (For
# variable arity functions, use -1 for the arity.)
#
# The +step+ parameter must be a proc object that accepts as its first
# parameter a FunctionProxy instance (representing the function
# invocation), with any subsequent parameters (up to the function's arity).
# The +step+ callback will be invoked once for each row of the result set.
#
# The +finalize+ parameter must be a +proc+ object that accepts only a
# single parameter, the FunctionProxy instance representing the current
# function invocation. It should invoke FunctionProxy#set_result to
# store the result of the function.
#
# Example:
#
# db.create_aggregate( "lengths", 1 ) do
# step do |func, value|
# func[ :total ] ||= 0
# func[ :total ] += ( value ? value.length : 0 )
# end
#
# finalize do |func|
# func.set_result( func[ :total ] || 0 )
# end
# end
#
# puts db.get_first_value( "select lengths(name) from table" )
#
# See also #create_aggregate_handler for a more object-oriented approach to
# aggregate functions.
def create_aggregate( name, arity, step=nil, finalize=nil,
text_rep=Constants::TextRep::ANY, &block )
# begin
if block
proxy = AggregateDefinitionProxy.new
proxy.instance_eval(&block)
step ||= proxy.step_callback
finalize ||= proxy.finalize_callback
end
step_callback = proc do |func,*args|
ctx = @driver.aggregate_context( func )
unless ctx[:__error]
begin
step.call( FunctionProxy.new( @driver, func, ctx ),
*args.map{|v| Value.new(self,v)} )
rescue Exception => e
ctx[:__error] = e
end
end
end
finalize_callback = proc do |func|
ctx = @driver.aggregate_context( func )
unless ctx[:__error]
begin
finalize.call( FunctionProxy.new( @driver, func, ctx ) )
rescue Exception => e
@driver.result_error( func,
"#{e.message} (#{e.class})", -1 )
end
else
e = ctx[:__error]
@driver.result_error( func,
"#{e.message} (#{e.class})", -1 )
end
end
result = @driver.create_function( @handle, name, arity, text_rep, nil,
nil, step_callback, finalize_callback )
Error.check( result, self )
self
end
# This is another approach to creating an aggregate function (see
# #create_aggregate). Instead of explicitly specifying the name,
# callbacks, arity, and type, you specify a factory object
# (the "handler") that knows how to obtain all of that information. The
# handler should respond to the following messages:
#
# +arity+:: corresponds to the +arity+ parameter of #create_aggregate. This
# message is optional, and if the handler does not respond to it,
# the function will have an arity of -1.
# +name+:: this is the name of the function. The handler _must_ implement
# this message.
# +new+:: this must be implemented by the handler. It should return a new
# instance of the object that will handle a specific invocation of
# the function.
#
# The handler instance (the object returned by the +new+ message, described
# above), must respond to the following messages:
#
# +step+:: this is the method that will be called for each step of the
# aggregate function's evaluation. It should implement the same
# signature as the +step+ callback for #create_aggregate.
# +finalize+:: this is the method that will be called to finalize the
# aggregate function's evaluation. It should implement the
# same signature as the +finalize+ callback for
# #create_aggregate.
#
# Example:
#
# class LengthsAggregateHandler
# def self.arity; 1; end
#
# def initialize
# @total = 0
# end
#
# def step( ctx, name )
# @total += ( name ? name.length : 0 )
# end
#
# def finalize( ctx )
# ctx.set_result( @total )
# end
# end
#
# db.create_aggregate_handler( LengthsAggregateHandler )
# puts db.get_first_value( "select lengths(name) from A" )
def create_aggregate_handler( handler )
arity = -1
text_rep = Constants::TextRep::ANY
arity = handler.arity if handler.respond_to?(:arity)
text_rep = handler.text_rep if handler.respond_to?(:text_rep)
name = handler.name
step = proc do |func,*args|
ctx = @driver.aggregate_context( func )
unless ctx[ :__error ]
ctx[ :handler ] ||= handler.new
begin
ctx[ :handler ].step( FunctionProxy.new( @driver, func, ctx ),
*args.map{|v| Value.new(self,v)} )
rescue Exception, StandardError => e
ctx[ :__error ] = e
end
end
end
finalize = proc do |func|
ctx = @driver.aggregate_context( func )
unless ctx[ :__error ]
ctx[ :handler ] ||= handler.new
begin
ctx[ :handler ].finalize( FunctionProxy.new( @driver, func, ctx ) )
rescue Exception => e
ctx[ :__error ] = e
end
end
if ctx[ :__error ]
e = ctx[ :__error ]
@driver.sqlite3_result_error( func, "#{e.message} (#{e.class})", -1 )
end
end
result = @driver.create_function( @handle, name, arity, text_rep, nil,
nil, step, finalize )
Error.check( result, self )
self
end
# Begins a new transaction. Note that nested transactions are not allowed
# by SQLite, so attempting to nest a transaction will result in a runtime
# exception.
#
# The +mode+ parameter may be either <tt>:deferred</tt> (the default),
# <tt>:immediate</tt>, or <tt>:exclusive</tt>.
#
# If a block is given, the database instance is yielded to it, and the
# transaction is committed when the block terminates. If the block
# raises an exception, a rollback will be performed instead. Note that if
# a block is given, #commit and #rollback should never be called
# explicitly or you'll get an error when the block terminates.
#
# If a block is not given, it is the caller's responsibility to end the
# transaction explicitly, either by calling #commit, or by calling
# #rollback.
def transaction( mode = :deferred )
execute "begin #{mode.to_s} transaction"
@transaction_active = true
if block_given?
abort = false
begin
yield self
rescue ::Object
abort = true
raise
ensure
abort and rollback or commit
end
end
true
end
# Commits the current transaction. If there is no current transaction,
# this will cause an error to be raised. This returns +true+, in order
# to allow it to be used in idioms like
# <tt>abort? and rollback or commit</tt>.
def commit
execute "commit transaction"
@transaction_active = false
true
end
# Rolls the current transaction back. If there is no current transaction,
# this will cause an error to be raised. This returns +true+, in order
# to allow it to be used in idioms like
# <tt>abort? and rollback or commit</tt>.
def rollback
execute "rollback transaction"
@transaction_active = false
true
end
# Returns +true+ if there is a transaction active, and +false+ otherwise.
def transaction_active?
@transaction_active
end
# Loads the corresponding driver, or if it is nil, attempts to locate a
# suitable driver.
def load_driver( driver )
case driver
when Class
# do nothing--use what was given
when Symbol, String
require "sqlite3/driver/#{driver.to_s.downcase}/driver"
driver = SQLite3::Driver.const_get( driver )::Driver
else
[ "Native", "DL" ].each do |d|
begin
require "sqlite3/driver/#{d.downcase}/driver"
driver = SQLite3::Driver.const_get( d )::Driver
break
rescue SyntaxError
raise
rescue ScriptError, Exception, NameError
end
end
raise "no driver for sqlite3 found" unless driver
end
@driver = driver.new
end
private :load_driver
# A helper class for dealing with custom functions (see #create_function,
# #create_aggregate, and #create_aggregate_handler). It encapsulates the
# opaque function object that represents the current invocation. It also
# provides more convenient access to the API functions that operate on
# the function object.
#
# This class will almost _always_ be instantiated indirectly, by working
# with the create methods mentioned above.
class FunctionProxy
# Create a new FunctionProxy that encapsulates the given +func+ object.
# If context is non-nil, the functions context will be set to that. If
# it is non-nil, it must quack like a Hash. If it is nil, then none of
# the context functions will be available.
def initialize( driver, func, context=nil )
@driver = driver
@func = func
@context = context
end
# Calls #set_result to set the result of this function.
def result=( result )
set_result( result )
end
# Set the result of the function to the given value. The function will
# then return this value.
def set_result( result, utf16=false )
@driver.result_text( @func, result, utf16 )
end
# Set the result of the function to the given error message.
# The function will then return that error.
def set_error( error )
@driver.result_error( @func, error.to_s, -1 )
end
# (Only available to aggregate functions.) Returns the number of rows
# that the aggregate has processed so far. This will include the current
# row, and so will always return at least 1.
def count
ensure_aggregate!
@driver.aggregate_count( @func )
end
# Returns the value with the given key from the context. This is only
# available to aggregate functions.
def []( key )
ensure_aggregate!
@context[ key ]
end
# Sets the value with the given key in the context. This is only
# available to aggregate functions.
def []=( key, value )
ensure_aggregate!
@context[ key ] = value
end
# A function for performing a sanity check, to ensure that the function
# being invoked is an aggregate function. This is implied by the
# existence of the context variable.
def ensure_aggregate!
unless @context
raise MisuseException, "function is not an aggregate"
end
end
private :ensure_aggregate!
end
# A proxy used for defining the callbacks to an aggregate function.
class AggregateDefinitionProxy # :nodoc:
attr_reader :step_callback, :finalize_callback
def step( &block )
@step_callback = block
end
def finalize( &block )
@finalize_callback = block
end
end
end
end

View file

@ -0,0 +1,184 @@
#--
# =============================================================================
# Copyright (c) 2004, Jamis Buck (jgb3@email.byu.edu)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * The names of its contributors may not be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# =============================================================================
#++
require 'dl/import'
module SQLite3 ; module Driver; module DL;
module API
extend ::DL::Importable
library_name = case RUBY_PLATFORM.downcase
when /darwin/
"libsqlite3.dylib"
when /linux/, /freebsd|netbsd|openbsd|dragonfly/, /solaris/
"libsqlite3.so"
when /win32/
"sqlite3.dll"
else
abort <<-EOF
== * UNSUPPORTED PLATFORM ======================================================
The platform '#{RUBY_PLATFORM}' is unsupported. Please help the author by
editing the following file to allow your sqlite3 library to be found, and
submitting a patch to jamis_buck@byu.edu. Thanks!
#{__FILE__}
=========================================================================== * ==
EOF
end
if defined? SQLITE3_LIB_PATH
library_name = File.join( SQLITE3_LIB_PATH, library_name )
end
dlload library_name
typealias "db", "void*"
typealias "stmt", "void*"
typealias "value", "void*"
typealias "context", "void*"
# until Ruby/DL supports 64-bit ints, we'll just treat them as 32-bit ints
typealias "int64", "unsigned long"
extern "const char *sqlite3_libversion()"
extern "int sqlite3_open(const char*,db*)"
extern "int sqlite3_open16(const void*,db*)"
extern "int sqlite3_close(db)"
extern "const char* sqlite3_errmsg(db)"
extern "void* sqlite3_errmsg16(db)"
extern "int sqlite3_errcode(db)"
extern "int sqlite3_prepare(db,const char*,int,stmt*,const char**)"
extern "int sqlite3_prepare16(db,const void*,int,stmt*,const void**)"
extern "int sqlite3_finalize(stmt)"
extern "int sqlite3_reset(stmt)"
extern "int sqlite3_step(stmt)"
extern "int64 sqlite3_last_insert_rowid(db)"
extern "int sqlite3_changes(db)"
extern "int sqlite3_total_changes(db)"
extern "void sqlite3_interrupt(db)"
extern "ibool sqlite3_complete(const char*)"
extern "ibool sqlite3_complete16(const void*)"
extern "int sqlite3_busy_handler(db,void*,void*)"
extern "int sqlite3_busy_timeout(db,int)"
extern "int sqlite3_set_authorizer(db,void*,void*)"
extern "void* sqlite3_trace(db,void*,void*)"
extern "int sqlite3_bind_blob(stmt,int,const void*,int,void*)"
extern "int sqlite3_bind_double(stmt,int,double)"
extern "int sqlite3_bind_int(stmt,int,int)"
extern "int sqlite3_bind_int64(stmt,int,int64)"
extern "int sqlite3_bind_null(stmt,int)"
extern "int sqlite3_bind_text(stmt,int,const char*,int,void*)"
extern "int sqlite3_bind_text16(stmt,int,const void*,int,void*)"
#extern "int sqlite3_bind_value(stmt,int,value)"
extern "int sqlite3_bind_parameter_count(stmt)"
extern "const char* sqlite3_bind_parameter_name(stmt,int)"
extern "int sqlite3_bind_parameter_index(stmt,const char*)"
extern "int sqlite3_column_count(stmt)"
extern "int sqlite3_data_count(stmt)"
extern "const void *sqlite3_column_blob(stmt,int)"
extern "int sqlite3_column_bytes(stmt,int)"
extern "int sqlite3_column_bytes16(stmt,int)"
extern "const char *sqlite3_column_decltype(stmt,int)"
extern "void *sqlite3_column_decltype16(stmt,int)"
extern "double sqlite3_column_double(stmt,int)"
extern "int sqlite3_column_int(stmt,int)"
extern "int64 sqlite3_column_int64(stmt,int)"
extern "const char *sqlite3_column_name(stmt,int)"
extern "const void *sqlite3_column_name16(stmt,int)"
extern "const char *sqlite3_column_text(stmt,int)"
extern "const void *sqlite3_column_text16(stmt,int)"
extern "int sqlite3_column_type(stmt,int)"
extern "int sqlite3_create_function(db,const char*,int,int,void*,void*,void*,void*)"
extern "int sqlite3_create_function16(db,const void*,int,int,void*,void*,void*,void*)"
extern "int sqlite3_aggregate_count(context)"
extern "const void *sqlite3_value_blob(value)"
extern "int sqlite3_value_bytes(value)"
extern "int sqlite3_value_bytes16(value)"
extern "double sqlite3_value_double(value)"
extern "int sqlite3_value_int(value)"
extern "int64 sqlite3_value_int64(value)"
extern "const char* sqlite3_value_text(value)"
extern "const void* sqlite3_value_text16(value)"
extern "const void* sqlite3_value_text16le(value)"
extern "const void* sqlite3_value_text16be(value)"
extern "int sqlite3_value_type(value)"
extern "void *sqlite3_aggregate_context(context,int)"
extern "void *sqlite3_user_data(context)"
extern "void *sqlite3_get_auxdata(context,int)"
extern "void sqlite3_set_auxdata(context,int,void*,void*)"
extern "void sqlite3_result_blob(context,const void*,int,void*)"
extern "void sqlite3_result_double(context,double)"
extern "void sqlite3_result_error(context,const char*,int)"
extern "void sqlite3_result_error16(context,const void*,int)"
extern "void sqlite3_result_int(context,int)"
extern "void sqlite3_result_int64(context,int64)"
extern "void sqlite3_result_null(context)"
extern "void sqlite3_result_text(context,const char*,int,void*)"
extern "void sqlite3_result_text16(context,const void*,int,void*)"
extern "void sqlite3_result_text16le(context,const void*,int,void*)"
extern "void sqlite3_result_text16be(context,const void*,int,void*)"
extern "void sqlite3_result_value(context,value)"
extern "int sqlite3_create_collation(db,const char*,int,void*,void*)"
extern "int sqlite3_create_collation16(db,const char*,int,void*,void*)"
extern "int sqlite3_collation_needed(db,void*,void*)"
extern "int sqlite3_collation_needed16(db,void*,void*)"
# ==== CRYPTO (NOT IN PUBLIC RELEASE) ====
if defined?( CRYPTO_API ) && CRYPTO_API
extern "int sqlite3_key(db,void*,int)"
extern "int sqlite3_rekey(db,void*,int)"
end
# ==== EXPERIMENTAL ====
if defined?( EXPERIMENTAL_API ) && EXPERIMENTAL_API
extern "int sqlite3_progress_handler(db,int,void*,void*)"
extern "int sqlite3_commit_hook(db,void*,void*)"
end
end
end ; end ; end

View file

@ -0,0 +1,338 @@
#--
# =============================================================================
# Copyright (c) 2004, Jamis Buck (jgb3@email.byu.edu)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * The names of its contributors may not be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# =============================================================================
#++
require 'sqlite3/driver/dl/api'
warn "The DL driver for sqlite3-ruby is deprecated and will be removed"
warn "in a future release. Please update your installation to use the"
warn "Native driver."
module Kernel
# Allows arbitrary objects to be passed as a pointer to functions.
# (Probably not very GC safe, but by encapsulating it like this we
# can change the implementation later.)
def to_ptr
ptr = DL.malloc(DL.sizeof("L"))
ptr.set_object self
ptr
end
end
class DL::PtrData
# The inverse of the Kernel#to_ptr operation.
def to_object
n = to_s(4).unpack("L").first
return nil if n < 1
ObjectSpace._id2ref(n) rescue self.to_s
end
def set_object(obj)
self[0] = [obj.object_id].pack("L")
end
end
module SQLite3 ; module Driver ; module DL
class Driver
STATIC = ::DL::PtrData.new(0)
TRANSIENT = ::DL::PtrData.new(-1)
def open( filename, utf16=false )
handle = ::DL::PtrData.new(0)
result = API.send( ( utf16 ? :sqlite3_open16 : :sqlite3_open ),
filename+"\0", handle.ref )
[ result, handle ]
end
def errmsg( db, utf16=false )
if utf16
msg = API.sqlite3_errmsg16( db )
msg.free = nil
msg.to_s(utf16_length(msg))
else
API.sqlite3_errmsg( db )
end
end
def prepare( db, sql, utf16=false )
handle = ::DL::PtrData.new(0)
remainder = ::DL::PtrData.new(0)
result = API.send( ( utf16 ? :sqlite3_prepare16 : :sqlite3_prepare ),
db, sql+"\0", sql.length, handle.ref, remainder.ref )
args = utf16 ? [ utf16_length(remainder) ] : []
remainder = remainder.to_s( *args )
[ result, handle, remainder ]
end
def complete?( sql, utf16=false )
API.send( utf16 ? :sqlite3_complete16 : :sqlite3_complete, sql+"\0" )
end
def value_blob( value )
blob = API.sqlite3_value_blob( value )
blob.free = nil
blob.to_s( API.sqlite3_value_bytes( value ) )
end
def value_text( value, utf16=false )
method = case utf16
when nil, false then :sqlite3_value_text
when :le then :sqlite3_value_text16le
when :be then :sqlite3_value_text16be
else :sqlite3_value_text16
end
result = API.send( method, value )
if utf16
result.free = nil
size = API.sqlite3_value_bytes( value )
result = result.to_s( size )
end
result
end
def column_blob( stmt, column )
blob = API.sqlite3_column_blob( stmt, column )
blob.free = nil
blob.to_s( API.sqlite3_column_bytes( stmt, column ) )
end
def result_text( func, text, utf16=false )
method = case utf16
when false, nil then :sqlite3_result_text
when :le then :sqlite3_result_text16le
when :be then :sqlite3_result_text16be
else :sqlite3_result_text16
end
s = text.to_s
API.send( method, func, s, s.length, TRANSIENT )
end
def busy_handler( db, data=nil, &block )
@busy_handler = block
unless @busy_handler_callback
@busy_handler_callback = ::DL.callback( "IPI" ) do |cookie, timeout|
@busy_handler.call( cookie, timeout ) || 0
end
end
API.sqlite3_busy_handler( db, block&&@busy_handler_callback, data )
end
def set_authorizer( db, data=nil, &block )
@authorizer_handler = block
unless @authorizer_handler_callback
@authorizer_handler_callback = ::DL.callback( "IPIPPPP"
) do |cookie,mode,a,b,c,d|
@authorizer_handler.call( cookie, mode,
a&&a.to_s, b&&b.to_s, c&&c.to_s, d&&d.to_s ) || 0
end
end
API.sqlite3_set_authorizer( db, block&&@authorizer_handler_callback,
data )
end
def trace( db, data=nil, &block )
@trace_handler = block
unless @trace_handler_callback
@trace_handler_callback = ::DL.callback( "IPS" ) do |cookie,sql|
@trace_handler.call( cookie ? cookie.to_object : nil, sql ) || 0
end
end
API.sqlite3_trace( db, block&&@trace_handler_callback, data )
end
def create_function( db, name, args, text, cookie,
func, step, final )
# begin
if @func_handler_callback.nil? && func
@func_handler_callback = ::DL.callback( "0PIP" ) do |context,nargs,args|
args = args.to_s(nargs*4).unpack("L*").map {|i| ::DL::PtrData.new(i)}
data = API.sqlite3_user_data( context ).to_object
data[:func].call( context, *args )
end
end
if @step_handler_callback.nil? && step
@step_handler_callback = ::DL.callback( "0PIP" ) do |context,nargs,args|
args = args.to_s(nargs*4).unpack("L*").map {|i| ::DL::PtrData.new(i)}
data = API.sqlite3_user_data( context ).to_object
data[:step].call( context, *args )
end
end
if @final_handler_callback.nil? && final
@final_handler_callback = ::DL.callback( "0P" ) do |context|
data = API.sqlite3_user_data( context ).to_object
data[:final].call( context )
end
end
data = { :cookie => cookie,
:name => name,
:func => func,
:step => step,
:final => final }
API.sqlite3_create_function( db, name, args, text, data,
( func ? @func_handler_callback : nil ),
( step ? @step_handler_callback : nil ),
( final ? @final_handler_callback : nil ) )
end
def aggregate_context( context )
ptr = API.sqlite3_aggregate_context( context, 4 )
ptr.free = nil
obj = ( ptr ? ptr.to_object : nil )
if obj.nil?
obj = Hash.new
ptr.set_object obj
end
obj
end
def bind_blob( stmt, index, value )
s = value.to_s
API.sqlite3_bind_blob( stmt, index, s, s.length, TRANSIENT )
end
def bind_text( stmt, index, value, utf16=false )
s = value.to_s
method = ( utf16 ? :sqlite3_bind_text16 : :sqlite3_bind_text )
API.send( method, stmt, index, s, s.length, TRANSIENT )
end
def column_text( stmt, column )
result = API.sqlite3_column_text( stmt, column )
result ? result.to_s : nil
end
def column_name( stmt, column )
result = API.sqlite3_column_name( stmt, column )
result ? result.to_s : nil
end
def column_decltype( stmt, column )
result = API.sqlite3_column_decltype( stmt, column )
result ? result.to_s : nil
end
def self.api_delegate( name )
define_method( name ) { |*args| API.send( "sqlite3_#{name}", *args ) }
end
api_delegate :aggregate_count
api_delegate :bind_double
api_delegate :bind_int
api_delegate :bind_null
api_delegate :bind_parameter_index
api_delegate :bind_parameter_name
api_delegate :busy_timeout
api_delegate :changes
api_delegate :close
api_delegate :column_bytes
api_delegate :column_bytes16
api_delegate :column_count
api_delegate :column_double
api_delegate :column_int
api_delegate :column_int64
api_delegate :column_type
api_delegate :data_count
api_delegate :errcode
api_delegate :finalize
api_delegate :interrupt
api_delegate :last_insert_rowid
api_delegate :libversion
api_delegate :reset
api_delegate :result_error
api_delegate :step
api_delegate :total_changes
api_delegate :value_bytes
api_delegate :value_bytes16
api_delegate :value_double
api_delegate :value_int
api_delegate :value_int64
api_delegate :value_type
# ==== EXPERIMENTAL ====
if defined?( EXPERIMENTAL_API ) && EXPERIMENTAL_API
def progress_handler( db, n, data=nil, &block )
@progress_handler = block
unless @progress_handler_callback
@progress_handler_callback = ::DL.callback( "IP" ) do |cookie|
@progress_handler.call( cookie )
end
end
API.sqlite3_progress_handler( db, n, block&&@progress_handler_callback,
data )
end
def commit_hook( db, data=nil, &block )
@commit_hook_handler = block
unless @commit_hook_handler_callback
@commit_hook_handler_callback = ::DL.callback( "IP" ) do |cookie|
@commit_hook_handler.call( cookie )
end
end
API.sqlite3_commit_hook( db, block&&@commit_hook_handler_callback,
data )
end
end
private
def utf16_length(ptr)
len = 0
loop do
break if ptr[len,1] == "\0"
len += 2
end
len
end
end
end ; end ; end

View file

@ -0,0 +1,243 @@
#--
# =============================================================================
# Copyright (c) 2004, Jamis Buck (jgb3@email.byu.edu)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * The names of its contributors may not be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# =============================================================================
#++
require 'sqlite3_api'
module SQLite3 ; module Driver ; module Native
class Driver
def initialize
@callback_data = Hash.new
@authorizer = Hash.new
@busy_handler = Hash.new
@trace = Hash.new
end
def complete?( sql, utf16=false )
API.send( utf16 ? :sqlite3_complete16 : :sqlite3_complete, sql ) != 0
end
def busy_handler( db, data=nil, &block )
if block
cb = API::CallbackData.new
cb.proc = block
cb.data = data
result = API.sqlite3_busy_handler( db, API::Sqlite3_ruby_busy_handler, cb )
# Reference the Callback object so that
# it is not deleted by the GC
@busy_handler[db] = cb
else
# Unreference the callback *after* having removed it
# from sqlite
result = API.sqlite3_busy_handler( db, nil, nil )
@busy_handler.delete(db)
end
result
end
def set_authorizer( db, data=nil, &block )
if block
cb = API::CallbackData.new
cb.proc = block
cb.data = data
result = API.sqlite3_set_authorizer( db, API::Sqlite3_ruby_authorizer, cb )
@authorizer[db] = cb # see comments in busy_handler
else
result = API.sqlite3_set_authorizer( db, nil, nil )
@authorizer.delete(db) # see comments in busy_handler
end
result
end
def trace( db, data=nil, &block )
if block
cb = API::CallbackData.new
cb.proc = block
cb.data = data
result = API.sqlite3_trace( db, API::Sqlite3_ruby_trace, cb )
@trace[db] = cb # see comments in busy_handler
else
result = API.sqlite3_trace( db, nil, nil )
@trace.delete(db) # see comments in busy_handler
end
result
end
def open( filename, utf16=false )
API.send( utf16 ? :sqlite3_open16 : :sqlite3_open, filename )
end
def errmsg( db, utf16=false )
API.send( utf16 ? :sqlite3_errmsg16 : :sqlite3_errmsg, db )
end
def prepare( db, sql, utf16=false )
API.send( ( utf16 ? :sqlite3_prepare16 : :sqlite3_prepare ),
db, sql )
end
def bind_text( stmt, index, value, utf16=false )
API.send( ( utf16 ? :sqlite3_bind_text16 : :sqlite3_bind_text ),
stmt, index, value.to_s )
end
def column_name( stmt, index, utf16=false )
API.send( ( utf16 ? :sqlite3_column_name16 : :sqlite3_column_name ),
stmt, index )
end
def column_decltype( stmt, index, utf16=false )
API.send(
( utf16 ? :sqlite3_column_decltype16 : :sqlite3_column_decltype ),
stmt, index )
end
def column_text( stmt, index, utf16=false )
API.send( ( utf16 ? :sqlite3_column_text16 : :sqlite3_column_text ),
stmt, index )
end
def create_function( db, name, args, text, cookie, func, step, final )
if func || ( step && final )
cb = API::CallbackData.new
cb.proc = cb.proc2 = nil
cb.data = cookie
end
if func
cb.proc = func
func = API::Sqlite3_ruby_function_step
step = final = nil
elsif step && final
cb.proc = step
cb.proc2 = final
func = nil
step = API::Sqlite3_ruby_function_step
final = API::Sqlite3_ruby_function_final
end
result = API.sqlite3_create_function( db, name, args, text, cb, func, step, final )
# see comments in busy_handler
if cb
@callback_data[ name ] = cb
else
@callback_data.delete( name )
end
return result
end
def value_text( value, utf16=false )
method = case utf16
when nil, false then :sqlite3_value_text
when :le then :sqlite3_value_text16le
when :be then :sqlite3_value_text16be
else :sqlite3_value_text16
end
API.send( method, value )
end
def result_text( context, result, utf16=false )
method = case utf16
when nil, false then :sqlite3_result_text
when :le then :sqlite3_result_text16le
when :be then :sqlite3_result_text16be
else :sqlite3_result_text16
end
API.send( method, context, result.to_s )
end
def result_error( context, value, utf16=false )
API.send( ( utf16 ? :sqlite3_result_error16 : :sqlite3_result_error ),
context, value )
end
def self.api_delegate( name )
define_method( name ) { |*args| API.send( "sqlite3_#{name}", *args ) }
end
api_delegate :libversion
api_delegate :close
api_delegate :last_insert_rowid
api_delegate :changes
api_delegate :total_changes
api_delegate :interrupt
api_delegate :busy_timeout
api_delegate :errcode
api_delegate :bind_blob
api_delegate :bind_double
api_delegate :bind_int
api_delegate :bind_int64
api_delegate :bind_null
api_delegate :bind_parameter_count
api_delegate :bind_parameter_name
api_delegate :bind_parameter_index
api_delegate :column_count
api_delegate :step
api_delegate :data_count
api_delegate :column_blob
api_delegate :column_bytes
api_delegate :column_bytes16
api_delegate :column_double
api_delegate :column_int
api_delegate :column_int64
api_delegate :column_type
api_delegate :finalize
api_delegate :reset
api_delegate :aggregate_count
api_delegate :value_blob
api_delegate :value_bytes
api_delegate :value_bytes16
api_delegate :value_double
api_delegate :value_int
api_delegate :value_int64
api_delegate :value_type
api_delegate :result_blob
api_delegate :result_double
api_delegate :result_int
api_delegate :result_int64
api_delegate :result_null
api_delegate :result_value
api_delegate :aggregate_context
end
end ; end ; end

View file

@ -0,0 +1,100 @@
#--
# =============================================================================
# Copyright (c) 2004, Jamis Buck (jgb3@email.byu.edu)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * The names of its contributors may not be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# =============================================================================
#++
require 'sqlite3/constants'
module SQLite3
class Exception < ::Exception
@code = 0
# The numeric error code that this exception represents.
def self.code
@code
end
# A convenience for accessing the error code for this exception.
def code
self.class.code
end
end
class SQLException < Exception; end
class InternalException < Exception; end
class PermissionException < Exception; end
class AbortException < Exception; end
class BusyException < Exception; end
class LockedException < Exception; end
class MemoryException < Exception; end
class ReadOnlyException < Exception; end
class InterruptException < Exception; end
class IOException < Exception; end
class CorruptException < Exception; end
class NotFoundException < Exception; end
class FullException < Exception; end
class CantOpenException < Exception; end
class ProtocolException < Exception; end
class EmptyException < Exception; end
class SchemaChangedException < Exception; end
class TooBigException < Exception; end
class ConstraintException < Exception; end
class MismatchException < Exception; end
class MisuseException < Exception; end
class UnsupportedException < Exception; end
class AuthorizationException < Exception; end
class FormatException < Exception; end
class RangeException < Exception; end
class NotADatabaseException < Exception; end
EXCEPTIONS = [
nil,
SQLException, InternalException, PermissionException,
AbortException, BusyException, LockedException, MemoryException,
ReadOnlyException, InterruptException, IOException, CorruptException,
NotFoundException, FullException, CantOpenException, ProtocolException,
EmptyException, SchemaChangedException, TooBigException,
ConstraintException, MismatchException, MisuseException,
UnsupportedException, AuthorizationException, FormatException,
RangeException, NotADatabaseException
].each_with_index { |e,i| e.instance_variable_set( :@code, i ) if e }
module Error
def check( result, db=nil, msg=nil )
unless result == Constants::ErrorCode::OK
msg = ( msg ? msg + ": " : "" ) + db.errmsg if db
raise(( EXCEPTIONS[result] || SQLite3::Exception ), msg)
end
end
module_function :check
end
end

View file

@ -0,0 +1,254 @@
#--
# =============================================================================
# Copyright (c) 2004, Jamis Buck (jgb3@email.byu.edu)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * The names of its contributors may not be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# =============================================================================
#++
require 'sqlite3/errors'
module SQLite3
# This module is intended for inclusion solely by the Database class. It
# defines convenience methods for the various pragmas supported by SQLite3.
#
# For a detailed description of these pragmas, see the SQLite3 documentation
# at http://sqlite.org/pragma.html.
module Pragmas
# Returns +true+ or +false+ depending on the value of the named pragma.
def get_boolean_pragma( name )
get_first_value( "PRAGMA #{name}" ) != "0"
end
private :get_boolean_pragma
# Sets the given pragma to the given boolean value. The value itself
# may be +true+ or +false+, or any other commonly used string or
# integer that represents truth.
def set_boolean_pragma( name, mode )
case mode
when String
case mode.downcase
when "on", "yes", "true", "y", "t": mode = "'ON'"
when "off", "no", "false", "n", "f": mode = "'OFF'"
else
raise Exception,
"unrecognized pragma parameter #{mode.inspect}"
end
when true, 1
mode = "ON"
when false, 0, nil
mode = "OFF"
else
raise Exception,
"unrecognized pragma parameter #{mode.inspect}"
end
execute( "PRAGMA #{name}=#{mode}" )
end
private :set_boolean_pragma
# Requests the given pragma (and parameters), and if the block is given,
# each row of the result set will be yielded to it. Otherwise, the results
# are returned as an array.
def get_query_pragma( name, *parms, &block ) # :yields: row
if parms.empty?
execute( "PRAGMA #{name}", &block )
else
args = "'" + parms.join("','") + "'"
execute( "PRAGMA #{name}( #{args} )", &block )
end
end
private :get_query_pragma
# Return the value of the given pragma.
def get_enum_pragma( name )
get_first_value( "PRAGMA #{name}" )
end
private :get_enum_pragma
# Set the value of the given pragma to +mode+. The +mode+ parameter must
# conform to one of the values in the given +enum+ array. Each entry in
# the array is another array comprised of elements in the enumeration that
# have duplicate values. See #synchronous, #default_synchronous,
# #temp_store, and #default_temp_store for usage examples.
def set_enum_pragma( name, mode, enums )
match = enums.find { |p| p.find { |i| i.to_s.downcase == mode.to_s.downcase } }
raise Exception,
"unrecognized #{name} #{mode.inspect}" unless match
execute( "PRAGMA #{name}='#{match.first.upcase}'" )
end
private :set_enum_pragma
# Returns the value of the given pragma as an integer.
def get_int_pragma( name )
get_first_value( "PRAGMA #{name}" ).to_i
end
private :get_int_pragma
# Set the value of the given pragma to the integer value of the +value+
# parameter.
def set_int_pragma( name, value )
execute( "PRAGMA #{name}=#{value.to_i}" )
end
private :set_int_pragma
# The enumeration of valid synchronous modes.
SYNCHRONOUS_MODES = [ [ 'full', 2 ], [ 'normal', 1 ], [ 'off', 0 ] ]
# The enumeration of valid temp store modes.
TEMP_STORE_MODES = [ [ 'default', 0 ], [ 'file', 1 ], [ 'memory', 2 ] ]
# Does an integrity check on the database. If the check fails, a
# SQLite3::Exception will be raised. Otherwise it
# returns silently.
def integrity_check
execute( "PRAGMA integrity_check" ) do |row|
raise Exception, row[0] if row[0] != "ok"
end
end
def auto_vacuum
get_boolean_pragma "auto_vacuum"
end
def auto_vacuum=( mode )
set_boolean_pragma "auto_vacuum", mode
end
def schema_cookie
get_int_pragma "schema_cookie"
end
def schema_cookie=( cookie )
set_int_pragma "schema_cookie", cookie
end
def user_cookie
get_int_pragma "user_cookie"
end
def user_cookie=( cookie )
set_int_pragma "user_cookie", cookie
end
def cache_size
get_int_pragma "cache_size"
end
def cache_size=( size )
set_int_pragma "cache_size", size
end
def default_cache_size
get_int_pragma "default_cache_size"
end
def default_cache_size=( size )
set_int_pragma "default_cache_size", size
end
def default_synchronous
get_enum_pragma "default_synchronous"
end
def default_synchronous=( mode )
set_enum_pragma "default_synchronous", mode, SYNCHRONOUS_MODES
end
def synchronous
get_enum_pragma "synchronous"
end
def synchronous=( mode )
set_enum_pragma "synchronous", mode, SYNCHRONOUS_MODES
end
def default_temp_store
get_enum_pragma "default_temp_store"
end
def default_temp_store=( mode )
set_enum_pragma "default_temp_store", mode, TEMP_STORE_MODES
end
def temp_store
get_enum_pragma "temp_store"
end
def temp_store=( mode )
set_enum_pragma "temp_store", mode, TEMP_STORE_MODES
end
def full_column_names
get_boolean_pragma "full_column_names"
end
def full_column_names=( mode )
set_boolean_pragma "full_column_names", mode
end
def parser_trace
get_boolean_pragma "parser_trace"
end
def parser_trace=( mode )
set_boolean_pragma "parser_trace", mode
end
def vdbe_trace
get_boolean_pragma "vdbe_trace"
end
def vdbe_trace=( mode )
set_boolean_pragma "vdbe_trace", mode
end
def database_list( &block ) # :yields: row
get_query_pragma "database_list", &block
end
def foreign_key_list( table, &block ) # :yields: row
get_query_pragma "foreign_key_list", table, &block
end
def index_info( index, &block ) # :yields: row
get_query_pragma "index_info", index, &block
end
def index_list( table, &block ) # :yields: row
get_query_pragma "index_list", table, &block
end
def table_info( table, &block ) # :yields: row
get_query_pragma "table_info", table, &block
end
end
end

View file

@ -0,0 +1,190 @@
#--
# =============================================================================
# Copyright (c) 2004, Jamis Buck (jgb3@email.byu.edu)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * The names of its contributors may not be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# =============================================================================
#++
require 'sqlite3/constants'
require 'sqlite3/errors'
module SQLite3
# The ResultSet object encapsulates the enumerability of a query's output.
# It is a simple cursor over the data that the query returns. It will
# very rarely (if ever) be instantiated directly. Instead, client's should
# obtain a ResultSet instance via Statement#execute.
class ResultSet
include Enumerable
# A trivial module for adding a +types+ accessor to an object.
module TypesContainer
attr_accessor :types
end
# A trivial module for adding a +fields+ accessor to an object.
module FieldsContainer
attr_accessor :fields
end
# Create a new ResultSet attached to the given database, using the
# given sql text.
def initialize( db, stmt )
@db = db
@driver = @db.driver
@stmt = stmt
commence
end
# A convenience method for compiling the virtual machine and stepping
# to the first row of the result set.
def commence
result = @driver.step( @stmt.handle )
check result
@first_row = true
end
private :commence
def check( result )
@eof = ( result == Constants::ErrorCode::DONE )
found = ( result == Constants::ErrorCode::ROW )
Error.check( result, @db ) unless @eof || found
end
private :check
# Reset the cursor, so that a result set which has reached end-of-file
# can be rewound and reiterated.
def reset( *bind_params )
@stmt.must_be_open!
@stmt.reset!(false)
@driver.reset( @stmt.handle )
@stmt.bind_params( *bind_params )
@eof = false
commence
end
# Query whether the cursor has reached the end of the result set or not.
def eof?
@eof
end
# Obtain the next row from the cursor. If there are no more rows to be
# had, this will return +nil+. If type translation is active on the
# corresponding database, the values in the row will be translated
# according to their types.
#
# The returned value will be an array, unless Database#results_as_hash has
# been set to +true+, in which case the returned value will be a hash.
#
# For arrays, the column names are accessible via the +fields+ property,
# and the column types are accessible via the +types+ property.
#
# For hashes, the column names are the keys of the hash, and the column
# types are accessible via the +types+ property.
def next
return nil if @eof
@stmt.must_be_open!
unless @first_row
result = @driver.step( @stmt.handle )
check result
end
@first_row = false
unless @eof
row = []
@driver.data_count( @stmt.handle ).times do |column|
case @driver.column_type( @stmt.handle, column )
when Constants::ColumnType::NULL then
row << nil
when Constants::ColumnType::BLOB then
row << @driver.column_blob( @stmt.handle, column )
else
row << @driver.column_text( @stmt.handle, column )
end
end
if @db.type_translation
row = @stmt.types.zip( row ).map do |type, value|
@db.translator.translate( type, value )
end
end
if @db.results_as_hash
new_row = Hash[ *( @stmt.columns.zip( row ).flatten ) ]
row.each_with_index { |value,idx| new_row[idx] = value }
row = new_row
else
row.extend FieldsContainer unless row.respond_to?(:fields)
row.fields = @stmt.columns
end
row.extend TypesContainer
row.types = @stmt.types
return row
end
nil
end
# Required by the Enumerable mixin. Provides an internal iterator over the
# rows of the result set.
def each
while row=self.next
yield row
end
end
# Closes the statement that spawned this result set.
# <em>Use with caution!</em> Closing a result set will automatically
# close any other result sets that were spawned from the same statement.
def close
@stmt.close
end
# Queries whether the underlying statement has been closed or not.
def closed?
@stmt.closed?
end
# Returns the types of the columns returned by this result set.
def types
@stmt.types
end
# Returns the names of the columns returned by this result set.
def columns
@stmt.columns
end
end
end

View file

@ -0,0 +1,258 @@
#--
# =============================================================================
# Copyright (c) 2004, Jamis Buck (jgb3@email.byu.edu)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * The names of its contributors may not be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# =============================================================================
#++
require 'sqlite3/errors'
require 'sqlite3/resultset'
class String
def to_blob
SQLite3::Blob.new( self )
end
end
module SQLite3
# A class for differentiating between strings and blobs, when binding them
# into statements.
class Blob < String; end
# A statement represents a prepared-but-unexecuted SQL query. It will rarely
# (if ever) be instantiated directly by a client, and is most often obtained
# via the Database#prepare method.
class Statement
# This is any text that followed the first valid SQL statement in the text
# with which the statement was initialized. If there was no trailing text,
# this will be the empty string.
attr_reader :remainder
# The underlying opaque handle used to access the SQLite @driver.
attr_reader :handle
# Create a new statement attached to the given Database instance, and which
# encapsulates the given SQL text. If the text contains more than one
# statement (i.e., separated by semicolons), then the #remainder property
# will be set to the trailing text.
def initialize( db, sql, utf16=false )
@db = db
@driver = @db.driver
@closed = false
@results = @columns = nil
result, @handle, @remainder = @driver.prepare( @db.handle, sql )
Error.check( result, @db )
end
# Closes the statement by finalizing the underlying statement
# handle. The statement must not be used after being closed.
def close
must_be_open!
@closed = true
@driver.finalize( @handle )
end
# Returns true if the underlying statement has been closed.
def closed?
@closed
end
# Binds the given variables to the corresponding placeholders in the SQL
# text.
#
# See Database#execute for a description of the valid placeholder
# syntaxes.
#
# Example:
#
# stmt = db.prepare( "select * from table where a=? and b=?" )
# stmt.bind_params( 15, "hello" )
#
# See also #execute, #bind_param, Statement#bind_param, and
# Statement#bind_params.
def bind_params( *bind_vars )
index = 1
bind_vars.flatten.each do |var|
if Hash === var
var.each { |key, val| bind_param key, val }
else
bind_param index, var
index += 1
end
end
end
# Binds value to the named (or positional) placeholder. If +param+ is a
# Fixnum, it is treated as an index for a positional placeholder.
# Otherwise it is used as the name of the placeholder to bind to.
#
# See also #bind_params.
def bind_param( param, value )
must_be_open!
reset! if active?
if Fixnum === param
case value
when Bignum then
@driver.bind_int64( @handle, param, value )
when Integer then
@driver.bind_int( @handle, param, value )
when Numeric then
@driver.bind_double( @handle, param, value.to_f )
when Blob then
@driver.bind_blob( @handle, param, value )
when nil then
@driver.bind_null( @handle, param )
else
@driver.bind_text( @handle, param, value )
end
else
param = param.to_s
param = ":#{param}" unless param[0] == ?:
index = @driver.bind_parameter_index( @handle, param )
raise Exception, "no such bind parameter '#{param}'" if index == 0
bind_param index, value
end
end
# Execute the statement. This creates a new ResultSet object for the
# statement's virtual machine. If a block was given, the new ResultSet will
# be yielded to it; otherwise, the ResultSet will be returned.
#
# Any parameters will be bound to the statement using #bind_params.
#
# Example:
#
# stmt = db.prepare( "select * from table" )
# stmt.execute do |result|
# ...
# end
#
# See also #bind_params, #execute!.
def execute( *bind_vars )
must_be_open!
reset! if active?
bind_params(*bind_vars) unless bind_vars.empty?
@results = ResultSet.new( @db, self )
if block_given?
yield @results
else
return @results
end
end
# Execute the statement. If no block was given, this returns an array of
# rows returned by executing the statement. Otherwise, each row will be
# yielded to the block.
#
# Any parameters will be bound to the statement using #bind_params.
#
# Example:
#
# stmt = db.prepare( "select * from table" )
# stmt.execute! do |row|
# ...
# end
#
# See also #bind_params, #execute.
def execute!( *bind_vars )
result = execute( *bind_vars )
rows = [] unless block_given?
while row = result.next
if block_given?
yield row
else
rows << row
end
end
rows
end
# Resets the statement. This is typically done internally, though it might
# occassionally be necessary to manually reset the statement.
def reset!(clear_result=true)
@driver.reset(@handle)
@results = nil if clear_result
end
# Returns true if the statement is currently active, meaning it has an
# open result set.
def active?
not @results.nil?
end
# Return an array of the column names for this statement. Note that this
# may execute the statement in order to obtain the metadata; this makes it
# a (potentially) expensive operation.
def columns
get_metadata unless @columns
return @columns
end
# Return an array of the data types for each column in this statement. Note
# that this may execute the statement in order to obtain the metadata; this
# makes it a (potentially) expensive operation.
def types
get_metadata unless @types
return @types
end
# A convenience method for obtaining the metadata about the query. Note
# that this will actually execute the SQL, which means it can be a
# (potentially) expensive operation.
def get_metadata
must_be_open!
@columns = []
@types = []
column_count = @driver.column_count( @handle )
column_count.times do |column|
@columns << @driver.column_name( @handle, column )
@types << @driver.column_decltype( @handle, column )
end
@columns.freeze
@types.freeze
end
private :get_metadata
# Performs a sanity check to ensure that the statement is not
# closed. If it is, an exception is raised.
def must_be_open! # :nodoc:
if @closed
raise SQLite3::Exception, "cannot use a closed statement"
end
end
end
end

View file

@ -0,0 +1,136 @@
#--
# =============================================================================
# Copyright (c) 2004, Jamis Buck (jgb3@email.byu.edu)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * The names of its contributors may not be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# =============================================================================
#++
require 'time'
module SQLite3
# The Translator class encapsulates the logic and callbacks necessary for
# converting string data to a value of some specified type. Every Database
# instance may have a Translator instance, in order to assist in type
# translation (Database#type_translation).
#
# Further, applications may define their own custom type translation logic
# by registering translator blocks with the corresponding database's
# translator instance (Database#translator).
class Translator
# Create a new Translator instance. It will be preinitialized with default
# translators for most SQL data types.
def initialize
@translators = Hash.new( proc { |type,value| value } )
register_default_translators
end
# Add a new translator block, which will be invoked to process type
# translations to the given type. The type should be an SQL datatype, and
# may include parentheses (i.e., "VARCHAR(30)"). However, any parenthetical
# information is stripped off and discarded, so type translation decisions
# are made solely on the "base" type name.
#
# The translator block itself should accept two parameters, "type" and
# "value". In this case, the "type" is the full type name (including
# parentheses), so the block itself may include logic for changing how a
# type is translated based on the additional data. The "value" parameter
# is the (string) data to convert.
#
# The block should return the translated value.
def add_translator( type, &block ) # :yields: type, value
@translators[ type_name( type ) ] = block
end
# Translate the given string value to a value of the given type. In the
# absense of an installed translator block for the given type, the value
# itself is always returned. Further, +nil+ values are never translated,
# and are always passed straight through regardless of the type parameter.
def translate( type, value )
unless value.nil?
@translators[ type_name( type ) ].call( type, value )
end
end
# A convenience method for working with type names. This returns the "base"
# type name, without any parenthetical data.
def type_name( type )
return "" if type.nil?
type = $1 if type =~ /^(.*?)\(/
type.upcase
end
private :type_name
# Register the default translators for the current Translator instance.
# This includes translators for most major SQL data types.
def register_default_translators
[ "date",
"datetime",
"time" ].each { |type| add_translator( type ) { |t,v| Time.parse( v ) } }
[ "decimal",
"float",
"numeric",
"double",
"real",
"dec",
"fixed" ].each { |type| add_translator( type ) { |t,v| v.to_f } }
[ "integer",
"smallint",
"mediumint",
"int",
"bigint" ].each { |type| add_translator( type ) { |t,v| v.to_i } }
[ "bit",
"bool",
"boolean" ].each do |type|
add_translator( type ) do |t,v|
!( v.strip.gsub(/00+/,"0") == "0" ||
v.downcase == "false" ||
v.downcase == "f" ||
v.downcase == "no" ||
v.downcase == "n" )
end
end
add_translator( "timestamp" ) { |type, value| Time.at( value.to_i ) }
add_translator( "tinyint" ) do |type, value|
if type =~ /\(\s*1\s*\)/
value.to_i == 1
else
value.to_i
end
end
end
private :register_default_translators
end
end

View file

@ -0,0 +1,89 @@
#--
# =============================================================================
# Copyright (c) 2004, Jamis Buck (jgb3@email.byu.edu)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * The names of its contributors may not be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# =============================================================================
#++
require 'sqlite3/constants'
module SQLite3
class Value
attr_reader :handle
def initialize( db, handle )
@driver = db.driver
@handle = handle
end
def null?
type == :null
end
def to_blob
@driver.value_blob( @handle )
end
def length( utf16=false )
if utf16
@driver.value_bytes16( @handle )
else
@driver.value_bytes( @handle )
end
end
def to_f
@driver.value_double( @handle )
end
def to_i
@driver.value_int( @handle )
end
def to_int64
@driver.value_int64( @handle )
end
def to_s( utf16=false )
@driver.value_text( @handle, utf16 )
end
def type
case @driver.value_type( @handle )
when Constants::ColumnType::INTEGER then :int
when Constants::ColumnType::FLOAT then :float
when Constants::ColumnType::TEXT then :text
when Constants::ColumnType::BLOB then :blob
when Constants::ColumnType::NULL then :null
end
end
end
end

View file

@ -0,0 +1,45 @@
#--
# =============================================================================
# Copyright (c) 2004, Jamis Buck (jgb3@email.byu.edu)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * The names of its contributors may not be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# =============================================================================
#++
module SQLite3
module Version
MAJOR = 1
MINOR = 2
TINY = 0
STRING = [ MAJOR, MINOR, TINY ].join( "." )
end
end