package arrowutils

import (
	
	

	
	
)

// EnsureSameSchema ensures that all the records have the same schema. In cases
// where the schema is not equal, virtual null columns are inserted in the
// records with the missing column. When we have static schemas in the execution
// engine, steps like these should be unnecessary.
func ( []arrow.Record) ([]arrow.Record, error) {
	if len() < 2 {
		return , nil
	}

	 := [0].Schema()
	 := false
	for  := range  {
		if ![].Schema().Equal() {
			 = true
			break
		}
	}
	if ! {
		return , nil
	}

	 := make(map[string]arrow.Field)
	for ,  := range  {
		for  := 0;  < .Schema().NumFields(); ++ {
			 := .Schema().Field()
			if ,  := [.Name]; ! {
				[.Name] = 
			}
		}
	}

	 := make([]string, 0, len())
	for  := range  {
		 = append(, )
	}
	sort.Strings()

	 := make([]arrow.Field, 0, len())
	for ,  := range  {
		 = append(, [])
	}
	 := arrow.NewSchema(, nil)

	 := make([]arrow.Record, len())
	var  []arrow.Record

	for  := range  {
		 := [].Schema()
		if .Equal() {
			[] = []
			continue
		}

		 := make([]arrow.Array, 0, len())
		 := [].NumRows()
		for  := 0;  < .NumFields(); ++ {
			 := .Field()
			if  := .FieldIndices(.Name);  != nil {
				if len() > 1 {
					,  := .FieldsByName(.Name)
					return nil, fmt.Errorf(
						"found multiple fields %v for name %s",
						,
						.Name,
					)
				}
				 = append(, [].Column([0]))
			} else {
				// Note that this VirtualNullArray will be read from, but the
				// merged output will be a physical null array, so there is no
				// virtual->physical conversion necessary before we return data.
				 = append(, MakeVirtualNullArray(.Type, int()))
			}
		}

		 = append(, [])
		[] = array.NewRecord(, , )
	}

	for ,  := range  {
		.Release()
	}

	return , nil
}