Automatic table creation.

@param persistenceServiceUnit persistence service unit
@throws Exception if an error occurs creating tables.
762474
private void createTables(PersistenceServiceUnit persistenceServiceUnit) throws Exception {
        // Run under a new transaction and commit right away
        LocalTransactionCurrent localTranCurrent = this.localTranCurrent;
        LocalTransactionCoordinator suspendedLTC = localTranCurrent.suspend();
        EmbeddableWebSphereTransactionManager tranMgr = this.tranMgr;
        Transaction suspendedTran = suspendedLTC == null ? tranMgr.suspend() : null;
        boolean psuIsPUSI = (persistenceServiceUnit instanceof PersistenceServiceUnitImpl) ? true : false;

        synchronized (persistenceServiceUnit) {
            try {
                if (psuIsPUSI) {
                    ((PersistenceServiceUnitImpl) persistenceServiceUnit).setTransactionManager(tranMgr);
                }
                persistenceServiceUnit.createTables();
            } finally {
                // resume
                if (psuIsPUSI) {
                    ((PersistenceServiceUnitImpl) persistenceServiceUnit).setTransactionManager(null);
                }
                if (suspendedTran != null)
                    tranMgr.resume(suspendedTran);
                else if (suspendedLTC != null)
                    localTranCurrent.resume(suspendedLTC);
            }
        }
    }
1022899
@Override
    public void start() {
        if(null != entityManagerFactory) {
            throw new IllegalStateException("Persistence service was already initialized.");
        }

        final Configuration configuration = new Configuration();

        //
        // We'll want to map these to settings
        //
        configuration.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "managed");
        configuration.setProperty(AvailableSettings.USE_GET_GENERATED_KEYS, TRUE_STRING);
        configuration.setProperty(AvailableSettings.USE_REFLECTION_OPTIMIZER, TRUE_STRING);
        configuration.setProperty(AvailableSettings.ORDER_UPDATES, TRUE_STRING);
        configuration.setProperty(AvailableSettings.ORDER_INSERTS, TRUE_STRING);
        configuration.setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, TRUE_STRING);
        configuration.setProperty("jadira.usertype.autoRegisterUserTypes", TRUE_STRING);
        configuration.setProperty(AvailableSettings.DIALECT, settings.getDatabaseSettings().getDialectClass());

        // turn on and off features based upon log level
        if(LOG.isDebugEnabled()) {
            configuration.setProperty(AvailableSettings.GENERATE_STATISTICS, TRUE_STRING);
            configuration.setProperty(AvailableSettings.SHOW_SQL, TRUE_STRING);
        } else {
            configuration.setProperty(AvailableSettings.GENERATE_STATISTICS, FALSE_STRING);
            configuration.setProperty(AvailableSettings.SHOW_SQL, FALSE_STRING);
        }

        // add in all the entities
        for (final Class<? extends Serializable> entity : settings.getDatabaseSettings().getEntities()) {
            LOG.debug("Adding entity: {}", entity.getCanonicalName());
            configuration.addAnnotatedClass(entity);
        }

        final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties())
            // set our connection provider
            .addService(ConnectionProvider.class, connectionProvider)
            .build();

        // create the actual entity manager
        this.entityManagerFactory = new EntityManagerFactoryImpl(PersistenceUnitTransactionType.RESOURCE_LOCAL,
                                                                 false,
                                                                 null,
                                                                 configuration,
                                                                 serviceRegistry,
                                                                 persistenceUnitName);

    }
1342355
public void createTable(TableSpec spec) throws SQLException {
        Statement s = createStatement();
        Iterator<String> iter = m_converter.getDDL(spec).iterator();
        while (iter.hasNext()) {
            String updateSQL = iter.next();
            s.executeUpdate(updateSQL);
        }
    }
