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

com.github.gkutiel.flip.db.SqlUtils Maven / Gradle / Ivy

package com.github.gkutiel.flip.db;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import com.github.gkutiel.flip.db.Indexs.Index;
import com.github.gkutiel.flip.utils.Utils;

enum SqlUtils {
	;
	private static String colDef(final Field col) {
		final StringBuilder colDef = new StringBuilder();

		colDef.append(col.getName());
		colDef.append(" ");
		colDef.append(FlipDB.JAVA_TO_SQL.get(col.getType()));

		return colDef.toString();
	}

	static String colDefs(final Class table) {
		final StringBuilder colDefs = new StringBuilder();

		final Field[] cols = table.getDeclaredFields();
		colDefs.append(colDef(cols[0]));
		for (int i = 1; i < cols.length; i++) {
			colDefs.append(",");
			colDefs.append(colDef(cols[i]));
		}

		return colDefs.toString();
	}

	static void createIndexes(final Connection con, final Class table) throws SQLException {
		for (final String sql : indexs(table))
			con.createStatement().execute(sql);
	}

	static String createTableSql(final Class table) {
		final StringBuilder sql = new StringBuilder();

		sql.append("CREATE TABLE IF NOT EXISTS ");
		sql.append(table.getSimpleName());
		sql.append("(");
		sql.append(SqlUtils.colDefs(table));
		sql.append(")");

		return sql.toString();
	}

	private static List indexs(final Class table) {
		final Indexs indexs = table.getAnnotation(Indexs.class);
		if (indexs == null) return Collections.emptyList();
		final Index[] is = indexs.value();
		if (is == null) return Collections.emptyList();

		final List sqls = new LinkedList<>();
		for (final Index index : is)
			sqls.add("CREATE INDEX ON " + table.getSimpleName() + "(" + Utils.Strings.concat(",", index.value()) + ")");
		return sqls;
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy