2
0

import.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. package csvimport
  2. import (
  3. "encoding/csv"
  4. "encoding/hex"
  5. "fmt"
  6. "io"
  7. "strconv"
  8. "strings"
  9. "github.com/danfragoso/pizzasql-next/pkg/storage"
  10. )
  11. // ImportOptions configures CSV import behavior
  12. type ImportOptions struct {
  13. TableName string // Target table name (required)
  14. HasHeader bool // First row is header (default: true)
  15. CreateTable bool // Create table if not exists
  16. IgnoreErrors bool // Continue on row errors
  17. NullValue string // String that represents NULL (default: "")
  18. Delimiter rune // CSV delimiter (default: ',')
  19. ColumnTypes map[string]string // Explicit column types for table creation
  20. }
  21. // DefaultImportOptions returns sensible defaults
  22. func DefaultImportOptions() ImportOptions {
  23. return ImportOptions{
  24. HasHeader: true,
  25. NullValue: "",
  26. Delimiter: ',',
  27. ColumnTypes: make(map[string]string),
  28. }
  29. }
  30. // ImportResult contains import statistics
  31. type ImportResult struct {
  32. RowsImported int64 `json:"rowsImported"`
  33. RowsSkipped int64 `json:"rowsSkipped"`
  34. TableCreated bool `json:"tableCreated"`
  35. Errors []string `json:"errors,omitempty"`
  36. }
  37. // ImportCSV imports CSV data into a table
  38. func ImportCSV(r io.Reader, schema *storage.SchemaManager, table *storage.TableManager, opts ImportOptions) (*ImportResult, error) {
  39. if opts.TableName == "" {
  40. return nil, fmt.Errorf("table name is required for CSV import")
  41. }
  42. result := &ImportResult{}
  43. // Create CSV reader
  44. csvReader := csv.NewReader(r)
  45. if opts.Delimiter != 0 {
  46. csvReader.Comma = opts.Delimiter
  47. }
  48. csvReader.FieldsPerRecord = -1 // Allow variable field count
  49. // Read all records
  50. records, err := csvReader.ReadAll()
  51. if err != nil {
  52. return result, fmt.Errorf("failed to read CSV: %w", err)
  53. }
  54. if len(records) == 0 {
  55. return result, nil
  56. }
  57. // Determine column names
  58. var columnNames []string
  59. startRow := 0
  60. if opts.HasHeader {
  61. columnNames = records[0]
  62. startRow = 1
  63. } else {
  64. // Generate column names if no header
  65. for i := range records[0] {
  66. columnNames = append(columnNames, fmt.Sprintf("column%d", i+1))
  67. }
  68. }
  69. // Check if table exists
  70. tableSchema, err := schema.GetSchema(opts.TableName)
  71. tableExists := err == nil
  72. if !tableExists {
  73. if !opts.CreateTable {
  74. return result, fmt.Errorf("table %s does not exist (use CreateTable option to auto-create)", opts.TableName)
  75. }
  76. // Create table with inferred schema
  77. tableSchema = inferSchema(opts.TableName, columnNames, records[startRow:], opts.ColumnTypes)
  78. if err := schema.CreateTable(tableSchema); err != nil {
  79. return result, fmt.Errorf("failed to create table %s: %w", opts.TableName, err)
  80. }
  81. result.TableCreated = true
  82. }
  83. // Build column type map for parsing
  84. columnTypeMap := make(map[string]string)
  85. for _, col := range tableSchema.Columns {
  86. columnTypeMap[strings.ToLower(col.Name)] = strings.ToUpper(col.Type)
  87. }
  88. // Import rows
  89. for i := startRow; i < len(records); i++ {
  90. record := records[i]
  91. row := make(storage.Row)
  92. for j, colName := range columnNames {
  93. if j >= len(record) {
  94. break
  95. }
  96. value := record[j]
  97. colType := columnTypeMap[strings.ToLower(colName)]
  98. // Handle NULL values
  99. if value == opts.NullValue {
  100. row[colName] = nil
  101. continue
  102. }
  103. // Parse value based on column type
  104. parsedValue, err := parseValue(value, colType)
  105. if err != nil {
  106. if opts.IgnoreErrors {
  107. result.Errors = append(result.Errors, fmt.Sprintf("row %d, column %s: %v", i+1, colName, err))
  108. row[colName] = value // Store as string
  109. } else {
  110. return result, fmt.Errorf("row %d, column %s: %w", i+1, colName, err)
  111. }
  112. } else {
  113. row[colName] = parsedValue
  114. }
  115. }
  116. // Insert row
  117. if err := table.Insert(opts.TableName, row); err != nil {
  118. if opts.IgnoreErrors {
  119. result.Errors = append(result.Errors, fmt.Sprintf("row %d: %v", i+1, err))
  120. result.RowsSkipped++
  121. } else {
  122. return result, fmt.Errorf("failed to insert row %d: %w", i+1, err)
  123. }
  124. } else {
  125. result.RowsImported++
  126. }
  127. }
  128. return result, nil
  129. }
  130. // inferSchema creates a schema based on column names and sample data
  131. func inferSchema(tableName string, columnNames []string, sampleData [][]string, explicitTypes map[string]string) *storage.Schema {
  132. columns := make([]storage.Column, len(columnNames))
  133. for i, name := range columnNames {
  134. colType := "TEXT" // Default type
  135. // Check for explicit type
  136. if explicit, ok := explicitTypes[name]; ok {
  137. colType = explicit
  138. } else {
  139. // Infer type from sample data
  140. colType = inferColumnType(sampleData, i)
  141. }
  142. columns[i] = storage.Column{
  143. Name: name,
  144. Type: colType,
  145. Nullable: true,
  146. }
  147. }
  148. // Use first column as primary key if it looks like an ID
  149. if len(columns) > 0 {
  150. firstCol := strings.ToLower(columns[0].Name)
  151. if firstCol == "id" || strings.HasSuffix(firstCol, "_id") || strings.HasSuffix(firstCol, "id") {
  152. columns[0].PrimaryKey = true
  153. columns[0].Nullable = false
  154. }
  155. }
  156. return &storage.Schema{
  157. Name: tableName,
  158. Columns: columns,
  159. PrimaryKey: columns[0].Name,
  160. }
  161. }
  162. // inferColumnType infers the column type from sample data
  163. func inferColumnType(sampleData [][]string, colIndex int) string {
  164. if len(sampleData) == 0 {
  165. return "TEXT"
  166. }
  167. allInts := true
  168. allFloats := true
  169. hasData := false
  170. for _, row := range sampleData {
  171. if colIndex >= len(row) {
  172. continue
  173. }
  174. value := strings.TrimSpace(row[colIndex])
  175. if value == "" {
  176. continue // Skip empty values for type inference
  177. }
  178. hasData = true
  179. // Try parsing as integer
  180. if _, err := strconv.ParseInt(value, 10, 64); err != nil {
  181. allInts = false
  182. }
  183. // Try parsing as float
  184. if _, err := strconv.ParseFloat(value, 64); err != nil {
  185. allFloats = false
  186. }
  187. }
  188. if !hasData {
  189. return "TEXT"
  190. }
  191. if allInts {
  192. return "INTEGER"
  193. }
  194. if allFloats {
  195. return "REAL"
  196. }
  197. return "TEXT"
  198. }
  199. // parseValue parses a string value based on the column type
  200. func parseValue(value string, colType string) (interface{}, error) {
  201. colType = strings.ToUpper(colType)
  202. switch {
  203. case strings.Contains(colType, "INT"):
  204. // Handle INTEGER, INT, BIGINT, SMALLINT
  205. i, err := strconv.ParseInt(value, 10, 64)
  206. if err != nil {
  207. return nil, fmt.Errorf("invalid integer value: %s", value)
  208. }
  209. return i, nil
  210. case strings.Contains(colType, "REAL") || strings.Contains(colType, "FLOAT") || strings.Contains(colType, "DOUBLE"):
  211. f, err := strconv.ParseFloat(value, 64)
  212. if err != nil {
  213. return nil, fmt.Errorf("invalid float value: %s", value)
  214. }
  215. return f, nil
  216. case strings.Contains(colType, "BLOB"):
  217. // Handle hex-encoded blob (0xABCD or just ABCD)
  218. hexStr := value
  219. if strings.HasPrefix(hexStr, "0x") || strings.HasPrefix(hexStr, "0X") {
  220. hexStr = hexStr[2:]
  221. }
  222. data, err := hex.DecodeString(hexStr)
  223. if err != nil {
  224. return nil, fmt.Errorf("invalid hex blob value: %s", value)
  225. }
  226. return data, nil
  227. case strings.Contains(colType, "BOOL"):
  228. lower := strings.ToLower(value)
  229. if lower == "1" || lower == "true" || lower == "yes" {
  230. return true, nil
  231. }
  232. if lower == "0" || lower == "false" || lower == "no" {
  233. return false, nil
  234. }
  235. return nil, fmt.Errorf("invalid boolean value: %s", value)
  236. default:
  237. // TEXT, VARCHAR, CHAR, etc.
  238. return value, nil
  239. }
  240. }