orientdb4r 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/.gitignore ADDED
@@ -0,0 +1,18 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ coverage
6
+ InstalledFiles
7
+ lib/bundler/man
8
+ pkg
9
+ rdoc
10
+ spec/reports
11
+ test/tmp
12
+ test/version_tmp
13
+ tmp
14
+
15
+ # YARD artifacts
16
+ .yardoc
17
+ _yardoc
18
+ doc/
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/README.rdoc ADDED
@@ -0,0 +1,65 @@
1
+ = orientdb4r - Ruby binding for Orient DB
2
+
3
+ A Ruby client for the NoSQL Graph/Document database Orient DB (http://orientdb.org).
4
+
5
+ == USAGE
6
+
7
+ require 'orientdb4r'
8
+
9
+ CLASS = 'myclass'
10
+
11
+ client = Orientdb4r.client # equivalent for :host => 'localhost', :port => 2480, :ssl => false
12
+
13
+ client.connect :database => 'temp', :user => 'admin', :password => 'admin'
14
+
15
+
16
+ client.create_class(CLASS) do |c|
17
+ c.property 'prop1', :integer
18
+ c.property 'prop2', :string, :mandatory => true, :notnull => :true, :min => 1, :max => 99
19
+ end
20
+
21
+
22
+ 1.upto(10) { |i| client.command "INSERT INTO #{CLASS} (prop1, prop2) VALUES (#{i}, 'string#{i}')" }
23
+
24
+
25
+ puts client.query "SELECT FROM #{CLASS}"
26
+ > {"@type"=>"d", "@rid"=>"#6:0", "@version"=>0, "@class"=>"testing", "prop1"=>1, "prop2"=>"string1"}
27
+ > {"@type"=>"d", "@rid"=>"#6:1", "@version"=>0, "@class"=>"testing", "prop1"=>2, "prop2"=>"string2"}
28
+ > {"@type"=>"d", "@rid"=>"#6:2", "@version"=>0, "@class"=>"testing", "prop1"=>3, "prop2"=>"string3"}
29
+ > {"@type"=>"d", "@rid"=>"#6:3", "@version"=>0, "@class"=>"testing", "prop1"=>4, "prop2"=>"string4"}
30
+ > {"@type"=>"d", "@rid"=>"#6:4", "@version"=>0, "@class"=>"testing", "prop1"=>5, "prop2"=>"string5"}
31
+ > {"@type"=>"d", "@rid"=>"#6:5", "@version"=>0, "@class"=>"testing", "prop1"=>6, "prop2"=>"string6"}
32
+ > {"@type"=>"d", "@rid"=>"#6:6", "@version"=>0, "@class"=>"testing", "prop1"=>7, "prop2"=>"string7"}
33
+ > {"@type"=>"d", "@rid"=>"#6:7", "@version"=>0, "@class"=>"testing", "prop1"=>8, "prop2"=>"string8"}
34
+ > {"@type"=>"d", "@rid"=>"#6:8", "@version"=>0, "@class"=>"testing", "prop1"=>9, "prop2"=>"string9"}
35
+ > {"@type"=>"d", "@rid"=>"#6:9", "@version"=>0, "@class"=>"testing", "prop1"=>10, "prop2"=>"string10"}
36
+ puts client.query "SELECT count(*) FROM #{CLASS}"
37
+ > {"@type"=>"d", "@version"=>0, "count"=>10, "@fieldTypes"=>"count=l"}
38
+ puts client.query "SELECT max(prop1) FROM #{CLASS}"
39
+ > {"@type"=>"d", "@version"=>0, "max"=>10}
40
+ puts client.query "SELECT FROM #{CLASS} WHERE prop2 LIKE '%10'"
41
+ > {"@type"=>"d", "@rid"=>"#6:9", "@version"=>0, "@class"=>"testing", "prop1"=>10, "prop2"=>"string10"}
42
+
43
+
44
+ client.drop_class CLASS
45
+ client.disconnect
46
+
47
+ == FEATURES/PROBLEMS
48
+
49
+ * Supports only REST API right now
50
+
51
+ == REQUIREMENTS
52
+
53
+ Tested on
54
+ * Ruby 1.9.3
55
+ * OrientDB 1.0.0
56
+
57
+ == AUTHOR
58
+
59
+ * vaclav.sykora@gmail.com
60
+ * https://plus.google.com/115674031373998885915
61
+
62
+ == LICENSE
63
+
64
+ * Apache License, Version 2.0, http://www.apache.org/licenses/
65
+ * see LICENSE file for more details...
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ require 'rake/testtask'
2
+
3
+ Rake::TestTask.new do |t|
4
+ t.libs << 'test'
5
+ end
6
+
7
+ desc "Run tests"
8
+ task :default => :test
@@ -0,0 +1,130 @@
1
+ module Orientdb4r
2
+
3
+ class Client
4
+ include Utils
5
+
6
+ ###
7
+ # Constructor.
8
+ def initialize
9
+ @connected = false
10
+ end
11
+
12
+ ###
13
+ # Connects client to the server.
14
+ def connect options
15
+ raise NotImplementedError, 'this should be overridden by concrete client'
16
+ end
17
+
18
+ ###
19
+ # Disconnects client from the server.
20
+ def disconnect
21
+ raise NotImplementedError, 'this should be overridden by concrete client'
22
+ end
23
+
24
+ ###
25
+ # Gets flag whenever the client is connected or not.
26
+ def connected?
27
+ @connected
28
+ end
29
+
30
+ ###
31
+ # Creates a new database.
32
+ # You can provide an additional authentication to the server with 'database.create' resource
33
+ # or the current one will be used.
34
+ def create_database(options)
35
+ raise NotImplementedError, 'this should be overridden by concrete client'
36
+ end
37
+
38
+ ###
39
+ # Gets informations about requested class.
40
+ def get_class(name)
41
+ raise NotImplementedError, 'this should be overridden by concrete client'
42
+ end
43
+
44
+ ###
45
+ # Executes a query against the database.
46
+ def query(sql)
47
+ raise NotImplementedError, 'this should be overridden by concrete client'
48
+ end
49
+
50
+ ###
51
+ # Executes a command against the database.
52
+ def command(sql, options={})
53
+ raise NotImplementedError, 'this should be overridden by concrete client'
54
+ end
55
+
56
+ ###
57
+ # Creates a new class in the schema.
58
+ def create_class(name, options={})
59
+ raise ArgumentError, "class name is blank" if blank?(name)
60
+ opt_pattern = { :extends => :optional , :cluster => :optional, :force => false }
61
+ verify_options(options, opt_pattern)
62
+
63
+ sql = "CREATE CLASS #{name}"
64
+ sql << " EXTENDS #{options[:extends]}" if options.include? :extends
65
+ sql << " CLUSTER #{options[:cluster]}" if options.include? :cluster
66
+
67
+ drop_class name if options[:force]
68
+
69
+ command sql, :http_code_500 => 'failed to create class (exists already, bad supperclass?)'
70
+
71
+ if block_given?
72
+ proxy = Orientdb4r::Utils::Proxy.new(self, name)
73
+ def proxy.property(property, type, options={})
74
+ self.target.send :create_property, self.context, property, type, options
75
+ end
76
+ yield proxy
77
+ end
78
+ end
79
+
80
+ ###
81
+ # Removes a class from the schema.
82
+ def drop_class(name)
83
+ # TODO in :mode=>:strict verify if the class is no a super class
84
+ raise ArgumentError, "class name is blank" if blank?(name)
85
+ command "DROP CLASS #{name}"
86
+ end
87
+
88
+ ###
89
+ # Creates a new property in the schema.
90
+ # You need to create the class before.
91
+ def create_property(clazz, property, type, options={})
92
+ raise ArgumentError, "class name is blank" if blank?(clazz)
93
+ raise ArgumentError, "property name is blank" if blank?(property)
94
+ opt_pattern = {
95
+ :mandatory => :optional , :notnull => :optional, :min => :optional, :max => :optional,
96
+ :regexp => :optional, :custom => :optional
97
+ }
98
+ verify_options(options, opt_pattern)
99
+
100
+ cmd = "CREATE PROPERTY #{clazz}.#{property} #{type.to_s}"
101
+ command cmd, :http_code_500 => 'failed to create property (exists already?)'
102
+
103
+ unless options.empty?
104
+ options.each do |k,v|
105
+ command "ALTER PROPERTY #{clazz}.#{property} #{k.to_s.upcase} #{v}"
106
+ end
107
+ end
108
+ end
109
+
110
+ protected
111
+
112
+ ###
113
+ # Asserts if the client is connected and raises an error if not.
114
+ def assert_connected
115
+ raise OrientdbError, "not connected" unless @connected
116
+ end
117
+
118
+ ###
119
+ # Around advice to meassure and print the method time.
120
+ def time_around(&block)
121
+ start = Time.now
122
+ rslt = block.call
123
+ Orientdb4r::DEFAULT_LOGGER.debug \
124
+ "#{aop_context[:class].name}##{aop_context[:method]}: elapsed time = #{Time.now - start} [s]"
125
+ rslt
126
+ end
127
+
128
+ end
129
+
130
+ end
@@ -0,0 +1,6 @@
1
+ module Orientdb4r
2
+
3
+ class Document
4
+ end
5
+
6
+ end
@@ -0,0 +1,165 @@
1
+ module Orientdb4r
2
+
3
+ class RestClient < Client
4
+ include Aop2
5
+
6
+ before [:query, :command, :get_class], :assert_connected
7
+ around [:query, :command], :time_around
8
+
9
+ attr_reader :host, :port, :ssl, :user, :password
10
+
11
+
12
+ def initialize(options) #:nodoc:
13
+ super()
14
+ options_pattern = { :host => 'localhost', :port => 2480, :ssl => false }
15
+ verify_and_sanitize_options(options, options_pattern)
16
+ @host = options[:host]
17
+ @port = options[:port]
18
+ @ssl = options[:ssl]
19
+ end
20
+
21
+
22
+ def connect(options) #:nodoc:
23
+ options_pattern = { :database => :mandatory, :user => :mandatory, :password => :mandatory }
24
+ verify_and_sanitize_options(options, options_pattern)
25
+ @database = options[:database]
26
+ @user = options[:user]
27
+ @password = options[:password]
28
+
29
+ @resource = ::RestClient::Resource.new(url, :user => user, :password => password)
30
+
31
+ begin
32
+ response = @resource["connect/#{@database}"].get
33
+ rslt = process_response(response, :mode => :strict)
34
+ @connected = true
35
+ rescue ::RestClient::Exception => e
36
+ @connected = false
37
+ raise process_error e, :http_code_401 => 'connect failed (bad credentials?)'
38
+ rescue Exception => e
39
+ Orientdb4r::DEFAULT_LOGGER.error e.message
40
+ Orientdb4r::DEFAULT_LOGGER.error e.backtrace.inspect
41
+ @connected = false
42
+ raise e
43
+ end
44
+ rslt
45
+ end
46
+
47
+
48
+ def disconnect #:nodoc:
49
+ return unless @connected
50
+
51
+ begin
52
+ response = @resource['disconnect'].get
53
+ rescue ::RestClient::Unauthorized
54
+ Orientdb4r::DEFAULT_LOGGER.warn '401 Unauthorized - bug in disconnect?'
55
+ ensure
56
+ @connected = false
57
+ end
58
+ end
59
+
60
+
61
+ def create_database(options) #:nodoc:
62
+ options_pattern = {
63
+ :database => :mandatory, :type => 'memory',
64
+ :user => :optional, :password => :optional, :ssl => false
65
+ }
66
+ verify_and_sanitize_options(options, options_pattern)
67
+
68
+ u = options.include?(:user) ? options[:user] : user
69
+ p = options.include?(:password) ? options[:password] : password
70
+ resource = ::RestClient::Resource.new(url, :user => u, :password => p)
71
+ begin
72
+ response = resource["database/#{options[:database]}/#{options[:type]}"].post ''
73
+ rescue ::RestClient::Exception => e
74
+ raise process_error e, \
75
+ :http_code_403 => 'forbidden operation (insufficient rights?)', \
76
+ :http_code_500 => 'failed to create database (exists already?)'
77
+
78
+ end
79
+ process_response(response)
80
+ end
81
+
82
+
83
+ def get_class(name) #:nodoc:
84
+ raise ArgumentError, "class name is blank" if blank?(name)
85
+
86
+ # there seems to be a bug in REST API, only data are returned
87
+ #response = @resource["class/#{@database}/#{name}"].get
88
+ #rslt = process_response(response)
89
+
90
+ # workaround - use metadate delivered by 'connect'
91
+ response = @resource["connect/#{@database}"].get
92
+ connect_info = process_response(response, :mode => :strict)
93
+ clazz = connect_info['classes'].select { |i| i['name'] == name }
94
+ raise ArgumentError, "class not found, name=#{name}" if 1 != clazz.size
95
+ clazz[0]
96
+ end
97
+
98
+ def query(sql) #:nodoc:
99
+ response = @resource["query/#{@database}/sql/#{URI.escape(sql)}"].get
100
+ rslt = process_response(response)
101
+ rslt['result']
102
+ end
103
+
104
+ def command(sql, options={}) #:nodoc:
105
+ begin
106
+ #puts "REQ #{sql}"
107
+ response = @resource["command/#{@database}/sql/#{URI.escape(sql)}"].post ''
108
+ rslt = process_response(response)
109
+ rslt
110
+ #puts "RESP #{response.code}"
111
+ rescue Exception => e
112
+ raise process_error e, options.select { |k,v| k.to_s.start_with? 'http_code' }
113
+ end
114
+ end
115
+
116
+ private
117
+
118
+ ###
119
+ # Gets URL of the REST interface.
120
+ def url
121
+ "http#{'s' if ssl}://#{host}:#{port}"
122
+ end
123
+
124
+ ###
125
+ # ==== options
126
+ # * strict
127
+ # * warning
128
+ def process_response(response, options={})
129
+ raise ArgumentError, 'response is null' if response.nil?
130
+
131
+ # raise problem if other code than 200
132
+ if options[:mode] == :strict and 200 != response.code
133
+ raise OrientdbError, "unexpeted return code, code=#{response.code}"
134
+ end
135
+ # log warning if other than 200 and raise problem if other code than 'Successful 2xx'
136
+ if options[:mode] == :warning
137
+ if 200 != response.code and 2 == (response.code / 100)
138
+ Orientdb4r::DEFAULT_LOGGER.warn "expected return code 200, but received #{response.code}"
139
+ elseif 200 != response.code
140
+ raise OrientdbError, "unexpeted return code, code=#{response.code}"
141
+ end
142
+ end
143
+
144
+ content_type = response.headers[:content_type]
145
+ content_type ||= 'text/plain'
146
+
147
+ rslt = case
148
+ when content_type.start_with?('text/plain')
149
+ response.body
150
+ when content_type.start_with?('application/json')
151
+ ::JSON.parse(response.body)
152
+ end
153
+
154
+ rslt
155
+ end
156
+
157
+ def process_error(error, messages={})
158
+ code = "http_code_#{error.http_code}".to_sym
159
+ msg = messages.include?(code) ? "#{messages[code]}, cause = " : ''
160
+ OrientdbError.new "#{msg}#{error.to_s}"
161
+ end
162
+
163
+ end
164
+
165
+ end
@@ -0,0 +1,173 @@
1
+ module Orientdb4r
2
+
3
+ module Utils
4
+
5
+ def verify_options(options, pattern)
6
+ # unknown key?
7
+ options.keys.each do |k|
8
+ raise ArgumentError, "unknow option: #{k}" unless pattern.keys.include? k
9
+ end
10
+ # missing mandatory option?
11
+ pattern.each do |k,v|
12
+ raise ArgumentError, "missing mandatory option: #{k}" if v == :mandatory and !options.keys.include? k
13
+ end
14
+ options
15
+ end
16
+
17
+ def verify_and_sanitize_options(options, pattern)
18
+ verify_options(options, pattern)
19
+
20
+ # set default values if missing in options
21
+ pattern.each do |k,v|
22
+ options[k] = v if !v.nil? and !options.keys.include? k
23
+ end
24
+ options
25
+ end
26
+
27
+
28
+ ###
29
+ # Checks if a given string is either 'nil' or empty string.
30
+ def blank?(str)
31
+ str.nil? or str.strip.empty?
32
+ end
33
+
34
+ ###
35
+ # Generates a random string with given length.
36
+ def random_string(len=8)
37
+ (0...len).map{65.+(rand(25)).chr}.join
38
+ end
39
+
40
+
41
+ class Proxy
42
+
43
+ attr_reader :target, :context
44
+
45
+ def initialize(target, context)
46
+ @target = target
47
+ @context = context
48
+ end
49
+
50
+ def proxy(&block)
51
+ block.call
52
+ end
53
+
54
+ end
55
+
56
+ end
57
+
58
+
59
+ # TODO extend it to work with already defined methods ('before :foo, :baz' after method definition)
60
+ module Aop2
61
+
62
+ def self.included(base)
63
+ base.extend ClassMethods2
64
+ base.init_aop_extension
65
+ end
66
+
67
+ def aop_context
68
+ Thread.current[:aop2_context]
69
+ end
70
+ def aop_context=(ctx={})
71
+ Thread.current[:aop2_context] = ctx
72
+ end
73
+
74
+ module ClassMethods2
75
+
76
+ def init_aop_extension
77
+ @hooks = {}
78
+ [:before, :after, :around].each { |where| @hooks[where] = Hash.new { |hash, key| hash[key] = [] }}
79
+ # will be like this:
80
+ # {:before=>{:disconnect=>[:assert_connected], :query=>[:assert_connected], :command=>[:assert_connected]}, :after=>{}, :around=>{}}
81
+ class << self
82
+ attr_reader :hooks
83
+ end
84
+ @@redefining = false # flag whether the process of method redefining is running
85
+ end
86
+ def method_added(method)
87
+ unless @@redefining # avoid recursion
88
+ redefine_method(method) if is_hooked?(method)
89
+ end
90
+ end
91
+
92
+ #----------------------------------------------------------------- Helpers
93
+
94
+ def is_hooked?(method)
95
+ # look into array of keys (method names) in 2nd level hashs (see above)
96
+ hooks.values.map(&:keys).flatten.uniq.include? method
97
+ end
98
+
99
+
100
+
101
+ def before(original_method, *hooks)
102
+ add_hook(:before, original_method, *hooks)
103
+ end
104
+ def after(original_method, *hooks)
105
+ add_hook(:after, original_method, *hooks)
106
+ end
107
+ def around(original_method, *hooks)
108
+ add_hook(:around, original_method, *hooks)
109
+ end
110
+
111
+
112
+ def add_hook(type, original_method, *hooks) #!!
113
+ Array(original_method).each do |method|
114
+ store_hook(type, method, *hooks)
115
+ end
116
+ end
117
+ def store_hook(type, method_name, *hook_methods) #!!
118
+ hooks[type.to_sym][method_name.to_sym] += hook_methods.flatten.map(&:to_sym)
119
+ end
120
+
121
+ def redefine_method(orig_method)
122
+ @@redefining = true
123
+
124
+ arity = instance_method(orig_method.to_sym).arity
125
+ params = ''
126
+ fixed_cnt = arity.abs
127
+ fixed_cnt -= 1 if arity < 0
128
+ # build up a list of params
129
+ 1.upto(fixed_cnt).each {|x| params << "p#{x},"}
130
+ params << "*argv" if arity < 0
131
+ params.gsub!(/,$/, '') # remove last ','
132
+
133
+ alias_method "#{orig_method}_aop2_orig".to_sym, orig_method.to_sym
134
+
135
+ class_eval <<-FILTER,__FILE__,__LINE__ + 1
136
+ def #{orig_method}(#{params})
137
+ self.aop_context = { :method => '#{orig_method}', :class => self.class }
138
+ begin
139
+ self.class.invoke_hooks(self, :before, :#{orig_method})
140
+ rslt = self.class.invoke_arround_hooks(self, :#{orig_method}, self.class.hooks[:around][:#{orig_method}].clone) {
141
+ #{orig_method}_aop2_orig(#{params})
142
+ }
143
+ self.class.invoke_hooks(self, :after, :#{orig_method})
144
+ # rescue Exception => e
145
+ # # TODO use logging
146
+ # $stderr.puts '' << e.class.name << ': ' << e.message
147
+ # $stderr.puts e.backtrace.inspect
148
+ # raise e
149
+ ensure
150
+ self.aop_context = nil
151
+ end
152
+ rslt
153
+ end
154
+ FILTER
155
+
156
+ @@redefining = false
157
+ end
158
+
159
+ def invoke_hooks(obj, hook_type, method_name)
160
+ hooks[hook_type][method_name.to_sym].each { |hook| obj.send hook }
161
+ end
162
+ def invoke_arround_hooks(obj, method_name, hooks, &block)
163
+ hook = hooks.slice! 0
164
+ return block.call if hook.nil? # call original method if no more hook
165
+
166
+ # invoke the hook with lambda containing recursion
167
+ obj.send(hook.to_sym) { invoke_arround_hooks(obj, method_name, hooks, &block); }
168
+ end
169
+
170
+ end # ClassMethods2
171
+ end # Aop2
172
+
173
+ end
@@ -0,0 +1,12 @@
1
+ module Orientdb4r
2
+
3
+ # Version history.
4
+ VERSION_HISTORY = [
5
+ ['0.1.1', '2012-06-08', 'First working version (including unit tests)'],
6
+ ['0.1.0', '2012-06-02', 'Initial version on Ruby-1.9.3p194 and OrientDB-1.0.0']
7
+ ]
8
+
9
+ # Current version.
10
+ VERSION = VERSION_HISTORY[0][0]
11
+
12
+ end
data/lib/orientdb4r.rb ADDED
@@ -0,0 +1,46 @@
1
+ require 'json'
2
+ require 'rest_client'
3
+ require 'logger'
4
+ require 'orientdb4r/version'
5
+
6
+
7
+ ###
8
+ # This module represents the entry point for using the Ruby OrientDB client.
9
+ module Orientdb4r
10
+
11
+ autoload :Utils, 'orientdb4r/utils'
12
+ autoload :Client, 'orientdb4r/client'
13
+ autoload :RestClient, 'orientdb4r/rest/client'
14
+
15
+
16
+ # Configuration of logging.
17
+ DEFAULT_LOGGER = Logger.new(STDOUT)
18
+ DEFAULT_LOGGER.level = Logger::INFO
19
+
20
+
21
+ class << self
22
+
23
+ ###
24
+ # Gets a new database client or an existing for the current thread.
25
+ def client options={}
26
+ Thread.current[:orientdb_client] ||= RestClient.new options
27
+ end
28
+
29
+ ###
30
+ # All calls to REST API will use the proxy specified here.
31
+ def rest_proxy(url)
32
+ RestClient.proxy = url
33
+ end
34
+
35
+ end
36
+
37
+
38
+ ###
39
+ # Basic error raised to signal an unexpected situation.
40
+ class OrientdbError < StandardError; end
41
+
42
+ end
43
+
44
+
45
+ Orientdb4r::DEFAULT_LOGGER.info \
46
+ "Orientdb4r #{Orientdb4r::VERSION}, running on Ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE}) [#{RUBY_PLATFORM}]"
@@ -0,0 +1,35 @@
1
+ # -*- encoding: utf-8 -*-
2
+
3
+ $:.unshift File.expand_path('../lib', __FILE__)
4
+ require 'orientdb4r/version'
5
+
6
+ Gem::Specification.new do |s|
7
+
8
+ s.name = %q{orientdb4r}
9
+ s.version = Orientdb4r::VERSION
10
+
11
+ s.required_rubygems_version = Gem::Requirement.new('> 1.3.1') if s.respond_to? :required_rubygems_version=
12
+ s.authors = ['Vaclav Sykora']
13
+ s.date = Orientdb4r::VERSION_HISTORY[0][1]
14
+ s.description = %q{Orientdb4r provides a simple interface on top of OrientDB's RESTful HTTP API.}
15
+ s.email = %q{vaclav.sykora@gmail.com}
16
+
17
+ s.files = `git ls-files`.split("\n")
18
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
19
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
20
+ s.require_paths = ["lib"]
21
+
22
+ s.extra_rdoc_files = [
23
+ "LICENSE",
24
+ "README.rdoc"
25
+ ]
26
+ s.homepage = %q{http://github.com/veny/orientdb4r}
27
+ s.rdoc_options = ['--charset=UTF-8']
28
+ s.require_paths = ['lib']
29
+ s.rubygems_version = %q{1.3.7}
30
+ s.summary = %q{Ruby binding for Orient DB.}
31
+
32
+ s.add_dependency(%q<rest-client>, ["~> 1.6.7"])
33
+ # s.add_development_dependency(%q<json>, ["~> 1.5.1"])
34
+
35
+ end
@@ -0,0 +1,66 @@
1
+ require 'test/unit'
2
+ require 'orientdb4r'
3
+
4
+ ###
5
+ # This class tests following operations:
6
+ # * CONNECT
7
+ # * DISCONNECT
8
+ # * CREATE DATABASE
9
+ class TestDatabase < Test::Unit::TestCase
10
+
11
+ Orientdb4r::DEFAULT_LOGGER.level = Logger::DEBUG
12
+
13
+ def setup
14
+ @client = Orientdb4r.client
15
+ end
16
+
17
+ ###
18
+ # CONNECT
19
+ def test_connect
20
+ rslt = @client.connect :database => 'temp', :user => 'admin', :password => 'admin'
21
+ assert_instance_of Hash, rslt
22
+ assert rslt.size > 0
23
+ assert rslt.include? 'classes'
24
+
25
+ # bad DB name
26
+ assert_raise Orientdb4r::OrientdbError do
27
+ @client.connect :database => 'unknown_db', :user => 'admin', :password => 'admin'
28
+ end
29
+ # bad credentials
30
+ assert_raise Orientdb4r::OrientdbError do
31
+ @client.connect :database => 'temp', :user => 'admin1', :password => 'admin'
32
+ end
33
+ end
34
+
35
+
36
+ ###
37
+ # DISCONNECT
38
+ def test_disconnect
39
+ @client.disconnect
40
+ assert !@client.connected?
41
+ # unable to query after disconnect
42
+ assert_raise Orientdb4r::OrientdbError do @client.query 'SELECT FROM OUser'; end
43
+ end
44
+
45
+
46
+ ###
47
+ # CREATE DATABASE
48
+ # Temporary disabled bacause of unknown way how to drop a new created datatabse.
49
+ def xtest_create_database
50
+ @client.create_database :database => 'UniT', :user => 'root', :password => 'root'
51
+ # creating an existing DB
52
+ assert_raise Orientdb4r::OrientdbError do
53
+ @client.create_database :database => 'UniT', :user => 'root', :password => 'root'
54
+ end
55
+ # insufficient rights
56
+ assert_raise Orientdb4r::OrientdbError do
57
+ @client.create_database :database => 'UniT1', :user => 'admin', :password => 'admin'
58
+ end
59
+
60
+ # By convention 3 users are always created by default every time you create a new database.
61
+ # Default users are: admin, reader, writer
62
+ @client.connect :database => 'UniT', :user => 'admin', :password => 'admin'
63
+ #@client.command "DROP DATABASE UniT" : NOT WORKING now
64
+ end
65
+
66
+ end
data/test/test_ddo.rb ADDED
@@ -0,0 +1,121 @@
1
+ require 'test/unit'
2
+ require 'orientdb4r'
3
+
4
+ ###
5
+ # This class tests Data Definition Operarions.
6
+ class TestDdo < Test::Unit::TestCase
7
+
8
+ CLASS = 'testing'
9
+ DB = 'temp'
10
+ Orientdb4r::DEFAULT_LOGGER.level = Logger::DEBUG
11
+
12
+ def initialize(params)
13
+ super params
14
+
15
+ @client = Orientdb4r.client
16
+ end
17
+
18
+ def setup
19
+ @client.connect :database => DB, :user => 'admin', :password => 'admin'
20
+ end
21
+
22
+ def teardown
23
+ # remove the testing class after each test
24
+ @client.drop_class(CLASS)
25
+ @client.disconnect
26
+ end
27
+
28
+
29
+ ###
30
+ # GET - Class
31
+ def test_get_class
32
+ ouser = {}
33
+ assert_nothing_thrown do ouser = @client.get_class 'OUser'; end
34
+ assert_equal 'OUser', ouser['name']
35
+ # class does not exist
36
+ assert_raise ArgumentError do @client.get_class 'OUserXXX'; end
37
+ end
38
+
39
+
40
+ ###
41
+ # CREATE TABLE
42
+ def test_create_class
43
+ assert_nothing_thrown do @client.create_class(CLASS); end
44
+ assert_nothing_thrown do @client.get_class(CLASS); end
45
+ # already exist
46
+ assert_raise Orientdb4r::OrientdbError do @client.create_class(CLASS); end
47
+
48
+ # create with :force=>true
49
+ assert_nothing_thrown do @client.create_class(CLASS, :force => true); end
50
+ assert_nothing_thrown do @client.get_class(CLASS); end
51
+ end
52
+
53
+
54
+ ###
55
+ # CREATE TABLE ... EXTENDS
56
+ def test_create_class_extends
57
+ assert_nothing_thrown do @client.create_class(CLASS, :extends => 'OUser'); end
58
+ assert_nothing_thrown do @client.get_class(CLASS); end
59
+
60
+ # bad super class
61
+ assert_raise Orientdb4r::OrientdbError do @client.create_class(CLASS, :extends => 'nonExistingSuperClass'); end
62
+ end
63
+
64
+
65
+ ###
66
+ # DROP TABLE
67
+ def test_drop_table
68
+ assert_nothing_thrown do @client.drop_class(CLASS); end
69
+
70
+ # the class is not visible in class list delivered by connect
71
+ rslt = @client.connect :database => DB, :user => 'admin', :password => 'admin'
72
+ assert rslt['classes'].select { |i| i['name'] == CLASS }.empty?
73
+ end
74
+
75
+
76
+ ###
77
+ # CREATE PROPERTY
78
+ def test_create_property
79
+ @client.create_class(CLASS)
80
+ assert_nothing_thrown do @client.create_property(CLASS, 'prop1', :integer); end
81
+ clazz = @client.get_class(CLASS)
82
+ assert clazz.include? 'properties'
83
+ assert_instance_of Array, clazz['properties']
84
+ props = clazz['properties'].select { |i| i['name'] == 'prop1' }
85
+ assert_equal 1, props.size
86
+ assert_equal 'INTEGER', props[0]['type']
87
+
88
+ # already exist
89
+ assert_raise Orientdb4r::OrientdbError do @client.create_property(CLASS, 'prop1', :integer); end
90
+ end
91
+
92
+
93
+ ###
94
+ # CREATE CLASS + PROPERTY
95
+ def test_create_class_with_properties
96
+ assert_nothing_thrown do
97
+ @client.create_class(CLASS) do |c|
98
+ c.property 'prop1', :integer
99
+ c.property 'prop2', :string, :mandatory => true, :notnull => :true, :min => 1, :max => 99
100
+ end
101
+ end
102
+
103
+ clazz = @client.get_class(CLASS)
104
+ assert_equal 2, clazz['properties'].size
105
+
106
+ prop1 = clazz['properties'].select { |i| i['name'] == 'prop1' }[0]
107
+ assert_equal 'INTEGER', prop1['type']
108
+ assert !prop1['mandatory']
109
+ assert !prop1['notNull']
110
+ assert prop1['min'].nil?
111
+ assert prop1['max'].nil?
112
+
113
+ prop2 = clazz['properties'].select { |i| i['name'] == 'prop2' }[0]
114
+ assert_equal 'STRING', prop2['type']
115
+ assert prop2['mandatory']
116
+ assert prop2['notNull']
117
+ assert_equal '1', prop2['min']
118
+ assert_equal '99', prop2['max']
119
+ end
120
+
121
+ end
data/test/test_dmo.rb ADDED
@@ -0,0 +1,53 @@
1
+ require 'test/unit'
2
+ require 'orientdb4r'
3
+
4
+ ###
5
+ # This class tests Data Manipulation Operarions.
6
+ class TestDmo < Test::Unit::TestCase
7
+ include Orientdb4r::Utils
8
+
9
+ CLASS = 'testing'
10
+ DB = 'temp'
11
+ Orientdb4r::DEFAULT_LOGGER.level = Logger::DEBUG
12
+
13
+
14
+ def setup
15
+ @client = Orientdb4r.client
16
+ @client.connect :database => DB, :user => 'admin', :password => 'admin'
17
+ @client.create_class(CLASS) do |c|
18
+ c.property 'prop1', :integer
19
+ c.property 'prop2', :string, :mandatory => true, :notnull => :true, :min => 1, :max => 99
20
+ end
21
+ end
22
+
23
+ def teardown
24
+ # remove the testing class after each test
25
+ @client.drop_class(CLASS)
26
+ @client.disconnect
27
+ end
28
+
29
+
30
+ ###
31
+ # INSERT INTO
32
+ def test_insert
33
+ assert_nothing_thrown do
34
+ 1.upto(10) do |i|
35
+ @client.command "INSERT INTO #{CLASS} (prop1, prop2) VALUES (#{i}, '#{random_string}')"
36
+ end
37
+ end
38
+
39
+ assert_equal 10, @client.query("SELECT count(*) FROM #{CLASS}")[0]['count'].to_i
40
+ end
41
+
42
+
43
+ ###
44
+ # SELECT
45
+ def test_query
46
+ 1.upto(10) do |i|
47
+ @client.command "INSERT INTO #{CLASS} (prop1, prop2) VALUES (#{i}, 'string#{i}')"
48
+ end
49
+
50
+ puts @client.query("SELECT FROM #{CLASS}")
51
+ end
52
+
53
+ end
metadata ADDED
@@ -0,0 +1,81 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: orientdb4r
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Vaclav Sykora
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-06-08 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: rest-client
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ~>
20
+ - !ruby/object:Gem::Version
21
+ version: 1.6.7
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ~>
28
+ - !ruby/object:Gem::Version
29
+ version: 1.6.7
30
+ description: Orientdb4r provides a simple interface on top of OrientDB's RESTful HTTP
31
+ API.
32
+ email: vaclav.sykora@gmail.com
33
+ executables: []
34
+ extensions: []
35
+ extra_rdoc_files:
36
+ - LICENSE
37
+ - README.rdoc
38
+ files:
39
+ - .gitignore
40
+ - LICENSE
41
+ - README.rdoc
42
+ - Rakefile
43
+ - lib/orientdb4r.rb
44
+ - lib/orientdb4r/client.rb
45
+ - lib/orientdb4r/document.rb
46
+ - lib/orientdb4r/rest/client.rb
47
+ - lib/orientdb4r/utils.rb
48
+ - lib/orientdb4r/version.rb
49
+ - orientdb4r.gemspec
50
+ - test/test_database.rb
51
+ - test/test_ddo.rb
52
+ - test/test_dmo.rb
53
+ homepage: http://github.com/veny/orientdb4r
54
+ licenses: []
55
+ post_install_message:
56
+ rdoc_options:
57
+ - --charset=UTF-8
58
+ require_paths:
59
+ - lib
60
+ required_ruby_version: !ruby/object:Gem::Requirement
61
+ none: false
62
+ requirements:
63
+ - - ! '>='
64
+ - !ruby/object:Gem::Version
65
+ version: '0'
66
+ required_rubygems_version: !ruby/object:Gem::Requirement
67
+ none: false
68
+ requirements:
69
+ - - ! '>'
70
+ - !ruby/object:Gem::Version
71
+ version: 1.3.1
72
+ requirements: []
73
+ rubyforge_project:
74
+ rubygems_version: 1.8.19
75
+ signing_key:
76
+ specification_version: 3
77
+ summary: Ruby binding for Orient DB.
78
+ test_files:
79
+ - test/test_database.rb
80
+ - test/test_ddo.rb
81
+ - test/test_dmo.rb