Class: OpalORM::QueryBuilder
- Inherits:
-
Object
- Object
- OpalORM::QueryBuilder
- Defined in:
- lib/opal_orm/query_builder.rb
Instance Attribute Summary collapse
-
#query ⇒ Object
readonly
Returns the value of attribute query.
Class Method Summary collapse
Instance Method Summary collapse
-
#build! ⇒ Object
def foreign_key(ref_name) @foreign_keys << ref_name end.
- #foreign_key_valid?(key) ⇒ Boolean
-
#initialize(name) ⇒ QueryBuilder
constructor
A new instance of QueryBuilder.
- #integer(name, *options) ⇒ Object
- #string(name, *options) ⇒ Object
Constructor Details
#initialize(name) ⇒ QueryBuilder
Returns a new instance of QueryBuilder.
14 15 16 17 18 |
# File 'lib/opal_orm/query_builder.rb', line 14 def initialize(name) @table_name = name @columns = [] @foreign_keys = [] end |
Instance Attribute Details
#query ⇒ Object (readonly)
Returns the value of attribute query.
12 13 14 |
# File 'lib/opal_orm/query_builder.rb', line 12 def query @query end |
Class Method Details
.create_table_query(name, &prc) ⇒ Object
5 6 7 8 9 10 |
# File 'lib/opal_orm/query_builder.rb', line 5 def self.create_table_query(name, &prc) manager = new(name) prc.call(manager) manager.build! end |
Instance Method Details
#build! ⇒ Object
def foreign_key(ref_name)
@foreign_keys << ref_name
end
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/opal_orm/query_builder.rb', line 32 def build! query_start = "CREATE TABLE #{@table_name} (" column_queries = @columns.map do |col_info| result = [] case col_info[:type] when :string result = "#{col_info[:name]} VARCHAR(255) " when :integer result = "#{col_info[:name]} INTEGER " end unless col_info[:options].nil? col_info[:options].each do |key| case col_info[:options] when :null result += "NOT NULL" unless col_info[:options][:null] end end end result end column_queries.unshift("id INTEGER PRIMARY KEY") foreign_keys = @foreign_keys.map do |ref_name| if foreign_key_valid?(ref_name) "FOREIGN KEY(#{ref_name}) REFERENCES #{@table_name.singularize}(id)" else raise ForeignKeyMissingError, "Error adding foreign key contsraint for #{ref_name}: couldn't find column named #{ref_name}." end end query_end = ");" @query = query_start + column_queries.concat(foreign_keys).join(",\n") + query_end @query end |
#foreign_key_valid?(key) ⇒ Boolean
68 69 70 |
# File 'lib/opal_orm/query_builder.rb', line 68 def foreign_key_valid?(key) @columns.any? {|col| key == col[:name]} end |
#integer(name, *options) ⇒ Object
24 25 26 |
# File 'lib/opal_orm/query_builder.rb', line 24 def integer(name, *) @columns << {type: :integer, name: name, options: } end |
#string(name, *options) ⇒ Object
20 21 22 |
# File 'lib/opal_orm/query_builder.rb', line 20 def string(name, *) @columns << {type: :string, name: name, options: } end |