package bun

import (
	
	
	
	

	
	
)

type mapSliceModel struct {
	mapModel
	dest *[]map[string]interface{}

	keys []string
}

var _ model = (*mapSliceModel)(nil)

func ( *DB,  *[]map[string]interface{}) *mapSliceModel {
	return &mapSliceModel{
		mapModel: mapModel{
			db: ,
		},
		dest: ,
	}
}

func ( *mapSliceModel) () interface{} {
	return .dest
}

func ( *mapSliceModel) ( int) {
	if  > 100 {
		 = 100
	}
	if  := *.dest; len() <  {
		*.dest = make([]map[string]interface{}, 0, )
	}
}

func ( *mapSliceModel) ( context.Context,  *sql.Rows) (int, error) {
	,  := .Columns()
	if  != nil {
		return 0, 
	}

	.rows = 
	.columns = 
	 := makeDest(, len())

	 := *.dest
	if len() > 0 {
		 = [:0]
	}

	var  int

	for .Next() {
		.m = make(map[string]interface{}, len(.columns))

		.scanIndex = 0
		if  := .Scan(...);  != nil {
			return 0, 
		}

		 = append(, .m)
		++
	}
	if  := .Err();  != nil {
		return 0, 
	}

	*.dest = 
	return , nil
}

func ( *mapSliceModel) ( schema.Formatter,  []byte) ( []byte,  error) {
	if  := .initKeys();  != nil {
		return nil, 
	}

	for ,  := range .keys {
		if  > 0 {
			 = append(, ", "...)
		}
		 = .AppendIdent(, )
	}

	return , nil
}

func ( *mapSliceModel) ( schema.Formatter,  []byte) ( []byte,  error) {
	if  := .initKeys();  != nil {
		return nil, 
	}
	 := *.dest

	 = append(, "VALUES "...)
	if .db.features.Has(feature.ValuesRow) {
		 = append(, "ROW("...)
	} else {
		 = append(, '(')
	}

	if .IsNop() {
		for  := range .keys {
			if  > 0 {
				 = append(, ", "...)
			}
			 = append(, '?')
		}
		return , nil
	}

	for ,  := range  {
		if  > 0 {
			 = append(, "), "...)
			if .db.features.Has(feature.ValuesRow) {
				 = append(, "ROW("...)
			} else {
				 = append(, '(')
			}
		}

		for ,  := range .keys {
			if  > 0 {
				 = append(, ", "...)
			}
			 = .Dialect().Append(, , [])
		}
	}

	 = append(, ')')

	return , nil
}

func ( *mapSliceModel) () error {
	if .keys != nil {
		return nil
	}

	 := *.dest
	if len() == 0 {
		return errors.New("bun: map slice is empty")
	}

	 := [0]
	 := make([]string, 0, len())

	for  := range  {
		 = append(, )
	}

	sort.Strings()
	.keys = 

	return nil
}