Class: TSQLStmt

Inherits:
Object
  • Object
show all
Defined in:
lib/tsql_shparser/tsql_stmt.rb

Overview

The main class which identifies the various clauses for the t-SQL Statement. It constructs the TSQLStmt object from the array of tokens parsed by the Parser. Generates a TokenStream object out of this array and provides methods to query the TokenStream.

Constant Summary collapse

VERSION =
"0.0.1"
@@follow =

Hash used in determining which clauses follow the clause indicated by the key

{   
  'SELECT' => ['INTO','FROM','JOIN','WHERE','GROUP','HAVING','UNION','ORDER'],
  'FROM'   => ['JOIN','WHERE','GROUP','HAVING','UNION','ORDER'],
  'JOIN'   => ['WHERE','GROUP','HAVING','UNION','ORDER'],
  'WHERE'  => ['GROUP','HAVING','UNION','ORDER'],
  'GROUP'  => ['HAVING','UNION','ORDER'],
  'HAVING' => ['UNION','ORDER'],
  'UNION'  => ['ORDER'],
  'SET'    => ['FROM','JOIN','WHERE','UNION'],  # Part of the UPDATE
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(st) ⇒ TSQLStmt

Constructor: takes in array of tokens created by the ShParser. Each array has tokens of exactly one SQL statement. Sometimes the array may have some extra tokens towards the end, since the parser could not correctly identify the end of the statement.



93
94
95
96
97
98
99
100
101
# File 'lib/tsql_shparser/tsql_stmt.rb', line 93

def initialize(st)  
  @stmt = st
  if (@stmt and @stmt[0])
    @typ  = @stmt[0].token_value
    @typ  = 'INTO' if ((@typ == 'SELECT') and (TokenStream.new(@stmt).find_matching_word('INTO') > 0))
    @line = @stmt[0].line
    @col  = @stmt[0].col
  end    
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(methId, *args) ⇒ Object



625
626
627
628
629
# File 'lib/tsql_shparser/tsql_stmt.rb', line 625

def method_missing(methId,*args)
  str = methId.id2name
  str = ((str[-1] == ?s) ? str.chop : (str + 's'))
  self.send(str,*args) if self.respond_to?(str)
end

Instance Attribute Details

#colObject (readonly)

Returns the value of attribute col.



87
88
89
# File 'lib/tsql_shparser/tsql_stmt.rb', line 87

def col
  @col
end

#lineObject (readonly)

Returns the value of attribute line.



86
87
88
# File 'lib/tsql_shparser/tsql_stmt.rb', line 86

def line
  @line
end

#stmtObject (readonly)

Convert the array of tokens to a TokenStream object



175
176
177
# File 'lib/tsql_shparser/tsql_stmt.rb', line 175

def stmt
  @stmt
end

#typObject (readonly)

Returns the value of attribute typ.



84
85
86
# File 'lib/tsql_shparser/tsql_stmt.rb', line 84

def typ
  @typ
end

Instance Method Details

#alias_columns(all = false) ⇒ Object Also known as: column_aliases



422
423
424
425
426
427
428
# File 'lib/tsql_shparser/tsql_stmt.rb', line 422

def alias_columns(all=false)
  cols = TokenStream.new
  self.list_select_expressions.each{|list|
    cols += name_picker(list)
  }
  cols - columns_select
end

#alias_from(all = false) ⇒ Object Also known as: from_aliases



431
432
433
434
# File 'lib/tsql_shparser/tsql_stmt.rb', line 431

def alias_from(all=false)
  tbls = name_picker(clause_from)
  tbls - tables_from(all)
end

#alias_hash(of = "ALL") ⇒ Object



436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
# File 'lib/tsql_shparser/tsql_stmt.rb', line 436

def alias_hash(of="ALL")
  case of.upcase
  when "FROM"
    name_alias  = name_picker(clause_from).to_arr
    names = tables_from.to_arr
  when "JOIN"
    name_alias = []
    clause_join.each{|list|
      name_alias  += name_picker(list).to_arr
    }
    names = tables_join.to_arr    
  when "ALL"
    name_alias  = name_picker(clause_from).to_arr 
    clause_join.each{|list|
      name_alias += name_picker(list).to_arr
    }
    names = (tables_from + tables_join).to_arr    
  end
  
  a_hash={}

  names.each{|nm|
    i = name_alias.index(nm)
    a = nil
    a = name_alias[i+1] if i and (not names.include?(name_alias[i+1]))
    a_hash[nm] = a if a
  }
  
  a_hash
end

#alias_join(all = false) ⇒ Object Also known as: join_aliases



533
534
535
536
537
# File 'lib/tsql_shparser/tsql_stmt.rb', line 533

def alias_join(all=false)
  tbls = TokenStream.new
  clause_join.each{|list| tbls += name_picker(list)}
  tbls - tables_join(all) - columns_join_on(all)
end

#clause_fromObject Also known as: from



409
410
411
412
413
414
415
416
# File 'lib/tsql_shparser/tsql_stmt.rb', line 409

def clause_from     
  k,n = clause('FROM')
  if n > 0
    k.pop if k[-1].token_value == 'OUTER'
    k.pop if ['CROSS','INNER','LEFT','RIGHT','FULL'].include?(k[-1].token_value)
  end
  k
end

#clause_group_byObject Also known as: group_by



542
# File 'lib/tsql_shparser/tsql_stmt.rb', line 542

def clause_group_by;  k,n = clause('GROUP'); k; end

#clause_havingObject Also known as: having



545
# File 'lib/tsql_shparser/tsql_stmt.rb', line 545

def clause_having; k,n = clause('HAVING');   k; end

#clause_intoObject Also known as: into



384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/tsql_shparser/tsql_stmt.rb', line 384

def clause_into

  into = TokenStream.new

  if @stmt
    n = nil
    @stmt.each_with_index{|tok,i|
      (n = i; break) if tok.token_value == 'INTO'
    }
    into = self.stmt.slice(n..(n+1)) if n       
  end
  
  into
  
end

#clause_joinObject Also known as: join_on



510
511
512
513
514
515
516
517
518
# File 'lib/tsql_shparser/tsql_stmt.rb', line 510

def clause_join

  return [] unless @stmt
 
  join,n = clause('JOIN')
  prev = ((n > 1) ? @stmt.slice((n-2)..(n-1)) : [])
  list_join(join,prev)

end

#clause_order_byObject Also known as: order_by



400
401
402
403
404
405
406
407
# File 'lib/tsql_shparser/tsql_stmt.rb', line 400

def clause_order_by
  order_by = TokenStream.new
  return order_by  unless @stmt
  
  n = self.stmt.find_matching_word('ORDER')
  order_by = self.stmt.slice(n..-1) if n > 0 
  order_by
end

#clause_setObject Also known as: set



548
# File 'lib/tsql_shparser/tsql_stmt.rb', line 548

def clause_set;    k,n = clause('SET');      k; end

#clause_whereObject Also known as: where



539
# File 'lib/tsql_shparser/tsql_stmt.rb', line 539

def clause_where;    k,n = clause('WHERE');  k; end

#columns_allObject Also known as: all_columns



286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/tsql_shparser/tsql_stmt.rb', line 286

def columns_all
  all_cols = TokenStream.new
  return all_cols if ['DROP','TRUNCATE'].include?(self.typ)

  all_cols += columns_select(true)   + columns_insert(true) +
              columns_update(true)   + columns_from(true)   +
              columns_join_on(true)  + columns_where(true)  + 
              columns_group_by(true) + columns_having(true) + 
              columns_order_by() 

  list_union.each{|st|
    n = 0
    st.each_with_index{|tok,i| (n=i; break) if tok.token_value == 'SELECT'}
    ss = TSQLStmt.new(st.slice(n..-1))
    all_cols += ss.columns_select(true)   + ss.columns_from(true)   +
                ss.columns_join_on(true)  + ss.columns_where(true)  + 
                ss.columns_group_by(true) + ss.columns_having(true) + 
                ss.columns_order_by() 
  }
  all_cols 
end

#columns_delete(all = false) ⇒ Object



245
246
247
248
249
250
251
252
# File 'lib/tsql_shparser/tsql_stmt.rb', line 245

def columns_delete(all=false)
  cols = TokenStream.new
  return cols unless self.typ == 'DELETE'  
  
  i = ((@stmt[1].token_value == 'FROM') ? 3 : 2)   
  
  cols
end

#columns_from(all = false) ⇒ Object



418
419
420
# File 'lib/tsql_shparser/tsql_stmt.rb', line 418

def columns_from(all=false)
  name_picker(clause_from,(all ? "columns_all" : "")){|i,prev| false } 
end

#columns_group_by(all = false) ⇒ Object Also known as: group_by_columns



543
# File 'lib/tsql_shparser/tsql_stmt.rb', line 543

def columns_group_by(all=false); name_picker(clause_group_by,(all ? "columns_all" : "")) end

#columns_having(all = false) ⇒ Object Also known as: having_columns



546
# File 'lib/tsql_shparser/tsql_stmt.rb', line 546

def columns_having(all=false); name_picker(clause_having,(all ? "columns_all" : "")) end

#columns_insert(all = false) ⇒ Object Also known as: insert_columns



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/tsql_shparser/tsql_stmt.rb', line 254

def columns_insert(all=false)
  cols = TokenStream.new
  return cols unless self.typ == 'INSERT'
  
  j = 0
  i = ((@stmt[1].token_value == 'INTO') ? 3 : 2)  

  return cols if ((@stmt[i] == nil) or (@stmt[i].token_value == 'EXECUTE') or (@stmt[i].token_value == 'EXEC'))
  
  if (@stmt[i].token_value == LEFT_PARAN)
    j = self.stmt.find_matching_paran(i)
  end
  j += i

  cols += name_picker(self.stmt.slice(i..j)) if j > i
  cols += name_picker(self.stmt.slice((j+1)..-1),"columns_all") if all
  cols
end

#columns_join_on(all = false) ⇒ Object Also known as: join_columns



520
521
522
523
524
525
526
527
528
529
530
# File 'lib/tsql_shparser/tsql_stmt.rb', line 520

def columns_join_on(all=false)
  cols = TokenStream.new
  clause_join.each{|list|
    cols += name_picker(list,(all ? "columns_all" : "columns_join_on")){|i,prev| 
                  ((i < 1) or (not ['JOIN','AS',RIGHT_PARAN].include?(prev.token_value))) and
                  ((i < 1) or (prev.token_type != :Id))  and
                  (i > list.to_arr.index('ON'))
             }
  }
  cols
end

#columns_order_byObject Also known as: order_by_columns



591
592
593
594
595
596
597
# File 'lib/tsql_shparser/tsql_stmt.rb', line 591

def columns_order_by
  # Does not handle case ... end 
  clause_order_by.select{|tok| 
    (not ['ORDER','BY',',','ASC','DESC'].include?(tok.token_value)) and (tok.token_type == :Id)
    #((tok.token_type == :Number) or (tok.token_type == :Id))
  }
end

#columns_select(all = false) ⇒ Object Also known as: select_columns



274
275
276
277
278
279
280
281
282
283
284
# File 'lib/tsql_shparser/tsql_stmt.rb', line 274

def columns_select(all=false)
  cols = TokenStream.new
  self.list_select_expressions.each{|list|
    cols += name_picker(list,(all ? "columns_all" :"columns_select")){|i,prev,nxt| 
                  ((nxt == nil) or (nxt.token_value != '=')) and
                  ((i < 1) or (not ['AS',RIGHT_PARAN,'END'].include?(prev.token_value))) and
                  ((i < 1) or (not [:Id,:String,:Number,:HostVariable].include?(prev.token_type)))
             }
  }
  cols
end

#columns_update(all = false) ⇒ Object Also known as: update_columns



550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/tsql_shparser/tsql_stmt.rb', line 550

def columns_update(all=false)
  cols = TokenStream.new
  return cols unless self.typ == 'UPDATE'
  if all
    cols += name_picker(clause_set,"columns_all")
  else
    cols += name_picker(clause_set,"columns_update"){|i,prev,nxt|
       ((i < 1) or (['SET',','].include?(prev.token_value))) and
       ((nxt == nil) or (nxt.token_value == '='))
    }
  end

  cols
end

#columns_where(all = false) ⇒ Object Also known as: where_columns



540
# File 'lib/tsql_shparser/tsql_stmt.rb', line 540

def columns_where(all=false); name_picker(clause_where,(all ? "columns_all" : "columns_where"));   end

#hdr_deleteObject



242
# File 'lib/tsql_shparser/tsql_stmt.rb', line 242

def hdr_delete; hdr('DELETE');  end

#hdr_insertObject



240
# File 'lib/tsql_shparser/tsql_stmt.rb', line 240

def hdr_insert; hdr('INSERT');  end

#hdr_selectObject



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/tsql_shparser/tsql_stmt.rb', line 222

def hdr_select
  hdr = TokenStream.new
  return hdr unless ((self.typ == 'SELECT') or (self.typ == 'INTO'))
  prev = nil
  @stmt.each{|tok|
    if (tok.token_type == :KeyWord)
      hdr += [tok]
    elsif (tok.token_type == :Number) and (prev.token_value == 'TOP') 
      hdr += [tok]
    else 
      break 
    end
    prev = tok
  }
  hdr
end

#hdr_updateObject



241
# File 'lib/tsql_shparser/tsql_stmt.rb', line 241

def hdr_update; hdr('UPDATE');  end

#list_join(join_cl, prev) ⇒ Object



467
468
469
470
471
472
473
474
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
# File 'lib/tsql_shparser/tsql_stmt.rb', line 467

def list_join(join_cl,prev)

  join_lyst = []
  return join_lyst if join_cl.length == 0
  
  n = join_cl.find_matching_word('JOIN',1)
  
  while n > 0
    j = join_cl.slice(0..n)
    if ((prev.length > 0) and (prev[-1].token_value == 'OUTER'))
      j.unshift(prev[-1])
      prev = prev.slice(0...-1)
    end
    
    if ((prev.length > 0) and (['INNER','LEFT','RIGHT','CROSS','FULL'].include?(prev[-1].token_value)))
      j.unshift(prev[-1])
    end

    prev = j
    
    j = j.slice(0...-1) if (j[-1].token_value == 'OUTER')
    j = j.slice(0...-1) if (['INNER','LEFT','RIGHT','CROSS','FULL'].include?(j[-1].token_value))
    join_lyst << TokenStream.new(j) 
     

    join_cl = join_cl.slice((n+1)..-1)
    n = join_cl.find_matching_word('JOIN',1)
  end

  if ((prev.length > 0) and (prev[-1].token_value == 'OUTER'))
    join_cl.unshift(prev[-1])
    prev = prev.slice(0...-1)
  end

  if ((prev.length > 0) and (['INNER','LEFT','RIGHT','CROSS','FULL'].include?(prev[-1].token_value)))
    join_cl.unshift(prev[-1])
  end
  
  join_lyst << join_cl
  join_lyst
  
end

#list_select_expressionsObject

List all the expressions in the SELECT part of the statement Returns an array of TokenStream objects. Each object in the array is exactly one expression of the SELECT.



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/tsql_shparser/tsql_stmt.rb', line 180

def list_select_expressions
  columns,list = [],[]
  return unless (@stmt and ((self.typ == 'SELECT') or (self.typ == 'INTO')))

  # Skip the header part of the SELECT
  prev,n = nil,nil
  @stmt.each_with_index{|tok,i|
    
    (prev = tok; next) if ["SELECT","ALL", "DISTINCT", "TOP", "PERCENT", "WITH", "TIES"].include?(tok.token_value)
    next if ((tok.token_value =~ /^\d+$/) and prev and (prev.token_value == 'TOP'))
    n = i
    break
  }
  
  # Find the end of the expression list. 
  if n       
     m   = self.stmt.find_matching_word(@@follow['SELECT'],n)  
    list = self.stmt.slice(n..((m == 0) ? -1: n+m-1))     
  end

  i = 0
  column = TokenStream.new
  
  while i < list.length            
      tok = list[i]        
      k = ((tok.token_value == LEFT_PARAN) ? list.find_matching_paran(i) : 1)                
      raise "I cannot find matching paran in:\n #{list.slice(i..-1).to_arr.inspect}\n" if k == 0
      
      column += list.slice(i...(i+k))       
      if (list[i+k-1] and (list[i+k-1].token_value == ","))
        columns << column
        column = TokenStream.new
      end
      i += k         
  end
  columns << column
rescue 
  puts $!.to_s
ensure 
  return columns
end

#list_sub_selects(st = nil) ⇒ Object



599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
# File 'lib/tsql_shparser/tsql_stmt.rb', line 599

def list_sub_selects(st=nil)
  return [] unless @stmt
  
  sub_selects = []
  
  ss = st || self.stmt
  begin
    n,prev = nil,nil
    
    # Find the first occurance of SELECT
    ss.each_with_index{|tok,i|
      (n = i; break) if ((tok.token_value == 'SELECT') and prev and (prev.token_value == LEFT_PARAN))
      prev = tok
    }

    if n
      m = ss.find_matching_paran(n-1)
      sub_selects << ss.slice((n-1)...(n+m))
      ss = ss.slice((n+m)..-1)
    end

  end while n
  
  sub_selects
end

#list_unionObject



565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
# File 'lib/tsql_shparser/tsql_stmt.rb', line 565

def list_union

  return [] unless @stmt
  
  union_lyst = []
  
  n = self.stmt.find_matching_word('UNION')
  return union_lyst if n == 0
  
  union_cl = self.stmt.slice(n..-1)
  n = union_cl.find_matching_word('UNION',1)
  while n > 0
    u = union_cl.slice(0..n)
    union_lyst << u
    union_cl = union_cl.slice((n+1)..-1)
    n = union_cl.find_matching_word('UNION',1)
  end
  
  n = union_cl.find_matching_word('ORDER',1)
  union_lyst << ((n > 0) ? union_cl.slice(0..n) : union_cl)
  
  union_lyst
  
end

#table_alterObject Also known as: alter_table



313
314
# File 'lib/tsql_shparser/tsql_stmt.rb', line 313

def table_alter; TokenStream.new(((self.typ == 'ALTER') and 
(@stmt[1].token_value == 'TABLE')) ? [@stmt[2]] : []); end

#table_createObject Also known as: create_table



311
312
# File 'lib/tsql_shparser/tsql_stmt.rb', line 311

def table_create; TokenStream.new(((self.typ == 'CREATE') and 
(self.typ == 'TABLE')) ? [@stmt[2]] : []); end

#table_deleteObject Also known as: delete_table



345
346
347
348
349
350
351
# File 'lib/tsql_shparser/tsql_stmt.rb', line 345

def table_delete    
  tbl = []
  if (self.typ == 'DELETE')
    tbl = ((@stmt[1].token_value == 'FROM') ? [@stmt[2]] : [@stmt[1]])
  end
  TokenStream.new(tbl)
end

#table_insertObject Also known as: insert_table



337
338
339
340
341
342
343
# File 'lib/tsql_shparser/tsql_stmt.rb', line 337

def table_insert 
  tbl = []
  if (self.typ == 'INSERT')
    tbl = ((@stmt[1].token_value == 'INTO') ? [@stmt[2]] : [@stmt[1]])
  end
  TokenStream.new(tbl)
end

#table_intoObject Also known as: into_table



308
# File 'lib/tsql_shparser/tsql_stmt.rb', line 308

def table_into;   TokenStream.new((self.typ == 'INTO') ? [clause_into[1]] : []);  end

#table_truncateObject Also known as: truncate_table



310
# File 'lib/tsql_shparser/tsql_stmt.rb', line 310

def table_truncate; TokenStream.new((self.typ == 'TRUNCATE') ? [@stmt[2]] : []); end

#table_updateObject Also known as: update_table



309
# File 'lib/tsql_shparser/tsql_stmt.rb', line 309

def table_update; TokenStream.new((self.typ == 'UPDATE') ? [@stmt[1]] : []); end

#tables_all(kind = nil) ⇒ Object Also known as: all_tables



367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/tsql_shparser/tsql_stmt.rb', line 367

def tables_all(kind=nil)
  mod_tbls = table_insert + table_delete + table_update + table_into + table_create +
             tables_drop  + table_truncate + table_alter
  ref_tbls = tables_where + tables_from(true) + tables_join(true)
  list_union.each{|st|
    n = 0
    st.each_with_index{|tok,i| (n=i; break) if tok.token_value == 'SELECT'}
    ss = TSQLStmt.new(st.slice(n..-1))
    ref_tbls += ss.tables_from(true) + ss.tables_join(true)
  }
  all_tbls = mod_tbls + ref_tbls
  (kind ? ((kind == 'mod') ? mod_tbls : ref_tbls) : all_tbls)
end

#tables_dropObject Also known as: drop_tables



315
316
317
318
319
# File 'lib/tsql_shparser/tsql_stmt.rb', line 315

def tables_drop
  tbls = TokenStream.new
  tbls = TokenStream.new(@stmt.select{|tok| tok.token_type == :Id}) if ((self.typ == 'DROP') and @stmt[1] and (@stmt[1].token_value == 'TABLE')) 
  tbls
end

#tables_from(all = false) ⇒ Object Also known as: from_tables



321
322
323
324
325
326
327
# File 'lib/tsql_shparser/tsql_stmt.rb', line 321

def tables_from(all=false)
  tbls = name_picker(clause_from,(all ? "tables_all" : "tables_from")){|i,prev| 
              ((i < 1) or (not ['AS',RIGHT_PARAN].include?(prev.token_value))) and
              ((i < 1) or (prev.token_type != :Id))
         } 
  tbls
end

#tables_join(all = false) ⇒ Object Also known as: join_tables



353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/tsql_shparser/tsql_stmt.rb', line 353

def tables_join(all=false)
  tbls = TokenStream.new
  clause_join.each{|list|
 
  tbls += name_picker(list,(all ? "tables_all" : "tables_join")){|i,prev,nxt| 
              ((i < 1) or (not ['AS',RIGHT_PARAN].include?(prev.token_value))) and
              ((i < 1) or (prev.token_type != :Id)) and 
              (i < list.to_arr.index('ON'))

         } 
  }
  tbls
end

#tables_modifiedObject Also known as: modified_tables



382
# File 'lib/tsql_shparser/tsql_stmt.rb', line 382

def tables_modified;   tables_all('mod');  end

#tables_referredObject Also known as: referred_tables



381
# File 'lib/tsql_shparser/tsql_stmt.rb', line 381

def tables_referred;    tables_all('ref');  end

#tables_where(all = false) ⇒ Object Also known as: where_tables



329
330
331
332
333
334
335
# File 'lib/tsql_shparser/tsql_stmt.rb', line 329

def tables_where(all=false)
  tbls = TokenStream.new
  list_sub_selects(clause_where).each{|ss|
    tbls += TSQLStmt.new(ss.slice(1...-1)).tables_all
  }
  tbls
end