<commit_before>/*
Copyright 2009-2010 <NAME> 

Licensed under the Apache License, Version 2.0 (the "License"); 
you may not use this file except in compliance with the License. 
You may obtain a copy of the License at 

http://www.apache.org/licenses/LICENSE-2.0 

Unless required by applicable law or agreed to in writing, software 
distributed under the License is distributed on an "AS IS" BASIS, 
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
See the License for the specific language governing permissions and 
limitations under the License. 
*/


package activejdbc;

import javalite.common.Convert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.*;
import java.util.*;
import static activejdbc.LogFilter.*;

/**
 * @author <NAME>
 */
public class DB {
    
    private String dbName;
    final static Logger logger = LoggerFactory.getLogger(DB.class);

    public DB(String dbName){
        this.dbName = dbName;
    }

    public void open(String driver, String url, String user, String password) {
        try {
            Class.forName(driver);
            Connection connection = DriverManager.getConnection(url, user, password);
            ConnectionsAccess.attach(dbName, connection);
        } catch (Exception e) {
            throw new InitException(e);
        }
    }

    /**
     * Another way to open connection if we need to pass some driver-specific parameters
     * @param driver driver class name
     * @param url JDBC URL
     * @param props connection properties
     */
    public void open(String driver, String url, Properties props) {
        try {
            Class.forName(driver);
            Connection connection = DriverManager.getConnection(url, props);
            ConnectionsAccess.attach(dbName, connection);
        } catch (Exception e) {
            throw new InitException(e);
        }
    }

    public void open(String jndiName) {
        try {
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup(jndiName);
            Connection connection = ds.getConnection();
            ConnectionsAccess.attach(dbName, connection);
        } catch (Exception e) {
            throw new InitException(e);
        }
    }

    public void open(DataSource datasource)
    {
        try {
            Connection connection = datasource.getConnection();
            ConnectionsAccess.attach(dbName, connection);
        } catch (Exception e) {
            throw new InitException(e);
        }
    }


    public void open(String jndiName, Properties jndiProperties) {
        try {
            Context ctx = new InitialContext(jndiProperties);
            DataSource ds = (DataSource) ctx.lookup(jndiName);
            Connection connection = ds.getConnection();
            ConnectionsAccess.attach(dbName, connection);
        } catch (Exception e) {
            throw new InitException(e);
        }
    }


    public void open(ConnectionSpec spec){
        if(spec instanceof ConnectionJdbcSpec){
            openJdbc((ConnectionJdbcSpec)spec);
        }else if(spec instanceof ConnectionJndiSpec){
            openJndi((ConnectionJndiSpec)spec);
        }else{
            throw new IllegalArgumentException("this spec not supported: " + spec.getClass());
        }
    }

    private void openJdbc(ConnectionJdbcSpec spec) {

        if(spec.getProps()!= null){
            open(spec.getDriver(), spec.getUrl(), spec.getProps());
        }else{
            open(spec.getDriver(), spec.getUrl(), spec.getUser(), spec.getPassword());
        }
    }

    private void openJndi(ConnectionJndiSpec spec) {
        if(spec.getContext() != null){
            openContext(spec.getContext(), spec.getDataSourceJndiName());
        }else{
            open(spec.getDataSourceJndiName());
        }
    }

    private void openContext(InitialContext context, String jndiName) {
        try {         
            DataSource ds = (DataSource) context.lookup(jndiName);
            Connection connection = ds.getConnection();
            ConnectionsAccess.attach(dbName, connection);
        } catch (Exception e) {
            throw new InitException(e);
        }
    }


    public void close() {
        try {
            Connection connection = ConnectionsAccess.getConnection(dbName);
            StatementCache.instance().cleanStatementCache(connection);

            if(connection != null){
                connection.close();
                log(logger, "Closed connection: " + connection);
                ConnectionsAccess.detach(dbName);
            }else{
                logger.warn("Cannot close connection if it is null");
            }

        } catch (Exception e) {
            logException("Could not close connection", e);
        }
    }

    
    public Long count(String table){
        String sql = "SELECT COUNT(*) FROM " + table ;
        return Convert.toLong(firstCell(sql));
    }

