Android Open Source - DKO Temporary Table Factory






From Project

Back to project page DKO.

License

The source code is released under:

GNU Lesser General Public License

If you think the Android project DKO listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package org.kered.dko;
/*from  w  w w .  ja  v a 2 s  . c o m*/
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.sql.DataSource;

import org.kered.dko.Constants.DB_TYPE;
import org.kered.dko.Field.FK;
import org.kered.dko.Field.PK;

class TemporaryTableFactory {

  static class DummyTableWithName<T extends Table> extends Table {

    final String name = "NOSCO_"+ Math.round(Math.random() * Integer.MAX_VALUE);
    Class<T> cls = null;
    private List<Field<?>> fields = null;
    private Collection<T> set = null;

    @SuppressWarnings("rawtypes")
    public static Field.PK<?> PK = new Field.PK();

    @SuppressWarnings("unused")
    protected DummyTableWithName(final Field[] _fields, final Object[] _objects, final int _start, final int _end) {
      // TODO Auto-generated method stub
    }

    public DummyTableWithName(final Class<T> cls, final List<Field<?>> fields, final Collection<T> set) {
      this.cls = cls;
      this.fields = fields;
      this.set = set;
    }

    public static String _SCHEMA_NAME = null;

    @Override
    public List<Field<?>> fields() {
      // TODO Auto-generated method stub
      return null;
    }

    @Override
    protected FK[] FKS() {
      // TODO Auto-generated method stub
      return null;
    }

    @Override
    public <S> S get(final Expression.Select<S> field) {
      // TODO Auto-generated method stub
      return null;
    }

    @Override
    public <S> Table set(final Expression.Select<S> field, final S value) {
      return null;
      // TODO Auto-generated method stub

    }

    @Override
    public boolean insert() throws SQLException {
      // TODO Auto-generated method stub
      return false;
    }

    @Override
    public boolean update() throws SQLException {
      // TODO Auto-generated method stub
      return false;
    }

    @Override
    public boolean delete() throws SQLException {
      // TODO Auto-generated method stub
      return false;
    }

    @Override
    public boolean save() throws SQLException {
      // TODO Auto-generated method stub
      return false;
    }

    @Override
    public boolean exists() throws SQLException {
      // TODO Auto-generated method stub
      return false;
    }

    @Override
    public boolean insert(final DataSource ds) throws SQLException {
      // TODO Auto-generated method stub
      return false;
    }

    @Override
    public boolean update(final DataSource ds) throws SQLException {
      // TODO Auto-generated method stub
      return false;
    }

    @Override
    public boolean delete(final DataSource ds) throws SQLException {
      // TODO Auto-generated method stub
      return false;
    }

    @Override
    public boolean save(final DataSource ds) throws SQLException {
      // TODO Auto-generated method stub
      return false;
    }

    @Override
    public boolean exists(final DataSource ds) throws SQLException {
      // TODO Auto-generated method stub
      return false;
    }

    @Override
    protected Object __NOSCO_PRIVATE_mapType(final Object o) {
      // TODO Auto-generated method stub
      return null;
    }

