解析表

@param schemaItem 视图对象
@param sqlTableSource sqlTableSource
@param tableItems 表对象列表
@param tableItemTmp 表对象(临时)
548484
private static void visitSelectTable(SchemaItem schemaItem, SQLTableSource sqlTableSource,
                                         List<TableItem> tableItems, TableItem tableItemTmp) {
        if (sqlTableSource instanceof SQLExprTableSource) {
            SQLExprTableSource sqlExprTableSource = (SQLExprTableSource) sqlTableSource;
            TableItem tableItem;
            if (tableItemTmp != null) {
                tableItem = tableItemTmp;
            } else {
                tableItem = new TableItem(schemaItem);
            }
            tableItem.setSchema(sqlExprTableSource.getSchema());
            tableItem.setTableName(sqlExprTableSource.getTableName());
            if (tableItem.getAlias() == null) {
                tableItem.setAlias(sqlExprTableSource.getAlias());
            }
            if (tableItems.isEmpty()) {
                // 第一张表为主表
                tableItem.setMain(true);
            }
            tableItems.add(tableItem);
        } else if (sqlTableSource instanceof SQLJoinTableSource) {
            SQLJoinTableSource sqlJoinTableSource = (SQLJoinTableSource) sqlTableSource;
            SQLTableSource leftTableSource = sqlJoinTableSource.getLeft();
            visitSelectTable(schemaItem, leftTableSource, tableItems, null);
            SQLTableSource rightTableSource = sqlJoinTableSource.getRight();
            TableItem rightTableItem = new TableItem(schemaItem);
            // 解析on条件字段
            visitOnCondition(sqlJoinTableSource.getCondition(), rightTableItem);
            visitSelectTable(schemaItem, rightTableSource, tableItems, rightTableItem);

        } else if (sqlTableSource instanceof SQLSubqueryTableSource) {
            SQLSubqueryTableSource subQueryTableSource = (SQLSubqueryTableSource) sqlTableSource;
            MySqlSelectQueryBlock sqlSelectQuery = (MySqlSelectQueryBlock) subQueryTableSource.getSelect().getQuery();
            TableItem tableItem;
            if (tableItemTmp != null) {
                tableItem = tableItemTmp;
            } else {
                tableItem = new TableItem(schemaItem);
            }
            tableItem.setAlias(subQueryTableSource.getAlias());
            tableItem.setSubQuerySql(SQLUtils.toMySqlString(sqlSelectQuery));
            tableItem.setSubQuery(true);
            tableItem.setSubQueryFields(collectSelectQueryFields(sqlSelectQuery));
            visitSelectTable(schemaItem, sqlSelectQuery.getFrom(), tableItems, tableItem);
        }
    }
1308371
private static void visitOnCondition(SQLExpr expr, TableItem tableItem) {
        if (!(expr instanceof SQLBinaryOpExpr)) {
            throw new UnsupportedOperationException();
        }
        SQLBinaryOpExpr sqlBinaryOpExpr = (SQLBinaryOpExpr) expr;
        if (sqlBinaryOpExpr.getOperator() == BooleanAnd) {
            visitOnCondition(sqlBinaryOpExpr.getLeft(), tableItem);
            visitOnCondition(sqlBinaryOpExpr.getRight(), tableItem);
        } else if (sqlBinaryOpExpr.getOperator() == Equality) {
            FieldItem leftFieldItem = new FieldItem();
            visitColumn(sqlBinaryOpExpr.getLeft(), leftFieldItem);
            if (leftFieldItem.getColumnItems().size() != 1 || leftFieldItem.isMethod() || leftFieldItem.isBinaryOp()) {
                throw new UnsupportedOperationException("Unsupported for complex of on-condition");
            }
            FieldItem rightFieldItem = new FieldItem();
            visitColumn(sqlBinaryOpExpr.getRight(), rightFieldItem);
            if (rightFieldItem.getColumnItems().size() != 1 || rightFieldItem.isMethod()
                || rightFieldItem.isBinaryOp()) {
                throw new UnsupportedOperationException("Unsupported for complex of on-condition");
            }
            tableItem.getRelationFields().add(new RelationFieldsPair(leftFieldItem, rightFieldItem));
        } else {
            throw new UnsupportedOperationException("Unsupported for complex of on-condition");
        }
    }
628709
public static void createTables(Connection connection) throws Exception {
        StringBuilder sB = new StringBuilder();
        sB.append("CREATE TABLE ");
        sB.append(TABLE_METADATA);
        sB.append(" (");
        sB.append(MetadataTableFields.COLUMN_KEY.getFieldName()).append(" TEXT NOT NULL, ");
        sB.append(MetadataTableFields.COLUMN_VALUE.getFieldName()).append(" TEXT NOT NULL ");
        sB.append(");");
        String CREATE_TABLE_PROJECT = sB.toString();

        try (Statement statement = connection.createStatement()) {
            statement.setQueryTimeout(30); // set timeout to 30 sec.

            statement.executeUpdate(CREATE_TABLE_PROJECT);
        } catch (Exception e) {
            throw new IOException(e.getLocalizedMessage());
        }
    }
47588
private Optional<ThriftTableMetadata> getTableMetadataInternal(SchemaTableName schemaTableName)
    {
        requireNonNull(schemaTableName, "schemaTableName is null");
        PrestoThriftNullableTableMetadata thriftTableMetadata = getTableMetadata(schemaTableName);
        if (thriftTableMetadata.getTableMetadata() == null) {
            return Optional.empty();
        }
        ThriftTableMetadata tableMetadata = new ThriftTableMetadata(thriftTableMetadata.getTableMetadata(), typeManager);
        if (!Objects.equals(schemaTableName, tableMetadata.getSchemaTableName())) {
            throw new PrestoException(THRIFT_SERVICE_INVALID_RESPONSE, "Requested and actual table names are different");
        }
        return Optional.of(tableMetadata);
    }
244616
@Override
    protected void validate(List<TableInfo> tableInfos)
    {
        for (TableInfo tableInfo : tableInfos)
        {
            try
            {
                if (!client.tableExists(tableInfo.getTableName()))
                {
                    throw new SchemaGenerationException("Table: " + tableInfo.getTableName() + " does not exist ");
                }
            }
            catch (Exception e)
            {
                logger.error("Error while validating tables, Caused by: " + e.getMessage());
                throw new KunderaException("Error while validating tables, Caused by: " + e.getMessage());
            }
        }
    }
225022
@Override
    public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException
    {
        checkClosed();
        this.sysCatalog.setString(1, "TABLES");
        JDBC4ResultSet res = (JDBC4ResultSet) this.sysCatalog.executeQuery();
        VoltTable vtable = res.getVoltTable().clone(0);

        List<String> typeStrings = null;
        if (types != null) {
            typeStrings = Arrays.asList(types);
        }

        // If no pattern is specified, default to matching any/all.
        if (tableNamePattern == null || tableNamePattern.length() == 0)
        {
            tableNamePattern = "%";
        }

        Pattern table_pattern = computeJavaPattern(tableNamePattern);

        // Filter tables based on type and pattern
        while (res.next()) {
            if (typeStrings == null || typeStrings.contains(res.getString("TABLE_TYPE"))) {
                Matcher table_matcher = table_pattern.matcher(res.getString("TABLE_NAME"));
                if (table_matcher.matches())
                {
                    vtable.addRow(res.getRowData());
                }
            }
        }

        return new JDBC4ResultSet(this.sysCatalog, vtable);
    }
359832
@Override
    public java.util.concurrent.Future<PutItemResult> putItemAsync(String tableName, java.util.Map<String, AttributeValue> item) {

        return putItemAsync(new PutItemRequest().withTableName(tableName).withItem(item));
    }
1370959
public TableMetaReader createTableMetaReader(
      GenDialect dialect,
      DataSource dataSource,
      String schemaName,
      String tableNamePattern,
      String ignoredTableNamePattern,
      List<String> tableTypes) {
    return new TableMetaReader(
        dialect, dataSource, schemaName, tableNamePattern, ignoredTableNamePattern, tableTypes);
  }
