csv2db/sql.go

45 lines
915 B
Go
Raw Permalink Normal View History

2022-09-18 12:43:16 +05:00
package main
import (
"database/sql"
"fmt"
)
2022-10-09 17:23:59 +05:00
func createTable(tx *sql.Tx, tableName string, header []string, fieldTypes string, overWrite bool) error {
if overWrite {
_, err := tx.Exec(fmt.Sprintf("IF object_id('%s', 'U') IS NOT NULL DROP TABLE %s", tableName, tableName))
2022-09-18 12:43:16 +05:00
if err != nil {
return fmt.Errorf("drop table: %v", err)
}
}
2022-10-09 17:23:59 +05:00
sql := fmt.Sprintf("CREATE TABLE %s (", tableName)
2022-09-18 12:43:16 +05:00
for i, v := range header {
var fieldType FieldType
2022-09-21 21:36:40 +05:00
err := fieldType.UnmarshalText([]byte(fieldTypes[i : i+1]))
2022-09-18 12:43:16 +05:00
if err != nil {
return fmt.Errorf("detect field type: %v", err)
}
2022-09-21 21:36:40 +05:00
if fieldType == Skip {
continue
}
2022-09-18 12:43:16 +05:00
sql += fmt.Sprintf(`"%s" %s`, v, fieldType.SqlFieldType())
if i+1 < len(header) {
sql += ", "
} else {
sql += ") WITH (DATA_COMPRESSION = PAGE)"
}
}
_, err := tx.Exec(sql)
if err != nil {
return fmt.Errorf("execute table creation: %v", err)
}
return nil
}