/ Check-in [451e0faf]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Fix the schemalint.tcl script to handle identifiers that require quoting.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | schemalint
Files: files | file ages | folders
SHA1: 451e0fafbe5b7e9c67d9b584d5e16796c3196881
User & Date: dan 2015-11-30 18:17:55
Context
2015-11-30
19:16
Add a rule to main.mk to build the schemalint.tcl script into an executable. Similar to the way the sqlite3_analyzer executable is built. check-in: b8251065 user: dan tags: schemalint
18:17
Fix the schemalint.tcl script to handle identifiers that require quoting. check-in: 451e0faf user: dan tags: schemalint
2015-11-23
18:28
In the CREATE INDEX statements output by schemalint.tcl, avoid declaring an explicit collation sequence that is the same as the column's default. check-in: d3aa067c user: dan tags: schemalint
Changes
Hide Diffs Unified Diffs Show Whitespace Changes Patch

Changes to src/where.c.

3938
3939
3940
3941
3942
3943
3944
3945

3946
3947
3948
3949
3950
3951
3952
....
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035

4036
4037
4038
4039
4040
4041
4042
4043
....
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
    zOp = "eq";
  }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GE|WO_GT) ){
    zOp = "range";
  }
  pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);

  if( zOp ){
    const char *zFmt = bOr ? "%z{{%s %s %s %lld}}" : "%z{%s %s %s %lld}";

    zBuf = whereAppendPrintf(db, zFmt, zIn, 
        zOp, pTab->aCol[pTerm->u.leftColumn].zName, 
        (pColl ? pColl->zName : "BINARY"),
        pTerm->prereqRight
    );
  }else{
    zBuf = zIn;
................................................................................

      struct SrcList_item *pItem = &pWInfo->pTabList->a[ii];
      if( pItem->pSelect ) continue;
      pTab = pItem->pTab;
      nCol = pTab->nCol;

      /* Append the table name to the buffer. */
      zBuf = whereAppendPrintf(db, "%s", pTab->zName);

      /* Append the list of columns required to create a covering index */
      zBuf = whereAppendPrintf(db, "%z {cols", zBuf);
      if( 0==(pItem->colUsed & ((u64)1 << (sizeof(Bitmask)*8-1))) ){
        for(iCol=0; iCol<nCol; iCol++){
          if( iCol==(sizeof(Bitmask)*8-1) ) break;
          if( pItem->colUsed & ((u64)1 << iCol) ){

            zBuf = whereAppendPrintf(db, "%z %s", zBuf, pTab->aCol[iCol].zName);
          }
        }
      }
      zBuf = whereAppendPrintf(db, "%z}",zBuf);

      /* Append the contents of WHERE clause */
      zBuf = whereTraceWC(pParse, 1, pItem, zBuf, p->pWC);
................................................................................
          Expr *pExpr = pOrderBy->a[i].pExpr; 
          CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);

          pExpr = sqlite3ExprSkipCollate(pExpr);
          if( pExpr->op==TK_COLUMN && pExpr->iTable==pItem->iCursor ){
            if( pExpr->iColumn>=0 ){
              const char *zName = pTab->aCol[pExpr->iColumn].zName;
              zBuf = whereAppendPrintf(db, "%z%s%s %s %s", zBuf,
                  bFirst ? " {orderby " : " ", zName, pColl->zName,
                  (pOrderBy->a[i].sortOrder ? "DESC" : "ASC")
              );
              bFirst = 0;
            }
          }
        }







|
>







 







|







>
|







 







|