1276244
private void generateDataSourceSingleThread(SQLiteDatabaseSchema schema, String dataSourceName) {
		// class DataSourceSingleThread
		String daoFactoryName = BindDaoFactoryBuilder.generateDaoFactoryName(schema);
		TypeSpec.Builder clazzBuilder = TypeSpec.classBuilder(DATA_SOURCE_SINGLE_THREAD_NAME)
				.addSuperinterface(TypeUtility.typeName(daoFactoryName));

		// _context field
		clazzBuilder.addField(FieldSpec.builder(SQLContextInSessionImpl.class, "_context", Modifier.PRIVATE).build());

		// constructor
		MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder();
		constructorBuilder.addStatement("_context=new $T($L.this)", SQLContextInSessionImpl.class, dataSourceName);

		// all dao
		for (SQLiteDaoDefinition dao : schema.getCollection()) {
			TypeName daoImplName = BindDaoBuilder.daoTypeName(dao);

			// dao with external connections
			{
				String daoFieldName = extractDaoFieldNameForInternalDataSource(dao);
				MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("get" + dao.getName())
						.addModifiers(Modifier.PUBLIC).addJavadoc("\nretrieve dao $L\n", dao.getName())
						.returns(daoImplName);
				methodBuilder.beginControlFlow("if ($L==null)", daoFieldName);
				methodBuilder.addStatement("$L=new $T(this)", daoFieldName, daoImplName);
				methodBuilder.endControlFlow();
				methodBuilder.addStatement("return $L", daoFieldName);
				clazzBuilder.addMethod(methodBuilder.build());

				clazzBuilder.addField(FieldSpec.builder(daoImplName, daoFieldName, Modifier.PROTECTED).build());
			}
		}

		// constructor
		clazzBuilder.addMethod(constructorBuilder.build());

		// public SQLContext context()
		{
			MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("context").addModifiers(Modifier.PUBLIC)
					.returns(SQLContext.class);
			methodBuilder.addAnnotation(Override.class);
			methodBuilder.addStatement("return _context");
			clazzBuilder.addMethod(methodBuilder.build());
		}

		// onSessionOpened
		{
			MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onSessionOpened")
					.addModifiers(Modifier.PROTECTED).returns(Void.TYPE);
			if (schema.hasLiveData()) {
				methodBuilder.addComment("support for live data");
				methodBuilder.addStatement("_context.onSessionOpened()");
			}

			clazzBuilder.addMethod(methodBuilder.build());
		}

		// onSessionClear
		{
			MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onSessionClear")
					.addModifiers(Modifier.PROTECTED).returns(Void.TYPE);
			if (schema.hasLiveData()) {
				methodBuilder.addComment("support for live data");
				methodBuilder.addStatement("_context.onSessionOpened()");
			}

			clazzBuilder.addMethod(methodBuilder.build());
		}

		// onSessionClosed
		{
			MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onSessionClosed")
					.addModifiers(Modifier.PROTECTED).returns(Void.TYPE);

			if (schema.hasLiveData()) {
				methodBuilder.addComment("support for live data");
				methodBuilder.addStatement("$T daosWithEvents=_context.onSessionClosed()",
						ParameterizedTypeName.get(Set.class, Integer.class));

				for (SQLiteDaoDefinition dao : schema.getCollection()) {

					String daoFieldName = extractDaoFieldNameForInternalDataSource(dao);
					if (dao.hasLiveData()) {
						methodBuilder.beginControlFlow("if ($L!=null && daosWithEvents.contains($L))", daoFieldName,
								dao.daoUidName);
						methodBuilder.addStatement("$L.invalidateLiveData()", daoFieldName);
						methodBuilder.endControlFlow();
					} else {
						methodBuilder.addComment("$S has no live data", daoFieldName);
					}
				}
			}

			clazzBuilder.addMethod(methodBuilder.build());
		}

		// build method bindToThread
		{
			MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("bindToThread").addModifiers(Modifier.PUBLIC)
					.returns(TypeUtility.typeName(DATA_SOURCE_SINGLE_THREAD_NAME));

			// methodBuilder.addStatement("_context.bindToThread()");
			methodBuilder.addStatement("return this");
			clazzBuilder.addMethod(methodBuilder.build());

			// build single thread daoFactory used in transaction
			classBuilder.addField(FieldSpec
					.builder(TypeUtility.typeName(DATA_SOURCE_SINGLE_THREAD_NAME), "_daoFactorySingleThread",
							Modifier.PROTECTED)
					.addJavadoc("Used only in transactions (that can be executed one for time\n")
					.initializer("new DataSourceSingleThread()").build());
		}
		
		// build transactions
		{
			SchemaUtility.generateTransaction(clazzBuilder, schema, false);
		}

		classBuilder.addType(clazzBuilder.build());

	}
24992
private String buildTableName(Elements elementUtils, SQLiteDatabaseSchema schema) {
		tableName = getSimpleName();
		tableName = schema.classNameConverter.convert(tableName);

		String temp = AnnotationUtility.extractAsString(getElement(), BindSqlType.class, AnnotationAttributeType.NAME);
		if (StringUtils.hasText(temp)) {
			tableName = temp;
		}

		return tableName;

	}
467860
@Override
    public void exportSchema(final String persistenceUnit, List<TableInfo> schemas)
    {
        super.exportSchema(persistenceUnit, schemas);
    }