834376
private DBService createDefaultDBService() {
        m_logger.info("Creating DBService for default tenant");
        String dbServiceName = ServerParams.instance().getModuleParamString("DBService", "dbservice");
        if (Utils.isEmpty(dbServiceName)) {
            throw new RuntimeException("'DBService.dbservice' parameter is not defined.");
        }

        DBService dbservice = null;
        Tenant defaultTenant = TenantService.instance().getDefaultTenant();
        boolean bDBOpened = false;
        while (!bDBOpened) {
            try {
                // Find and call the constructor DBService(Tenant).
                @SuppressWarnings("unchecked")
                Class<DBService> serviceClass = (Class<DBService>) Class.forName(dbServiceName);
                Constructor<DBService> constructor = serviceClass.getConstructor(Tenant.class);
                dbservice = constructor.newInstance(defaultTenant);
                dbservice.initialize();
                dbservice.start();
                bDBOpened = true;
            } catch (IllegalArgumentException e) {
                throw new RuntimeException("Cannot load specified 'dbservice': " + dbServiceName, e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Could not load dbservice class '" + dbServiceName + "'", e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("Required constructor missing for dbservice class: " + dbServiceName, e);
            } catch (SecurityException | InstantiationException | IllegalAccessException e) {
                throw new RuntimeException("Could not invoke constructor for dbservice class: " + dbServiceName, e);
            } catch (InvocationTargetException e) {
                // This is thrown when a constructor is invoked via reflection.
                if (!(e.getTargetException() instanceof DBNotAvailableException)) {
                    throw new RuntimeException("Could not invoke constructor for dbservice class: " + dbServiceName, e);
                }
            } catch (DBNotAvailableException e) {
                // Fall through to retry.
            } catch (Throwable e) {
                throw new RuntimeException("Failed to initialize default DBService: " + dbServiceName, e);
            }
            if (!bDBOpened) {
                m_logger.info("Database is not reachable. Waiting to retry");
                try {
                    Thread.sleep(db_connect_retry_wait_millis);
                } catch (InterruptedException ex2) {
                    // ignore
                }
            }
        }
        return dbservice;
        
    }
408095
@Override
    public void load(String persistenceUnit, Map<String, Object> puProperties)
    {
        setPersistenceUnit(persistenceUnit);

        // Load Client Specific Stuff
        logger.info("Loading client metadata for persistence unit : " + persistenceUnit);
        loadClientMetadata(puProperties);

        // initialize the client
        logger.info("Initializing client for persistence unit : " + persistenceUnit);
        initialize(puProperties);

        // Construct Pool
        logger.info("Constructing pool for persistence unit : " + persistenceUnit);
        connectionPoolOrConnection = createPoolOrConnection();
    }
167995
@Override
	public JobStatus createJobStatus(long jobInstanceId) {
		logger.entering(CLASSNAME, "createJobStatus", jobInstanceId);
		Connection conn = null;
		PreparedStatement statement = null;
		JobStatus jobStatus = new JobStatus(jobInstanceId);
		try {
			conn = getConnection();
			statement = conn.prepareStatement("INSERT INTO jobstatus (id, obj) VALUES(?, ?)");
			statement.setLong(1, jobInstanceId);
			statement.setBytes(2, serializeObject(jobStatus));
			statement.executeUpdate();

		} catch (SQLException e) {
			throw new PersistenceException(e);
		} catch (IOException e) {
			throw new PersistenceException(e);
		} finally {
			cleanupConnection(conn, null, statement);
		}
		logger.exiting(CLASSNAME, "createJobStatus");
		return jobStatus;
	}
52057
private synchronized PersistenceServiceUnit createPsu() throws Exception {
        if (psu != null) {
            return psu;
        }

        // Load the PSU including the most recent entities.
        PersistenceServiceUnit retMe = createLatestPsu();

        // If any tables are not up to the current code level, re-load the PSU with backleveled entities.
        int instanceVersion = getJobInstanceTableVersion(retMe);
        if (instanceVersion < 3) {
            logger.fine("The GROUPNAMES column could not be found. The persistence service unit will exclude the V3 instance entity.");
            retMe.close();
            retMe = createPsu(instanceVersion, MAX_EXECUTION_VERSION);
        }

        int executionVersion = getJobExecutionTableVersion(retMe);
        if (executionVersion < 2) {
            logger.fine("The JOBPARAMETERS table could not be found. The persistence service unit will exclude the V2 execution entity.");
            retMe.close();
            retMe = createPsu(instanceVersion, executionVersion);
        }

        //222050 - Backout 205106 RemotablePartitionEntity.class.getName());

        // Perform recovery immediately, before returning from this method, so that
        // other callers won't be able to access the PSU (via getPsu()) until recovery is complete.
        new WSStartupRecoveryServiceImpl().setIPersistenceManagerService(JPAPersistenceManagerImpl.this).setPersistenceServiceUnit(retMe).recoverLocalJobsInInflightStates();
        //222050 - Backout 205106 .recoverLocalPartitionsInInflightStates();

        // Make sure we assign psu before leaving the synchronized block.
        psu = retMe;

        return psu;
    }
736166
public final void loadSqlTables() throws Exception {
    for (Class<?> clazz : this.mngSettings.getClasses()) {
      TableSql tableSql = new TableSql();
      makeTableSqlFromXml(tableSql, clazz);
      this.tablesMap.put(clazz.getSimpleName(), tableSql);
    }
    for (Class<?> clazz : this.mngSettings.getClasses()) {
      TableSql tableSql = this.tablesMap.get(clazz.getSimpleName());
      StringBuffer sbIdNamesUc = new StringBuffer("");
      for (int i = 0; i < tableSql.getIdColumnsNames().length; i++) {
        if (i > 0) {
          sbIdNamesUc.append(",");
        }
        sbIdNamesUc.append(tableSql.getIdColumnsNames()[i].toUpperCase());
      }
      Field[] fields = getUtlReflection().retrieveFields(clazz);
      for (Field field : fields) {
        FieldSql fieldSql = tableSql.getFieldsMap().get(field.getName());
        if (fieldSql != null) { //if persistable or composite (foreign CID)
          String fldTypeSmpNm = field.getType().getSimpleName();
          try {
            TableSql tableSqlForeign = this.tablesMap.get(fldTypeSmpNm);
            if (tableSqlForeign != null) {
              //if it's foreign entity according entities list ORDER
              //make sure ORDER of entities!!!
              fieldSql.setForeignEntity(fldTypeSmpNm);
              String isNullableStr = this.mngSettings
                .lazFldSts(clazz, field.getName()).get("isNullable");
              if (fieldSql.getDefinition() != null // FK composite ID
                && !Boolean.valueOf(isNullableStr)
                  && !fieldSql.getDefinition().contains("not null")) {
                fieldSql.setDefinition(fieldSql.getDefinition() + " not null");
              }
              //FK:
              StringBuffer sbForeignIdNamesUc = new StringBuffer("");
              for (int i = 0; i < tableSqlForeign.getIdColumnsNames()
                .length; i++) {
                if (i > 0) {
                  sbForeignIdNamesUc.append(",");
                }
                sbForeignIdNamesUc.append(tableSqlForeign
                  .getIdColumnsNames()[i].toUpperCase());
              }
              String fkNames;
              if (tableSqlForeign.getIdColumnsNames().length > 1) {
                // composite FK:
                fkNames = sbForeignIdNamesUc.toString();
                // check if it is also primary key:
                boolean isAlsoPk = true;
                if (tableSql.getIdColumnsNames().length
                  == tableSqlForeign.getIdColumnsNames().length) {
                  for (int i = 0; i < tableSql.getIdColumnsNames()
                    .length; i++) {
                    if (!tableSqlForeign.getIdColumnsNames()[0]
                      .equals(tableSql.getIdColumnsNames()[0])) {
                      isAlsoPk = false;
                      break;
                    }
                  }
                }
                if (isAlsoPk) {
                  fieldSql.setTypeField(ETypeField.COMPOSITE_FK_PK);
                } else {
                  fieldSql.setTypeField(ETypeField.COMPOSITE_FK);
                }
                for (String cIdNm : tableSqlForeign.getIdColumnsNames()) {
                  FieldSql fldCid = new FieldSql();
                  fldCid.setTypeField(ETypeField.DERIVED_FROM_COMPOSITE);
                  if (!Boolean.valueOf(isNullableStr)
                      && !tableSqlForeign.getFieldsMap()
                        .get(cIdNm).getDefinition().contains("not null")) {
                    fldCid.setDefinition(tableSqlForeign.getFieldsMap()
                      .get(cIdNm).getDefinition() + " not null");
                  } else if (Boolean.valueOf(isNullableStr)
                      && fldCid.getDefinition().contains("not null")) {
                    fldCid.setDefinition(tableSqlForeign.getFieldsMap()
                      .get(cIdNm).getDefinition().replace(" not null", ""));
                  } else {
                    fldCid.setDefinition(tableSqlForeign.getFieldsMap()
                      .get(cIdNm).getDefinition());
                  }
                  fldCid.setForeignEntity(tableSqlForeign.getFieldsMap()
                    .get(cIdNm).getForeignEntity());
                  tableSql.getFieldsMap().put(cIdNm, fldCid);
                }
              } else {
                fkNames = field.getName().toUpperCase();
                if (fieldSql.getDefinition() == null) {
                  throw new ExceptionWithCode(ExceptionWithCode
                    .CONFIGURATION_MISTAKE,
                      "Where is no definition FID class/name: "
                        + clazz.getSimpleName() + "/" + field.getName());
                }
              }
              int hc = fldTypeSmpNm.hashCode();
              String hashCfesn;
              if (hc < 0) {
                hc = -hc;
                hashCfesn = "M" + hc;
              } else {
                hashCfesn = String.valueOf(hc);
              }

              String constraintFk = "constraint fk"
                + clazz.getSimpleName()
                + hashCfesn + field.getName()
                + " foreign key (" + fkNames
                + ") references " + fldTypeSmpNm.toUpperCase()
                + " (" + sbForeignIdNamesUc + ")";
              String constraint = tableSql.getConstraint();
              if (constraint != null) {
                constraint += ",\n" + constraintFk;
              } else {
                constraint = constraintFk;
              }
              tableSql.setConstraint(constraint);
            }
            //if field is PK, make sure NOT NULL:
            if (sbIdNamesUc.toString().contains(field.getName().toUpperCase())
                && !fieldSql.getDefinition().contains("not null")) {
              fieldSql.setDefinition(fieldSql.getDefinition()
                + " not null");
            }
          } catch (Exception e) {
            this.logger.error(null, ASrvOrm.class, "Error on load SQL tables:"
              + " class/field/fieldSql/tableSql - " + clazz.getSimpleName()
                + "/" + field.getName() + "/" + fieldSql + "/" + tableSql);
            throw e;
          }
        }
      }
      try {
        for (String colIdNm : tableSql.getIdColumnsNames()) {
          if (tableSql.getFieldsMap().get(colIdNm) == null) {
          throw new ExceptionWithCode(ExceptionWithCode.CONFIGURATION_MISTAKE,
            "Where is no column ID class/name: " + clazz.getSimpleName()
              + "/" + colIdNm);
          }
        }
        //PK if complex (composite or foreign entity):
        if (tableSql.getIdColumnsNames().length > 1 || tableSql.getFieldsMap()
          .get(tableSql.getIdColumnsNames()[0]).getForeignEntity() != null) {
          String constraintPk = "constraint pk"
            + clazz.getSimpleName() + tableSql.getIdColumnsNames()[0]
              + " primary key (" + sbIdNamesUc + ")";
          if (tableSql.getConstraint() == null) {
            tableSql.setConstraint(constraintPk);
          } else {
            tableSql.setConstraint(constraintPk
              + ",\n" + tableSql.getConstraint());
          }
        }
        String constraintAdd = this.mngSettings.lazClsSts(clazz)
          .get("constraintAdd");
        if (constraintAdd != null) {
          if (tableSql.getConstraint() == null) {
            tableSql.setConstraint(constraintAdd);
          } else {
            tableSql.setConstraint(tableSql.getConstraint()
              + ",\n" + constraintAdd);
          }
        }
      } catch (Exception e) {
        this.logger.error(null, ASrvOrm.class, "Error on load SQL tables:"
          + " class/tableSql - " + clazz.getSimpleName() + "/" + tableSql);
        throw e;
      }
    }
  }
1049659
private void createTables(Connection conn) throws DatabaseException {
        LOGGER.debug("Creating database structure");

        try (InputStream is = FileUtils.getResourceAsStream(DB_STRUCTURE_RESOURCE)) {
            final String dbStructure = IOUtils.toString(is, StandardCharsets.UTF_8);

            Statement statement = null;
            try {
                statement = conn.createStatement();
                statement.execute(dbStructure);
            } catch (SQLException ex) {
                LOGGER.debug("", ex);
                throw new DatabaseException("Unable to create database statement", ex);
            } finally {
                DBUtils.closeStatement(statement);
            }
        } catch (IOException ex) {
            throw new DatabaseException("Unable to create database schema", ex);
        }
    }
118181
@Override
    public void createTableIfDoesNotExist(final String tableName, final String... colFamily)
            throws MasterNotRunningException, IOException
    {
        if (!admin.tableExists(Bytes.toBytes(tableName)))
        {
            HTableDescriptor htDescriptor = new HTableDescriptor(TableName.valueOf(tableName));
            for (String columnFamily : colFamily)
            {
                HColumnDescriptor familyMetadata = new HColumnDescriptor(columnFamily);
                htDescriptor.addFamily(familyMetadata);
            }
            admin.createTable(htDescriptor);
        }
    }
1150694
protected void createSequence(PersistenceBroker broker, FieldDescriptor field,
                                  String sequenceName, long maxKey) throws Exception
    {
        Statement stmt = null;
        try
        {
            stmt = broker.serviceStatementManager().getGenericStatement(field.getClassDescriptor(), Query.NOT_SCROLLABLE);
            stmt.execute(sp_createSequenceQuery(sequenceName, maxKey));
        }
        catch (Exception e)
        {
            log.error(e);
            throw new SequenceManagerException("Could not create new row in "+SEQ_TABLE_NAME+" table - TABLENAME=" +
                    sequenceName + " field=" + field.getColumnName(), e);
        }
        finally
        {
            try
            {
                if (stmt != null) stmt.close();
            }
            catch (SQLException sqle)
            {
                if(log.isDebugEnabled())
                    log.debug("Threw SQLException while in createSequence and closing stmt", sqle);
                // ignore it
            }
        }
    }
1374687
@Override
  public ListenableFuture<Table> createTableAsync(CreateTableRequest request) {
    return createUnaryListener(request, createTableRpc, request.getParent()).getAsyncResult();
  }
639289
@Override
	public void visit(SQLiteDatabaseSchema schema, SQLiteEntity entity) throws Exception {
		int indexCounter = 0;

		// generate the class name that represents the table
		String classTableName = getTableClassName(entity.getSimpleName());

		FindIndexesVisitor indexVisitor = new FindIndexesVisitor();
		List<? extends AnnotationMirror> annotationMirrors = entity.getElement().getAnnotationMirrors();
		for (AnnotationMirror annotationMirror : annotationMirrors) {
			Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues = annotationMirror
					.getElementValues();

			if (BindSqlType.class.getName().equals(annotationMirror.getAnnotationType().toString())) {
				for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : elementValues
						.entrySet()) {
					// The 'entry.getKey()' here is the annotation attribute
					// name.
					String key = entry.getKey().getSimpleName().toString();
					entry.getValue().accept(indexVisitor, key);
				}
			}
		}

		PackageElement pkg = elementUtils.getPackageOf(entity.getElement());
		String packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString();

		AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, packageName, classTableName);
		classBuilder = TypeSpec.classBuilder(classTableName).addModifiers(Modifier.PUBLIC)
				.addSuperinterface(SQLiteTable.class);

		BindTypeContext context = new BindTypeContext(classBuilder, TypeUtility.typeName(packageName, classTableName),
				Modifier.STATIC, Modifier.PRIVATE);

		// javadoc for class
		classBuilder.addJavadoc("<p>");
		classBuilder.addJavadoc("\nEntity <code>$L</code> is associated to table <code>$L</code>\n",
				entity.getSimpleName(), entity.getTableName());
		classBuilder.addJavadoc("This class represents table associated to entity.\n");
		classBuilder.addJavadoc("</p>\n");
		JavadocUtility.generateJavadocGeneratedBy(classBuilder);
		classBuilder.addJavadoc(" @see $T\n", TypeUtility.className(entity.getName()));

		{
			// @formatter:off
			// table_name
			FieldSpec fieldSpec = FieldSpec
					.builder(String.class, "TABLE_NAME", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
					.initializer("\"$L\"", entity.getTableName())
					.addJavadoc("Costant represents typeName of table $L\n", entity.getTableName()).build();
			classBuilder.addField(fieldSpec);
			// @formatter:on
		}

		StringBuilder bufferTable = new StringBuilder();
		StringBuilder bufferForeignKey = new StringBuilder();
		// shared between create table and drop table
		StringBuilder bufferIndexesCreate = new StringBuilder();
		StringBuilder bufferDropTable = new StringBuilder();
		StringBuilder bufferIndexesDrop = new StringBuilder();

		bufferTable.append("CREATE TABLE " + entity.getTableName());
		// define column typeName set

		String separator = "";
		bufferTable.append(" (");

		// for each column, that need to be persisted on table
		for (SQLProperty item : entity.getCollection()) {
			bufferTable.append(separator);
			bufferTable.append(item.columnName);
			bufferTable.append(" " + SQLTransformer.columnTypeAsString(item));

			switch (item.columnType) {
			case PRIMARY_KEY:
			case PRIMARY_KEY_UNMANGED:
				bufferTable.append(" PRIMARY KEY");
				if (!item.isType(String.class) && item.columnType == ColumnType.PRIMARY_KEY) {
					bufferTable.append(" AUTOINCREMENT");
				}
				bufferTable.append(" NOT NULL");
				break;
			case UNIQUE:
				bufferTable.append(" UNIQUE");
				break;
			case INDEXED:
				bufferIndexesCreate.append(String.format(" CREATE INDEX idx_%s_%s ON %s(%s);", entity.getTableName(),
						item.columnName, entity.getTableName(), item.columnName));
				bufferIndexesDrop.append(
						String.format(" DROP INDEX IF EXISTS idx_%s_%s;", entity.getTableName(), item.columnName));
				break;
			case STANDARD:
				break;
			}

			boolean nullable = item.isNullable();

			// if it is not primary key and it is not nullable, then add not
			// null
			if (!nullable && !(item.columnType == ColumnType.PRIMARY_KEY
					|| item.columnType == ColumnType.PRIMARY_KEY_UNMANGED)) {
				bufferTable.append(" NOT NULL");
			}

			// foreign key
			String foreignClassName = item.foreignParentClassName;
			if (item.isForeignKey()) {
				SQLiteEntity reference = model.getEntity(foreignClassName);

				if (reference == null) {
					// check if we have a DAO associated into DataSource
					// definition
					boolean found = false;
					for (SQLiteDaoDefinition daoDefinition : schema.getCollection()) {
						if (daoDefinition.getEntityClassName().equals(foreignClassName)) {
							found = true;
						}
					}

					if (!found) {
						throw new NoDaoElementFound(schema, TypeUtility.className(foreignClassName));
					} else {
						throw new InvalidBeanTypeException(item, foreignClassName);
					}
				}

				// foreign key can ben used only with column type
				// long/Long
				if (!TypeUtility.isTypeIncludedIn(item.getPropertyType().getTypeName(), Long.class, Long.TYPE,
						String.class)) {
					throw new InvalidForeignKeyTypeException(item);
				}

				bufferForeignKey.append(", FOREIGN KEY(" + item.columnName + ") REFERENCES " + reference.getTableName()
						+ "(" + reference.getPrimaryKey().columnName + ")");

				if (item.onDeleteAction != ForeignKeyAction.NO_ACTION) {
					bufferForeignKey.append(" ON DELETE " + item.onDeleteAction.toString().replaceAll("_", " "));
				}

				if (item.onUpdateAction != ForeignKeyAction.NO_ACTION) {
					bufferForeignKey.append(" ON UPDATE " + item.onUpdateAction.toString().replaceAll("_", " "));
				}

				// INSERT as dependency only if reference is another entity.
				// Same entity can not be own dependency.
				if (!entity.equals(reference)) {
					entity.referedEntities.add(reference);
				}

			}

			separator = ", ";
		}

		// add foreign key
		bufferTable.append(bufferForeignKey.toString());		
		
				
		// add multicolumn indexes (UNIQUE)
		{
			Triple<String, String, String> multiIndexes = buldIndexes(entity, indexVisitor.getUniqueIndexes(), true,
					indexCounter);
			
			// add constraint unique (if present)
			bufferTable.append(multiIndexes.value2);
			// close the table definition
			bufferTable.append(");");
			
			if (!StringUtils.isEmpty(multiIndexes.value0)) {
				bufferTable.append(multiIndexes.value0 + ";");
				bufferIndexesDrop.append(multiIndexes.value1 + ";");
			}						
		}
		
		// add indexes creation one table
				if (bufferIndexesCreate.length() > 0) {
					bufferTable.append(bufferIndexesCreate.toString());
				}

		// add multicolumn indexes (NOT UNIQUE)
		{
			Pair<String, String> multiIndexes = buldIndexes(entity, indexVisitor.getNotUniqueIndexes(), false,
					indexCounter);
			if (!StringUtils.isEmpty(multiIndexes.value0)) {
				bufferTable.append(multiIndexes.value0 + ";");
				bufferIndexesDrop.append(multiIndexes.value1 + ";");
			}
		}
				
		

		{
			// create table SQL
			// @formatter:off
			FieldSpec.Builder fieldSpec = FieldSpec.builder(String.class, "CREATE_TABLE_SQL")
					.addModifiers(Modifier.STATIC, Modifier.FINAL, Modifier.PUBLIC);
			// @formatter:on

			// @formatter:off
			fieldSpec.addJavadoc("<p>\nDDL to create table $L\n</p>\n", entity.getTableName());
			fieldSpec.addJavadoc("\n<pre>$L</pre>\n", bufferTable.toString());
			// @formatter:on

			classBuilder.addField(fieldSpec.initializer("$S", bufferTable.toString()).build());
		}

		// drop table SQL
		// index does not need to be dropped, they are automatically detroyed
		// with tables
		if (bufferIndexesDrop.length() > 0) {
			bufferDropTable.append(bufferIndexesDrop.toString());
		}

		bufferDropTable.append("DROP TABLE IF EXISTS " + entity.getTableName() + ";");

		{
			// @formatter:off
			FieldSpec fieldSpec = FieldSpec.builder(String.class, "DROP_TABLE_SQL")
					.addModifiers(Modifier.STATIC, Modifier.FINAL, Modifier.PUBLIC)
					.initializer("$S", bufferDropTable.toString())
					.addJavadoc("<p>\nDDL to drop table $L\n</p>\n", entity.getTableName())
					.addJavadoc("\n<pre>$L</pre>\n", bufferDropTable.toString()).build();
			// @formatter:on
			classBuilder.addField(fieldSpec);
		}

		// define column typeName set
		for (ModelProperty item : entity.getCollection()) {
			item.accept(this);
		}

		ManagedPropertyPersistenceHelper.generateFieldPersistance(context, entity.getCollection(), PersistType.BYTE,
				true, Modifier.STATIC, Modifier.PUBLIC);

		model.sqlForCreate.add(bufferTable.toString());
		model.sqlForDrop.add(bufferDropTable.toString());

		generateColumnsArray(entity);

		TypeSpec typeSpec = classBuilder.build();
		JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);

	}
