tiny_tds 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- data/CHANGELOG +3 -0
- data/MIT-LICENSE +22 -0
- data/README.rdoc +181 -0
- data/ext/tiny_tds/client.c +225 -0
- data/ext/tiny_tds/client.h +19 -0
- data/ext/tiny_tds/extconf.rb +75 -0
- data/ext/tiny_tds/result.c +390 -0
- data/ext/tiny_tds/result.h +29 -0
- data/ext/tiny_tds/tiny_tds_ext.c +12 -0
- data/ext/tiny_tds/tiny_tds_ext.h +17 -0
- data/lib/tiny_tds.rb +19 -0
- data/lib/tiny_tds/client.rb +77 -0
- data/lib/tiny_tds/error.rb +29 -0
- data/lib/tiny_tds/result.rb +8 -0
- metadata +81 -0
data/CHANGELOG
ADDED
data/MIT-LICENSE
ADDED
@@ -0,0 +1,22 @@
|
|
1
|
+
Copyright (c) 2010 Ken Collins, <ken@metaskills.net>
|
2
|
+
|
3
|
+
Permission is hereby granted, free of charge, to any person
|
4
|
+
obtaining a copy of this software and associated documentation
|
5
|
+
files (the "Software"), to deal in the Software without
|
6
|
+
restriction, including without limitation the rights to use,
|
7
|
+
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
8
|
+
copies of the Software, and to permit persons to whom the
|
9
|
+
Software is furnished to do so, subject to the following
|
10
|
+
conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be
|
13
|
+
included in all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
16
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
17
|
+
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
18
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
19
|
+
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
20
|
+
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
21
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
22
|
+
OTHER DEALINGS IN THE SOFTWARE.
|
data/README.rdoc
ADDED
@@ -0,0 +1,181 @@
|
|
1
|
+
|
2
|
+
= TinyTds - A modern, simple and fast FreeTDS library for Ruby using DB-Library.
|
3
|
+
|
4
|
+
The TinyTds gem is meant to serve the extremely common use-case of connecting, querying and iterating over results to Microsoft SQL Server databases from ruby. Even though it uses FreeTDS's DB-Library, it is NOT meant to serve as direct 1:1 mapping of that complex C API.
|
5
|
+
|
6
|
+
The benefits are speed, automatic casting to ruby primitives, and proper encoding support. It converts all SQL Server datatypes to native ruby objects supporting :utc or :local time zones for time-like types. To date it is the only ruby client library that allows client encoding options, defaulting to UTF-8, while connecting to SQL Server. It also properly encodes all string and binary data. The motivation for TinyTds is to become the de-facto low level connection mode for the SQL Server adapter for ActiveRecord. For further details see the special thanks section at the bottom
|
7
|
+
|
8
|
+
The API is simple and consists of these classes:
|
9
|
+
|
10
|
+
* TinyTds::Client - Your connection to the database.
|
11
|
+
* TinyTds::Result - Returned from issuing an #execute on the connection. It includes Enumerable.
|
12
|
+
* TinyTds::Error - A wrapper for all exceptions.
|
13
|
+
|
14
|
+
|
15
|
+
|
16
|
+
== Install
|
17
|
+
|
18
|
+
Installing with rubygems should just work. TinyTds is tested on ruby version 1.8.6, 1.8.7, 1.9.1, 1.9.2 as well as REE.
|
19
|
+
|
20
|
+
$ gem install tiny_tds
|
21
|
+
|
22
|
+
Although we search for FreeTDS's libraries and headers, you may have to specify include and lib directories using "--with-freetds-include=/some/local/include/freetds" and "--with-freetds-lib=/some/local/lib"
|
23
|
+
|
24
|
+
|
25
|
+
|
26
|
+
== FreeTDS Compatibility
|
27
|
+
|
28
|
+
TinyTds is developed primarily for FreeTDS 0.82 and tested with SQL Server 2000, 2005, and 2008 using TDS Version 8.0. We utilize FreeTDS's db-lib client library. We compile against sybdb.h and define MSDBLIB which means that our client enables Microsoft behavior in the db-lib API where it diverges from Sybase's. You do NOT need to compile FreeTDS with the "--enable-msdblib" option for our client to work properly. However, please make sure to compile FreeTDS with libiconv support for encodings to work at their best. Run "tsql -C" in your console and check for "iconv library: yes".
|
29
|
+
|
30
|
+
|
31
|
+
|
32
|
+
== Data Types
|
33
|
+
|
34
|
+
Our goal is to support every SQL Server data type and covert it to a logical ruby object. When dates or times are returned, they are instantiated to either :utc or :local time depending on the query options. Under ruby 1.9, all strings are encoded to the connection's encoding and all binary data types are associated to ruby's ASCII-8BIT/BINARY encoding.
|
35
|
+
|
36
|
+
Below is a list of the data types we plan to support using future versions of FreeTDS. They are associated with SQL Server 2008. All unsupported data types are returned as properly encoded strings.
|
37
|
+
|
38
|
+
* [date]
|
39
|
+
* [datetime2]
|
40
|
+
* [datetimeoffset]
|
41
|
+
* [time]
|
42
|
+
|
43
|
+
|
44
|
+
|
45
|
+
== TinyTds::Client Usage
|
46
|
+
|
47
|
+
Connect to a database.
|
48
|
+
|
49
|
+
client = TinyTds::Client.new(:user => 'sa', :password => 'secret', :dataserver => 'mytds_box')
|
50
|
+
|
51
|
+
Creating a new client takes a hash of options. For valid iconv encoding options, see the output of "iconv -l". Only a few have been tested and highly recommended to leave blank for the UTF-8 default.
|
52
|
+
|
53
|
+
* :username - The database server user.
|
54
|
+
* :password - The user password.
|
55
|
+
* :dataserver - The name for your server as defined in freetds.conf.
|
56
|
+
* :database - The default database to use.
|
57
|
+
* :appname - Short string seen in SQL Servers process/activity window.
|
58
|
+
* :tds_version - TDS version. Defaults to 80, not recommended to change.
|
59
|
+
* :login_timeout - Seconds to wait for login. Default to 60 seconds.
|
60
|
+
* :timeout - Seconds to wait for a response to a SQL command. Default 5 seconds.
|
61
|
+
* :encoding - Any valid iconv value like CP1251 or ISO-8859-1. Default UTF-8.
|
62
|
+
|
63
|
+
Close and free a clients connection.
|
64
|
+
|
65
|
+
client.close
|
66
|
+
client.closed? # => true
|
67
|
+
|
68
|
+
Escape strings.
|
69
|
+
|
70
|
+
client.escape("How's It Going'") # => "How''s It Going''"
|
71
|
+
|
72
|
+
Send a SQL string to the database and return a TinyTds::Result object.
|
73
|
+
|
74
|
+
result = client.execute("SELECT * FROM [datatypes]")
|
75
|
+
|
76
|
+
|
77
|
+
|
78
|
+
== TinyTds::Result Usage
|
79
|
+
|
80
|
+
A result object is returned by the client's execute command. It is important that you either return the data from the query, most likely with the #each method, or that you cancel the results before asking the client to execute another SQL batch. Failing to do so will yield an error.
|
81
|
+
|
82
|
+
Calling #each on the result will lazily load each row from the database.
|
83
|
+
|
84
|
+
result.each do |row|
|
85
|
+
# By default each row is a hash.
|
86
|
+
# The keys are the fields, as you'd expect.
|
87
|
+
# The values are pre-built ruby primitives mapped from their corresponding types.
|
88
|
+
# Here's an leemer: http://is.gd/g61xo
|
89
|
+
end
|
90
|
+
|
91
|
+
Once a result returns its rows, you can access the fields. Returns nil if the data has not yet been loaded or there are no rows returned.
|
92
|
+
|
93
|
+
result.fields # => [ ... ]
|
94
|
+
|
95
|
+
You can cancel a result object's data from being loading by the server.
|
96
|
+
|
97
|
+
result = client.execute("SELECT * FROM [super_big_table]")
|
98
|
+
result.cancel
|
99
|
+
|
100
|
+
If the SQL executed by the client returns affected rows, you can easily find out how many.
|
101
|
+
|
102
|
+
result.each
|
103
|
+
result.affected_rows # => 24
|
104
|
+
|
105
|
+
This pattern is so common for UPDATE and DELETE statements that the #do method cancels any need for loading the result data and returns the #affected_rows.
|
106
|
+
|
107
|
+
result = client.execute("DELETE FROM [datatypes]")
|
108
|
+
result.do # => 72
|
109
|
+
|
110
|
+
Likewise for INSERT statements, the #insert method cancels any need for loading the result data and executes a SCOPE_IDENTITY() for the primary key.
|
111
|
+
|
112
|
+
result = client.execute("INSERT INTO [datatypes] ([xml]) VALUES ('<html><br/></html>')")
|
113
|
+
result.insert # => 420
|
114
|
+
|
115
|
+
|
116
|
+
|
117
|
+
== Query Options
|
118
|
+
|
119
|
+
Every TinyTds::Result object can pass query options to the #each method. The defaults are defined and configurable by setting options in the TinyTds::Client.default_query_options hash. The default values are:
|
120
|
+
|
121
|
+
* :as => :hash - Object for each row yielded. Can be set to :array.
|
122
|
+
* :symbolize_keys => false - Row hash keys. Defaults to shared/frozen string keys.
|
123
|
+
* :cache_rows => true - Successive calls to #each returns the cached rows.
|
124
|
+
* :timezone => :local - Local to the ruby client or :utc for UTC.
|
125
|
+
|
126
|
+
Each result gets a copy of the default options you specify at the client level and can be overridden by passing an options hash to the #each method. For example
|
127
|
+
|
128
|
+
result.each(:as => :array, :cache_rows => false) do |row|
|
129
|
+
# Each row is now an array of values ordered by #fields.
|
130
|
+
# Rows are yielded and forgotten about, freeing memory.
|
131
|
+
end
|
132
|
+
|
133
|
+
Besides the standard query options, the result object can take one additional option. Using :first => true will only load the first row of data and cancel all remaining results.
|
134
|
+
|
135
|
+
result = client.execute("SELECT * FROM [super_big_table]")
|
136
|
+
result.each(:first => true) # => [{'id' => 24}]
|
137
|
+
|
138
|
+
|
139
|
+
|
140
|
+
== Row Caching
|
141
|
+
|
142
|
+
By default row caching is turned on because the SQL Server adapter for ActiveRecord would not work without it. I hope to find some time to create some performance patches for ActiveRecord that would allow it to take advantages of lazily created yielded rows from result objects. Currently only TinyTds and the Mysql2 gem allow such a performance gain.
|
143
|
+
|
144
|
+
|
145
|
+
|
146
|
+
== Development & Testing
|
147
|
+
|
148
|
+
We use bundler for development. Simply run "bundle install" then "rake" to build the gem and run the unit tests. The tests assume you have created a database named "tinytds_test" accessible by a database owner named "tinytds". Before running the test rake task, you may need to define a pair of environment variables that help the client connect to your specific FreeTDS database server name and which schema (2000, 2005 or 2008) to use. For example:
|
149
|
+
|
150
|
+
$ env TINYTDS_UNIT_DATASERVER=mydbserver TINYTDS_SCHEMA=sqlserver_2008 rake
|
151
|
+
|
152
|
+
For help and support.
|
153
|
+
|
154
|
+
* Github Source: http://github.com/rails-sqlserver/tiny_tds
|
155
|
+
* Github Issues: http://github.com/rails-sqlserver/tiny_tds/issues
|
156
|
+
* IRC Room: #rails-sqlserver on irc.freenode.net
|
157
|
+
|
158
|
+
Current to do list.
|
159
|
+
|
160
|
+
* Test 0.83 development of FreeTDS.
|
161
|
+
* Handle multiple result sets.
|
162
|
+
* Find someone brave enough to compile/test for Windows.
|
163
|
+
* Install an interrupt handler.
|
164
|
+
* Allow #escape to accept all ruby primitives.
|
165
|
+
* Get bug reports!
|
166
|
+
|
167
|
+
|
168
|
+
|
169
|
+
== About Me
|
170
|
+
|
171
|
+
My name is Ken Collins and I have no love for Microsoft nor do I work on Windows or have I ever owned a PC. I currently maintain the SQL Server adapter for ActiveRecord and wrote this library as my first cut into learning ruby C extensions. Hopefully it will help promote the power of ruby and the rails framework to those that have not yet discovered it. My blog is http://metaskills.net and I can be found on twitter as @metaskills. Enjoy!
|
172
|
+
|
173
|
+
|
174
|
+
|
175
|
+
== Special Thanks
|
176
|
+
|
177
|
+
* Erik Bryn for joining the project and helping me thru a few tight spots. - http://github.com/ebryn
|
178
|
+
* To the authors and contributors of the Mysql2 gem for inspiration. - http://github.com/brianmario/mysql2
|
179
|
+
* Yehuda Katz for articulating ruby's need for proper encoding support. Especially in database drivers - http://yehudakatz.com/2010/05/05/ruby-1-9-encodings-a-primer-and-the-solution-for-rails/
|
180
|
+
* Josh Clayton of Thoughtbot for writing about ruby C extensions. - http://robots.thoughtbot.com/post/1037240922/get-your-c-on
|
181
|
+
|
@@ -0,0 +1,225 @@
|
|
1
|
+
|
2
|
+
#include <tiny_tds_ext.h>
|
3
|
+
#include <client.h>
|
4
|
+
#include <errno.h>
|
5
|
+
|
6
|
+
VALUE cTinyTdsClient;
|
7
|
+
extern VALUE mTinyTds, cTinyTdsError;
|
8
|
+
static ID intern_source_eql, intern_severity_eql, intern_db_error_number_eql, intern_os_error_number_eql;
|
9
|
+
static ID intern_new, intern_dup, intern_transpose_iconv_encoding, intern_local_offset, intern_gsub;
|
10
|
+
VALUE opt_escape_regex, opt_escape_dblquote;
|
11
|
+
|
12
|
+
// Lib Macros
|
13
|
+
|
14
|
+
#define GET_CLIENT_WRAPPER(self) \
|
15
|
+
tinytds_client_wrapper *cwrap; \
|
16
|
+
Data_Get_Struct(self, tinytds_client_wrapper, cwrap)
|
17
|
+
|
18
|
+
#define REQUIRE_OPEN_CLIENT(cwrap) \
|
19
|
+
if(cwrap->closed) { \
|
20
|
+
rb_raise(cTinyTdsError, "closed connection"); \
|
21
|
+
return Qnil; \
|
22
|
+
}
|
23
|
+
|
24
|
+
|
25
|
+
// Lib Backend (Helpers)
|
26
|
+
|
27
|
+
static VALUE rb_tinytds_raise_error(DBPROCESS *dbproc, int cancel, char *error, char *source, int severity, int dberr, int oserr) {
|
28
|
+
if (cancel) { dbsqlok(dbproc); dbcancel(dbproc); }
|
29
|
+
VALUE e = rb_exc_new2(cTinyTdsError, error);
|
30
|
+
rb_funcall(e, intern_source_eql, 1, rb_str_new2(source));
|
31
|
+
if (severity)
|
32
|
+
rb_funcall(e, intern_severity_eql, 1, INT2FIX(severity));
|
33
|
+
if (dberr)
|
34
|
+
rb_funcall(e, intern_db_error_number_eql, 1, INT2FIX(dberr));
|
35
|
+
if (oserr)
|
36
|
+
rb_funcall(e, intern_os_error_number_eql, 1, INT2FIX(oserr));
|
37
|
+
rb_exc_raise(e);
|
38
|
+
return Qnil;
|
39
|
+
}
|
40
|
+
|
41
|
+
|
42
|
+
// Lib Backend (Memory Management & Handlers)
|
43
|
+
|
44
|
+
int tinytds_err_handler(DBPROCESS *dbproc, int severity, int dberr, int oserr, char *dberrstr, char *oserrstr) {
|
45
|
+
static char *source = "error";
|
46
|
+
if (dberr == SYBESMSG)
|
47
|
+
return INT_CONTINUE;
|
48
|
+
rb_tinytds_raise_error(dbproc, 0, dberrstr, source, severity, dberr, oserr);
|
49
|
+
return INT_CONTINUE;
|
50
|
+
}
|
51
|
+
|
52
|
+
int tinytds_msg_handler(DBPROCESS *dbproc, DBINT msgno, int msgstate, int severity, char *msgtext, char *srvname, char *procname, int line) {
|
53
|
+
static char *source = "message";
|
54
|
+
if (severity)
|
55
|
+
rb_tinytds_raise_error(dbproc, 1, msgtext, source, severity, msgno, msgstate);
|
56
|
+
return 0;
|
57
|
+
}
|
58
|
+
|
59
|
+
static void rb_tinytds_client_mark(void *ptr) {
|
60
|
+
tinytds_client_wrapper *cwrap = (tinytds_client_wrapper *)ptr;
|
61
|
+
if (cwrap) {
|
62
|
+
rb_gc_mark(cwrap->charset);
|
63
|
+
}
|
64
|
+
}
|
65
|
+
|
66
|
+
static void rb_tinytds_client_free(void *ptr) {
|
67
|
+
tinytds_client_wrapper *cwrap = (tinytds_client_wrapper *)ptr;
|
68
|
+
if (cwrap->login)
|
69
|
+
dbloginfree(cwrap->login);
|
70
|
+
if (cwrap->client && !cwrap->closed) {
|
71
|
+
dbclose(cwrap->client);
|
72
|
+
cwrap->closed = 1;
|
73
|
+
}
|
74
|
+
xfree(ptr);
|
75
|
+
}
|
76
|
+
|
77
|
+
static VALUE allocate(VALUE klass) {
|
78
|
+
VALUE obj;
|
79
|
+
tinytds_client_wrapper *cwrap;
|
80
|
+
obj = Data_Make_Struct(klass, tinytds_client_wrapper, rb_tinytds_client_mark, rb_tinytds_client_free, cwrap);
|
81
|
+
cwrap->closed = 1;
|
82
|
+
cwrap->charset = Qnil;
|
83
|
+
return obj;
|
84
|
+
}
|
85
|
+
|
86
|
+
|
87
|
+
// TinyTds::Client (public)
|
88
|
+
|
89
|
+
static VALUE rb_tinytds_tds_version(VALUE self) {
|
90
|
+
GET_CLIENT_WRAPPER(self);
|
91
|
+
return INT2FIX(dbtds(cwrap->client));
|
92
|
+
}
|
93
|
+
|
94
|
+
static VALUE rb_tinytds_close(VALUE self) {
|
95
|
+
GET_CLIENT_WRAPPER(self);
|
96
|
+
if (cwrap->client && !cwrap->closed) {
|
97
|
+
dbclose(cwrap->client);
|
98
|
+
cwrap->closed = 1;
|
99
|
+
}
|
100
|
+
return Qtrue;
|
101
|
+
}
|
102
|
+
|
103
|
+
static VALUE rb_tinytds_closed(VALUE self) {
|
104
|
+
GET_CLIENT_WRAPPER(self);
|
105
|
+
return cwrap->closed ? Qtrue : Qfalse;
|
106
|
+
}
|
107
|
+
|
108
|
+
static VALUE rb_tinytds_execute(VALUE self, VALUE sql) {
|
109
|
+
GET_CLIENT_WRAPPER(self);
|
110
|
+
REQUIRE_OPEN_CLIENT(cwrap);
|
111
|
+
dbcmd(cwrap->client, StringValuePtr(sql));
|
112
|
+
if (dbsqlexec(cwrap->client) == FAIL) {
|
113
|
+
// TODO: Account for dbsqlexec() returned FAIL.
|
114
|
+
rb_warn("TinyTds: dbsqlexec() returned FAIL.\n");
|
115
|
+
return Qfalse;
|
116
|
+
}
|
117
|
+
VALUE result = rb_tinytds_new_result_obj(cwrap->client);
|
118
|
+
rb_iv_set(result, "@query_options", rb_funcall(rb_iv_get(self, "@query_options"), intern_dup, 0));
|
119
|
+
GET_RESULT_WRAPPER(result);
|
120
|
+
rwrap->local_offset = rb_funcall(cTinyTdsClient, intern_local_offset, 0);
|
121
|
+
#ifdef HAVE_RUBY_ENCODING_H
|
122
|
+
rwrap->encoding = cwrap->encoding;
|
123
|
+
#endif
|
124
|
+
return result;
|
125
|
+
}
|
126
|
+
|
127
|
+
static VALUE rb_tinytds_charset(VALUE self) {
|
128
|
+
GET_CLIENT_WRAPPER(self);
|
129
|
+
return cwrap->charset;
|
130
|
+
}
|
131
|
+
|
132
|
+
static VALUE rb_tinytds_encoding(VALUE self) {
|
133
|
+
GET_CLIENT_WRAPPER(self);
|
134
|
+
#ifdef HAVE_RUBY_ENCODING_H
|
135
|
+
return rb_enc_from_encoding(cwrap->encoding);
|
136
|
+
#else
|
137
|
+
return Qnil;
|
138
|
+
#endif
|
139
|
+
}
|
140
|
+
|
141
|
+
static VALUE rb_tinytds_escape(VALUE self, VALUE string) {
|
142
|
+
Check_Type(string, T_STRING);
|
143
|
+
GET_CLIENT_WRAPPER(self);
|
144
|
+
VALUE new_string = rb_funcall(string, intern_gsub, 2, opt_escape_regex, opt_escape_dblquote);
|
145
|
+
#ifdef HAVE_RUBY_ENCODING_H
|
146
|
+
rb_enc_associate(new_string, cwrap->encoding);
|
147
|
+
#endif
|
148
|
+
return new_string;
|
149
|
+
}
|
150
|
+
|
151
|
+
|
152
|
+
// TinyTds::Client (protected)
|
153
|
+
|
154
|
+
static VALUE rb_tinytds_connect(VALUE self, VALUE user, VALUE pass, VALUE dataserver, VALUE database, VALUE app, VALUE version, VALUE ltimeout, VALUE timeout, VALUE charset) {
|
155
|
+
if (dbinit() == FAIL) {
|
156
|
+
rb_raise(cTinyTdsError, "failed dbinit() function");
|
157
|
+
return self;
|
158
|
+
}
|
159
|
+
dberrhandle(tinytds_err_handler);
|
160
|
+
dbmsghandle(tinytds_msg_handler);
|
161
|
+
GET_CLIENT_WRAPPER(self);
|
162
|
+
cwrap->login = dblogin();
|
163
|
+
if (!NIL_P(user))
|
164
|
+
dbsetluser(cwrap->login, StringValuePtr(user));
|
165
|
+
if (!NIL_P(pass))
|
166
|
+
dbsetlpwd(cwrap->login, StringValuePtr(pass));
|
167
|
+
if (!NIL_P(app))
|
168
|
+
dbsetlapp(cwrap->login, StringValuePtr(app));
|
169
|
+
if (!NIL_P(version))
|
170
|
+
dbsetlversion(cwrap->login, NUM2INT(version));
|
171
|
+
if (!NIL_P(ltimeout))
|
172
|
+
dbsetlogintime(NUM2INT(ltimeout));
|
173
|
+
if (!NIL_P(timeout))
|
174
|
+
dbsettime(NUM2INT(timeout));
|
175
|
+
if (!NIL_P(charset))
|
176
|
+
DBSETLCHARSET(cwrap->login, StringValuePtr(charset));
|
177
|
+
cwrap->client = dbopen(cwrap->login, StringValuePtr(dataserver));
|
178
|
+
if (!NIL_P(database))
|
179
|
+
dbuse(cwrap->client, StringValuePtr(database));
|
180
|
+
if (cwrap->client) {
|
181
|
+
cwrap->closed = 0;
|
182
|
+
cwrap->charset = charset;
|
183
|
+
#ifdef HAVE_RUBY_ENCODING_H
|
184
|
+
VALUE transposed_encoding = rb_funcall(cTinyTdsClient, intern_transpose_iconv_encoding, 1, charset);
|
185
|
+
cwrap->encoding = rb_enc_find(StringValuePtr(transposed_encoding));
|
186
|
+
#endif
|
187
|
+
}
|
188
|
+
return self;
|
189
|
+
}
|
190
|
+
|
191
|
+
|
192
|
+
// Lib Init
|
193
|
+
|
194
|
+
void init_tinytds_client() {
|
195
|
+
cTinyTdsClient = rb_define_class_under(mTinyTds, "Client", rb_cObject);
|
196
|
+
rb_define_alloc_func(cTinyTdsClient, allocate);
|
197
|
+
/* Define TinyTds::Client Public Methods */
|
198
|
+
rb_define_method(cTinyTdsClient, "tds_version", rb_tinytds_tds_version, 0);
|
199
|
+
rb_define_method(cTinyTdsClient, "close", rb_tinytds_close, 0);
|
200
|
+
rb_define_method(cTinyTdsClient, "closed?", rb_tinytds_closed, 0);
|
201
|
+
rb_define_method(cTinyTdsClient, "execute", rb_tinytds_execute, 1);
|
202
|
+
rb_define_method(cTinyTdsClient, "charset", rb_tinytds_charset, 0);
|
203
|
+
rb_define_method(cTinyTdsClient, "encoding", rb_tinytds_encoding, 0);
|
204
|
+
rb_define_method(cTinyTdsClient, "escape", rb_tinytds_escape, 1);
|
205
|
+
/* Define TinyTds::Client Protected Methods */
|
206
|
+
rb_define_protected_method(cTinyTdsClient, "connect", rb_tinytds_connect, 9);
|
207
|
+
/* Intern TinyTds::Error Accessors */
|
208
|
+
intern_source_eql = rb_intern("source=");
|
209
|
+
intern_severity_eql = rb_intern("severity=");
|
210
|
+
intern_db_error_number_eql = rb_intern("db_error_number=");
|
211
|
+
intern_os_error_number_eql = rb_intern("os_error_number=");
|
212
|
+
/* Intern Misc */
|
213
|
+
intern_new = rb_intern("new");
|
214
|
+
intern_dup = rb_intern("dup");
|
215
|
+
intern_transpose_iconv_encoding = rb_intern("transpose_iconv_encoding");
|
216
|
+
intern_local_offset = rb_intern("local_offset");
|
217
|
+
intern_gsub = rb_intern("gsub");
|
218
|
+
/* Escape Regexp Global */
|
219
|
+
opt_escape_regex = rb_funcall(rb_cRegexp, intern_new, 1, rb_str_new2("\\\'"));
|
220
|
+
opt_escape_dblquote = rb_str_new2("''");
|
221
|
+
rb_global_variable(&opt_escape_regex);
|
222
|
+
rb_global_variable(&opt_escape_dblquote);
|
223
|
+
}
|
224
|
+
|
225
|
+
|
@@ -0,0 +1,19 @@
|
|
1
|
+
|
2
|
+
#ifndef TINYTDS_CLIENT_H
|
3
|
+
#define TINYTDS_CLIENT_H
|
4
|
+
|
5
|
+
void init_tinytds_client();
|
6
|
+
|
7
|
+
typedef struct {
|
8
|
+
LOGINREC *login;
|
9
|
+
RETCODE return_code;
|
10
|
+
DBPROCESS *client;
|
11
|
+
short int closed;
|
12
|
+
VALUE charset;
|
13
|
+
#ifdef HAVE_RUBY_ENCODING_H
|
14
|
+
rb_encoding *encoding;
|
15
|
+
#endif
|
16
|
+
} tinytds_client_wrapper;
|
17
|
+
|
18
|
+
|
19
|
+
#endif
|
@@ -0,0 +1,75 @@
|
|
1
|
+
require 'mkmf'
|
2
|
+
|
3
|
+
FREETDS_LIBRARIES = ['sybdb']
|
4
|
+
FREETDS_HEADERS = ['sqlfront.h', 'sybdb.h', 'syberror.h']
|
5
|
+
|
6
|
+
dir_config('freetds')
|
7
|
+
|
8
|
+
def root_paths
|
9
|
+
eop_regexp = /#{File::SEPARATOR}bin$/
|
10
|
+
paths = ENV['PATH'].split(File::PATH_SEPARATOR)
|
11
|
+
bin_paths = paths.select{ |p| p =~ eop_regexp }
|
12
|
+
bin_paths.map{ |p| p.sub(eop_regexp,'') }.compact.reject{ |p| p.empty? }.uniq
|
13
|
+
end
|
14
|
+
|
15
|
+
def have_freetds_libraries?(*libraries)
|
16
|
+
libraries.all? { |l| have_library(l) }
|
17
|
+
end
|
18
|
+
|
19
|
+
def find_freetds_libraries_path
|
20
|
+
root_paths.detect do |path|
|
21
|
+
[['lib'],['lib','freetds']].detect do |lpaths|
|
22
|
+
dir = File.join path, *lpaths
|
23
|
+
message = "looking for library directory #{dir} ..."
|
24
|
+
if File.directory?(dir)
|
25
|
+
puts "#{message} yes"
|
26
|
+
if with_ldflags("#{$LDFLAGS} -L#{dir}".strip) { have_freetds_libraries?(*FREETDS_LIBRARIES) }
|
27
|
+
$LDFLAGS += "#{$LDFLAGS} -L#{dir}".strip
|
28
|
+
true
|
29
|
+
else
|
30
|
+
false
|
31
|
+
end
|
32
|
+
else
|
33
|
+
puts "#{message} no"
|
34
|
+
false
|
35
|
+
end
|
36
|
+
end
|
37
|
+
end
|
38
|
+
end
|
39
|
+
|
40
|
+
def have_freetds_headers?(*headers)
|
41
|
+
headers.all? { |h| have_header(h) }
|
42
|
+
end
|
43
|
+
|
44
|
+
def find_freetds_include_path
|
45
|
+
root_paths.detect do |path|
|
46
|
+
[['include'],['include','freetds']].detect do |ipaths|
|
47
|
+
dir = File.join path, *ipaths
|
48
|
+
message = "looking for include directory #{dir} ..."
|
49
|
+
if File.directory?(dir)
|
50
|
+
puts "#{message} yes"
|
51
|
+
if with_cppflags("#{$CPPFLAGS} -I#{dir}".strip) { have_freetds_headers?(*FREETDS_HEADERS) }
|
52
|
+
$CPPFLAGS += "#{$CPPFLAGS} -I#{dir}".strip
|
53
|
+
true
|
54
|
+
else
|
55
|
+
false
|
56
|
+
end
|
57
|
+
else
|
58
|
+
puts "#{message} no"
|
59
|
+
false
|
60
|
+
end
|
61
|
+
end
|
62
|
+
end
|
63
|
+
end
|
64
|
+
|
65
|
+
def have_freetds?
|
66
|
+
(have_freetds_libraries?(*FREETDS_LIBRARIES) || find_freetds_libraries_path) &&
|
67
|
+
(have_freetds_headers?(*FREETDS_HEADERS) || find_freetds_include_path)
|
68
|
+
end
|
69
|
+
|
70
|
+
unless have_freetds?
|
71
|
+
abort "-----\nCan not find FreeTDS's db-lib or include directory.\n-----"
|
72
|
+
end
|
73
|
+
|
74
|
+
create_makefile('tiny_tds/tiny_tds')
|
75
|
+
|
@@ -0,0 +1,390 @@
|
|
1
|
+
|
2
|
+
#include <tiny_tds_ext.h>
|
3
|
+
|
4
|
+
VALUE cTinyTdsResult;
|
5
|
+
extern VALUE mTinyTds, cTinyTdsClient, cTinyTdsError;
|
6
|
+
VALUE cBigDecimal, cDate, cDateTime, cRational;
|
7
|
+
VALUE opt_decimal_zero, opt_float_zero, opt_one, opt_zero, opt_four, opt_19hdr, opt_tenk, opt_onemil;
|
8
|
+
static ID intern_new, intern_utc, intern_local, intern_localtime, intern_merge,
|
9
|
+
intern_civil, intern_new_offset, intern_plus, intern_divide;
|
10
|
+
static ID sym_symbolize_keys, sym_as, sym_array, sym_cache_rows, sym_first, sym_timezone, sym_local, sym_utc;
|
11
|
+
|
12
|
+
#ifdef HAVE_RUBY_ENCODING_H
|
13
|
+
rb_encoding *binaryEncoding;
|
14
|
+
#define ENCODED_STR_NEW(_data, _len) ({ \
|
15
|
+
VALUE _val = rb_str_new((char *)_data, (long)_len); \
|
16
|
+
rb_enc_associate(_val, rwrap->encoding); \
|
17
|
+
_val; \
|
18
|
+
})
|
19
|
+
#define ENCODED_STR_NEW2(_data2) ({ \
|
20
|
+
VALUE _val = rb_str_new2((char *)_data2); \
|
21
|
+
rb_enc_associate(_val, rwrap->encoding); \
|
22
|
+
_val; \
|
23
|
+
})
|
24
|
+
#else
|
25
|
+
#define ENCODED_STR_NEW(_data, _len) \
|
26
|
+
rb_str_new((char *)_data, (long)_len);
|
27
|
+
#define ENCODED_STR_NEW2(_data2) \
|
28
|
+
rb_str_new2((char *)_data2);
|
29
|
+
#endif
|
30
|
+
|
31
|
+
|
32
|
+
// Lib Backend (Memory Management)
|
33
|
+
|
34
|
+
static void rb_tinytds_result_mark(void *ptr) {
|
35
|
+
tinytds_result_wrapper *rwrap = (tinytds_result_wrapper *)ptr;
|
36
|
+
if (rwrap) {
|
37
|
+
rb_gc_mark(rwrap->local_offset);
|
38
|
+
rb_gc_mark(rwrap->fields);
|
39
|
+
rb_gc_mark(rwrap->rows);
|
40
|
+
}
|
41
|
+
}
|
42
|
+
|
43
|
+
static void rb_tinytds_result_free(void *ptr) {
|
44
|
+
tinytds_result_wrapper *rwrap = (tinytds_result_wrapper *)ptr;
|
45
|
+
xfree(ptr);
|
46
|
+
}
|
47
|
+
|
48
|
+
VALUE rb_tinytds_new_result_obj(DBPROCESS *c) {
|
49
|
+
VALUE obj;
|
50
|
+
tinytds_result_wrapper *rwrap;
|
51
|
+
obj = Data_Make_Struct(cTinyTdsResult, tinytds_result_wrapper, rb_tinytds_result_mark, rb_tinytds_result_free, rwrap);
|
52
|
+
rwrap->client = c;
|
53
|
+
rwrap->return_code = 0;
|
54
|
+
rwrap->local_offset = Qnil;
|
55
|
+
rwrap->fields = Qnil;
|
56
|
+
rwrap->rows = Qnil;
|
57
|
+
rwrap->number_of_fields = 0;
|
58
|
+
rwrap->number_of_rows = 0;
|
59
|
+
rb_obj_call_init(obj, 0, NULL);
|
60
|
+
return obj;
|
61
|
+
}
|
62
|
+
|
63
|
+
|
64
|
+
// Lib Backend (Helpers)
|
65
|
+
|
66
|
+
static VALUE rb_tinytds_result_fetch_row(VALUE self, ID timezone, int symbolize_keys, int as_array) {
|
67
|
+
/* Wrapper And Local Vars */
|
68
|
+
GET_RESULT_WRAPPER(self);
|
69
|
+
VALUE row;
|
70
|
+
unsigned int i = 0;
|
71
|
+
/* One-Time Fields Info & Container */
|
72
|
+
if (NIL_P(rwrap->fields)) {
|
73
|
+
rwrap->number_of_fields = dbnumcols(rwrap->client);
|
74
|
+
rwrap->fields = rb_ary_new2(rwrap->number_of_fields);
|
75
|
+
for (i = 0; i < rwrap->number_of_fields; i++) {
|
76
|
+
char *colname = dbcolname(rwrap->client, i+1);
|
77
|
+
VALUE field = symbolize_keys ? ID2SYM(rb_intern(colname)) : rb_obj_freeze(rb_str_new2(colname));
|
78
|
+
rb_ary_store(rwrap->fields, i, field);
|
79
|
+
}
|
80
|
+
}
|
81
|
+
/* Create Empty Row */
|
82
|
+
if (as_array) {
|
83
|
+
row = rb_ary_new2(rwrap->number_of_fields);
|
84
|
+
} else {
|
85
|
+
row = rb_hash_new();
|
86
|
+
}
|
87
|
+
/* Storing Values */
|
88
|
+
for (i = 0; i < rwrap->number_of_fields; i++) {
|
89
|
+
VALUE val = Qnil;
|
90
|
+
int col = i+1;
|
91
|
+
int coltype = dbcoltype(rwrap->client, col);
|
92
|
+
BYTE *data = dbdata(rwrap->client, col);
|
93
|
+
DBINT data_len = dbdatlen(rwrap->client, col);
|
94
|
+
int null_val = ((data == NULL) && (data_len == 0));
|
95
|
+
if (!null_val) {
|
96
|
+
switch(coltype) {
|
97
|
+
case SYBINT1:
|
98
|
+
val = INT2FIX(*(DBTINYINT *)data);
|
99
|
+
break;
|
100
|
+
case SYBINT2:
|
101
|
+
val = INT2FIX(*(DBSMALLINT *)data);
|
102
|
+
break;
|
103
|
+
case SYBINT4:
|
104
|
+
val = INT2NUM(*(DBINT *)data);
|
105
|
+
break;
|
106
|
+
case SYBINT8:
|
107
|
+
val = LONG2NUM(*(long *)data);
|
108
|
+
break;
|
109
|
+
case SYBBIT:
|
110
|
+
val = *(int *)data ? Qtrue : Qfalse;
|
111
|
+
break;
|
112
|
+
case SYBNUMERIC:
|
113
|
+
case SYBDECIMAL: {
|
114
|
+
DBTYPEINFO *data_info = dbcoltypeinfo(rwrap->client, col);
|
115
|
+
int data_slength = (int)data_info->precision + (int)data_info->scale + 1;
|
116
|
+
char converted_decimal[data_slength];
|
117
|
+
dbconvert(rwrap->client, coltype, data, data_len, SYBVARCHAR, (BYTE *)converted_decimal, -1);
|
118
|
+
val = rb_funcall(cBigDecimal, intern_new, 1, rb_str_new2((char *)converted_decimal));
|
119
|
+
break;
|
120
|
+
}
|
121
|
+
case SYBFLT8: {
|
122
|
+
double col_to_double = *(double *)data;
|
123
|
+
val = (col_to_double == 0.000000) ? opt_float_zero : rb_float_new(col_to_double);
|
124
|
+
break;
|
125
|
+
}
|
126
|
+
case SYBREAL: {
|
127
|
+
float col_to_float = *(float *)data;
|
128
|
+
val = (col_to_float == 0.0) ? opt_float_zero : rb_float_new(col_to_float);
|
129
|
+
break;
|
130
|
+
}
|
131
|
+
case SYBMONEY: {
|
132
|
+
DBMONEY *money = (DBMONEY *)data;
|
133
|
+
char converted_money[25];
|
134
|
+
long money_value = ((long)money->mnyhigh << 32) | money->mnylow;
|
135
|
+
sprintf(converted_money, "%ld", money_value);
|
136
|
+
val = rb_funcall(cBigDecimal, intern_new, 2, rb_str_new2(converted_money), opt_four);
|
137
|
+
val = rb_funcall(val, intern_divide, 1, opt_tenk);
|
138
|
+
break;
|
139
|
+
}
|
140
|
+
case SYBMONEY4: {
|
141
|
+
DBMONEY4 *money = (DBMONEY4 *)data;
|
142
|
+
char converted_money[20];
|
143
|
+
sprintf(converted_money, "%f", money->mny4 / 10000.0);
|
144
|
+
val = rb_funcall(cBigDecimal, intern_new, 1, rb_str_new2(converted_money));
|
145
|
+
break;
|
146
|
+
}
|
147
|
+
case SYBBINARY:
|
148
|
+
case SYBIMAGE:
|
149
|
+
val = rb_str_new((char *)data, (long)data_len);
|
150
|
+
#ifdef HAVE_RUBY_ENCODING_H
|
151
|
+
rb_enc_associate(val, binaryEncoding);
|
152
|
+
#endif
|
153
|
+
break;
|
154
|
+
case 36: { // SYBUNIQUE
|
155
|
+
char converted_unique[32];
|
156
|
+
dbconvert(rwrap->client, coltype, data, 32, SYBVARCHAR, (BYTE *)converted_unique, -1);
|
157
|
+
val = ENCODED_STR_NEW2(converted_unique);
|
158
|
+
break;
|
159
|
+
}
|
160
|
+
case SYBDATETIME4:
|
161
|
+
dbconvert(rwrap->client, coltype, data, data_len, SYBDATETIME, data, data_len);
|
162
|
+
case SYBDATETIME: {
|
163
|
+
DBDATEREC date_rec;
|
164
|
+
dbdatecrack(rwrap->client, &date_rec, (DBDATETIME *)data);
|
165
|
+
int year = date_rec.year,
|
166
|
+
month = date_rec.month,
|
167
|
+
day = date_rec.day,
|
168
|
+
hour = date_rec.hour,
|
169
|
+
min = date_rec.minute,
|
170
|
+
sec = date_rec.second,
|
171
|
+
msec = date_rec.millisecond;
|
172
|
+
if (year+month+day+hour+min+sec+msec != 0) {
|
173
|
+
VALUE offset = (timezone == intern_local) ? rwrap->local_offset : opt_zero;
|
174
|
+
/* Use DateTime */
|
175
|
+
if (year < 1902 || year+month+day > 2058) {
|
176
|
+
VALUE datetime_sec = INT2NUM(sec);
|
177
|
+
if (msec != 0) {
|
178
|
+
#ifdef HAVE_RUBY_ENCODING_H
|
179
|
+
VALUE rational_msec = rb_Rational2(INT2NUM(msec*1000), opt_onemil);
|
180
|
+
#else
|
181
|
+
VALUE rational_msec = rb_funcall(cRational, intern_new, 2, INT2NUM(msec*1000), opt_onemil);
|
182
|
+
#endif
|
183
|
+
datetime_sec = rb_funcall(datetime_sec, intern_plus, 1, rational_msec);
|
184
|
+
}
|
185
|
+
val = rb_funcall(cDateTime, intern_civil, 7, INT2NUM(year), INT2NUM(month), INT2NUM(day), INT2NUM(hour), INT2NUM(min), datetime_sec, offset);
|
186
|
+
val = rb_funcall(val, intern_new_offset, 1, offset);
|
187
|
+
/* Use Time */
|
188
|
+
} else {
|
189
|
+
val = rb_funcall(rb_cTime, timezone, 7, INT2NUM(year), INT2NUM(month), INT2NUM(day), INT2NUM(hour), INT2NUM(min), INT2NUM(sec), INT2NUM(msec*1000));
|
190
|
+
}
|
191
|
+
}
|
192
|
+
break;
|
193
|
+
}
|
194
|
+
case SYBCHAR:
|
195
|
+
case SYBTEXT:
|
196
|
+
val = ENCODED_STR_NEW(data, data_len);
|
197
|
+
break;
|
198
|
+
default:
|
199
|
+
val = ENCODED_STR_NEW(data, data_len);
|
200
|
+
break;
|
201
|
+
}
|
202
|
+
}
|
203
|
+
if (as_array) {
|
204
|
+
rb_ary_store(row, i, val);
|
205
|
+
} else {
|
206
|
+
rb_hash_aset(row, rb_ary_entry(rwrap->fields, i), val);
|
207
|
+
}
|
208
|
+
}
|
209
|
+
return row;
|
210
|
+
}
|
211
|
+
|
212
|
+
|
213
|
+
// TinyTds::Client (public)
|
214
|
+
|
215
|
+
static VALUE rb_tinytds_result_each(int argc, VALUE * argv, VALUE self) {
|
216
|
+
GET_RESULT_WRAPPER(self);
|
217
|
+
/* Local Vars */
|
218
|
+
VALUE defaults, opts, block;
|
219
|
+
ID timezone;
|
220
|
+
int symbolize_keys = 0, as_array = 0, cache_rows = 0, first = 0;
|
221
|
+
/* Merge Options Hash, Populate Opts & Block Var */
|
222
|
+
defaults = rb_iv_get(self, "@query_options");
|
223
|
+
if (rb_scan_args(argc, argv, "01&", &opts, &block) == 1) {
|
224
|
+
opts = rb_funcall(defaults, intern_merge, 1, opts);
|
225
|
+
} else {
|
226
|
+
opts = defaults;
|
227
|
+
}
|
228
|
+
/* Locals From Options */
|
229
|
+
if (rb_hash_aref(opts, sym_first) == Qtrue)
|
230
|
+
first = 1;
|
231
|
+
if (rb_hash_aref(opts, sym_symbolize_keys) == Qtrue)
|
232
|
+
symbolize_keys = 1;
|
233
|
+
if (rb_hash_aref(opts, sym_as) == sym_array)
|
234
|
+
as_array = 1;
|
235
|
+
if (rb_hash_aref(opts, sym_cache_rows) == Qtrue)
|
236
|
+
cache_rows = 1;
|
237
|
+
if (rb_hash_aref(opts, sym_timezone) == sym_local) {
|
238
|
+
timezone = intern_local;
|
239
|
+
} else if (rb_hash_aref(opts, sym_timezone) == sym_utc) {
|
240
|
+
timezone = intern_utc;
|
241
|
+
} else {
|
242
|
+
rb_warn(":timezone option must be :utc or :local - defaulting to :local");
|
243
|
+
timezone = intern_local;
|
244
|
+
}
|
245
|
+
/* Make The Rows Or Yield Existing */
|
246
|
+
if (NIL_P(rwrap->rows)) {
|
247
|
+
rwrap->rows = rb_ary_new();
|
248
|
+
RETCODE return_code;
|
249
|
+
while (return_code != NO_MORE_RESULTS) {
|
250
|
+
return_code = dbresults(rwrap->client);
|
251
|
+
if (return_code != FAIL) {
|
252
|
+
/* If no actual rows, return the empty array. */
|
253
|
+
if (DBROWS(rwrap->client) != SUCCEED)
|
254
|
+
return rwrap->rows;
|
255
|
+
unsigned long rowi = 0;
|
256
|
+
while (dbnextrow(rwrap->client) != NO_MORE_ROWS) {
|
257
|
+
VALUE row = rb_tinytds_result_fetch_row(self, timezone, symbolize_keys, as_array);
|
258
|
+
if (cache_rows)
|
259
|
+
rb_ary_store(rwrap->rows, rowi, row);
|
260
|
+
if (!NIL_P(block))
|
261
|
+
rb_yield(row);
|
262
|
+
if (first)
|
263
|
+
dbcanquery(rwrap->client);
|
264
|
+
rowi++;
|
265
|
+
}
|
266
|
+
rwrap->number_of_rows = rowi;
|
267
|
+
} else {
|
268
|
+
// TODO: Account for failed dbresults() must have returned FAIL.
|
269
|
+
rb_warn("TinyTds: dbresults() must have returned FAIL.\n");
|
270
|
+
}
|
271
|
+
}
|
272
|
+
if (return_code == FAIL) {
|
273
|
+
// TODO: Account for something in the dbresults() while loop set the return code to FAIL.
|
274
|
+
rb_warn("TinyTds: Something in the dbresults() while loop set the return code to FAIL.\n");
|
275
|
+
}
|
276
|
+
} else if (!NIL_P(block)) {
|
277
|
+
unsigned long i;
|
278
|
+
for (i = 0; i < rwrap->number_of_rows; i++) {
|
279
|
+
rb_yield(rb_ary_entry(rwrap->rows, i));
|
280
|
+
}
|
281
|
+
}
|
282
|
+
return rwrap->rows;
|
283
|
+
}
|
284
|
+
|
285
|
+
static VALUE rb_tinytds_result_fields(VALUE self) {
|
286
|
+
GET_RESULT_WRAPPER(self);
|
287
|
+
return rwrap->fields;
|
288
|
+
}
|
289
|
+
|
290
|
+
static VALUE rb_tinytds_result_cancel(VALUE self) {
|
291
|
+
GET_RESULT_WRAPPER(self);
|
292
|
+
if (rwrap->client)
|
293
|
+
dbcancel(rwrap->client);
|
294
|
+
return Qtrue;
|
295
|
+
}
|
296
|
+
|
297
|
+
static VALUE rb_tinytds_result_do(VALUE self) {
|
298
|
+
GET_RESULT_WRAPPER(self);
|
299
|
+
if (rwrap->client) {
|
300
|
+
dbcancel(rwrap->client);
|
301
|
+
return LONG2NUM((long)dbcount(rwrap->client));
|
302
|
+
} else {
|
303
|
+
return Qnil;
|
304
|
+
}
|
305
|
+
}
|
306
|
+
|
307
|
+
static VALUE rb_tinytds_result_affected_rows(VALUE self) {
|
308
|
+
GET_RESULT_WRAPPER(self);
|
309
|
+
if (rwrap->client) {
|
310
|
+
return LONG2NUM((long)dbcount(rwrap->client));
|
311
|
+
} else {
|
312
|
+
return Qnil;
|
313
|
+
}
|
314
|
+
}
|
315
|
+
|
316
|
+
static VALUE rb_tinytds_result_insert(VALUE self) {
|
317
|
+
GET_RESULT_WRAPPER(self);
|
318
|
+
if (rwrap->client) {
|
319
|
+
dbcancel(rwrap->client);
|
320
|
+
VALUE identity = Qnil;
|
321
|
+
dbcmd(rwrap->client, "SELECT CAST(SCOPE_IDENTITY() AS bigint) AS Ident");
|
322
|
+
if (dbsqlexec(rwrap->client) != FAIL && dbresults(rwrap->client) != FAIL && DBROWS(rwrap->client) != FAIL) {
|
323
|
+
while (dbnextrow(rwrap->client) != NO_MORE_ROWS) {
|
324
|
+
int col = 1;
|
325
|
+
BYTE *data = dbdata(rwrap->client, col);
|
326
|
+
DBINT data_len = dbdatlen(rwrap->client, col);
|
327
|
+
int null_val = ((data == NULL) && (data_len == 0));
|
328
|
+
if (!null_val)
|
329
|
+
identity = LONG2NUM(*(long *)data);
|
330
|
+
}
|
331
|
+
}
|
332
|
+
return identity;
|
333
|
+
} else {
|
334
|
+
return Qnil;
|
335
|
+
}
|
336
|
+
}
|
337
|
+
|
338
|
+
|
339
|
+
// Lib Init
|
340
|
+
|
341
|
+
void init_tinytds_result() {
|
342
|
+
/* Data Classes */
|
343
|
+
cBigDecimal = rb_const_get(rb_cObject, rb_intern("BigDecimal"));
|
344
|
+
cDate = rb_const_get(rb_cObject, rb_intern("Date"));
|
345
|
+
cDateTime = rb_const_get(rb_cObject, rb_intern("DateTime"));
|
346
|
+
cRational = rb_const_get(rb_cObject, rb_intern("Rational"));
|
347
|
+
/* Define TinyTds::Result */
|
348
|
+
cTinyTdsResult = rb_define_class_under(mTinyTds, "Result", rb_cObject);
|
349
|
+
/* Define TinyTds::Result Public Methods */
|
350
|
+
rb_define_method(cTinyTdsResult, "each", rb_tinytds_result_each, -1);
|
351
|
+
rb_define_method(cTinyTdsResult, "fields", rb_tinytds_result_fields, 0);
|
352
|
+
rb_define_method(cTinyTdsResult, "cancel", rb_tinytds_result_cancel, 0);
|
353
|
+
rb_define_method(cTinyTdsResult, "do", rb_tinytds_result_do, 0);
|
354
|
+
rb_define_method(cTinyTdsResult, "affected_rows", rb_tinytds_result_affected_rows, 0);
|
355
|
+
rb_define_method(cTinyTdsResult, "insert", rb_tinytds_result_insert, 0);
|
356
|
+
/* Intern String Helpers */
|
357
|
+
intern_new = rb_intern("new");
|
358
|
+
intern_utc = rb_intern("utc");
|
359
|
+
intern_local = rb_intern("local");
|
360
|
+
intern_merge = rb_intern("merge");
|
361
|
+
intern_localtime = rb_intern("localtime");
|
362
|
+
intern_civil = rb_intern("civil");
|
363
|
+
intern_new_offset = rb_intern("new_offset");
|
364
|
+
intern_plus = rb_intern("+");
|
365
|
+
intern_divide = rb_intern("/");
|
366
|
+
/* Symbol Helpers */
|
367
|
+
sym_symbolize_keys = ID2SYM(rb_intern("symbolize_keys"));
|
368
|
+
sym_as = ID2SYM(rb_intern("as"));
|
369
|
+
sym_array = ID2SYM(rb_intern("array"));
|
370
|
+
sym_cache_rows = ID2SYM(rb_intern("cache_rows"));
|
371
|
+
sym_first = ID2SYM(rb_intern("first"));
|
372
|
+
sym_local = ID2SYM(intern_local);
|
373
|
+
sym_utc = ID2SYM(intern_utc);
|
374
|
+
sym_timezone = ID2SYM(rb_intern("timezone"));
|
375
|
+
/* Data Conversion Options */
|
376
|
+
opt_decimal_zero = rb_str_new2("0.0");
|
377
|
+
rb_global_variable(&opt_decimal_zero);
|
378
|
+
opt_float_zero = rb_float_new((double)0);
|
379
|
+
rb_global_variable(&opt_float_zero);
|
380
|
+
opt_one = INT2NUM(1);
|
381
|
+
opt_zero = INT2NUM(0);
|
382
|
+
opt_four = INT2NUM(4);
|
383
|
+
opt_19hdr = INT2NUM(1900);
|
384
|
+
opt_tenk = INT2NUM(10000);
|
385
|
+
opt_onemil = INT2NUM(1000000);
|
386
|
+
/* Encoding */
|
387
|
+
#ifdef HAVE_RUBY_ENCODING_H
|
388
|
+
binaryEncoding = rb_enc_find("binary");
|
389
|
+
#endif
|
390
|
+
}
|
@@ -0,0 +1,29 @@
|
|
1
|
+
|
2
|
+
#ifndef TINYTDS_RESULT_H
|
3
|
+
#define TINYTDS_RESULT_H
|
4
|
+
|
5
|
+
void init_tinytds_result();
|
6
|
+
VALUE rb_tinytds_new_result_obj(DBPROCESS *c);
|
7
|
+
|
8
|
+
typedef struct {
|
9
|
+
DBPROCESS *client;
|
10
|
+
RETCODE return_code;
|
11
|
+
VALUE local_offset;
|
12
|
+
VALUE fields;
|
13
|
+
VALUE rows;
|
14
|
+
#ifdef HAVE_RUBY_ENCODING_H
|
15
|
+
rb_encoding *encoding;
|
16
|
+
#endif
|
17
|
+
long number_of_fields;
|
18
|
+
unsigned long number_of_rows;
|
19
|
+
} tinytds_result_wrapper;
|
20
|
+
|
21
|
+
|
22
|
+
#define GET_RESULT_WRAPPER(self) \
|
23
|
+
tinytds_result_wrapper *rwrap; \
|
24
|
+
Data_Get_Struct(self, tinytds_result_wrapper, rwrap)
|
25
|
+
|
26
|
+
|
27
|
+
|
28
|
+
|
29
|
+
#endif
|
@@ -0,0 +1,17 @@
|
|
1
|
+
#ifndef TINYTDS_EXT
|
2
|
+
#define TINYTDS_EXT
|
3
|
+
#define MSDBLIB
|
4
|
+
|
5
|
+
#include <ruby.h>
|
6
|
+
#include <sqlfront.h>
|
7
|
+
#include <sybdb.h>
|
8
|
+
#include <syberror.h>
|
9
|
+
|
10
|
+
#ifdef HAVE_RUBY_ENCODING_H
|
11
|
+
#include <ruby/encoding.h>
|
12
|
+
#endif
|
13
|
+
|
14
|
+
#include <client.h>
|
15
|
+
#include <result.h>
|
16
|
+
|
17
|
+
#endif
|
data/lib/tiny_tds.rb
ADDED
@@ -0,0 +1,19 @@
|
|
1
|
+
# encoding: UTF-8
|
2
|
+
require 'date'
|
3
|
+
require 'bigdecimal'
|
4
|
+
require 'rational' unless RUBY_VERSION >= '1.9.2'
|
5
|
+
|
6
|
+
require 'tiny_tds/error'
|
7
|
+
require 'tiny_tds/tiny_tds'
|
8
|
+
require 'tiny_tds/client'
|
9
|
+
require 'tiny_tds/result'
|
10
|
+
|
11
|
+
require 'tiny_tds/tiny_tds'
|
12
|
+
|
13
|
+
|
14
|
+
# = TinyTds
|
15
|
+
#
|
16
|
+
# Tiny Ruby Wrapper For FreeTDS Using DB-Library
|
17
|
+
module TinyTds
|
18
|
+
VERSION = '0.1.0'
|
19
|
+
end
|
@@ -0,0 +1,77 @@
|
|
1
|
+
module TinyTds
|
2
|
+
class Client
|
3
|
+
|
4
|
+
TDS_VERSIONS_SETTERS = {
|
5
|
+
'unknown' => 0,
|
6
|
+
'46' => 1,
|
7
|
+
'100' => 2,
|
8
|
+
'42' => 3,
|
9
|
+
'70' => 4,
|
10
|
+
'80' => 5,
|
11
|
+
'90' => 6 # TODO: untested
|
12
|
+
}.freeze
|
13
|
+
|
14
|
+
TDS_VERSIONS_GETTERS = {
|
15
|
+
0 => {:name => 'DBTDS_UNKNOWN', :description => 'Unknown'},
|
16
|
+
1 => {:name => 'DBTDS_2_0', :description => 'Pre 4.0 SQL Server'},
|
17
|
+
2 => {:name => 'DBTDS_3_4', :description => 'Microsoft SQL Server (3.0)'},
|
18
|
+
3 => {:name => 'DBTDS_4_0', :description => '4.0 SQL Server'},
|
19
|
+
4 => {:name => 'DBTDS_4_2', :description => '4.2 SQL Server'},
|
20
|
+
5 => {:name => 'DBTDS_4_6', :description => '2.0 OpenServer and 4.6 SQL Server.'},
|
21
|
+
6 => {:name => 'DBTDS_4_9_5', :description => '4.9.5 (NCR) SQL Server'},
|
22
|
+
7 => {:name => 'DBTDS_5_0', :description => '5.0 SQL Server'},
|
23
|
+
8 => {:name => 'DBTDS_7_0', :description => 'Microsoft SQL Server 7.0'},
|
24
|
+
9 => {:name => 'DBTDS_8_0', :description => 'Microsoft SQL Server 2000'},
|
25
|
+
10 => {:name => 'DBTDS_9_0', :description => 'Microsoft SQL Server 2005'}
|
26
|
+
}.freeze
|
27
|
+
|
28
|
+
@@default_query_options = {
|
29
|
+
:as => :hash,
|
30
|
+
:symbolize_keys => false,
|
31
|
+
:cache_rows => true,
|
32
|
+
:timezone => :local
|
33
|
+
}
|
34
|
+
|
35
|
+
attr_reader :query_options
|
36
|
+
|
37
|
+
def self.default_query_options
|
38
|
+
@@default_query_options
|
39
|
+
end
|
40
|
+
|
41
|
+
# Most, if not all, iconv encoding names can be found by ruby. Just in case, you can
|
42
|
+
# overide this method to return a string name that Encoding.find would work with. Default
|
43
|
+
# is to return the passed encoding.
|
44
|
+
def self.transpose_iconv_encoding(encoding)
|
45
|
+
encoding
|
46
|
+
end
|
47
|
+
|
48
|
+
|
49
|
+
def initialize(opts={})
|
50
|
+
@query_options = @@default_query_options.dup
|
51
|
+
user = opts[:username]
|
52
|
+
pass = opts[:password]
|
53
|
+
dataserver = opts[:dataserver]
|
54
|
+
database = opts[:database]
|
55
|
+
appname = opts[:appname] || 'TinyTds'
|
56
|
+
version = TDS_VERSIONS_SETTERS[opts[:tds_version].to_s] || TDS_VERSIONS_SETTERS['80']
|
57
|
+
ltimeout = opts[:login_timeout] || 60
|
58
|
+
timeout = opts[:timeout] || 5
|
59
|
+
encoding = (opts[:encoding].nil? || opts[:encoding].downcase == 'utf8') ? 'UTF-8' : opts[:encoding].upcase
|
60
|
+
raise ArgumentError, 'missing :username option' if user.nil? || user.empty?
|
61
|
+
connect(user, pass, dataserver, database, appname, version, ltimeout, timeout, encoding)
|
62
|
+
end
|
63
|
+
|
64
|
+
def tds_version_info
|
65
|
+
info = TDS_VERSIONS_GETTERS[tds_version]
|
66
|
+
"#{info[:name]} - #{info[:description]}" if info
|
67
|
+
end
|
68
|
+
|
69
|
+
|
70
|
+
private
|
71
|
+
|
72
|
+
def self.local_offset
|
73
|
+
::Time.local(2010).utc_offset.to_r / 86400
|
74
|
+
end
|
75
|
+
|
76
|
+
end
|
77
|
+
end
|
@@ -0,0 +1,29 @@
|
|
1
|
+
module TinyTds
|
2
|
+
class Error < StandardError
|
3
|
+
|
4
|
+
SEVERITIES = [
|
5
|
+
{:number => 1, :severity => 'EXINFO', :explanation => 'Informational, non-error.'},
|
6
|
+
{:number => 2, :severity => 'EXUSER', :explanation => 'User error.'},
|
7
|
+
{:number => 3, :severity => 'EXNONFATAL', :explanation => 'Non-fatal error.'},
|
8
|
+
{:number => 4, :severity => 'EXCONVERSION', :explanation => 'Error in DB-Library data conversion.'},
|
9
|
+
{:number => 5, :severity => 'EXSERVER', :explanation => 'The Server has returned an error flag.'},
|
10
|
+
{:number => 6, :severity => 'EXTIME', :explanation => 'We have exceeded our timeout period while waiting for a response from the Server - the DBPROCESS is still alive.'},
|
11
|
+
{:number => 7, :severity => 'EXPROGRAM', :explanation => 'Coding error in user program.'},
|
12
|
+
{:number => 8, :severity => 'EXRESOURCE', :explanation => 'Running out of resources - the DBPROCESS may be dead.'},
|
13
|
+
{:number => 9, :severity => 'EXCOMM', :explanation => 'Failure in communication with Server - the DBPROCESS is dead.'},
|
14
|
+
{:number => 10, :severity => 'EXFATAL', :explanation => 'Fatal error - the DBPROCESS is dead.'},
|
15
|
+
{:number => 11, :severity => 'EXCONSISTENCY', :explanation => 'Internal software error - notify Sybase Technical Support.'}
|
16
|
+
].freeze
|
17
|
+
|
18
|
+
attr_accessor :source, :severity, :db_error_number, :os_error_number
|
19
|
+
|
20
|
+
def initialize(message)
|
21
|
+
super
|
22
|
+
@severity = nil
|
23
|
+
@db_error_number = nil
|
24
|
+
@os_error_number = nil
|
25
|
+
end
|
26
|
+
|
27
|
+
|
28
|
+
end
|
29
|
+
end
|
metadata
ADDED
@@ -0,0 +1,81 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: tiny_tds
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
hash: 27
|
5
|
+
prerelease: false
|
6
|
+
segments:
|
7
|
+
- 0
|
8
|
+
- 1
|
9
|
+
- 0
|
10
|
+
version: 0.1.0
|
11
|
+
platform: ruby
|
12
|
+
authors:
|
13
|
+
- Ken Collins
|
14
|
+
- Erik Bryn
|
15
|
+
autorequire:
|
16
|
+
bindir: bin
|
17
|
+
cert_chain: []
|
18
|
+
|
19
|
+
date: 2010-10-17 00:00:00 -04:00
|
20
|
+
default_executable:
|
21
|
+
dependencies: []
|
22
|
+
|
23
|
+
description: TinyTds - A modern, simple and fast FreeTDS library for Ruby using DB-Library. Developed for the ActiveRecord SQL Server adapter.
|
24
|
+
email: ken@metaskills.net
|
25
|
+
executables: []
|
26
|
+
|
27
|
+
extensions:
|
28
|
+
- ext/tiny_tds/extconf.rb
|
29
|
+
extra_rdoc_files: []
|
30
|
+
|
31
|
+
files:
|
32
|
+
- CHANGELOG
|
33
|
+
- MIT-LICENSE
|
34
|
+
- README.rdoc
|
35
|
+
- ext/tiny_tds/client.c
|
36
|
+
- ext/tiny_tds/client.h
|
37
|
+
- ext/tiny_tds/extconf.rb
|
38
|
+
- ext/tiny_tds/result.c
|
39
|
+
- ext/tiny_tds/result.h
|
40
|
+
- ext/tiny_tds/tiny_tds_ext.c
|
41
|
+
- ext/tiny_tds/tiny_tds_ext.h
|
42
|
+
- lib/tiny_tds/client.rb
|
43
|
+
- lib/tiny_tds/error.rb
|
44
|
+
- lib/tiny_tds/result.rb
|
45
|
+
- lib/tiny_tds.rb
|
46
|
+
has_rdoc: true
|
47
|
+
homepage: http://github.com/rails-sqlserver/tiny_tds
|
48
|
+
licenses: []
|
49
|
+
|
50
|
+
post_install_message:
|
51
|
+
rdoc_options:
|
52
|
+
- --charset=UTF-8
|
53
|
+
require_paths:
|
54
|
+
- lib
|
55
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
56
|
+
none: false
|
57
|
+
requirements:
|
58
|
+
- - ">="
|
59
|
+
- !ruby/object:Gem::Version
|
60
|
+
hash: 3
|
61
|
+
segments:
|
62
|
+
- 0
|
63
|
+
version: "0"
|
64
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
65
|
+
none: false
|
66
|
+
requirements:
|
67
|
+
- - ">="
|
68
|
+
- !ruby/object:Gem::Version
|
69
|
+
hash: 3
|
70
|
+
segments:
|
71
|
+
- 0
|
72
|
+
version: "0"
|
73
|
+
requirements: []
|
74
|
+
|
75
|
+
rubyforge_project:
|
76
|
+
rubygems_version: 1.3.7
|
77
|
+
signing_key:
|
78
|
+
specification_version: 3
|
79
|
+
summary: TinyTds - A modern, simple and fast FreeTDS library for Ruby using DB-Library.
|
80
|
+
test_files: []
|
81
|
+
|