package cn.hmsoft.jdbc.generator;

import cn.hmsoft.jdbc.entity.DateFormatType;

public class OracleSQLGenerator extends AbstractSQLGenerator {

	@Override
	public String[] getNextSequence(String sequenceName) {
		String[] array = new String[1];
		array[0] = "select " + sequenceName + ".nextval from dual";
		return array;
	}

	@Override
	public String list(String sql, int start, int limit) {
		return "select * from (" + " select row_.*, rownum rownum_" + " from ( " + sql + " ) row_ )"
				+ " where rownum_ < " + (start + limit) + " and" + " rownum_ >= " + start;
	}

	@Override
	public String queryTables(String databaseName) {
		return "select t1.table_name table_name,t2.comments table_comment,num_rows row_count from user_all_tables t1,user_tab_comments t2 where t1.table_name=t2.table_name and  (1=1 or ''=?)  order by t1.table_name";
	}

	@Override
	public String queryColumns(String databaseName, String tableName) {
		return "select t2.column_name column_name,column_id,nullable,data_length column_length,data_type as s04,data_type column_type,t2.comments column_comment from user_tab_columns t1,user_col_comments t2 where (1=1 or ''=?) and t1.table_name=t2.table_name and t1.COLUMN_NAME=t2.column_name and upper(t1.table_name)=upper(?) order by t1.COLUMN_ID";
	}

	@Override
	public String queryCurrentTime() {
		return "select sysdate ldt01 from dual";
	}

	@Override
	public String random(String sql, int rowCount) {
		return "select t.* from (" + sql + " order by dbms_random.value()) t where rownum<= " + rowCount;
	}

	@Override
	public String isNull(String columnName) {
		return "nvl(" + columnName + ",?)";
	}

	@Override
	public String isNull(String columnName, String otherColumn) {
		return "nvl(" + columnName + "," + otherColumn + ")";
	}

	@Override
	public String concatValues(String columnName) {
		return "to_char(wmsys.wm_concat(" + columnName + "))";
	}

	@Override
	public String random() {
		return " dbms_random.value() ";
	}

	@Override
	public String formatDate(String columnName, DateFormatType format) {
		if (format == DateFormatType.LongDate)
			return " to_char(" + columnName + ",'yyyy-MM-dd HH24:mi:ss') ";
		else if (format == DateFormatType.ShortDate)
			return " to_char(" + columnName + ",'yyyy-MM-dd') ";
		else if (format == DateFormatType.LongTime)
			return " to_char(" + columnName + ",'HH24:mi:ss') ";
		else if (format == DateFormatType.HourMinute)
			return " to_char(" + columnName + ",'HH24:mi') ";
		else if (format == DateFormatType.MinuteSecond)
			return " to_char(" + columnName + ",'mi:ss') ";
		return " to_char(" + columnName + ",'yyyy-MM-dd HH24:mi:ss') ";
	}

}