335127
@Override
    protected void create(List<TableInfo> tableInfos)
    {
        StatementResult result = null;
        String statement = null;

        for (TableInfo tableInfo : tableInfos)
        {
            try
            {
                result = tableAPI.executeSync("DROP TABLE IF EXISTS " + tableInfo.getTableName());
                if (!result.isSuccessful())
                {
                    throw new SchemaGenerationException("Unable to DROP TABLE " + tableInfo.getTableName());
                }
                statement = buildCreateDDLQuery(tableInfo);
                result = tableAPI.executeSync(statement);
                if (!result.isSuccessful())
                {
                    throw new SchemaGenerationException("Unable to CREATE TABLE " + tableInfo.getTableName());
                }
                createIndexOnTable(tableInfo);
            }
            catch (IllegalArgumentException e)
            {
                logger.error("Invalid Statement. Caused By: ", e);
                throw new SchemaGenerationException(e, "Invalid Statement. Caused By: ");
            }
            catch (FaultException e)
            {
                logger.error("Statement couldn't be executed. Caused By: ", e);
                throw new SchemaGenerationException(e, "Statement couldn't be executed. Caused By: ");
            }
        }
    }
423406
@Override
	public void createResource() throws Exception {
		cluster = builder.getCluster();
		session = cluster.connect();

		session.execute(String.format("CREATE KEYSPACE IF NOT EXISTS %s with replication={'class':'SimpleStrategy', 'replication_factor':1};", keySpace));
		session.execute(String.format("CREATE TABLE IF NOT EXISTS %s.%s (sink_id text, sub_id int, checkpoint_id bigint, PRIMARY KEY (sink_id, sub_id));", keySpace, table));

		try {
			session.close();
		} catch (Exception e) {
			LOG.error("Error while closing session.", e);
		}
		try {
			cluster.close();
		} catch (Exception e) {
			LOG.error("Error while closing cluster.", e);
		}
	}
