2020-08-06 20:58:47 +03:00
|
|
|
package sqlite3
|
|
|
|
|
|
|
|
import "C"
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
2023-08-21 19:05:17 +03:00
|
|
|
"errors"
|
2020-08-06 20:58:47 +03:00
|
|
|
"fmt"
|
|
|
|
"reflect"
|
|
|
|
"strings"
|
|
|
|
|
2023-11-20 04:06:36 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/kind"
|
|
|
|
"github.com/neilotoole/sq/libsq/core/lg"
|
2023-04-02 22:49:45 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/lg/lga"
|
|
|
|
"github.com/neilotoole/sq/libsq/core/lg/lgm"
|
2023-11-20 04:06:36 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/record"
|
2020-08-23 13:42:15 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/sqlz"
|
2023-11-20 04:06:36 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/core/stringz"
|
|
|
|
"github.com/neilotoole/sq/libsq/driver"
|
2023-11-21 00:42:38 +03:00
|
|
|
"github.com/neilotoole/sq/libsq/source/metadata"
|
2020-08-06 20:58:47 +03:00
|
|
|
)
|
|
|
|
|
2023-07-09 04:34:53 +03:00
|
|
|
// recordMetaFromColumnTypes returns record.Meta for colTypes.
|
|
|
|
func recordMetaFromColumnTypes(ctx context.Context, colTypes []*sql.ColumnType,
|
|
|
|
) (record.Meta, error) {
|
2023-07-03 18:34:19 +03:00
|
|
|
sColTypeData := make([]*record.ColumnTypeData, len(colTypes))
|
|
|
|
ogColNames := make([]string, len(colTypes))
|
2020-08-06 20:58:47 +03:00
|
|
|
for i, colType := range colTypes {
|
|
|
|
// sqlite is very forgiving at times, e.g. execute
|
|
|
|
// a query with a non-existent column name.
|
|
|
|
// This can manifest as an empty db type name. This also
|
|
|
|
// happens for functions such as COUNT(*).
|
|
|
|
dbTypeName := colType.DatabaseTypeName()
|
|
|
|
|
2023-07-03 18:34:19 +03:00
|
|
|
kind := kindFromDBTypeName(ctx, colType.Name(), dbTypeName, colType.ScanType())
|
2023-05-22 18:08:14 +03:00
|
|
|
colTypeData := record.NewColumnTypeData(colType, kind)
|
2020-08-06 20:58:47 +03:00
|
|
|
|
|
|
|
// It's necessary to explicitly set the scan type because
|
|
|
|
// the backing driver doesn't set it for whatever reason.
|
2023-07-03 18:34:19 +03:00
|
|
|
setScanType(ctx, colTypeData) // REVISIT: Legacy? Do we still need this?
|
|
|
|
|
|
|
|
sColTypeData[i] = colTypeData
|
|
|
|
ogColNames[i] = colTypeData.Name
|
|
|
|
}
|
|
|
|
|
2023-07-04 20:31:47 +03:00
|
|
|
mungedColNames, err := driver.MungeResultColNames(ctx, ogColNames)
|
2023-07-03 18:34:19 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
recMeta := make(record.Meta, len(colTypes))
|
|
|
|
for i := range sColTypeData {
|
2023-07-09 04:34:53 +03:00
|
|
|
recMeta[i] = record.NewFieldMeta(sColTypeData[i], mungedColNames[i])
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return recMeta, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// setScanType ensures colTypeData.ScanType is set appropriately.
|
|
|
|
// If the scan type is nil, a scan type will be set based upon
|
|
|
|
// the col kind. The scan type can be nil in the case where rows.ColumnTypes
|
|
|
|
// was invoked before rows.Next (this is necessary for an empty table).
|
|
|
|
//
|
|
|
|
// If the scan type is NOT a sql.NullTYPE, the corresponding sql.NullTYPE will
|
|
|
|
// be set.
|
2023-07-03 18:34:19 +03:00
|
|
|
func setScanType(ctx context.Context, colType *record.ColumnTypeData) {
|
2020-08-23 13:42:15 +03:00
|
|
|
scanType, knd := colType.ScanType, colType.Kind
|
2020-08-06 20:58:47 +03:00
|
|
|
|
|
|
|
if scanType != nil {
|
|
|
|
// If the scan type is already set, ensure it's sql.NullTYPE.
|
|
|
|
switch scanType {
|
|
|
|
default:
|
2022-12-24 07:05:26 +03:00
|
|
|
// If it's not one of these types, we use "any".
|
|
|
|
colType.ScanType = sqlz.RTypeAny
|
2020-08-06 20:58:47 +03:00
|
|
|
case sqlz.RTypeInt64:
|
|
|
|
colType.ScanType = sqlz.RTypeNullInt64
|
|
|
|
case sqlz.RTypeFloat64:
|
|
|
|
colType.ScanType = sqlz.RTypeNullFloat64
|
|
|
|
case sqlz.RTypeString:
|
|
|
|
colType.ScanType = sqlz.RTypeNullString
|
|
|
|
case sqlz.RTypeBool:
|
|
|
|
colType.ScanType = sqlz.RTypeNullBool
|
|
|
|
case sqlz.RTypeTime:
|
|
|
|
colType.ScanType = sqlz.RTypeNullTime
|
|
|
|
case sqlz.RTypeBytes:
|
|
|
|
// no need to change if it's []byte
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-23 13:42:15 +03:00
|
|
|
switch knd {
|
2020-08-06 20:58:47 +03:00
|
|
|
default:
|
|
|
|
// Shouldn't happen?
|
2023-07-03 18:34:19 +03:00
|
|
|
lg.FromContext(ctx).Warn("Unknown kind for col",
|
2023-04-02 22:49:45 +03:00
|
|
|
lga.Col, colType.Name,
|
|
|
|
lga.DBType, colType.DatabaseTypeName,
|
|
|
|
)
|
2022-12-24 07:05:26 +03:00
|
|
|
scanType = sqlz.RTypeAny
|
2020-08-06 20:58:47 +03:00
|
|
|
|
2023-11-22 00:49:52 +03:00
|
|
|
case kind.Text:
|
2020-08-06 20:58:47 +03:00
|
|
|
scanType = sqlz.RTypeNullString
|
|
|
|
|
2023-11-22 00:49:52 +03:00
|
|
|
case kind.Decimal:
|
|
|
|
scanType = sqlz.RTypeNullDecimal
|
2020-08-23 13:42:15 +03:00
|
|
|
case kind.Int:
|
2020-08-06 20:58:47 +03:00
|
|
|
scanType = sqlz.RTypeNullInt64
|
|
|
|
|
2020-08-23 13:42:15 +03:00
|
|
|
case kind.Bool:
|
2020-08-06 20:58:47 +03:00
|
|
|
scanType = sqlz.RTypeNullBool
|
|
|
|
|
2020-08-23 13:42:15 +03:00
|
|
|
case kind.Float:
|
2020-08-06 20:58:47 +03:00
|
|
|
scanType = sqlz.RTypeNullFloat64
|
|
|
|
|
2020-08-23 13:42:15 +03:00
|
|
|
case kind.Bytes:
|
2020-08-06 20:58:47 +03:00
|
|
|
scanType = sqlz.RTypeBytes
|
|
|
|
|
2020-08-23 13:42:15 +03:00
|
|
|
case kind.Datetime:
|
2020-08-06 20:58:47 +03:00
|
|
|
scanType = sqlz.RTypeNullTime
|
|
|
|
|
2020-08-23 13:42:15 +03:00
|
|
|
case kind.Date:
|
2020-08-06 20:58:47 +03:00
|
|
|
scanType = sqlz.RTypeNullTime
|
|
|
|
|
2020-08-23 13:42:15 +03:00
|
|
|
case kind.Time:
|
2020-08-06 20:58:47 +03:00
|
|
|
scanType = sqlz.RTypeNullString
|
|
|
|
}
|
|
|
|
|
|
|
|
colType.ScanType = scanType
|
|
|
|
}
|
|
|
|
|
2020-08-23 13:42:15 +03:00
|
|
|
// kindFromDBTypeName determines the kind.Kind from the database
|
|
|
|
// type name. For example, "VARCHAR(64)" -> kind.Text.
|
2020-08-06 20:58:47 +03:00
|
|
|
// See https://www.sqlite.org/datatype3.html#determination_of_column_affinity
|
|
|
|
// The scanType arg may be nil (it may not be available to the caller): when
|
|
|
|
// non-nil it may be used to determine ambiguous cases. For example,
|
|
|
|
// dbTypeName is empty string for "COUNT(*)"
|
2023-07-03 18:34:19 +03:00
|
|
|
func kindFromDBTypeName(ctx context.Context, colName, dbTypeName string, scanType reflect.Type) kind.Kind {
|
|
|
|
log := lg.FromContext(ctx)
|
2020-08-06 20:58:47 +03:00
|
|
|
if dbTypeName == "" {
|
|
|
|
// dbTypeName can be empty for functions such as COUNT() etc.
|
|
|
|
// But we can infer the type from scanType (if non-nil).
|
|
|
|
if scanType == nil {
|
|
|
|
// According to the SQLite3 docs:
|
2022-12-24 07:05:26 +03:00
|
|
|
//
|
2020-08-06 20:58:47 +03:00
|
|
|
// 3. If the declared type for a column contains the
|
|
|
|
// string "BLOB" or **if no type is specified** then the
|
|
|
|
// column has affinity BLOB.
|
2022-12-24 07:05:26 +03:00
|
|
|
//
|
|
|
|
// However, I'm not certain how significant that claim is. It
|
|
|
|
// might be more appropriate to return kind.Unknown here.
|
2020-08-23 13:42:15 +03:00
|
|
|
return kind.Bytes
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
switch scanType {
|
|
|
|
default:
|
2022-12-24 07:05:26 +03:00
|
|
|
return kind.Unknown
|
2020-08-06 20:58:47 +03:00
|
|
|
case sqlz.RTypeInt64:
|
2020-08-23 13:42:15 +03:00
|
|
|
return kind.Int
|
2020-08-06 20:58:47 +03:00
|
|
|
case sqlz.RTypeFloat64:
|
2020-08-23 13:42:15 +03:00
|
|
|
return kind.Float
|
2020-08-06 20:58:47 +03:00
|
|
|
case sqlz.RTypeString:
|
2020-08-23 13:42:15 +03:00
|
|
|
return kind.Text
|
2022-12-24 07:05:26 +03:00
|
|
|
case sqlz.RTypeBytes:
|
|
|
|
return kind.Bytes
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-23 13:42:15 +03:00
|
|
|
var knd kind.Kind
|
2020-08-06 20:58:47 +03:00
|
|
|
dbTypeName = strings.ToUpper(dbTypeName)
|
|
|
|
|
|
|
|
// See the examples of type names in the sqlite docs linked above.
|
|
|
|
// Given variations such as VARCHAR(255), we first trim the parens
|
|
|
|
// parts. Thus VARCHAR(255) becomes VARCHAR.
|
|
|
|
i := strings.IndexRune(dbTypeName, '(')
|
|
|
|
if i > 0 {
|
|
|
|
dbTypeName = dbTypeName[0:i]
|
|
|
|
}
|
|
|
|
|
|
|
|
// Try direct matches against common type names
|
|
|
|
switch dbTypeName {
|
|
|
|
case "INT", "INTEGER", "TINYINT", "SMALLINT", "MEDIUMINT", "BIGINT", "UNSIGNED BIG INT", "INT2", "INT8":
|
2020-08-23 13:42:15 +03:00
|
|
|
knd = kind.Int
|
2020-08-06 20:58:47 +03:00
|
|
|
case "REAL", "DOUBLE", "DOUBLE PRECISION", "FLOAT":
|
2020-08-23 13:42:15 +03:00
|
|
|
knd = kind.Float
|
2020-08-06 20:58:47 +03:00
|
|
|
case "DECIMAL":
|
2020-08-23 13:42:15 +03:00
|
|
|
knd = kind.Decimal
|
2020-08-06 20:58:47 +03:00
|
|
|
case "TEXT", "CHARACTER", "VARCHAR", "VARYING CHARACTER", "NCHAR", "NATIVE CHARACTER", "NVARCHAR", "CLOB":
|
2020-08-23 13:42:15 +03:00
|
|
|
knd = kind.Text
|
2020-08-06 20:58:47 +03:00
|
|
|
case "BLOB":
|
2020-08-23 13:42:15 +03:00
|
|
|
knd = kind.Bytes
|
2020-08-06 20:58:47 +03:00
|
|
|
case "DATETIME", "TIMESTAMP":
|
2020-08-23 13:42:15 +03:00
|
|
|
knd = kind.Datetime
|
2020-08-06 20:58:47 +03:00
|
|
|
case "DATE":
|
2020-08-23 13:42:15 +03:00
|
|
|
knd = kind.Date
|
2020-08-06 20:58:47 +03:00
|
|
|
case "TIME":
|
2020-08-23 13:42:15 +03:00
|
|
|
knd = kind.Time
|
2020-08-06 20:58:47 +03:00
|
|
|
case "BOOLEAN":
|
2020-08-23 13:42:15 +03:00
|
|
|
knd = kind.Bool
|
2020-08-06 20:58:47 +03:00
|
|
|
case "NUMERIC":
|
|
|
|
// NUMERIC is problematic. It could be an int, float, big decimal, etc.
|
2020-08-23 13:42:15 +03:00
|
|
|
// kind.Decimal is safest as it can accept any numeric value.
|
|
|
|
knd = kind.Decimal
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// If we have a match, return now.
|
2020-08-23 13:42:15 +03:00
|
|
|
if knd != kind.Unknown {
|
|
|
|
return knd
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// We didn't find an exact match, we'll use the Affinity rules
|
|
|
|
// per the SQLite link provided earlier, noting that we default
|
2020-08-23 13:42:15 +03:00
|
|
|
// to kind.Text (the docs specify default affinity NUMERIC, which
|
2022-12-24 07:05:26 +03:00
|
|
|
// sq handles as kind.Text).
|
2020-08-06 20:58:47 +03:00
|
|
|
switch {
|
|
|
|
default:
|
2020-08-23 13:42:15 +03:00
|
|
|
knd = kind.Unknown
|
2023-04-02 22:49:45 +03:00
|
|
|
log.Warn("Unknown SQLite database column type: using alt",
|
|
|
|
lga.DBType, dbTypeName,
|
|
|
|
lga.Col, colName,
|
|
|
|
lga.Kind, knd,
|
|
|
|
)
|
2020-08-06 20:58:47 +03:00
|
|
|
case strings.Contains(dbTypeName, "INT"):
|
2020-08-23 13:42:15 +03:00
|
|
|
knd = kind.Int
|
2020-08-06 20:58:47 +03:00
|
|
|
case strings.Contains(dbTypeName, "TEXT"),
|
|
|
|
strings.Contains(dbTypeName, "CHAR"),
|
|
|
|
strings.Contains(dbTypeName, "CLOB"):
|
2020-08-23 13:42:15 +03:00
|
|
|
knd = kind.Text
|
2020-08-06 20:58:47 +03:00
|
|
|
case strings.Contains(dbTypeName, "BLOB"):
|
2020-08-23 13:42:15 +03:00
|
|
|
knd = kind.Bytes
|
2020-08-06 20:58:47 +03:00
|
|
|
case strings.Contains(dbTypeName, "REAL"),
|
|
|
|
strings.Contains(dbTypeName, "FLOA"),
|
|
|
|
strings.Contains(dbTypeName, "DOUB"):
|
2020-08-23 13:42:15 +03:00
|
|
|
knd = kind.Float
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2020-08-23 13:42:15 +03:00
|
|
|
return knd
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// DBTypeForKind returns the database type for kind.
|
2020-08-23 13:42:15 +03:00
|
|
|
// For example: Int --> INTEGER
|
|
|
|
func DBTypeForKind(knd kind.Kind) string {
|
|
|
|
switch knd {
|
2020-08-06 20:58:47 +03:00
|
|
|
default:
|
2023-04-02 22:49:45 +03:00
|
|
|
panic(fmt.Sprintf("unknown kind {%s}", knd))
|
2020-08-23 13:42:15 +03:00
|
|
|
case kind.Text, kind.Null, kind.Unknown:
|
2020-08-06 20:58:47 +03:00
|
|
|
return "TEXT"
|
2020-08-23 13:42:15 +03:00
|
|
|
case kind.Int:
|
2020-08-06 20:58:47 +03:00
|
|
|
return "INTEGER"
|
2020-08-23 13:42:15 +03:00
|
|
|
case kind.Float:
|
2020-08-06 20:58:47 +03:00
|
|
|
return "REAL"
|
2020-08-23 13:42:15 +03:00
|
|
|
case kind.Bytes:
|
2020-08-06 20:58:47 +03:00
|
|
|
return "BLOB"
|
2020-08-23 13:42:15 +03:00
|
|
|
case kind.Decimal:
|
2020-08-06 20:58:47 +03:00
|
|
|
return "NUMERIC"
|
2020-08-23 13:42:15 +03:00
|
|
|
case kind.Bool:
|
2020-08-06 20:58:47 +03:00
|
|
|
return "BOOLEAN"
|
2020-08-23 13:42:15 +03:00
|
|
|
case kind.Datetime:
|
2020-08-06 20:58:47 +03:00
|
|
|
return "DATETIME"
|
2020-08-23 13:42:15 +03:00
|
|
|
case kind.Date:
|
2020-08-06 20:58:47 +03:00
|
|
|
return "DATE"
|
2020-08-23 13:42:15 +03:00
|
|
|
case kind.Time:
|
2020-08-06 20:58:47 +03:00
|
|
|
return "TIME"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-16 00:06:40 +03:00
|
|
|
// getTableMetadata returns metadata for tblName in db.
|
2023-11-21 00:42:38 +03:00
|
|
|
func getTableMetadata(ctx context.Context, db sqlz.DB, tblName string) (*metadata.Table, error) {
|
2023-05-03 15:36:10 +03:00
|
|
|
log := lg.FromContext(ctx)
|
2023-11-21 00:42:38 +03:00
|
|
|
tblMeta := &metadata.Table{Name: tblName}
|
2020-08-16 00:06:40 +03:00
|
|
|
// Note that there's no easy way of getting the physical size of
|
|
|
|
// a table, so tblMeta.Size remains nil.
|
|
|
|
|
|
|
|
// But we can get the row count and table type ("table" or "view")
|
|
|
|
const tpl = `SELECT
|
|
|
|
(SELECT COUNT(*) FROM %q),
|
|
|
|
(SELECT type FROM sqlite_master WHERE name = %q LIMIT 1),
|
2023-08-21 19:05:17 +03:00
|
|
|
(SELECT 1 FROM sqlite_master WHERE name = %q AND substr("sql",0,21) == 'CREATE VIRTUAL TABLE') AS is_virtual,
|
2020-08-16 00:06:40 +03:00
|
|
|
(SELECT name FROM pragma_database_list ORDER BY seq LIMIT 1)`
|
2023-08-21 19:05:17 +03:00
|
|
|
|
2020-08-16 00:06:40 +03:00
|
|
|
var schema string
|
2023-08-21 19:05:17 +03:00
|
|
|
var isVirtualTbl sql.NullBool
|
|
|
|
query := fmt.Sprintf(tpl, tblMeta.Name, tblMeta.Name, tblMeta.Name)
|
|
|
|
err := db.QueryRowContext(ctx, query).Scan(&tblMeta.RowCount, &tblMeta.DBTableType, &isVirtualTbl, &schema)
|
2020-08-16 00:06:40 +03:00
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
|
2023-08-21 19:05:17 +03:00
|
|
|
switch {
|
|
|
|
case isVirtualTbl.Valid && isVirtualTbl.Bool:
|
|
|
|
tblMeta.TableType = sqlz.TableTypeVirtual
|
|
|
|
case tblMeta.DBTableType == sqlz.TableTypeView:
|
2020-08-16 00:06:40 +03:00
|
|
|
tblMeta.TableType = sqlz.TableTypeView
|
2023-08-21 19:05:17 +03:00
|
|
|
case tblMeta.DBTableType == sqlz.TableTypeTable:
|
|
|
|
tblMeta.TableType = sqlz.TableTypeTable
|
2020-08-16 00:06:40 +03:00
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
|
|
|
tblMeta.FQName = schema + "." + tblName
|
|
|
|
|
|
|
|
// cid name type notnull dflt_value pk
|
|
|
|
// 0 actor_id INT 1 <null> 1
|
|
|
|
// 1 film_id INT 1 <null> 2
|
|
|
|
// 2 last_update TIMESTAMP 1 <null> 0
|
|
|
|
query = fmt.Sprintf("PRAGMA TABLE_INFO('%s')", tblMeta.Name)
|
|
|
|
rows, err := db.QueryContext(ctx, query)
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
2023-04-02 22:49:45 +03:00
|
|
|
defer lg.WarnIfCloseError(log, lgm.CloseDBRows, rows)
|
2020-08-16 00:06:40 +03:00
|
|
|
|
|
|
|
for rows.Next() {
|
2023-11-21 00:42:38 +03:00
|
|
|
col := &metadata.Column{}
|
2020-08-16 00:06:40 +03:00
|
|
|
var notnull int64
|
|
|
|
defaultValue := &sql.NullString{}
|
|
|
|
pkValue := &sql.NullInt64{}
|
|
|
|
err = rows.Scan(&col.Position, &col.Name, &col.BaseType, ¬null, defaultValue, pkValue)
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
|
2023-08-21 19:05:17 +03:00
|
|
|
if col.BaseType == "" {
|
|
|
|
// The TABLE_INFO pragma doesn't return column types for virtual tables.
|
|
|
|
//
|
|
|
|
// REVISIT: This logic should be pulled out into a separate query for
|
|
|
|
// all "untyped" columns, instead of invoking it for every untyped column.
|
|
|
|
if col.BaseType, err = getTypeOfColumn(ctx, db, tblMeta.Name, col.Name); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-16 00:06:40 +03:00
|
|
|
col.PrimaryKey = pkValue.Int64 > 0 // pkVal can be 0,1,2 etc
|
|
|
|
col.ColumnType = col.BaseType
|
|
|
|
col.Nullable = notnull == 0
|
|
|
|
col.DefaultValue = defaultValue.String
|
2023-07-03 18:34:19 +03:00
|
|
|
col.Kind = kindFromDBTypeName(ctx, col.Name, col.BaseType, nil)
|
2020-08-16 00:06:40 +03:00
|
|
|
|
|
|
|
tblMeta.Columns = append(tblMeta.Columns, col)
|
|
|
|
}
|
|
|
|
|
|
|
|
err = rows.Err()
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return tblMeta, nil
|
|
|
|
}
|
|
|
|
|
2023-08-21 19:05:17 +03:00
|
|
|
// getAllTableMetadata gets metadata for each of the
|
|
|
|
// non-system tables in db's schema. Arg schemaName is used to
|
2023-11-21 00:42:38 +03:00
|
|
|
// set Table.FQName; it is not used to select which schema
|
2023-08-21 19:05:17 +03:00
|
|
|
// to introspect.
|
2023-11-21 00:42:38 +03:00
|
|
|
func getAllTableMetadata(ctx context.Context, db sqlz.DB, schemaName string) ([]*metadata.Table, error) {
|
2023-05-03 15:36:10 +03:00
|
|
|
log := lg.FromContext(ctx)
|
2020-08-06 20:58:47 +03:00
|
|
|
// This query returns a row for each column of each table,
|
|
|
|
// order by table name then col id (ordinal).
|
|
|
|
// Results will look like:
|
|
|
|
//
|
|
|
|
// table_name type cid name type "notnull" dflt_value pk
|
|
|
|
// actor table 0 actor_id numeric 1 <null> 1
|
|
|
|
// actor table 1 first_name VARCHAR(45) 1 <null> 0
|
|
|
|
// actor table 2 last_name VARCHAR(45) 1 <null> 0
|
|
|
|
// actor table 3 last_update TIMESTAMP 1 <null> 0
|
|
|
|
// address table 0 address_id int 1 <null> 1
|
|
|
|
// address table 1 address VARCHAR(50) 1 <null> 0
|
|
|
|
// address table 2 address2 VARCHAR(50) 0 NULL 0
|
|
|
|
// address table 3 district VARCHAR(20) 1 <null> 0
|
|
|
|
//
|
|
|
|
// Note: dflt_value of col "address2" is the string "NULL", rather
|
|
|
|
// that NULL value itself.
|
|
|
|
const query = `
|
2023-08-21 19:05:17 +03:00
|
|
|
SELECT m.name as table_name, m.type, p.cid, p.name, p.type, p.'notnull' as 'notnull', p.dflt_value, p.pk,
|
|
|
|
(substr(m.sql, 0, 21) == 'CREATE VIRTUAL TABLE') AS is_virtual
|
2020-08-06 20:58:47 +03:00
|
|
|
FROM sqlite_master AS m JOIN pragma_table_info(m.name) AS p
|
|
|
|
ORDER BY m.name, p.cid
|
|
|
|
`
|
|
|
|
|
2023-11-21 00:42:38 +03:00
|
|
|
var tblMetas []*metadata.Table
|
2020-08-16 00:06:40 +03:00
|
|
|
var tblNames []string
|
2020-08-06 20:58:47 +03:00
|
|
|
var curTblName string
|
2020-08-16 00:06:40 +03:00
|
|
|
var curTblType string
|
2023-08-21 19:05:17 +03:00
|
|
|
var curTblIsVirtual bool
|
2023-11-21 00:42:38 +03:00
|
|
|
var curTblMeta *metadata.Table
|
2020-08-06 20:58:47 +03:00
|
|
|
|
|
|
|
rows, err := db.QueryContext(ctx, query)
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
2023-04-02 22:49:45 +03:00
|
|
|
defer lg.WarnIfCloseError(log, lgm.CloseDBRows, rows)
|
2020-08-06 20:58:47 +03:00
|
|
|
|
|
|
|
for rows.Next() {
|
2020-08-16 00:06:40 +03:00
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return nil, ctx.Err()
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
2023-11-21 00:42:38 +03:00
|
|
|
col := &metadata.Column{}
|
2020-08-06 20:58:47 +03:00
|
|
|
var notnull int64
|
2020-08-18 22:13:25 +03:00
|
|
|
colDefault := &sql.NullString{}
|
2020-08-06 20:58:47 +03:00
|
|
|
pkValue := &sql.NullInt64{}
|
2020-08-16 00:06:40 +03:00
|
|
|
|
2023-08-21 19:05:17 +03:00
|
|
|
err = rows.Scan(
|
|
|
|
&curTblName,
|
|
|
|
&curTblType,
|
|
|
|
&col.Position,
|
|
|
|
&col.Name,
|
|
|
|
&col.BaseType,
|
|
|
|
¬null,
|
|
|
|
colDefault,
|
|
|
|
pkValue,
|
|
|
|
&curTblIsVirtual,
|
|
|
|
)
|
2020-08-06 20:58:47 +03:00
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if strings.HasPrefix(curTblName, "sqlite_") {
|
|
|
|
// Skip system table "sqlite_sequence" etc.
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2023-08-21 19:05:17 +03:00
|
|
|
if col.BaseType == "" {
|
|
|
|
// The TABLE_INFO pragma doesn't return column types for virtual tables.
|
|
|
|
//
|
|
|
|
// REVISIT: This logic should be pulled out into a separate query for
|
|
|
|
// all "untyped" columns, instead of invoking it for every untyped column.
|
|
|
|
if col.BaseType, err = getTypeOfColumn(ctx, db, curTblName, col.Name); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
if curTblMeta == nil || curTblMeta.Name != curTblName {
|
2023-11-21 00:42:38 +03:00
|
|
|
// On our first time encountering a new table name, we create a new Table
|
|
|
|
curTblMeta = &metadata.Table{
|
2020-08-16 00:06:40 +03:00
|
|
|
Name: curTblName,
|
2023-08-21 19:05:17 +03:00
|
|
|
FQName: schemaName + "." + curTblName,
|
2020-08-16 00:06:40 +03:00
|
|
|
Size: nil, // No easy way of getting the storage size of a table
|
|
|
|
DBTableType: curTblType,
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-08-21 19:05:17 +03:00
|
|
|
switch {
|
|
|
|
case curTblIsVirtual:
|
|
|
|
curTblMeta.TableType = sqlz.TableTypeVirtual
|
|
|
|
case curTblMeta.DBTableType == sqlz.TableTypeView:
|
2020-08-16 00:06:40 +03:00
|
|
|
curTblMeta.TableType = sqlz.TableTypeView
|
2023-08-21 19:05:17 +03:00
|
|
|
case curTblMeta.DBTableType == sqlz.TableTypeTable:
|
|
|
|
curTblMeta.TableType = sqlz.TableTypeTable
|
2020-08-16 00:06:40 +03:00
|
|
|
default:
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2020-08-16 00:06:40 +03:00
|
|
|
tblNames = append(tblNames, curTblName)
|
2020-08-06 20:58:47 +03:00
|
|
|
tblMetas = append(tblMetas, curTblMeta)
|
|
|
|
}
|
|
|
|
|
|
|
|
col.PrimaryKey = pkValue.Int64 > 0 // pkVal can be 0,1,2 etc
|
|
|
|
col.ColumnType = col.BaseType
|
|
|
|
col.Nullable = notnull == 0
|
2020-08-18 22:13:25 +03:00
|
|
|
col.DefaultValue = colDefault.String
|
2023-07-03 18:34:19 +03:00
|
|
|
col.Kind = kindFromDBTypeName(ctx, col.Name, col.BaseType, nil)
|
2020-08-06 20:58:47 +03:00
|
|
|
|
|
|
|
curTblMeta.Columns = append(curTblMeta.Columns, col)
|
|
|
|
}
|
|
|
|
|
|
|
|
err = rows.Err()
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2020-08-16 00:06:40 +03:00
|
|
|
// Separately, we need to get the row counts for the tables
|
|
|
|
var rowCounts []int64
|
2023-04-02 22:49:45 +03:00
|
|
|
rowCounts, err = getTblRowCounts(ctx, db, tblNames)
|
2020-08-16 00:06:40 +03:00
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
for i := range rowCounts {
|
|
|
|
tblMetas[i].RowCount = rowCounts[i]
|
|
|
|
}
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
return tblMetas, nil
|
|
|
|
}
|
2020-08-16 00:06:40 +03:00
|
|
|
|
|
|
|
// getTblRowCounts returns the number of rows in each table.
|
2023-04-02 22:49:45 +03:00
|
|
|
func getTblRowCounts(ctx context.Context, db sqlz.DB, tblNames []string) ([]int64, error) {
|
2023-05-03 15:36:10 +03:00
|
|
|
log := lg.FromContext(ctx)
|
2023-04-02 22:49:45 +03:00
|
|
|
|
2020-08-16 00:06:40 +03:00
|
|
|
// See: https://stackoverflow.com/questions/7524612/how-to-count-rows-from-multiple-tables-in-sqlite
|
|
|
|
//
|
|
|
|
// Several approaches were benchmarked. Ultimately the union-based
|
|
|
|
// query was selected.
|
|
|
|
//
|
|
|
|
// BenchmarkGetTblRowCounts/benchGetTblRowCountsBaseline-16 864 43631750 ns/op
|
|
|
|
// BenchmarkGetTblRowCounts/getTblRowCounts-16 3948 9126191 ns/op
|
|
|
|
//
|
|
|
|
// That query looks like:
|
|
|
|
//
|
|
|
|
// SELECT COUNT(*) FROM "actor"
|
|
|
|
// UNION ALL
|
|
|
|
// SELECT COUNT(*) FROM "address"
|
|
|
|
// UNION ALL
|
|
|
|
// SELECT COUNT(*) FROM "category"
|
|
|
|
//
|
|
|
|
// Note that there is a limit (SQLITE_MAX_COMPOUND_SELECT)
|
|
|
|
// to the number of "terms" (SELECT clauses) in a query.
|
|
|
|
// See https://www.sqlite.org/limits.html#max_compound_select
|
|
|
|
//
|
|
|
|
// Thus if len(tblNames) > 500, we need to execute multiple queries.
|
|
|
|
const maxCompoundSelect = 500
|
|
|
|
|
|
|
|
tblCounts := make([]int64, len(tblNames))
|
|
|
|
|
|
|
|
var sb strings.Builder
|
|
|
|
var query string
|
|
|
|
var terms int
|
|
|
|
var j int
|
|
|
|
|
|
|
|
for i := 0; i < len(tblNames); i++ {
|
|
|
|
if terms > 0 {
|
|
|
|
sb.WriteString(" UNION ALL ")
|
|
|
|
}
|
|
|
|
sb.WriteString(fmt.Sprintf("SELECT COUNT(*) FROM %q", tblNames[i]))
|
|
|
|
terms++
|
|
|
|
|
|
|
|
if terms != maxCompoundSelect && i != len(tblNames)-1 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
query = sb.String()
|
|
|
|
|
|
|
|
rows, err := db.QueryContext(ctx, query)
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
for rows.Next() {
|
|
|
|
err = rows.Scan(&tblCounts[j])
|
|
|
|
if err != nil {
|
2023-04-02 22:49:45 +03:00
|
|
|
lg.WarnIfCloseError(log, lgm.CloseDBRows, rows)
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
j++
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = rows.Err(); err != nil {
|
2023-04-02 22:49:45 +03:00
|
|
|
lg.WarnIfCloseError(log, lgm.CloseDBRows, rows)
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
err = rows.Close()
|
|
|
|
if err != nil {
|
2023-05-22 18:08:14 +03:00
|
|
|
return nil, errw(err)
|
2020-08-16 00:06:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
terms = 0
|
|
|
|
sb.Reset()
|
|
|
|
}
|
|
|
|
|
|
|
|
return tblCounts, nil
|
|
|
|
}
|
2023-08-21 19:05:17 +03:00
|
|
|
|
|
|
|
// getTypeOfColumn executes "SELECT typeof(colName)", returning the first result.
|
|
|
|
// Empty string is returned if there are no rows in that table, as SQLite determines
|
|
|
|
// type on a per-cell basis, not per-column.
|
|
|
|
func getTypeOfColumn(ctx context.Context, db sqlz.DB, tblName, colName string) (string, error) {
|
|
|
|
colTypeQuery := fmt.Sprintf(`SELECT typeof(%s) FROM %s LIMIT 1`,
|
|
|
|
stringz.DoubleQuote(colName), stringz.DoubleQuote(tblName))
|
|
|
|
|
|
|
|
var colType string
|
|
|
|
if err := db.QueryRowContext(ctx, colTypeQuery).Scan(&colType); err != nil {
|
|
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return "", errw(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return colType, nil
|
|
|
|
}
|