예제 #1
0
// Adds a new column.
func (table *Table) Add(name string, length int) int {
	_, exists := table.Columns[name]
	if exists {
		return st.ColumnAlreadyExists
	}
	if len(name) > constant.MaxColumnNameLength {
		return st.ColumnNameTooLong
	}
	if length <= 0 {
		return st.InvalidColumnLength
	}
	var numberOfRows int
	numberOfRows, status := table.NumberOfRows()
	if status == st.OK && numberOfRows > 0 {
		// Rebuild data file if there are already rows in the table.
		// (To leave space for the new column)
		status = table.RebuildDataFile(name, length)
		table.pushNewColumn(name, length)
	} else {
		newColumn := table.pushNewColumn(name, length)
		// Write definition of the new column into definition file.
		_, err := table.DefFile.Seek(0, 2)
		if err != nil {
			logg.Err("table", "Add", err.Error())
			return st.CannotSeekTableDefFile
		}
		_, err = table.DefFile.WriteString(column.ColumnToDef(newColumn))
		if err != nil {
			logg.Err("table", "Add", err.Error())
			return st.CannotWriteTableDefFile
		}
	}
	table.RowLength += length
	return st.OK
}
예제 #2
0
// Removes a column.
func (table *Table) Remove(name string) int {
	var theColumn *column.Column
	// Find index of the column.
	var columnIndex int
	for i, column := range table.ColumnsInOrder {
		if column.Name == name {
			theColumn = table.ColumnsInOrder[i]
			columnIndex = i
			break
		}
	}
	if theColumn == nil {
		return st.ColumnNameNotFound
	}
	if strings.HasPrefix(name, "~") {
		return st.CannotRemoveSpecialColumn
	}
	length := theColumn.Length
	// Remove the column from columns array.
	table.ColumnsInOrder = append(table.ColumnsInOrder[:columnIndex], table.ColumnsInOrder[columnIndex+1:]...)
	// Remove the column from columns map.
	// table.Columns[name] = nil, true
	delete(table.Columns, name)
	numberOfRows, status := table.NumberOfRows()
	if status != st.OK {
		return status
	}
	if numberOfRows > 0 {
		// Rebuild data file if there are already rows in the table.
		// (To remove data in the deleted column)
		status = table.RebuildDataFile("", 0)
	} else {
		status = util.RemoveLine(table.DefFilePath, column.ColumnToDef(theColumn))
	}
	table.RowLength -= length
	if status != st.OK {
		return status
	}
	return st.OK
}