    @Override
    protected void __NOSCO_PRIVATE_preExecute(final SqlContext context, final Connection conn) throws SQLException {
      Statement stmt = null;
      PreparedStatement ps = null;
      try {
        stmt = conn.createStatement();
        final StringBuffer sqlSb = new StringBuffer();
        String tableName = (context.dbType==Constants.DB_TYPE.SQLSERVER ? "#" : "") + name;
        if (context.dbType==Constants.DB_TYPE.DERBY) tableName = "SESSION."+tableName;
        String fluff = "";
        if (context.dbType==Constants.DB_TYPE.SQLSERVER) fluff = "TEMPORARY ";
        if (context.dbType==Constants.DB_TYPE.ORACLE || context.dbType==Constants.DB_TYPE.DERBY) fluff = "GLOBAL TEMPORARY ";
        String create = context.dbType==Constants.DB_TYPE.DERBY ? "DECLARE " : "CREATE ";
        sqlSb.append(create+ fluff +"TABLE "+ tableName + "(");
        final List<String> placeholders = new ArrayList<String>();
        for (int i=0; i<fields.size(); ++i) {
          final Field<?> field = fields.get(i);
          placeholders.add("?");
          sqlSb.append(field.NAME);
          sqlSb.append(" ");
          sqlSb.append(field.SQL_TYPE);
          if (context.dbType==Constants.DB_TYPE.MYSQL && "varchar".equals(field.SQL_TYPE.toLowerCase())) {
            sqlSb.append("(4096)");
          }
          if (context.dbType==Constants.DB_TYPE.DERBY && "varchar".equals(field.SQL_TYPE.toLowerCase())) {
            sqlSb.append("(32672)");
          }
          if (i < fields.size()-1) sqlSb.append(", ");
        }
        sqlSb.append(")");
        if (context.dbType==Constants.DB_TYPE.ORACLE || context.dbType==Constants.DB_TYPE.DERBY) {
          sqlSb.append(" ON COMMIT PRESERVE ROWS");
        }
        if (context.dbType==Constants.DB_TYPE.DERBY) {
          sqlSb.append(" NOT LOGGED");
        }
        final String sql = sqlSb.toString();
        Util.log(sql, null);
        stmt.execute(sql);
        String sqlInsert = "insert into "+ tableName +" values ("+ Util.join(",", placeholders) +")";
        Util.log(sqlInsert, null);
        ps = conn.prepareStatement(sqlInsert);
        int i = 0;
        int added = 0;
        for (final T t : set) {
          ++i;
          for (int j=0; j<fields.size(); ++j) {
            final Field<?> field = fields.get(j);
            final Object o = t.get(field);
            Util.setBindingWithTypeFixes(ps, j+1, o);
          }
          ps.addBatch();
          if (i%64 == 0) {
            for (int x : ps.executeBatch()) {
              if (context.dbType==DB_TYPE.ORACLE && x==-2) {
                // from oracle's docs:  a value of -2 indicates that a element was processed 
                // successfully, but that the number of effected rows is unknown.
                x = 1;
              }
              added += x;
            }
          }
        }
        if (i%64 != 0) {
          for (int x : ps.executeBatch()) {
            if (context.dbType==DB_TYPE.ORACLE && x==-2) {
              // from oracle's docs:  a value of -2 indicates that a element was processed 
              // successfully, but that the number of effected rows is unknown.
              x = 1;
            }
            added += x;
          }
        }
//        ResultSet rs = stmt.executeQuery("select count(1) from "+ tableName);
//        while (rs.next()) {
//          System.err.println("tmp table "+ tableName +" has "+ rs.getLong(1) +" rows");
//        }
//        rs.close();
        //System.out.println("added "+ added);
      } catch (final SQLException e) {
        throw e;
      } finally {
        try {
          if (stmt!=null && !stmt.isClosed()) stmt.close();
        } catch (final SQLException e) {
          e.printStackTrace();
        }
        try {
          if (ps!=null && !ps.isClosed()) ps.close();
        } catch (final SQLException e) {
          e.printStackTrace();
        }
      }
    }
    @Override
    protected void __NOSCO_PRIVATE_postExecute(final SqlContext context, final Connection conn) throws SQLException {
      Statement stmt = null;
      String tableName = (context.dbType==Constants.DB_TYPE.SQLSERVER ? "#" : "") + name;
      if (context.dbType==Constants.DB_TYPE.DERBY) tableName = "SESSION."+tableName;
      try {
        stmt = conn.createStatement();
        if (context.dbType==DB_TYPE.ORACLE) {
          // oracle requires a TRUNCATE before a drop for tmp tables, otherwise you get:
          // ORA-14452: attempt to create, alter or drop an index on temporary table already in use
          final String sql = "TRUNCATE TABLE "+ tableName;
          Util.log(sql, null);
          stmt.execute(sql);
        }
        final String sql = "DROP TABLE "+ tableName;
        Util.log(sql, null);
        stmt.execute(sql);
      } catch (final SQLException e) {
        throw e;
      } finally {
        try {
          if (stmt!=null && !stmt.isClosed()) stmt.close();
        } catch (final SQLException e) {
          e.printStackTrace();
        }
      }
    }

  }

  @SuppressWarnings("unchecked")
  static <T extends Table> DummyTableWithName createTemporaryTable(final Class<T> cls, final List<Field<?>> fields, final Collection<T> set) {
    return new DummyTableWithName<T>(cls, fields, set);
  }

}




Java Source Code List