    /**
     * Runs a count query, returns a number of matching records.
     *
     * @param table table in which to count rows. 
     * @param query this is a filtering query for the count. If '*' provided, all records will be counted. Example:
     * <code>"age > 65 AND department = 'accounting'"</code>
     * @param params parameters for placeholder substitution.
     * @return copunt number of records found in a table.
     */
    public Long count(String table, String query, Object... params) {

        if(query.trim().equals("*") && params.length == 0){
            return count(table);
        }
        if(query.trim().equals("*") && params.length != 0){
            throw new IllegalArgumentException("cannot use '*' and parameters");
        }
<commit_msg>swithed from exception to warning in cases when DB.close() cannot close a connection<commit_after>/*
Copyright 2009-2010 <NAME> 

Licensed under the Apache License, Version 2.0 (the "License"); 
you may not use this file except in compliance with the License. 
You may obtain a copy of the License at 

http://www.apache.org/licenses/LICENSE-2.0 

Unless required by applicable law or agreed to in writing, software 
distributed under the License is distributed on an "AS IS" BASIS, 
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
See the License for the specific language governing permissions and 
limitations under the License. 
*/


package activejdbc;

import javalite.common.Convert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.*;
import java.util.*;
import static activejdbc.LogFilter.*;

/**
 * @author <NAME>
 */
public class DB {
    
    private String dbName;
    final static Logger logger = LoggerFactory.getLogger(DB.class);

    public DB(String dbName){
        this.dbName = dbName;
    }

    public void open(String driver, String url, String user, String password) {
        try {
            Class.forName(driver);
            Connection connection = DriverManager.getConnection(url, user, password);
            ConnectionsAccess.attach(dbName, connection);
        } catch (Exception e) {
            throw new InitException(e);
        }
    }

    /**
     * Another way to open connection if we need to pass some driver-specific parameters
     * @param driver driver class name
     * @param url JDBC URL
     * @param props connection properties
     */
    public void open(String driver, String url, Properties props) {
        try {
            Class.forName(driver);
            Connection connection = DriverManager.getConnection(url, props);
            ConnectionsAccess.attach(dbName, connection);
        } catch (Exception e) {
            throw new InitException(e);
        }
    }

    public void open(String jndiName) {
        try {
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup(jndiName);
            Connection connection = ds.getConnection();
            ConnectionsAccess.attach(dbName, connection);
        } catch (Exception e) {
            throw new InitException(e);
        }
    }

    public void open(DataSource datasource)
    {
        try {
            Connection connection = datasource.getConnection();
            ConnectionsAccess.attach(dbName, connection);
        } catch (Exception e) {
            throw new InitException(e);
        }
    }


    public void open(String jndiName, Properties jndiProperties) {
        try {
            Context ctx = new InitialContext(jndiProperties);
            DataSource ds = (DataSource) ctx.lookup(jndiName);
            Connection connection = ds.getConnection();
            ConnectionsAccess.attach(dbName, connection);
        } catch (Exception e) {
            throw new InitException(e);
        }
    }


    public void open(ConnectionSpec spec){
        if(spec instanceof ConnectionJdbcSpec){
            openJdbc((ConnectionJdbcSpec)spec);
        }else if(spec instanceof ConnectionJndiSpec){
            openJndi((ConnectionJndiSpec)spec);
        }else{
            throw new IllegalArgumentException("this spec not supported: " + spec.getClass());
        }
    }

    private void openJdbc(ConnectionJdbcSpec spec) {

        if(spec.getProps()!= null){
            open(spec.getDriver(), spec.getUrl(), spec.getProps());
        }else{
            open(spec.getDriver(), spec.getUrl(), spec.getUser(), spec.getPassword());
        }
    }

    private void openJndi(ConnectionJndiSpec spec) {
        if(spec.getContext() != null){
            openContext(spec.getContext(), spec.getDataSourceJndiName());
        }else{
            open(spec.getDataSourceJndiName());
        }
    }

    private void openContext(InitialContext context, String jndiName) {
        try {         
            DataSource ds = (DataSource) context.lookup(jndiName);
            Connection connection = ds.getConnection();
            ConnectionsAccess.attach(dbName, connection);
        } catch (Exception e) {
            throw new InitException(e);
        }
    }


    public void close() {
        try {
            Connection connection = ConnectionsAccess.getConnection(dbName);
            StatementCache.instance().cleanStatementCache(connection);

            if(connection != null){
                connection.close();
                log(logger, "Closed connection: " + connection);
                ConnectionsAccess.detach(dbName);
            }else{
                logger.warn("Cannot close connection if it is null");
            }

        } catch (Exception e) {
            logger.warn("Could not close connection: " + e);
        }
    }

    
    public Long count(String table){
        String sql = "SELECT COUNT(*) FROM " + table ;
        return Convert.toLong(firstCell(sql));
    }

    /**
     * Runs a count query, returns a number of matching records.
     *
     * @param table table in which to count rows. 
     * @param query this is a filtering query for the count. If '*' provided, all records will be counted. Example:
     * <code>"age > 65 AND department = 'accounting'"</code>
     * @param params parameters for placeholder substitution.
     * @return copunt number of records found in a table.
     */
    public Long count(String table, String query, Object... params) {

        if(query.trim().equals("*") && params.length == 0){
            return count(table);
        }
        if(query.trim().equals("*") && params.length != 0){
            throw new IllegalArgumentException("cannot use '*' and parameters");
        }

{'fraction_non_alphanumeric': 0.09766726480389644, 'fraction_numerical': 0.0030761343245321714, 'mean_word_length': 2.335423197492163, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5618053', 'n_tokens_mistral': 3077, 'n_tokens_neox': 2962, 'n_words': 911}