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

com.github.gkutiel.Db Maven / Gradle / Ivy

The newest version!
package com.github.gkutiel;

import static org.slf4j.LoggerFactory.getLogger;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.security.InvalidParameterException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.slf4j.Logger;
import com.github.gkutiel.ParamHandler.BigDecimalHandler;
import com.github.gkutiel.ParamHandler.BlobHandler;
import com.github.gkutiel.ParamHandler.BooleanHandler;
import com.github.gkutiel.ParamHandler.ByteHandler;
import com.github.gkutiel.ParamHandler.DateHandler;
import com.github.gkutiel.ParamHandler.DoubleHandler;
import com.github.gkutiel.ParamHandler.IntHandler;
import com.github.gkutiel.ParamHandler.LongHandler;
import com.github.gkutiel.ParamHandler.StringHandler;
import com.github.gkutiel.ParamHandler.UUIDHandler;
import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;

public class Db {

	public class Stmt {

		private final Object[] params;
		private final String sql;

		Stmt(final String sql, final Object... params) {
			this.sql = sql;
			this.params = params;
		}

		public long execute() {
			try (final Connection con = pool.getConnection(); final PreparedStatement ps = stmt(con);) {
				ps.execute();
				return autoGeneratedId(ps);
			} catch (final SQLException e) {
				throw new RuntimeException(e);
			}
		}

		public  T firstOf(final Class type) {
			try (Connection con = pool.getConnection();
					PreparedStatement ps = stmt(con);
					ResultSet rs = ps.executeQuery();) {
				if (!rs.next()) return null;
				return to(rs, type);
			} catch (final SQLException e) {
				throw new RuntimeException(e);
			}
		}

		public  List listOf(final Class type) {
			try (Connection con = pool.getConnection();
					PreparedStatement ps = stmt(con);
					ResultSet rs = ps.executeQuery();) {
				final List res = new ArrayList<>();
				while (rs.next())
					res.add(to(rs, type));
				return res;
			} catch (final SQLException e) {
				throw new RuntimeException(e);
			}
		}

		private long autoGeneratedId(final PreparedStatement ps) {
			try (ResultSet rs = ps.getGeneratedKeys();) {
				if (!rs.next()) return -1;
				return rs.getLong(1);
			} catch (final SQLException e) {
				throw new RuntimeException(e);
			}
		}

		@SuppressWarnings("unchecked") private  T getVal(final Class type, final String name, final ResultSet rs) {
			try {
				return (T) paramHandlers.get(type).get(rs, name);
			} catch (final SQLException e) {
				throw new RuntimeException(e);
			}
		}

		private void setParam(final PreparedStatement ps, final int paramIndex, final Object param) {
			try {
				final Class type = param.getClass();
				final ParamHandler paramHandler = paramHandlers.get(type);
				if (paramHandler == null) throw new InvalidParameterException("unsupported type " + type);
				paramHandler.set(ps, paramIndex, param);
			} catch (final SQLException e) {
				throw new RuntimeException(e);
			}
		}

		private PreparedStatement stmt(final Connection con) {
			try {
				final PreparedStatement ps = con.prepareStatement(sql);
				for (int paramIndex = 0; paramIndex < params.length; paramIndex++)
					setParam(ps, paramIndex + 1, params[paramIndex]);
				log.debug(ps.toString());
				return ps;
			} catch (final SQLException e) {
				throw new RuntimeException(e);
			}
		}

		@SuppressWarnings("unchecked") private  T to(final ResultSet rs, final Class type) {
			try {
				if (paramHandlers.containsKey(type)) return (T) paramHandlers.get(type).get(rs,
						rs.getMetaData().getColumnLabel(1));
				final T res = type.newInstance();
				final Field[] fields = type.getFields();
				for (final Field field : fields)
					field.set(res, getVal(field.getType(), field.getName(), rs));
				return res;
			} catch (final Exception e) {
				throw new RuntimeException(e);
			}
		}
	}

	private static final Logger log = getLogger(Db.class);

	private static Map, ParamHandler> paramHandlers = paramHandlers();

	public static Db from(final String url) {
		return from(url, "root", "");
	}

	public static Db from(final String url, final String usr, final String pwd) {
		try {
			final BoneCPConfig config = new BoneCPConfig();
			config.setJdbcUrl(url);
			config.setMinConnectionsPerPartition(1);
			config.setMaxConnectionsPerPartition(8);
			config.setPartitionCount(8);
			config.setUsername(usr);
			config.setPassword(pwd);
			return new Db(new BoneCP(config));
		} catch (final SQLException e) {
			throw new RuntimeException(e);
		}
	}

	private static Map, ParamHandler> paramHandlers() {
		final Map, ParamHandler> handlers = new HashMap<>();

		final BooleanHandler booleanHandler = new BooleanHandler();
		final ByteHandler byteHandler = new ByteHandler();
		final DoubleHandler doubleHandler = new DoubleHandler();
		final IntHandler intHandler = new IntHandler();
		final LongHandler longHandler = new LongHandler();

		handlers.put(BigDecimal.class, new BigDecimalHandler());
		handlers.put(Blob.class, new BlobHandler());
		handlers.put(boolean.class, booleanHandler);
		handlers.put(Boolean.class, booleanHandler);
		handlers.put(byte.class, byteHandler);
		handlers.put(Byte.class, byteHandler);
		handlers.put(Date.class, new DateHandler());
		handlers.put(double.class, doubleHandler);
		handlers.put(Double.class, doubleHandler);
		handlers.put(int.class, intHandler);
		handlers.put(Integer.class, intHandler);
		handlers.put(long.class, longHandler);
		handlers.put(Long.class, longHandler);
		handlers.put(String.class, new StringHandler());
		handlers.put(UUID.class, new UUIDHandler());

		return handlers;
	}

	private final BoneCP pool;

	private Db(final BoneCP pool) {
		this.pool = pool;
	}

	public Stmt stmt(final String sql, final Object... args) {
		return new Stmt(sql, args);
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy