Class: PgQuery

Inherits:
Object
  • Object
show all
Defined in:
lib/pg_query/parse.rb,
lib/pg_query/version.rb,
lib/pg_query/parse_error.rb

Defined Under Namespace

Classes: ParseError

Constant Summary collapse

VERSION =
'0.2.0'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(query, parsetree, warnings = []) ⇒ PgQuery

Returns a new instance of PgQuery.



26
27
28
29
30
# File 'lib/pg_query/parse.rb', line 26

def initialize(query, parsetree, warnings = [])
  @query = query
  @parsetree = parsetree
  @warnings = warnings
end

Instance Attribute Details

#parsetreeObject (readonly)

Returns the value of attribute parsetree.



24
25
26
# File 'lib/pg_query/parse.rb', line 24

def parsetree
  @parsetree
end

#queryObject (readonly)

Returns the value of attribute query.



23
24
25
# File 'lib/pg_query/parse.rb', line 23

def query
  @query
end

#warningsObject (readonly)

Returns the value of attribute warnings.



25
26
27
# File 'lib/pg_query/parse.rb', line 25

def warnings
  @warnings
end

Class Method Details

._raw_parse(input) ⇒ Object



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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'ext/pg_query/pg_query.c', line 34

static VALUE pg_query_raw_parse(VALUE self, VALUE input)
{
  Check_Type(input, T_STRING);
  
  MemoryContext ctx = NULL;
  VALUE result;
  ErrorData* error = NULL;
  char stderr_buffer[STDERR_BUFFER_LEN + 1] = {0};
  int stderr_global;
  int stderr_pipe[2];

  ctx = AllocSetContextCreate(TopMemoryContext,
                "pg_query_raw_parse",
                ALLOCSET_DEFAULT_MINSIZE,
                ALLOCSET_DEFAULT_INITSIZE,
                ALLOCSET_DEFAULT_MAXSIZE);
  MemoryContextSwitchTo(ctx);
  
  // Setup pipe for stderr redirection
  if (pipe(stderr_pipe) != 0)
    rb_raise(rb_eIOError, "Failed to open pipe, too many open file descriptors");

  fcntl(stderr_pipe[0], F_SETFL, fcntl(stderr_pipe[0], F_GETFL) | O_NONBLOCK);
  
  // Redirect stderr to the pipe
  stderr_global = dup(STDERR_FILENO);
  dup2(stderr_pipe[1], STDERR_FILENO);
  close(stderr_pipe[1]);
  
  // Parse it!
  PG_TRY();
  {
    List *tree;
    char *str;
    
    str = StringValueCStr(input);
    tree = raw_parser(str);
    
    str = nodeToString(tree);
  
    // Save stderr for result
    read(stderr_pipe[0], stderr_buffer, STDERR_BUFFER_LEN);
  
    result = rb_ary_new();
    rb_ary_push(result, rb_tainted_str_new_cstr(str));
    rb_ary_push(result, rb_str_new2(stderr_buffer));
  
    pfree(str);
  }
  PG_CATCH();
  {
    error = CopyErrorData();
    FlushErrorState();
  }
  PG_END_TRY();
  
  // Restore stderr, close pipe & return to previous PostgreSQL memory context
  dup2(stderr_global, STDERR_FILENO);
  close(stderr_pipe[0]);
  MemoryContextSwitchTo(TopMemoryContext);
  MemoryContextDelete(ctx);
  
  // If we got an error, throw a ParseError exception
  if (error) raise_parse_error(error);
  
  return result;
}

.normalize(input) ⇒ Object



370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
# File 'ext/pg_query/pg_query.c', line 370

static VALUE pg_query_normalize(VALUE self, VALUE input)
{
  Check_Type(input, T_STRING);
  
  MemoryContext ctx = NULL;
  VALUE result;
  ErrorData* error = NULL;
  
  ctx = AllocSetContextCreate(TopMemoryContext,
                "pg_query_normalize",
                ALLOCSET_DEFAULT_MINSIZE,
                ALLOCSET_DEFAULT_INITSIZE,
                ALLOCSET_DEFAULT_MAXSIZE);
  MemoryContextSwitchTo(ctx);
  
  PG_TRY();
  {
    List *tree;
    char *str;
    pgssConstLocations jstate;
    int query_len;
    
    /* Parse query */
    str = StringValueCStr(input);
    tree = raw_parser(str);
    
    /* Set up workspace for constant recording */
    jstate.clocations_buf_size = 32;
    jstate.clocations = (pgssLocationLen *)
      palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
    jstate.clocations_count = 0;
    
    /* Walk tree and record const locations */
    const_record_walker((Node *) tree, &jstate);
    
    /* Normalize query */
    query_len = (int) strlen(str);
    str = generate_normalized_query(&jstate, str, &query_len, PG_UTF8);
  
    result = rb_tainted_str_new_cstr(str);
  
    pfree(str);
  }
  PG_CATCH();
  {
    error = CopyErrorData();
    FlushErrorState();
  }
  PG_END_TRY();

  MemoryContextSwitchTo(TopMemoryContext);
  MemoryContextDelete(ctx);
  
  // If we got an error, throw a ParseError exception
  if (error) raise_parse_error(error);
  
  return result;
}

.parse(query) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/pg_query/parse.rb', line 4

def self.parse(query)
  parsetree, stderr = _raw_parse(query)
  
  parsetree = [] if parsetree == '<>'
  
  if !parsetree.nil? && !parsetree.empty?
    parsetree = parsetree_to_json(parsetree)
    parsetree = JSON.parse(parsetree, max_nesting: 1000)
  end
  
  warnings = []
  stderr.each_line do |line|
    next unless line[/^WARNING/]
    warnings << line.strip
  end
  
  PgQuery.new(query, parsetree, warnings)
end

.parsetree_to_json(str) ⇒ Object



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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/pg_query/parse.rb', line 33

def self.parsetree_to_json(str)
  str.strip!
  control_chars = '(){}: '
  location = nil # :hashname, :key, :value
  structure_stack = [] # :hash, :array (when delimiter opens we push, when delimiter closes we pop)
  open_string = false
  escaped_string = false
  next_char_is_escaped = false
  double_hash_close_in = 0 # This is used to ask for an additional closing delimiter (added when x = 1 and we reach a closing delimiter)
  out = ""

  i = 0
  loop do
    break if i > str.size-1
  
    c = str[i]
    last_location = location
    char_is_escaped = next_char_is_escaped
    next_char_is_escaped = false
    if control_chars.include?(c) && !char_is_escaped && (!open_string || !escaped_string)
      # Space is not always a control character, skip in those cases
      if c == ' ' && last_location == :hashname && str[i+1] != ':'
        out += c
        i += 1
        next
      end
      
      # Keep empty nodes as empty hashes (e.g. nodes that can't be output)
      if c == '{' && str[i+1] == '}'
        out += "{}"
        out += ", " if i+2 < str.size && !'})'.include?(str[i+2])
        i += 2 # Skip {}
        next
      end
    
      location = nil # All control characters reset location
    
      # This should never happen, but if it does, catch it
      if open_string
        out += '"' unless escaped_string
        open_string = false
        escaped_string = false
      end
    
      # Write out JSON control characters
      if last_location == :hashname
        out += ': {'
      elsif last_location == :key
        out += ': '
      end
    
      case c
      when '('
        out += '['
      when ')'
        out += ']'
      when '{'
        out += '{'
      when '}'
        out += '}}'
      when ':'
        # No JSON equivalent
      end
      
      # Handle double hash closes (required for out-of-place nodes like ANY)
      case c
      when '{'  
        if double_hash_close_in > 0
          double_hash_close_in += 1
        end
      when '}'
        if double_hash_close_in == 1
          out += '}}'
          double_hash_close_in = 0
        elsif double_hash_close_in > 1
          double_hash_close_in -= 1
        end
      end
    
      # Write out delimiter if needed
      if (last_location == :value || '})'.include?(c)) && i+1 < str.size && !'})'.include?(str[i+1])
        out += ', '
      end
    
      # Determine new location
      case c
      when '{'
        structure_stack << :hash
        location = :hashname
      when '('
        structure_stack << :array
        location = :value if !control_chars.include?(str[i+1])
      when '}', ')'
        structure_stack.pop
      when ':'
        location = :key
      when ' '
        location = :value if [:value, :key].include?(last_location) && !control_chars.include?(str[i+1])
      end
    else
      if char_is_escaped
        case c
        when '"'
          out += "\\\""
        when '\\'
          out += "\\\\"
        else
          out += c
        end
      elsif str[i] == '<' && str[i+1] == '>' && control_chars.include?(str[i+2])
        # Make <> into null values
        i += 1
        out += "null"
      elsif c == '\\'
        next_char_is_escaped = true # For next round
        # Ignore all other cases
      elsif c[/[A-Z]/] && !open_string && last_location != :value && last_location != :hashname && structure_stack.last == :hash
        # We were not expecting a node name here, but this can happen (e.g. with ANY), try to construct into valid expression
        location = :hashname
        double_hash_close_in = 1
        open_string = true
        out += '"lexpr": {"'
        out += c
      elsif control_chars.include?(str[i-1]) && !open_string && !'0123456789'.include?(c)
        open_string = true
        escaped_string = true if c == '"'
        out += '"' unless escaped_string
        out += c
        c = nil # To avoid close string taking care of us...
      else
        out += c
      end
    
      # Close string if next element is control character
      if open_string && !char_is_escaped && c != '\\' &&
         ((last_location == :hashname && ((str[i+1] == '}') || (str[i+1] == ' ' && str[i+2] == ':') || (str[i+1] == ' ' && str[i+2] == ' ' && str[i+3] == ':'))) ||
          (last_location != :hashname && !escaped_string && control_chars.include?(str[i+1])) || 
          (escaped_string && c == '"'))
        out += '"' unless escaped_string
        open_string = false
        escaped_string = false
      end
    end

    i += 1
  end
  out
end