/*
Copyright (C) 2000-2010  Ministere de la culture et de la communication (France), AJLSM
See LICENCE file
*/
package fr.gouv.culture.sdx.utils.database;

import fr.gouv.culture.sdx.exception.SDXException;
import fr.gouv.culture.sdx.utils.constants.Node;
import fr.gouv.culture.sdx.utils.save.SaveParameters;
import fr.gouv.culture.sdx.utils.save.Saveable;

/**
 * Created by gVim
 * User: Pierre Dittgen
 * Date: 2 nov 2004
 */
public class POSTGRESQLDatabase extends JDBCDatabase {

	protected final String FIELD_KEY = "sdx_key";

	protected String getTableCreationQuery() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("CREATE TABLE ").append(getTableName());
		buffer.append(" ( ").append(FIELD_ID).append(" VARCHAR(255) NOT NULL,");
		buffer.append(FIELD_PROPERTY_NAME).append(" VARCHAR(255) NOT NULL, ");
	    buffer.append(FIELD_PROPERTY_VALUE).append(" VARCHAR(255) NOT NULL, ");
		buffer.append(FIELD_KEY).append(" SERIAL, ");
		buffer.append("PRIMARY KEY (").append(FIELD_KEY).append("))");

		return buffer.toString();
	}
	
	/* (non-Javadoc)
	 * @see fr.gouv.culture.sdx.utils.AbstractSdxObject#initToSax()
	 */
	protected boolean initToSax() {
		this._xmlizable_objects.put("Database_Type","POSTGRESQLDatabase");
		this._xmlizable_objects.put("JDBC_Table_Name",this.tableName);
		this._xmlizable_objects.put("Data_Source_Identifier",this.dsi);
		return true;
	}

	/** Save the database
	 * @see fr.gouv.culture.sdx.utils.save.Saveable#backup(fr.gouv.culture.sdx.utils.save.SaveParameters)
	 */
	public void backup(SaveParameters save_config) throws SDXException {
		super.backup(save_config);
		if(save_config != null)
			if(save_config.getAttributeAsBoolean(Saveable.ALL_SAVE_ATTRIB,false))
			{
				save_config.setAttribute(Node.Name.TYPE,"POSTGRESQL");
			}
	}

	/**
	 * Overloaded from AbstractJDBCDatabase
	 */
    protected String getCreateIndiciesQuery(String fieldName) {
        return "CREATE INDEX " + getTableName() + '_' + fieldName + "_idx" 
			+ " ON " + getTableName() + " (" + fieldName + ")";
    }

	
	/** 
	 * @see fr.gouv.culture.sdx.utils.database.AbstractJDBCDatabase#getAllEntitiesWithLimitQuery(long, long)
	 * POSTGRESQL implementation
	 * SELECT * FROM &gt;table_name&lt; LIMIT &gt;number&lt; OFFSET &gt;offset&lt; ;
	 */
	protected String getEntriesWithLimitQuery(long offset, long number) {
		String query = "SELECT * FROM " + getTableName();
		query += " LIMIT " + String.valueOf(number) + " OFFSET " + String.valueOf(offset) + ";";
		return query;
	}
	
	/** Restore the database
	 * @see fr.gouv.culture.sdx.utils.save.Saveable#restore(fr.gouv.culture.sdx.utils.save.SaveParameters)
	 */
	public void restore(SaveParameters save_config) throws SDXException {
		super.restore(save_config);
	}
}

