package TemporaryDatabase;
import ModSQL.*;
import java.sql.*;
import java.util.*;

/* TemporaryDatabase/TableData.java
 *
 * Copyright (c) 2003 Chris Studholme <chris.studholme@utoronto.ca>
 *
 * May be copied or modified under the terms of the GNU General Public
 * License.  See COPYING for more information.
 */

/**
 * <p>Temporary (in memory) database table.
 *
 * @author chris.studholme@utoronto.ca
 */
class TableData {

  public String name;
  public ArrayList columns;
  private ArrayList rows;
  private int nrows;

  public long sig=0;  // increment with each update to table

  private int ref_count;  // number of objects accessing table data

  public TableData(String name) {
    this.name = name;
    columns = new ArrayList();
    rows = new ArrayList();
    nrows=0;
    ref_count=0;
  }

  /* Acquire access to table data.
   *
   * @return number of row addresses in table
   */
  public int access() {
    ++ref_count;
    return rows.size();
  }

  /**
   * Release access to table data.
   */
  public void release() {
    if (--ref_count<=0) {
      ref_count=0;
      if (nrows<rows.size()) {
	// compress table
	for (int i=rows.size()-1; i>=0; --i) 
	  if (rows.get(i)==null)
	    rows.remove(i);
	++sig;
      }
    }
  }

  /* number of rows in table
   */
  public long size() {
    return nrows;
  }

  /**
   * Add a new row.  The new row is added to the end of the table and the
   * number of row addresses (after adding the row) is returned.  The new
   * row can then be accessed with get(returned_value-1).
   *
   * @return number of row addresses in table
   */
  public int add() {
    Object[] row = new Object[columns.size()];
    rows.add(row);
    ++nrows;
    ++sig;
    return rows.size();
  }

  /**
   * Delete a row of data.
   */
  public void remove(int rowid) {
    if (rows.get(rowid)!=null) {
      rows.set(rowid,null);
      --nrows;
      ++sig;
    }
  }

  /**
   * Get a row of data.  If the row referenced by rowid has been removed,
   * null will be returned.
   *
   * @return column array or null if row has been removed
   */
  public Object[] get(int rowid) {
    return (Object[])rows.get(rowid);
  }

  /* compute maximum string length of column i
   */
  public int maxStringLength(int index) {
    int max=0;
    Iterator i = rows.iterator();
    while (i.hasNext()) {
      Object[] row = (Object[])i.next();
      if (row!=null) {
	String s = (String)row[index];
	if (s!=null && s.length()>max)
	  max = s.length();
      }
    }
    return max;
  }


};

