/*
Copyright © 2020 Marvin

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package dbutil

import (
	"database/sql"

	"github.com/pingcap/errors"
)

// ColumnData saves column's data.
type ColumnData struct {
	Data   []byte
	IsNull bool
}

// ScanRow scans rows into a map.
func ScanRow(rows *sql.Rows) (map[string]*ColumnData, error) {
	cols, err := rows.Columns()
	if err != nil {
		return nil, errors.Trace(err)
	}

	colVals := make([][]byte, len(cols))
	colValsI := make([]interface{}, len(colVals))
	for i := range colValsI {
		colValsI[i] = &colVals[i]
	}

	err = rows.Scan(colValsI...)
	if err != nil {
		return nil, errors.Trace(err)
	}

	result := make(map[string]*ColumnData)
	for i := range colVals {
		data := &ColumnData{
			Data:   colVals[i],
			IsNull: colVals[i] == nil,
		}
		result[cols[i]] = data
	}

	return result, nil
}