3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
....
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
....
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
    zOp = "eq";
  }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GE|WO_GT) ){
    zOp = "range";
  }
  pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);

  if( zOp ){
    const char *zFmt = bOr ? "%z{{%s \"%w\" \"%w\" %lld}}" :
                             "%z{%s \"%w\" \"%w\" %lld}";
    zBuf = whereAppendPrintf(db, zFmt, zIn, 
        zOp, pTab->aCol[pTerm->u.leftColumn].zName, 
        (pColl ? pColl->zName : "BINARY"),
        pTerm->prereqRight
    );
  }else{
    zBuf = zIn;
................................................................................

      struct SrcList_item *pItem = &pWInfo->pTabList->a[ii];
      if( pItem->pSelect ) continue;
      pTab = pItem->pTab;
      nCol = pTab->nCol;

      /* Append the table name to the buffer. */
      zBuf = whereAppendPrintf(db, "\"%w\"", pTab->zName);

      /* Append the list of columns required to create a covering index */
      zBuf = whereAppendPrintf(db, "%z {cols", zBuf);
      if( 0==(pItem->colUsed & ((u64)1 << (sizeof(Bitmask)*8-1))) ){
        for(iCol=0; iCol<nCol; iCol++){
          if( iCol==(sizeof(Bitmask)*8-1) ) break;
          if( pItem->colUsed & ((u64)1 << iCol) ){
            const char *zName = pTab->aCol[iCol].zName;
            zBuf = whereAppendPrintf(db, "%z \"%w\"", zBuf, zName);
          }
        }
      }
      zBuf = whereAppendPrintf(db, "%z}",zBuf);

      /* Append the contents of WHERE clause */
      zBuf = whereTraceWC(pParse, 1, pItem, zBuf, p->pWC);
................................................................................
          Expr *pExpr = pOrderBy->a[i].pExpr; 
          CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);

          pExpr = sqlite3ExprSkipCollate(pExpr);
          if( pExpr->op==TK_COLUMN && pExpr->iTable==pItem->iCursor ){
            if( pExpr->iColumn>=0 ){
              const char *zName = pTab->aCol[pExpr->iColumn].zName;
              zBuf = whereAppendPrintf(db, "%z%s\"%w\" \"%w\" %s", zBuf,
                  bFirst ? " {orderby " : " ", zName, pColl->zName,
                  (pOrderBy->a[i].sortOrder ? "DESC" : "ASC")
              );
              bFirst = 0;
            }
          }
        }

Changes to test/schemalint.test.

23
24
25
26
27
28
29
30
31
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
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
  CREATE TABLE t1(a, b, c);
  CREATE TABLE t2(x, y, z);
}

do_trace_test 1.1 {
  SELECT b, c, y, z FROM t1, t2 WHERE c=? AND z=?
} {
  {t1 {cols b c} {eq c BINARY 0}}
  {t2 {cols y z} {eq z BINARY 0}}
}

do_trace_test 1.2 {
  SELECT a FROM t1 WHERE b>10
} {
  {t1 {cols a b} {range b BINARY 0}}
}

do_trace_test 1.3 {
  SELECT b FROM t1 WHERE b IN (10, 20, 30)
} {
  {t1 {cols b} {eq b BINARY 0}}
}

do_trace_test 1.4 {
  SELECT * FROM t1, t2 WHERE x=a
} {
  {t1 {cols a b c} {eq a BINARY 2}} 
  {t2 {cols x y z} {eq x BINARY 1}}
}

do_trace_test 1.5 {
  SELECT * FROM t1 WHERE a IN (1, 2, 3)
} {
  {t1 {cols a b c} {eq a BINARY 0}}
}

#-----------------------------------------------------------------------
# Cases involving OR clauses in the WHERE clause.
#
do_trace_test 2.1 {
  SELECT * FROM t1 WHERE a=? OR b=?
} {
  {t1 {cols a b c} {or {{eq a BINARY 0}} {{eq b BINARY 0}}}}
}

do_trace_test 2.2 {
  SELECT * FROM t1 WHERE a=? OR (b=? AND c=?)
} {
  {t1 {cols a b c} {or {{eq a BINARY 0}} {{eq b BINARY 0} {eq c BINARY 0}}}}
}

do_trace_test 2.3 {
  SELECT * FROM t1 WHERE (a=? AND b=?) OR c=?
} {
  {t1 {cols a b c} {or {{eq c BINARY 0}} {{eq a BINARY 0} {eq b BINARY 0}}}}
}

#-----------------------------------------------------------------------
# Cases involving ORDER BY.
#
do_trace_test 3.1 {
  SELECT * FROM t1 ORDER BY a;
} {{t1 {cols a b c} {orderby a BINARY ASC}}}

do_trace_test 3.2 {
  SELECT * FROM t1 WHERE a=? ORDER BY b;
} {{t1 {cols a b c} {eq a BINARY 0} {orderby b BINARY ASC}}}

do_trace_test 3.3 {
  SELECT min(a) FROM t1;
} {{t1 {cols a} {orderby a BINARY ASC}}}

do_trace_test 3.4 {
  SELECT max(a) FROM t1;
} {{t1 {cols a} {orderby a BINARY DESC}}}

finish_test








|
|





|





|





|
|





|








|





|





|







|



|



|



|



