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

com.wizarius.orm.database.postgres.driver.PostgresDriver Maven / Gradle / Ivy

The newest version!
package com.wizarius.orm.database.postgres.driver;

import com.wizarius.orm.database.DBException;
import com.wizarius.orm.database.actions.IDBDialect;
import com.wizarius.orm.database.connection.ConnectionDriver;
import com.wizarius.orm.database.connection.ConnectionParametersList;
import com.wizarius.orm.database.postgres.PostgresDialect;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

@Slf4j
public class PostgresDriver implements ConnectionDriver {
    private final String url;
    private final String driver;
    private final String username;
    private final String password;
    private final IDBDialect dialect;

    public PostgresDriver(String driver, String username, String password, String databaseName, String hostname, int port, ConnectionParametersList params) {
        this.driver = driver;
        this.username = username;
        this.password = password;
        this.dialect = new PostgresDialect();
        StringBuilder sb = new StringBuilder();
        if (params != null) {
            sb.append("?");
            sb.append(params.get(0).getKey()).append("=");
            sb.append(params.get(0).getValue()).append("&");
            for (int i = 1; i < params.size(); i++) {
                sb.append(params.get(i).getKey()).append("=");
                sb.append(params.get(i).getValue()).append("&");
            }
            sb.setLength(sb.length() - 1);
        }
        this.url = "jdbc:postgresql://" + hostname + ":" + port + "/" + databaseName + sb.toString();
    }

    /**
     * Returns sql connection
     *
     * @return jdbc connection
     * @throws DBException on unable to initialize
     */
    @Override
    public Connection getConnection() throws DBException {
        log.debug("Get postgres connection");
        Connection con;
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            throw new DBException("Unable to open connection", e);
        }
        return con;
    }

    /**
     * Returns connection url
     *
     * @return connection url
     */
    @Override
    public String getURL() {
        return this.url;
    }

    /**
     * Returns db dialect
     *
     * @return db dialect
     */
    @Override
    public IDBDialect getDialect() {
        return dialect;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy