Sha256: 7149e7a508cf543b1049dfe90297b78a41e1ef6e0b618dffd24ff1560d520e0c

Contents?: true

Size: 1.27 KB

Versions: 5

Compression:

Stored size: 1.27 KB

Contents

require 'pg_query'

module PgObjects
  ##
  # Reads directives from SQL-comments
  #
  #    --!depends_on [name_of_dependency]
  #
  # name_of_dependency: short or full name of object as well as object_name
  #
  class Parser
    ROUTES = [
      ['DefineStmt', 'defnames', 0, 'String', 'str'],
      ['CreateFunctionStmt', 'funcname', 0, 'String', 'str'],
      %w[CreateTrigStmt trigname],
      %w[CreateEventTrigStmt trigname],
      %w[CompositeTypeStmt typevar RangeVar relname],
      %w[ViewStmt view RangeVar relname],
      ['CreateConversionStmt', 'conversion_name', 0, 'String', 'str'],
      %w[CreateTableAsStmt into IntoClause rel RangeVar relname],
      ['CreateOpClassStmt', 'opclassname', 0, 'String', 'str']
    ].freeze

    class << self
      def fetch_directives(text)
        {
          depends_on: fetch_dependencies(text)
        }
      end

      def fetch_object_name(text)
        parsed = PgQuery.parse(text).tree.dig(0, 'RawStmt', 'stmt')
        ROUTES.map { |route| parsed.dig(*route) }.compact[0]
      rescue PgQuery::ParseError, NoMethodError
        nil
      end

      private

      def fetch_dependencies(text)
        text.split("\n").select { |ln| ln =~ /^(--|#)!/ }.map { |ln| ln.split[1] if ln =~ /!depends_on/ }.compact
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
pg_objects-0.5.11 lib/pg_objects/parser.rb
pg_objects-0.5.10 lib/pg_objects/parser.rb
pg_objects-0.5.9 lib/pg_objects/parser.rb
pg_objects-0.5.8 lib/pg_objects/parser.rb
pg_objects-0.5.7 lib/pg_objects/parser.rb