23
24
25
26
27
28
29
30
31
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
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
  CREATE TABLE t1(a, b, c);
  CREATE TABLE t2(x, y, z);
}

do_trace_test 1.1 {
  SELECT b, c, y, z FROM t1, t2 WHERE c=? AND z=?
} {
  {"t1" {cols "b" "c"} {eq "c" "BINARY" 0}}
  {"t2" {cols "y" "z"} {eq "z" "BINARY" 0}}
}

do_trace_test 1.2 {
  SELECT a FROM t1 WHERE b>10
} {
  {"t1" {cols "a" "b"} {range "b" "BINARY" 0}}
}

do_trace_test 1.3 {
  SELECT b FROM t1 WHERE b IN (10, 20, 30)
} {
  {"t1" {cols "b"} {eq "b" "BINARY" 0}}
}

do_trace_test 1.4 {
  SELECT * FROM t1, t2 WHERE x=a
} {
  {"t1" {cols "a" "b" "c"} {eq "a" "BINARY" 2}} 
  {"t2" {cols "x" "y" "z"} {eq "x" "BINARY" 1}}
}

do_trace_test 1.5 {
  SELECT * FROM t1 WHERE a IN (1, 2, 3)
} {
  {"t1" {cols "a" "b" "c"} {eq "a" "BINARY" 0}}
}

#-----------------------------------------------------------------------
# Cases involving OR clauses in the WHERE clause.
#
do_trace_test 2.1 {
  SELECT * FROM t1 WHERE a=? OR b=?
} {
  {"t1" {cols "a" "b" "c"} {or {{eq "a" "BINARY" 0}} {{eq "b" "BINARY" 0}}}}
}

do_trace_test 2.2 {
  SELECT * FROM t1 WHERE a=? OR (b=? AND c=?)
} {
  {"t1" {cols "a" "b" "c"} {or {{eq "a" "BINARY" 0}} {{eq "b" "BINARY" 0} {eq "c" "BINARY" 0}}}}
}

do_trace_test 2.3 {
  SELECT * FROM t1 WHERE (a=? AND b=?) OR c=?
} {
  {"t1" {cols "a" "b" "c"} {or {{eq "c" "BINARY" 0}} {{eq "a" "BINARY" 0} {eq "b" "BINARY" 0}}}}
}

#-----------------------------------------------------------------------
# Cases involving ORDER BY.
#
do_trace_test 3.1 {
  SELECT * FROM t1 ORDER BY a;
} {{"t1" {cols "a" "b" "c"} {orderby "a" "BINARY" ASC}}}

do_trace_test 3.2 {
  SELECT * FROM t1 WHERE a=? ORDER BY b;
} {{"t1" {cols "a" "b" "c"} {eq "a" "BINARY" 0} {orderby "b" "BINARY" ASC}}}

do_trace_test 3.3 {
  SELECT min(a) FROM t1;
} {{"t1" {cols "a"} {orderby "a" "BINARY" ASC}}}

do_trace_test 3.4 {
  SELECT max(a) FROM t1;
} {{"t1" {cols "a"} {orderby "a" "BINARY" DESC}}}

finish_test

Changes to tool/schemalint.tcl.

6
7
8
9
10
11
12



































13
14
15
16
17
18
19
...
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
...
181
182
183
184
185
186
187















188
189
190
191
192
193
194
195
196
197
198
199
200
...
344
345
346
347
348
349
350

351
352
353
354
355
356
357
...
358
359
360
361
362
363
364



365
366
367


368
369
370
371
372
373
374
...
436
437
438
439
440
441
442




















































443
444
445
446
447
448
449
450
451
452
453
454
  puts stderr "  Switches are:"
  puts stderr "  -select SQL     (recommend indexes for SQL statement)"
  puts stderr "  -verbose        (increase verbosity of output)"
  puts stderr "  -test           (run internal tests and then exit)"
  puts stderr ""
  exit
}




































