ofbiz实体引擎(八) 创建表

    /**
     * @author 郑小康
     *
     * 1.检验实体是否为空
     *
     * 2.检验视图实体是否为空
     *
     * 3.获取数据库连接
     *
     * 4.根据对应的ModelEntity来创建表 其中modelEntities是关系表的集合
     *
     * */
    public String createTable(ModelEntity entity, Map<String, ModelEntity> modelEntities, boolean addFks) {
        if (entity == null) {
            return "ModelEntity was null and is required to create a table ModelEntity是空,不能创建表";
        }
        if (entity instanceof ModelViewEntity) {
            return "ERROR: Cannot create table for a view entity 不能为视图实体创建表";
        }

        Connection connection = null;
        Statement stmt = null;

        try {
            connection = getConnection();
        } catch (SQLException e) {
            String errMsg = "在建表过程中Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString();
            Debug.logError(e, errMsg, module);
            return errMsg;
        } catch (GenericEntityException e) {
            String errMsg = "在建表过程中 Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString();
            Debug.logError(e, errMsg, module);
            return errMsg;
        }

        StringBuilder sqlBuf = new StringBuilder("CREATE TABLE ");
        sqlBuf.append(entity.getTableName(this.datasourceInfo));
        sqlBuf.append(" (");
        Iterator<ModelField> fieldIter = entity.getFieldsIterator();
        while (fieldIter.hasNext()) {
            ModelField field = fieldIter.next();
            ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType());
            if (type == null) {
                return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not creating table.";
            }

            sqlBuf.append(field.getColName());
            sqlBuf.append(" ");
            sqlBuf.append(type.getSqlType());

            if ("String".equals(type.getJavaType()) || "java.lang.String".equals(type.getJavaType())) {
                // if there is a characterSet, add the CHARACTER SET arg here
                if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) {
                    sqlBuf.append(" CHARACTER SET ");
                    sqlBuf.append(this.datasourceInfo.getCharacterSet());
                }
                // if there is a collate, add the COLLATE arg here
                if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) {
                    sqlBuf.append(" COLLATE ");
                    sqlBuf.append(this.datasourceInfo.getCollate());
                }
            }

            if (field.getIsNotNull() || field.getIsPk()) {
                if (this.datasourceInfo.getAlwaysUseConstraintKeyword()) {
                    sqlBuf.append(" CONSTRAINT NOT NULL, ");
                } else {
                    sqlBuf.append(" NOT NULL, ");
                }
            } else {
                sqlBuf.append(", ");
            }
        }

        String pkName = makePkConstraintName(entity, this.datasourceInfo.getConstraintNameClipLength());
        if (this.datasourceInfo.getUsePkConstraintNames()) {
            sqlBuf.append("CONSTRAINT ");
            sqlBuf.append(pkName);
        }
        sqlBuf.append(" PRIMARY KEY (");
        entity.colNameString(entity.getPkFieldsUnmodifiable(), sqlBuf, "");
        sqlBuf.append(")");

        if (addFks) {
            // NOTE: This is kind of a bad idea anyway since ordering table creations is crazy, if not impossible

            // go through the relationships to see if any foreign keys need to be added
            Iterator<ModelRelation> relationsIter = entity.getRelationsIterator();
            while (relationsIter.hasNext()) {
                ModelRelation modelRelation = relationsIter.next();
                if ("one".equals(modelRelation.getType())) {
                    ModelEntity relModelEntity = modelEntities.get(modelRelation.getRelEntityName());
                    if (relModelEntity == null) {
                        Debug.logError("Error adding foreign key: ModelEntity was null for related entity name " + modelRelation.getRelEntityName(), module);
                        continue;
                    }
                    if (relModelEntity instanceof ModelViewEntity) {
                        Debug.logError("Error adding foreign key: related entity is a view entity for related entity name " + modelRelation.getRelEntityName(), module);
                        continue;
                    }

                    String fkConstraintClause = makeFkConstraintClause(entity, modelRelation, relModelEntity, this.datasourceInfo.getConstraintNameClipLength(), this.datasourceInfo.getFkStyle(), this.datasourceInfo.getUseFkInitiallyDeferred());
                    if (UtilValidate.isNotEmpty(fkConstraintClause)) {
                        sqlBuf.append(", ");
                        sqlBuf.append(fkConstraintClause);
                    } else {
                        continue;
                    }
                }
            }
        }

        sqlBuf.append(")");

        // if there is a tableType, add the TYPE arg here
        if (UtilValidate.isNotEmpty(this.datasourceInfo.getTableType())) {
         // jaz:20101229 - This appears to be only used by mysql and now mysql has
            // deprecated (and in 5.5.x removed) the use of the TYPE keyword. This is
            // changed to ENGINE which is supported starting at 4.1
            sqlBuf.append(" ENGINE ");
            //sqlBuf.append(" TYPE ");
            sqlBuf.append(this.datasourceInfo.getTableType());
        }

        // if there is a characterSet, add the CHARACTER SET arg here
        if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) {
            sqlBuf.append(" CHARACTER SET ");
            sqlBuf.append(this.datasourceInfo.getCharacterSet());
        }

        // if there is a collate, add the COLLATE arg here
        if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) {
            sqlBuf.append(" COLLATE ");
            sqlBuf.append(this.datasourceInfo.getCollate());
        }

        if (Debug.verboseOn()) Debug.logVerbose("[createTable] sql=" + sqlBuf.toString(), module);
        try {
            stmt = connection.createStatement();
            stmt.executeUpdate(sqlBuf.toString());
        } catch (SQLException e) {
            return "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString();
        } finally {
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                Debug.logError(e, module);
            }
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                Debug.logError(e, module);
            }
        }
        return null;
    }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏源哥的专栏