.HelloWorld.java
org.kered.contactlensfinder.DB.java
org.kered.contactlensfinder.MainActivity.java
org.kered.contactlensfinder.ViewManufacturersActivity.java
org.kered.contactlensfinder.ViewProductsActivity.java
org.kered.contactlensfinder.ViewPropertiesActivity.java
org.kered.dko.AbstractQuery.java
org.kered.dko.Bulk.java
org.kered.dko.CSV.java
org.kered.dko.ClosableIterator.java
org.kered.dko.Condition.java
org.kered.dko.Constants.java
org.kered.dko.Context.java
org.kered.dko.DBQuery.java
org.kered.dko.DBRowIterator.java
org.kered.dko.Diff.java
org.kered.dko.DualIterator.java
org.kered.dko.Expression.java
org.kered.dko.Field.java
org.kered.dko.FilteringQuery.java
org.kered.dko.Function.java
org.kered.dko.InMemoryQuery.java
org.kered.dko.Join.java
org.kered.dko.LazyCacheIterable.java
org.kered.dko.LocalJoin.java
org.kered.dko.M.java
org.kered.dko.Main.java
org.kered.dko.MatryoshkaQuery.java
org.kered.dko.PeekableClosableIterator.java
org.kered.dko.PeekableIterator.java
org.kered.dko.QueryAddField.java
org.kered.dko.QueryFactory.java
org.kered.dko.QuerySnapshot.java
org.kered.dko.Query.java
org.kered.dko.SQLFunction.java
org.kered.dko.SelectAsMapIterable.java
org.kered.dko.SelectFromOAI.java
org.kered.dko.SelectSingleColumn.java
org.kered.dko.SoftJoinUtil.java
org.kered.dko.SoftJoin.java
org.kered.dko.SqlContext.java
org.kered.dko.Statistics.java
org.kered.dko.SubQueryField.java
org.kered.dko.TableInfo.java
org.kered.dko.TableWrapper.java
org.kered.dko.Table.java
org.kered.dko.TemporaryTableFactory.java
org.kered.dko.TmpTableBuilder.java
org.kered.dko.Tuple.java
org.kered.dko.UsageMonitor.java
org.kered.dko.UsageStats.java
org.kered.dko.Util.java
org.kered.dko.ant.ClassGenerator.java
org.kered.dko.ant.CodeGeneratorBase.java
org.kered.dko.ant.CodeGenerator.java
org.kered.dko.ant.DataSourceGenerator.java
org.kered.dko.ant.GsonGenerator.java
org.kered.dko.ant.JoinGenerator.java
org.kered.dko.ant.Main.java
org.kered.dko.ant.SchemaExtractorBase.java
org.kered.dko.ant.SchemaExtractor.java
org.kered.dko.ant.Util.java
org.kered.dko.datasource.CheapConnectionPoolingDataSource.java
org.kered.dko.datasource.ConnectionCountingDataSource.java
org.kered.dko.datasource.JDBCDriverDataSource.java
org.kered.dko.datasource.MatryoshkaDataSource.java
org.kered.dko.datasource.MirroredDataSource.java
org.kered.dko.datasource.ReflectedDataSource.java
org.kered.dko.datasource.SingleConnectionDataSource.java
org.kered.dko.datasource.SingleThreadedDataSource.java
org.kered.dko.datasource.UnClosableConnection.java
org.kered.dko.datasource.Util.java
org.kered.dko.json.CDL.java
org.kered.dko.json.CookieList.java
org.kered.dko.json.Cookie.java
org.kered.dko.json.HTTPTokener.java
org.kered.dko.json.HTTP.java
org.kered.dko.json.JSONArray.java
org.kered.dko.json.JSONException.java
org.kered.dko.json.JSONML.java
org.kered.dko.json.JSONObject.java
org.kered.dko.json.JSONString.java
org.kered.dko.json.JSONStringer.java
org.kered.dko.json.JSONTokener.java
org.kered.dko.json.JSONWriter.java
org.kered.dko.json.Pickle.java
org.kered.dko.json.XMLTokener.java
org.kered.dko.json.XML.java
org.kered.dko.junk.DerbyLoadTestSchema.java
org.kered.dko.junk.OracleCreateTestUser.java
org.kered.dko.junk.OracleLoadTestSchema.java
org.kered.dko.persistence.Util.java
org.kered.dko.util.DumpDatabase.java
sakila.Example0.java
sakila.Example1.java
sakila.Example2.java
sakila.Util.java