proc process_cmdline_args {ctxvar argv} {
  upvar $ctxvar G
  set nArg [llength $argv]
  set G(database) [lindex $argv end]

  for {set i 0} {$i < [llength $argv]-1} {incr i} {
................................................................................
  set rangeset [concat $rangeset $range]

  set lCols [list]
  set idxname $tname

  foreach {c collate dir} $rangeset {
    append idxname "_$c"
    set coldef $c

    if {[string compare -nocase $collate $aColl($c)]!=0} {
      append idxname [string tolower $collate]
      append coldef " COLLATE $collate"
    }

    if {$dir=="DESC"} {
      append coldef " DESC"
      append idxname "desc"
    }
    lappend lCols $coldef
  }

  set create_index "CREATE INDEX $idxname ON ${tname}("
  append create_index [join $lCols ", "]
  append create_index ");"

  set G(trial.$idxname) $create_index
}

proc expand_or_cons {L} {
................................................................................
      }
      set lRet $lNew
    } 
  }
  return $lRet
}
















proc sqlidx_get_coll_map {tname arrayvar} {
  upvar $arrayvar aColl
  set colnames [list]
  db eval "PRAGMA table_info = $tname" x { lappend colnames $x(name) }
  db eval "CREATE INDEX schemalint_test ON ${tname}([join $colnames ,])"

  db eval "PRAGMA index_xinfo = schemalint_test" x { 
    set aColl($x(name)) $x(coll)
  }
  db eval "DROP INDEX schemalint_test"
}

proc find_trial_indexes {ctxvar} {
................................................................................
# The following is test code only.
#
proc sqlidx_one_test {tn schema select expected} {
#  if {$tn!=2} return
  sqlidx_init_context C

  sqlite3 db ""

  db eval $schema
  lappend C(lSelect) $select
  analyze_selects C
  find_trial_indexes C

  set idxlist [run_trials C]
  if {$idxlist != [list {*}$expected]} {
................................................................................
    puts stderr "Test $tn failed"
    puts stderr "Expected: $expected"
    puts stderr "Got: $idxlist"
    exit -1
  }

  db close



}

proc sqlidx_internal_tests {} {



  # No indexes for a query with no constraints.
  sqlidx_one_test 0 {
    CREATE TABLE t1(a, b, c);
  } {
    SELECT * FROM t1;
  } {
................................................................................
    CREATE TABLE t1(a COLLATE NOCase, b, c);
  } {
    SELECT * FROM t1 WHERE a=?
  } {
    {CREATE INDEX t1_a ON t1(a);}
  }





















































  exit
}
# End of internal test code.
#-------------------------------------------------------------------------

sqlidx_init_context D
process_cmdline_args D $argv
open_database D
analyze_selects D
find_trial_indexes D
foreach idx [run_trials D] { puts $idx }








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|



|









|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



|
|
|







 







>







 







>
>
>



>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>












6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
...
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
...
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
...
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
428
429
430
...
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
  puts stderr "  Switches are:"
  puts stderr "  -select SQL     (recommend indexes for SQL statement)"
  puts stderr "  -verbose        (increase verbosity of output)"
  puts stderr "  -test           (run internal tests and then exit)"
  puts stderr ""
  exit
}

# Return the quoted version of identfier $id. Quotes are only added if 
# they are required by SQLite.
#
# This command currently assumes that quotes are required if the 
# identifier contains any ASCII-range characters that are not 
# alpha-numeric or underscores.
#
proc quote {id} {
  if {[requires_quote $id]} {
    set x [string map {\" \"\"} $id]
    return "\"$x\""
  }
  return $id
}
proc requires_quote {id} {
  foreach c [split $id {}] {
    if {[string is alnum $c]==0 && $c!="_"} {
      return 1
    }
  }
  return 0
}

# The argument passed to this command is a Tcl list of identifiers. The
# value returned is the same list, except with each item quoted and the
# elements comma-separated.
#
proc list_to_sql {L} {
  set ret [list]
  foreach l $L {
    lappend ret [quote $l]
  }
  join $ret ", "
}

proc process_cmdline_args {ctxvar argv} {
  upvar $ctxvar G
  set nArg [llength $argv]
  set G(database) [lindex $argv end]

  for {set i 0} {$i < [llength $argv]-1} {incr i} {
................................................................................
  set rangeset [concat $rangeset $range]

  set lCols [list]
  set idxname $tname

  foreach {c collate dir} $rangeset {
    append idxname "_$c"
    set coldef [quote $c]

    if {[string compare -nocase $collate $aColl($c)]!=0} {
      append idxname [string tolower $collate]
      append coldef " COLLATE [quote $collate]"
    }

    if {$dir=="DESC"} {
      append coldef " DESC"
      append idxname "desc"
    }
    lappend lCols $coldef
  }

  set create_index "CREATE INDEX [quote $idxname] ON [quote $tname]("
  append create_index [join $lCols ", "]
  append create_index ");"

  set G(trial.$idxname) $create_index
}

proc expand_or_cons {L} {
................................................................................
      }
      set lRet $lNew
    } 
  }
  return $lRet
}

