Class: Ferret::Schema

Inherits:
Object
  • Object
show all
Defined in:
lib/sql-ferret.rb

Instance Method Summary collapse

Constructor Details

#initialize(schema_source) ⇒ Schema

Returns a new instance of Schema.



475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
# File 'lib/sql-ferret.rb', line 475

def initialize schema_source
  raise 'type mismatch' unless schema_source.is_a? String
  super()
  @tables = {} # keyed by forced-lowercase names
  lineno = 0
  curtable = nil
  relocs = [] # a list of [[Proc]]:s
  @used_ids = Set.new
      # so we can avoid clashes when generating aliases;
      # forced downcase
  schema_source.each_line do |line|
    line.strip!
    lineno += 1
    ugh? context: 'parsing-ferret-schema',
        input: line,
        lineno: lineno do
      if line.empty? or line[0] == ?# then
        next
      elsif line =~ /^\[\s*(\w+)\s*\]\s*(#|$)/ then
        name = $1
        dname = name.downcase
        ugh 'duplicate table name', table: name \
            if @tables.has_key? dname
        curtable = @tables[dname] = Ferret::Table.new name
        @used_ids.add dname
      elsif line =~ /^(\w+)\s*:\s*/ then
        name, spec = $1, $'
        # Note that [[add_field]] will check the field's name
        # for uniquity.
        curtable.add_field(
            Ferret::Field.new(curtable, name, spec) do |thunk|
              relocs.push thunk
            end)
        @used_ids.add name.downcase
      else
        ugh 'unparseable-line'
      end
    end
  end
  # Now that we have loaded everything, we can resolve the
  # pointers.
  @tables.each_value do |table|
    ugh 'table-without-columns',
            table: table.name \
        unless table.has_columns?
  end
  relocs.each do |thunk|
    thunk.call self
  end
  return
end

Instance Method Details

#[](name) ⇒ Object



531
532
533
# File 'lib/sql-ferret.rb', line 531

def [] name
  return @tables[name.downcase]
end

#alias_generatorObject



527
528
529
# File 'lib/sql-ferret.rb', line 527

def alias_generator
  return Ferret::Alias_Generator.new(@used_ids)
end

#sql_to_create_table(name) ⇒ Object



539
540
541
542
543
544
545
546
# File 'lib/sql-ferret.rb', line 539

def sql_to_create_table name
  table = self[name]
  unless table then
    ugh 'unknown-table',
        table: name
  end
  return table.sql_to_create
end

#tablesObject



535
536
537
# File 'lib/sql-ferret.rb', line 535

def tables
  return @tables.values
end