All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.peekmoon.database.walker.Row Maven / Gradle / Ivy

package org.peekmoon.database.walker;

import java.sql.RowId;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.peekmoon.database.walker.schema.Key;
import org.peekmoon.database.walker.schema.PrimaryKey;
import org.peekmoon.database.walker.schema.Table;

public class Row {
	
	private final Table table;
	private final RowId rowId;
	private final List values;
	
	public Row(Table table, RowId rowId) {
		this.table = table;
		this.rowId = rowId;
		this.values = new ArrayList<>();
	}
	
	/**
	 * @return Values of primaryKey columns. If table have no primary key, value of all columns. 
	 */
	public KeyValue getPrimaryKeyValue() {
		KeyValue keyValue = new KeyValue();
		List columnsIdx;
		if (table.getPrimaryKey()==null) {
			columnsIdx = IntStream.range(0, values.size()).boxed().collect(Collectors.toList());
		} else {
			columnsIdx = table.getPrimaryKey().getColumnIdxs();
		}
		for (Integer idx : columnsIdx) {
			keyValue.add(values.get(idx));
		}
		return keyValue;
	}
	
	public void updateValue(String columnName, Object value) {
		// TODO : Changed value for primarykey is not allowed
		int idx = table.getColumnIdx(columnName);
		if (value!=null) {
			Object oldValue = values.get(idx);
			if (oldValue!=null && !oldValue.getClass().equals(value.getClass())) {
				throw new IllegalArgumentException("Old and new class are differents " + oldValue.getClass() + "=>" + value.getClass());
			}
		}
		values.set(idx, value);
	}

	void updatePrimaryKeyValue(KeyValue newValue) {
		if (table.getPrimaryKey()==null) throw new IllegalStateException("Row " + this + " have no primary key");
		updateKeyValue(table.getPrimaryKey(), newValue);
	}

	void updateKeyValue(Key key, KeyValue newValue) {
		if (!key.getTable().equals(table)) {
			throw new IllegalStateException("Try to update keyvalue " + newValue + " on row " + this + " with fk " + key);
		}
		int i=0;
		// Update primary key
		for (int idx : key.getColumnIdxs()) {
			values.set(idx, newValue.get(i++));	
		}
	}

	public void add(Object object) {
		values.add(object);
	}
	
	public List getValues() {
		return values;
	}
	
	public PrimaryKey getPrimaryKey() {
		return table.getPrimaryKey();
	}

	public Object getValue(int i) {
		return values.get(i);
	}

	public Table getTable() {
		return table;
	}
	
	public String toStringDetail() {
		StringBuilder lineColumnName = new StringBuilder();
		StringBuilder lineValue = new StringBuilder();
		for (int i=0; i