#--------------------------------------------------------------------------
# Argument $tname is the name of a table in the main database opened by
# database handle [db]. $arrayvar is the name of an array variable in the
# caller's context. This command populates the array with an entry mapping 
# from column name to default collation sequence for each column of table
# $tname. For example, if a table is declared:
#
#   CREATE TABLE t1(a COLLATE nocase, b, c COLLATE binary)
#
# the mapping is populated with:
#
#   map(a) -> "nocase"
#   map(b) -> "binary"
#   map(c) -> "binary"
#
proc sqlidx_get_coll_map {tname arrayvar} {
  upvar $arrayvar aColl
  set colnames [list]
  set qname [quote $tname]
  db eval "PRAGMA table_info = $qname" x { lappend colnames $x(name) }
  db eval "CREATE INDEX schemalint_test ON ${qname}([list_to_sql $colnames])"
  db eval "PRAGMA index_xinfo = schemalint_test" x { 
    set aColl($x(name)) $x(coll)
  }
  db eval "DROP INDEX schemalint_test"
}

proc find_trial_indexes {ctxvar} {
................................................................................
# The following is test code only.
#
proc sqlidx_one_test {tn schema select expected} {
#  if {$tn!=2} return
  sqlidx_init_context C

  sqlite3 db ""
  db collate "a b c" [list string compare]
  db eval $schema
  lappend C(lSelect) $select
  analyze_selects C
  find_trial_indexes C

  set idxlist [run_trials C]
  if {$idxlist != [list {*}$expected]} {
................................................................................
    puts stderr "Test $tn failed"
    puts stderr "Expected: $expected"
    puts stderr "Got: $idxlist"
    exit -1
  }

  db close

  upvar nTest nTest
  incr nTest
}

proc sqlidx_internal_tests {} {
  set nTest 0


  # No indexes for a query with no constraints.
  sqlidx_one_test 0 {
    CREATE TABLE t1(a, b, c);
  } {
    SELECT * FROM t1;
  } {
................................................................................
    CREATE TABLE t1(a COLLATE NOCase, b, c);
  } {
    SELECT * FROM t1 WHERE a=?
  } {
    {CREATE INDEX t1_a ON t1(a);}
  }

  # Tables with names that require quotes.
  #
  sqlidx_one_test 8.1 {
    CREATE TABLE "t t"(a, b, c);
  } {
    SELECT * FROM "t t" WHERE a=?
  } {
    {CREATE INDEX "t t_a" ON "t t"(a);}
  }
  sqlidx_one_test 8.2 {
    CREATE TABLE "t t"(a, b, c);
  } {
    SELECT * FROM "t t" WHERE b BETWEEN ? AND ?
  } {
    {CREATE INDEX "t t_b" ON "t t"(b);}
  }
  
  # Columns with names that require quotes.
  #
  sqlidx_one_test 9.1 {
    CREATE TABLE t3(a, "b b", c);
  } {
    SELECT * FROM t3 WHERE "b b" = ?
  } {
    {CREATE INDEX "t3_b b" ON t3("b b");}
  }
  sqlidx_one_test 9.2 {
    CREATE TABLE t3(a, "b b", c);
  } {
    SELECT * FROM t3 ORDER BY "b b"
  } {
    {CREATE INDEX "t3_b b" ON t3("b b");}
  }

  # Collations with names that require quotes.
  #
  sqlidx_one_test 10.1 {
    CREATE TABLE t4(a, b, c);
  } {
    SELECT * FROM t4 ORDER BY c COLLATE "a b c"
  } {
    {CREATE INDEX "t4_ca b c" ON t4(c COLLATE "a b c");}
  }
  sqlidx_one_test 10.2 {
    CREATE TABLE t4(a, b, c);
  } {
    SELECT * FROM t4 WHERE c = ? COLLATE "a b c"
  } {
    {CREATE INDEX "t4_ca b c" ON t4(c COLLATE "a b c");}
  }

  puts "All $nTest tests passed"
  exit
}
# End of internal test code.
#-------------------------------------------------------------------------

sqlidx_init_context D
process_cmdline_args D $argv
open_database D
analyze_selects D
find_trial_indexes D
foreach idx [run_trials D] { puts $idx }