1320559
public static void generate(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema,
			Set<GeneratedTypeElement> generatedEntities) throws Exception {
		BindTableGenerator visitor = new BindTableGenerator(elementUtils, filer, schema);

		List<SQLiteEntity> orderedEntities = BindDataSourceBuilder.orderEntitiesList(schema);

		for (SQLiteEntity item : orderedEntities) {
			visitor.visit(schema, item);
		}

		// generate table for generated entity
		for (GeneratedTypeElement genItem : generatedEntities) {
			visitor.visit(schema, genItem);
		}
	}
417175
@Setup(Level.Trial)
  public void setup() throws Exception {
    registry = new MutableHandlerRegistry();
    fullMethodNames = new ArrayList<>(serviceCount * methodCountPerService);
    for (int serviceIndex = 0; serviceIndex < serviceCount; ++serviceIndex) {
      String serviceName = randomString();
      ServerServiceDefinition.Builder serviceBuilder = ServerServiceDefinition.builder(serviceName);
      for (int methodIndex = 0; methodIndex < methodCountPerService; ++methodIndex) {
        String methodName = randomString();

        MethodDescriptor<Void, Void> methodDescriptor = MethodDescriptor.<Void, Void>newBuilder()
            .setType(MethodDescriptor.MethodType.UNKNOWN)
            .setFullMethodName(MethodDescriptor.generateFullMethodName(serviceName, methodName))
            .setRequestMarshaller(TestMethodDescriptors.voidMarshaller())
            .setResponseMarshaller(TestMethodDescriptors.voidMarshaller())
            .build();
        serviceBuilder.addMethod(methodDescriptor,
            new ServerCallHandler<Void, Void>() {
              @Override
              public Listener<Void> startCall(ServerCall<Void, Void> call,
                  Metadata headers) {
                return null;
              }
            });
        fullMethodNames.add(methodDescriptor.getFullMethodName());
      }
      registry.addService(serviceBuilder.build());
    }
  }