@@ -52,6 +52,14 @@ static int bind_blob(sqlite3_stmt *s, int i, const void *p, int n, int copy) {
52
52
return sqlite3_bind_zeroblob(s, i, 0);
53
53
}
54
54
55
+ // Faster retrieval of column data types (1 cgo call instead of n).
56
+ static void column_types(sqlite3_stmt *s, unsigned char *p, int n) {
57
+ int i = 0;
58
+ for (; i < n; ++i, ++p) {
59
+ *p = sqlite3_column_type(s, i);
60
+ }
61
+ }
62
+
55
63
// Macro for creating callback setter functions.
56
64
#define SET(x) \
57
65
static void set_##x(sqlite3 *db, void *conn, int enable) { \
@@ -489,6 +497,14 @@ func (c *Conn) exec(sql *C.char) error {
489
497
}
490
498
491
499
// Stmt is a prepared statement handle.
500
+ //
501
+ // SQLite automatically recompiles prepared statements when the database schema
502
+ // changes. A query like "SELECT * FROM x" may return a different number of
503
+ // columns from one execution to the next if the table is altered. The
504
+ // recompilation, if required, only happens at the start of execution (during a
505
+ // call to Exec or Query). Statements that are already running (Busy() == true)
506
+ // are not recompiled. Thus, the safest way of obtaining column information is
507
+ // to call Exec or Query first, followed by NumColumns, Columns, DeclTypes, etc.
492
508
// [http://www.sqlite.org/c3ref/stmt.html]
493
509
type Stmt struct {
494
510
Tail string // Uncompiled portion of the SQL string passed to Conn.Prepare
@@ -498,13 +514,13 @@ type Stmt struct {
498
514
499
515
text string // SQL text used to create this statement (minus the Tail)
500
516
nVars int // Number of bound parameters (or maximum ?NNN value)
501
- nCols int // Number of columns in each row
517
+ nCols int // Number of columns in each row (for the current run)
502
518
haveRow bool // Flag indicating row availability
503
519
504
- varNames []string // Names of bound parameters (or unnamedVars)
520
+ varNames []string // Names of bound parameters
505
521
colNames []string // Names of columns in the result set
506
522
colDecls []string // Column type declarations in upper case
507
- colTypes []byte // Data type codes for all columns in the current row
523
+ colTypes []uint8 // Data type codes for all columns in the current row
508
524
}
509
525
510
526
// newStmt creates a new prepared statement.
@@ -524,9 +540,6 @@ func newStmt(c *Conn, sql string) (*Stmt, error) {
524
540
if stmt != nil {
525
541
s .nVars = int (C .sqlite3_bind_parameter_count (stmt ))
526
542
s .nCols = int (C .sqlite3_column_count (stmt ))
527
- if s .nCols > 0 {
528
- s .colTypes = make ([]byte , s .nCols )
529
- }
530
543
runtime .SetFinalizer (s , (* Stmt ).Close )
531
544
}
532
545
if tail != nil {
@@ -638,12 +651,12 @@ func (s *Stmt) Params() []string {
638
651
// Columns returns the names of columns produced by the prepared statement.
639
652
// [http://www.sqlite.org/c3ref/column_name.html]
640
653
func (s * Stmt ) Columns () []string {
641
- if s .colNames == nil && s .nCols > 0 {
642
- names := make ([] string , s .nCols )
643
- for i := range names {
644
- name := C .sqlite3_column_name (s .stmt , C .int (i ))
645
- if name != nil {
646
- names [i ] = C . GoString ( name )
654
+ if len ( s .colNames ) != s .nCols {
655
+ names := resize ( s . colNames , s .nCols )
656
+ for i , old := range names {
657
+ new := goStr ( C .sqlite3_column_name (s .stmt , C .int (i ) ))
658
+ if old != new {
659
+ names [i ] = raw ( new ). Copy ( )
647
660
}
648
661
}
649
662
s .colNames = names
@@ -655,12 +668,16 @@ func (s *Stmt) Columns() []string {
655
668
// statement. The type declarations are normalized to upper case.
656
669
// [http://www.sqlite.org/c3ref/column_decltype.html]
657
670
func (s * Stmt ) DeclTypes () []string {
658
- if s .colDecls == nil && s .nCols > 0 {
659
- decls := make ([]string , s .nCols )
660
- for i := range decls {
661
- decl := C .sqlite3_column_decltype (s .stmt , C .int (i ))
662
- if decl != nil {
663
- decls [i ] = strings .ToUpper (C .GoString (decl ))
671
+ if len (s .colDecls ) != s .nCols {
672
+ decls := resize (s .colDecls , s .nCols )
673
+ for i , old := range decls {
674
+ new := goStr (C .sqlite3_column_decltype (s .stmt , C .int (i )))
675
+ if ! strings .EqualFold (old , new ) {
676
+ norm := strings .ToUpper (new )
677
+ if cStr (new ) == cStr (norm ) {
678
+ norm = raw (norm ).Copy () // ToUpper didn't reallocate
679
+ }
680
+ decls [i ] = norm
664
681
}
665
682
}
666
683
s .colDecls = decls
@@ -670,17 +687,15 @@ func (s *Stmt) DeclTypes() []string {
670
687
671
688
// DataTypes returns the data type codes of columns in the current row. Possible
672
689
// data types are INTEGER, FLOAT, TEXT, BLOB, and NULL. These represent the
673
- // actual storage classes used by SQLite to store each value. The returned slice
674
- // should not be modified.
690
+ // actual storage classes used by SQLite to store each value before any
691
+ // conversion. The returned slice should not be modified.
675
692
// [http://www.sqlite.org/c3ref/column_blob.html]
676
- func (s * Stmt ) DataTypes () []byte {
677
- if ! s .haveRow {
678
- return nil
679
- }
680
- for i , typ := range s .colTypes {
681
- if typ == 0 {
682
- s .colTypes [i ] = byte (C .sqlite3_column_type (s .stmt , C .int (i )))
693
+ func (s * Stmt ) DataTypes () []uint8 {
694
+ if len (s .colTypes ) == 0 {
695
+ if ! s .haveRow || s .nCols == 0 {
696
+ return nil
683
697
}
698
+ s .colType (0 )
684
699
}
685
700
return s .colTypes
686
701
}
@@ -803,27 +818,33 @@ func (s *Stmt) exec(args []interface{}) (err error) {
803
818
} else {
804
819
err = s .bindUnnamed (args )
805
820
}
806
- if err != nil {
807
- if s .nVars > 0 {
808
- C .sqlite3_clear_bindings (s .stmt )
821
+ if err == nil {
822
+ err = s .step ()
823
+ if s .nCols > 0 {
824
+ // If the statement was recompiled (v2 interface, no indication),
825
+ // then column counts, names, and declarations may have changed and
826
+ // need to be reloaded.
827
+ s .nCols = int (C .sqlite3_column_count (s .stmt ))
828
+ s .colNames = s .colNames [:0 ]
829
+ s .colDecls = s .colDecls [:0 ]
809
830
}
810
- return
831
+ } else if s .nVars > 0 {
832
+ C .sqlite3_clear_bindings (s .stmt )
811
833
}
812
- return s . step ()
834
+ return
813
835
}
814
836
815
837
// bindNamed binds statement parameters using the name/value pairs in args.
816
838
func (s * Stmt ) bindNamed (args NamedArgs ) error {
817
- if s .nVars == 0 {
818
- return nil
819
- }
820
- names := s .Params ()
821
- if names == nil {
822
- return pkgErr (MISUSE , "statement does not accept named arguments" )
823
- }
824
- for i , name := range names {
825
- if err := s .bind (C .int (i + 1 ), args [name ], name ); err != nil {
826
- return err
839
+ if s .nVars > 0 {
840
+ names := s .Params ()
841
+ if names == nil {
842
+ return pkgErr (MISUSE , "statement does not accept named arguments" )
843
+ }
844
+ for i , name := range names {
845
+ if err := s .bind (C .int (i + 1 ), args [name ], name ); err != nil {
846
+ return err
847
+ }
827
848
}
828
849
}
829
850
return nil
@@ -886,13 +907,9 @@ func (s *Stmt) bind(i C.int, v interface{}, name string) error {
886
907
// step evaluates the next step in the statement's program, automatically
887
908
// resetting the statement if the result is anything other than SQLITE_ROW.
888
909
func (s * Stmt ) step () error {
910
+ s .colTypes = s .colTypes [:0 ]
889
911
s .haveRow = C .sqlite3_step (s .stmt ) == ROW
890
- if s .haveRow {
891
- // Clear previous data types and reload new ones on demand
892
- for i := range s .colTypes {
893
- s .colTypes [i ] = 0
894
- }
895
- } else {
912
+ if ! s .haveRow {
896
913
// If step returned DONE, reset returns OK. Otherwise, reset returns the
897
914
// same error code as step (v2 interface).
898
915
rc := C .sqlite3_reset (s .stmt )
@@ -910,12 +927,17 @@ func (s *Stmt) step() error {
910
927
// INTEGER, FLOAT, TEXT, BLOB, or NULL). The value becomes undefined after a
911
928
// type conversion, so this method must be called for column i to cache the
912
929
// original value before using any other sqlite3_column_* functions.
913
- func (s * Stmt ) colType (i C.int ) (typ byte ) {
914
- if typ = s .colTypes [i ]; typ == 0 {
915
- typ = byte (C .sqlite3_column_type (s .stmt , i ))
916
- s .colTypes [i ] = typ
930
+ func (s * Stmt ) colType (i C.int ) byte {
931
+ if len (s .colTypes ) == 0 {
932
+ n := s .nCols
933
+ if cap (s .colTypes ) < n {
934
+ s .colTypes = make ([]uint8 , n )
935
+ } else {
936
+ s .colTypes = s .colTypes [:n ]
937
+ }
938
+ C .column_types (s .stmt , (* C .uchar )(cBytes (s .colTypes )), C .int (n ))
917
939
}
918
- return
940
+ return s . colTypes [ i ]
919
941
}
920
942
921
943
// scan scans the value of column i (starting at 0) into v.
@@ -1033,6 +1055,16 @@ func namedArgs(args []interface{}) (named NamedArgs) {
1033
1055
return
1034
1056
}
1035
1057
1058
+ // resize changes len(s) to n, reallocating s if needed.
1059
+ func resize (s []string , n int ) []string {
1060
+ if n <= cap (s ) {
1061
+ return s [:n ]
1062
+ }
1063
+ tmp := make ([]string , n )
1064
+ copy (tmp , s [:cap (s )])
1065
+ return tmp
1066
+ }
1067
+
1036
1068
// text returns the value of column i as a UTF-8 string. If copy is false, the
1037
1069
// string will point to memory allocated by SQLite.
1038
1070
func text (stmt * C.sqlite3_stmt , i C.int , copy bool ) string {
0 commit comments