yaml_conditions 0.0.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,34 @@
1
+ Manifest
2
+ README.rdoc
3
+ Rakefile
4
+ TESTS.rdoc
5
+ bin/console.sh
6
+ init.rb
7
+ lib/orms/active_record.rb
8
+ lib/orms/active_record/version2/delayed_job.rb
9
+ lib/orms/active_record/version_2.rb
10
+ lib/orms/active_record/version_3.rb
11
+ lib/orms/datamapper.rb
12
+ lib/yaml/conditions.rb
13
+ lib/yaml/query_builder.rb
14
+ lib/yaml/query_builder/sql/mysql.rb
15
+ lib/yaml/query_builder/sql/postgresql.rb
16
+ lib/yaml_conditions.rb
17
+ out.txt
18
+ spec/ar_spec_helper.rb
19
+ spec/cases/orms/active_record/version_2_delayed_job_spec.rb
20
+ spec/cases/orms/active_record/version_2_spec.rb
21
+ spec/connections/mysql/connection.rb
22
+ spec/connections/postgresql/connection.rb
23
+ spec/datamapper_spec_helper.rb
24
+ spec/models/delayed/job.rb
25
+ spec/models/delayed/performable_method.rb
26
+ spec/models/job.rb
27
+ spec/models/period.rb
28
+ spec/models/priority.rb
29
+ spec/models/user.rb
30
+ spec/models/user_data.rb
31
+ spec/schema.rb
32
+ spec/spec_helper.rb
33
+ tasks/yaml_conditions.rake
34
+ yaml_conditions.gemspec
@@ -0,0 +1,66 @@
1
+ = yaml_conditions
2
+
3
+ This is a tool for allowing queries based on serialized objects (via YAML) on relational databases (currently MySQL and Postrgres are supported).
4
+
5
+ == Frameworks supported
6
+
7
+ The idea is to support multiple ORMs. Currently we are only supporting ActiveRecord (version 2.x). We are working on extending support for ActiveRecord version 3.x, and then working on the integration with Datamapper.
8
+
9
+ == Usage (for ActiveRecord 2.x only for now)
10
+
11
+ Basically, we extend AR#find to allow a new option :yaml_conditions. If :yaml_contitions is not present, #find will behave exactly as it used to.
12
+
13
+ yaml_conditions parameter expects a Hash with all the key/values you want to filter the serialized object.
14
+
15
+ Below I summarized some samples so you can see how I use it.
16
+
17
+ Company.find(:all, :yaml_conditions => { :address => { :street => '5551 LEOPARD ST' } })
18
+
19
+ Company.find(:all, :yaml_conditions => { :status => :active })
20
+
21
+ Company.find(:first, :yaml_conditions => { :data => { { :street => '5551 LEOPARD ST' }, :status => :active } })
22
+
23
+ Company.find(:first, :yaml_conditions => { :data => { :owner => { :class => User, :name => 'Marcelo' } } })
24
+
25
+ Company.find(:first, :yaml_conditions => { :data => { { :street => '5551 LEOPARD ST' }, :status => :active }, :conditions => [ 'branches_counter > ?', 3] )
26
+
27
+ As you can see from the last sample, both yaml_conditions and conditions will be merged in order to find the expected results.
28
+
29
+ Company.find(:last, :yaml_conditions => { :data => { :user => { :last_name => 'Marcelo', :address => { :city => Yaml::NotSerializedField.new('Rio Negro') } } } })
30
+
31
+ On this last sample, the city attribute can be traversed on memory but it is not saved on the serialized field (i.e. handler), so we want to indicate that to avoid building an invalid SQL.
32
+
33
+ BTW: All methods ActiveRecord::Base#{last, first, all} rely on ActiveRecord::Base#find, so we can use yaml_conditions with these methods too. As an example:
34
+ Company.all(:yaml_conditions => { :data => { :address => { :street => '5551 LEAOPARD ST' } } }) behaves the same way as the first sample explained below.
35
+
36
+ == delayed_job
37
+
38
+ Just to give you a little background, I build this gem/plugin just to filter my YAML objects created via delayed_job plugin ;)
39
+
40
+ So, I added some custom magic for filtering Delayed::Job objects, like this:
41
+
42
+ Delayed::Job.first(:yaml_conditions => { :class => NotificationMailer, :handler => { :method => :new_registration, :args => [ User.find(1), '*', '*' ] } })
43
+
44
+ Delayed::Job.first(:yaml_conditions => { :handler => { :args => [ { :user => { :last_name => 'Marcelo', :address => { :city => 'Rio Negro' } } } ] } })
45
+
46
+ As you probably realize, '*' is interpreted (for Delayed::Job instances) as a wildcard.
47
+
48
+ == Installation
49
+
50
+ $ ruby script/plugin install git://github.com/marklazz/yaml_conditions.git)
51
+
52
+ OR install it as a gem
53
+
54
+ $ [sudo] gem install yaml_conditions
55
+
56
+ Enjoy!
57
+
58
+ == License
59
+
60
+ Copyright (c) 2010 Marcelo Giorgi
61
+
62
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
63
+
64
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
65
+
66
+ 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.
@@ -0,0 +1,16 @@
1
+ require 'rubygems'
2
+ require 'echoe'
3
+
4
+ # PACKAGING ============================================================
5
+
6
+ Echoe.new('yaml_conditions', '0.0.0.1') do |p|
7
+ p.description = ''
8
+ p.url = 'http://github.com/marklazz/yaml_conditions'
9
+ p.author = 'Marcelo Giorgi'
10
+ p.email = 'marklazz.uy@gmail.com'
11
+ p.ignore_pattern = [ 'tmp/*', 'script/*', '*.sh' ]
12
+ p.runtime_dependencies = []
13
+ p.development_dependencies = [ 'spec' ]
14
+ end
15
+
16
+ Dir["#{File.dirname(__FILE__)}/tasks/*.rake"].sort.each { |ext| load ext }
@@ -0,0 +1,12 @@
1
+ Before running the tests you should create a user yaml_conditions for mysql (and for postgresql too if you want to run them there).
2
+
3
+ Then to run the suite you should be able to do:
4
+
5
+ rake spec (which will run both suites for mysql and postgres)
6
+
7
+ Or run them individually:
8
+
9
+ rake mysql:spec
10
+ rake postgres:spec
11
+
12
+ Enjoy!
@@ -0,0 +1,2 @@
1
+ #!/bin/bash
2
+ irb -r /home/marcelo/workspace/yaml_conditions/lib/yaml_conditions.rb
data/init.rb ADDED
@@ -0,0 +1 @@
1
+ require File.dirname(__FILE__) + '/lib/yaml_conditions'
@@ -0,0 +1,8 @@
1
+ require 'active_record'
2
+ require(File.join(File.dirname(__FILE__), 'active_record', 'version2', 'delayed_job'))
3
+
4
+ if ::ActiveRecord::VERSION::MAJOR == 2
5
+ require File.join(File.dirname(__FILE__), 'active_record', 'version_2')
6
+ elsif ::ActiveRecord::VERSION::MAJOR == 3
7
+ require File.join(File.dirname(__FILE__), 'active_record', 'version_3')
8
+ end
@@ -0,0 +1,44 @@
1
+ module Orms
2
+ module ActiveRecordVersion2
3
+ module DelayedJob
4
+
5
+ def self.included(base)
6
+ base.send(:include, InstanceMethods)
7
+ base.extend(ClassMethods)
8
+ end
9
+
10
+ module InstanceMethods
11
+ end
12
+
13
+ module ClassMethods
14
+
15
+ CLASS_STRING_FORMAT = /^CLASS\:([A-Z][\w\:]+)$/
16
+ AR_STRING_FORMAT = /^AR\:([A-Z][\w\:]+)\:(\d+)$/
17
+
18
+ def __delayed_job_ar_to_string_(obj)
19
+ "AR:#{obj.class}:#{obj.id}"
20
+ end
21
+
22
+ def __delayed_job_class_to_string_(obj)
23
+ "CLASS:#{obj.name}"
24
+ end
25
+
26
+ def __serialize__to_yaml_value__(arg)
27
+ case arg
28
+ when Class then __delayed_job_class_to_string_(arg)
29
+ when ActiveRecord::Base then __delayed_job_ar_to_string_(arg)
30
+ else super(arg)
31
+ end
32
+ end
33
+
34
+ def __yaml_load_object_recursively__(arg)
35
+ case arg
36
+ when CLASS_STRING_FORMAT then $1.constantize
37
+ when AR_STRING_FORMAT then $1.constantize.find($2)
38
+ else super(arg)
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,45 @@
1
+ module Orms
2
+ module ActiveRecordVersion2
3
+
4
+ include Yaml::Conditions
5
+ include Yaml::QueryBuilder
6
+
7
+ def __include_delayedjob_adapter_if_necessary__
8
+ self.send(:include, ::Orms::ActiveRecordVersion2::DelayedJob)
9
+ @delayed_adapter_included = true
10
+ end
11
+
12
+ def find_with_yaml_conditions(*args)
13
+ options = args.last.is_a?(::Hash) ? args.last : {}
14
+ yaml_conditions = options[:yaml_conditions]
15
+ return find_without_yaml_conditions(*args) if yaml_conditions.blank?
16
+ __include_db_adapter_if_necessary__ if @db_adapter_included.nil?
17
+ __include_delayedjob_adapter_if_necessary__ if defined?(Delayed::Job) && self == Delayed::Job && @delayed_adapter_included.nil?
18
+ options = args.extract_options!
19
+ adapted_args = args << refactor_options(options)
20
+ selector = adapted_args.shift
21
+ result = find_without_yaml_conditions(:all, *adapted_args).select do |o|
22
+ __check_yaml_nested_hierarchy__(o, yaml_conditions)
23
+ end
24
+ selector == :all ? result : result.send(selector.to_sym)
25
+ end
26
+
27
+ def refactor_options(options)
28
+ sql_conditions = sanitize_sql(options.delete(:conditions))
29
+ yaml_conditions = options.delete(:yaml_conditions)
30
+ yaml_conditions.symbolize_keys! if yaml_conditions.is_a?(Hash)
31
+ options.merge!({ :conditions => __join_yaml_conditions__(sql_conditions, __build_yaml_conditions__(yaml_conditions)) })
32
+ end
33
+ end
34
+ end
35
+
36
+ module ActiveRecord
37
+ class Base
38
+ class << self
39
+ include Orms::ActiveRecordVersion2
40
+
41
+ alias_method :find_without_yaml_conditions, :find
42
+ alias_method :find, :find_with_yaml_conditions
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,7 @@
1
+ module Orms
2
+ module ActiveRecord
3
+
4
+ def where(*args, &blk)
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,4 @@
1
+ module Orms
2
+ class Datamapper
3
+ end
4
+ end
@@ -0,0 +1,19 @@
1
+ module Yaml
2
+ module Conditions
3
+ extend self
4
+ ParseObjectFromYaml = /\!ruby\/\w+\:([^\s]+)/
5
+
6
+ VERSION = '0.0.1'
7
+ end
8
+
9
+ class NotSerializedField
10
+
11
+ def initialize(value)
12
+ @value = value
13
+ end
14
+
15
+ def ==(v)
16
+ @value == v
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,150 @@
1
+ module Yaml
2
+ module QueryBuilder
3
+
4
+ def __include_db_adapter_if_necessary__
5
+ adapter_name = self.connection.adapter_name
6
+ adapter_capitalized = adapter_name.upcase[0].chr + adapter_name.downcase[1..-1]
7
+ adapter_module = ::Yaml::QueryBuilder::Sql.const_get("#{adapter_capitalized}Adapter".to_sym)
8
+ self.send(:include, adapter_module)
9
+ @db_adapter_included = true
10
+ end
11
+
12
+ def __build_yaml_conditions__(yaml_conditions)
13
+ yaml_conditions.inject("") do |conditions, (serialized_field,v)|
14
+ __join_yaml_conditions__(conditions, __build_yaml_attributes__(serialized_field, v))
15
+ end
16
+ end
17
+
18
+ def __serialize__to_yaml_value__(v)
19
+ return '' if v.nil?
20
+ v_s = v.to_s
21
+ v_s == '*' ? "" : v_s
22
+ end
23
+
24
+ def __build_yaml_conditions_for_list__(field, k,v)
25
+ v.map { |item| __resolve_yaml_conditions_by_structure__(field, k, item, true) }.join('AND ')
26
+ end
27
+
28
+
29
+ def __build_individual_yaml_conditions__(field, k,v, skip_key = false)
30
+ return "1 = 1" if v.is_a?(Yaml::NotSerializedField)
31
+ key_s = skip_key ? '' : "#{k}: "
32
+ "#{field} LIKE '%#{key_s}#{v.is_a?(Symbol) ? ':' + v.to_s : __serialize__to_yaml_value__(v)}%' "
33
+ end
34
+
35
+ def __resolve_yaml_conditions_by_structure__(field, k, v, skip_key = false)
36
+ if v.is_a?(Hash)
37
+ __build_yaml_attributes__(field, v, skip_key)
38
+ elsif v.is_a?(Array)
39
+ __build_yaml_conditions_for_list__(field, k, v)
40
+ else
41
+ __build_individual_yaml_conditions__(field, k, v, skip_key)
42
+ end
43
+ end
44
+
45
+ def __build_yaml_attributes__(field, yaml_conditions, skip_key = false)
46
+ current_conditions = ''
47
+ __filter_yaml_attributes_to_check_on__(yaml_conditions).each do |k,v|
48
+ conditions = __resolve_yaml_conditions_by_structure__(field, k, v, skip_key)
49
+ current_conditions = __join_yaml_conditions__(current_conditions, conditions)
50
+ end
51
+ current_conditions
52
+ end
53
+
54
+ def __check_yaml_nested_hierarchy_on_list__(value, yaml_conditions)
55
+ return false if !value.is_a?(Array) || value.length != yaml_conditions.length
56
+ yaml_conditions.zip(value).inject(true) do |result, (cond, nested_value)|
57
+ result &= __check_yaml_nested_hierarchy__(nested_value, cond)
58
+ end
59
+ end
60
+
61
+ def __check_yaml_nested_hierarchy__(value, yaml_conditions)
62
+ return true if value.nil? && yaml_conditions.nil? || yaml_conditions == '*'
63
+ return false if value.nil? || yaml_conditions.nil?
64
+ unless yaml_conditions.is_a?(Hash) || yaml_conditions.is_a?(Array)
65
+ object_built_from_conds = value.is_a?(String) ? __yaml_load_object_recursively__(value) : value
66
+ return yaml_conditions == object_built_from_conds
67
+ end
68
+ return __check_yaml_nested_hierarchy_on_list__(value, yaml_conditions) if yaml_conditions.is_a?(Array)
69
+ yaml_conditions.inject(true) do |accept, (field, conditions)|
70
+ accept &= begin
71
+ nested_value = __yaml_method_or_key__(value, field)
72
+ if conditions.is_a?(Hash)
73
+ (conditions[:class].blank? || __yaml_same_class__(conditions[:class].to_s, nested_value)) &&
74
+ __check_yaml_nested_hierarchy__(nested_value, __filter_yaml_attributes_to_check_on__(conditions.symbolize_keys!))
75
+ else
76
+ __check_yaml_nested_hierarchy__(nested_value, conditions)
77
+ end
78
+ end
79
+ end
80
+ end
81
+
82
+ def __yaml_method_or_key__(object, key)
83
+ value = if object.is_a?(Hash)
84
+ object[key.to_sym] || object[key.to_s]
85
+ elsif object.respond_to?(key.to_sym)
86
+ object.send(key)
87
+ end
88
+ if value.is_a?(String)
89
+ __yaml_load_object_recursively__(value)
90
+ else
91
+ value
92
+ end
93
+ rescue
94
+ nil
95
+ end
96
+
97
+ def __yaml_load_object_recursively__(object)
98
+ yaml_object = __yaml_deserialize__(object)
99
+ if yaml_object.respond_to?(:value) && yaml_object.respond_to?(:type_id) && yaml_object.type_id == 'struct'
100
+ yaml_object = yaml_object.value
101
+ yaml_object = yaml_object.keys.inject(yaml_object) do |yobject, key|
102
+ yobject[key] = yobject[key].is_a?(String) ? __yaml_load_object_recursively__(yobject[key]) : yobject[key]
103
+ yobject
104
+ end
105
+ yaml_object[:class] = yaml_object.class.to_s
106
+ yaml_object
107
+ else
108
+ yaml_object
109
+ end
110
+ end
111
+
112
+ def __yaml_deserialize__(source)
113
+ handler = YAML.load(source) rescue nil
114
+
115
+ unless handler.present?
116
+ if handler.nil? && source =~ ParseObjectFromYaml
117
+ handler_class = $1
118
+ end
119
+ __attempt_to_load__(handler_class || handler.class) rescue nil
120
+ handler = YAML.load(source)
121
+ end
122
+ handler
123
+ end
124
+
125
+ def __attempt_to_load__(klass)
126
+ klass.constantize
127
+ end
128
+
129
+ def __yaml_same_class__(class_string, nested_value)
130
+ klazz_s = class_string.gsub('Struct::', '')
131
+ klazz = klazz_s.constantize rescue nil
132
+ struct_klazz = nested_value.class.to_s[/^Struct::(.*)$/, 1]
133
+ klazz.present? && nested_value.is_a?(klazz) || struct_klazz.present? && struct_klazz == klazz_s
134
+ end
135
+
136
+ def __filter_yaml_attributes_to_check_on__(yaml_conditions)
137
+ yaml_conditions.reject { |k,v| k.to_s == 'class' }
138
+ end
139
+
140
+ def __join_yaml_conditions__(current_conditions, conditions)
141
+ if current_conditions.blank?
142
+ conditions
143
+ elsif conditions.blank?
144
+ current_conditions
145
+ else
146
+ [ "(#{conditions})", "(#{current_conditions})" ].join(' AND ')
147
+ end
148
+ end
149
+ end
150
+ end
@@ -0,0 +1,15 @@
1
+ module Yaml
2
+ module QueryBuilder
3
+ module Sql
4
+ module MysqlAdapter
5
+
6
+ def self.included(base)
7
+ base.extend(ClassMethods)
8
+ end
9
+
10
+ module ClassMethods
11
+ end
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,15 @@
1
+ module Yaml
2
+ module QueryBuilder
3
+ module Sql
4
+ module PostgresqlAdapter
5
+
6
+ def self.included(base)
7
+ base.extend(ClassMethods)
8
+ end
9
+
10
+ module ClassMethods
11
+ end
12
+ end
13
+ end
14
+ end
15
+ end