字符串分拆函数

在Oracle中,如果一个包含分隔符的字符串(比如说“55*62*77”,这个字符串是用*号做分隔符,可以拆分成三个数“55”,“62”和“77”),要将它们拆...

522
来自专栏数据之美

Hive 在多维统计分析中的应用 & 技巧总结

多维统计一般分两种,我们看看 Hive 中如何解决: 1、同属性的多维组合统计 (1)问题: 有如下数据,字段内容分别为:url, catePath...

3028
来自专栏康怀帅的专栏

MySQL 函数

函数相关内容。 字符函数 字符连接 CONCAT('a','b') 使用指定分隔符进行字符连接 CONCAT_WS('-','a','b') 数字格式化 FOR...

2784
来自专栏简书专栏

mysql必知必会2

语法:delete from {1} where {2} 第一对大括号替换为表名,第二对大括号替换为查询条件。 注意:删除语句一定要写删除条件,否则整张表删...

812
来自专栏绿巨人专栏

TypeScript: Week Reflection

3187
来自专栏chenssy

【死磕Sharding-jdbc】---SQL解析-INSERT解析

分析insert解析之前,首先看一下mysql官方对insert语法的定义,因为SQL解析跟语法息息相关:

892
来自专栏芋道源码1024

Sharding-JDBC 源码分析 —— SQL 解析(二)之SQL解析

1. 概述 2. SQLParsingEngine 3. SQLParser SQL解析器 3.2.1 #parseExpression() 和 SQLExp...

3925
来自专栏me的随笔

T-SQL基础(四)之集合运算

在逻辑查询处理方面,集合运算符应用于两个查询结果集,且外部的ORDER BY子句(如果有的话)应用于集合运算所得到的结果集。

1154
来自专栏乐沙弥的世界

PL/SQL --> 语言基础

PL/SQL是过程化的SQL语言,是ORACLE对SQL语言的扩展,在普通SQL语句的基础上增加了编程语言的特点。使得该语言不仅具有过程编程语

903
来自专栏Java3y

JDBC【PreparedStatment、批处理、处理二进制、自动主键、调用存储过程、函数】

1.PreparedStatement对象 PreparedStatement对象继承Statement对象,它比Statement对象更强大,使用起来更简单 ...

2633

扫码关注云+社区