1051590
@GuardedBy("this")
    private TableSource getTableSource(String databaseName, String tableName)
    {
        checkHoldsLock();

        checkReadable();
        Action<TableAndMore> tableAction = tableActions.get(new SchemaTableName(databaseName, tableName));
        if (tableAction == null) {
            return TableSource.PRE_EXISTING_TABLE;
        }
        switch (tableAction.getType()) {
            case ADD:
                return TableSource.CREATED_IN_THIS_TRANSACTION;
            case ALTER:
                throw new IllegalStateException("Tables are never altered in the current implementation");
            case DROP:
                throw new TableNotFoundException(new SchemaTableName(databaseName, tableName));
            case INSERT_EXISTING:
                return TableSource.PRE_EXISTING_TABLE;
            default:
                throw new IllegalStateException("Unknown action type");
        }
    }
1302361
protected void update(List<TableInfo> tableInfos)
    {
        try
        {
            createOrUpdateKeyspace(tableInfos);
        }
        catch (Exception ex)
        {
            log.error("Error occurred while creating {}, Caused by: .", databaseName, ex);
            throw new SchemaGenerationException(ex);
        }
    }
1249587
public boolean createTableIfNotExists(final String tableName, final String schema) {
        Connection conn = getConnection();

        try {
            return JdbcUtil.createTableIfNotExists(conn, tableName, schema);
        } finally {
            closeQuietly(conn);
        }
    }
1311096
private void parseTableSchemaFromXML(String tableName,
                                         StmtCommonTableScanShared tableScan,
                                         VoltXMLElement voltXMLElement) {
        assert("table".equals(voltXMLElement.name));
        List<VoltXMLElement> columnSet = voltXMLElement.findChildren("columns");
        assert(columnSet.size() == 1);
        columnSet = columnSet.get(0).children;
        for (int idx = 0; idx < columnSet.size(); idx += 1) {
            VoltXMLElement columnXML = columnSet.get(idx);
            assert("column".equals(columnXML.name));
            String columnName = columnXML.attributes.get("name");
            // If valuetype is not defined, then we will get type
            // "none", about which typeFromString will complain.
            // Note that the types may be widened from the type
            // of the base query of a recursive common table.  This
            // happens if the corresponding type in the recursive
            // query is wider than that of the base case.  But
            // HSQL will have taken care of this for us, so we
            // will not see the widening here.
            VoltType valueType = VoltType.typeFromString(columnXML.getStringAttribute("valuetype", "none"));
            Integer columnIndex = columnXML.getIntAttribute("index", null);
            assert(columnIndex != null);
            // These appear to be optional.  Certainly "bytes"
            // only appears if the type is variably sized.
            Integer size = columnXML.getIntAttribute("size", 0);
            Boolean inBytes = columnXML.getBoolAttribute("bytes", null);
            // This TVE holds the metadata.
            TupleValueExpression tve = new TupleValueExpression(tableName, tableName, columnName, columnName, columnIndex);
            tve.setValueType(valueType);
            tve.setDifferentiator(idx);
            if (size == 0) {
                if (valueType.isVariableLength()) {
                    size = valueType.defaultLengthForVariableLengthType();
                }
                else {
                    size = valueType.getLengthInBytesForFixedTypes();
                }
            }
            tve.setValueSize(size);
            if (inBytes != null) {
                tve.setInBytes(inBytes);
            }
            // There really is no aliasing going on here, so the table
            // name and column name are the same as the table alias and
            // column alias.
            SchemaColumn schemaColumn = new SchemaColumn(tableName, tableName, columnName, columnName, tve, idx);
            tableScan.addOutputColumn(schemaColumn);
        }
    }
1325543
void processAlterTableRename(Table table) {

        HsqlName name = readNewSchemaObjectName(SchemaObject.TABLE);

        name.setSchemaIfNull(table.getSchemaName());

        if (table.getSchemaName() != name.schema) {
            throw Error.error(ErrorCode.X_42505);
        }

        database.schemaManager.renameSchemaObject(table.getName(), name);
    }
482206
private void createIfNotExists(String tableName, String createTableStatement) throws SQLException {
		logger.entering(CLASSNAME, "createIfNotExists", new Object[] {tableName, createTableStatement});

		Connection conn = getConnection();
		DatabaseMetaData dbmd = conn.getMetaData();
		ResultSet rs = dbmd.getTables(null, schema, tableName, null);
		PreparedStatement ps = null;
		if(!rs.next()) {
			logger.log(Level.INFO, tableName + " table does not exists. Trying to create it.");
			ps = conn.prepareStatement(createTableStatement);
			ps.executeUpdate();
		}

		cleanupConnection(conn, rs, ps);
		logger.exiting(CLASSNAME, "createIfNotExists");
	}