<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 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

      https://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.
-%>
<%- include('/liquibase-changelog-header') -%>

<%_ fields.filter(field => field.liquibaseCustomSequenceGenerator).forEach((field, idx) => { _%>
    <changeSet id="<%= changelogDate %>-seq-<%- idx %>" author="jhipster">
        <createSequence sequenceName="<%- field.liquibaseSequenceGeneratorName %>" startValue="1050" incrementBy="50"/>
    </changeSet>

<%_ }); _%>
    <!--
        Added the entity <%= entity.entityClass %>.
    -->
    <changeSet id="<%= changelogDate %>-1" author="jhipster">
        <createTable tableName="<%= entity.entityTableName %>"<%- this.formatAsLiquibaseRemarks(entity.documentation, true) %>>
<%_ for (field of fields) { _%>
            <column name="<%= field.options?.fieldColumnName || field.columnName %>"<% if (['del_flag', 'tenant_id'].includes(field.columnName)) { %> defaultValue="0"<% } else { %><%- this.createDefaultValueLiquibaseAttribute(field, true) -%><% } %> type="<%= field.columnType %>"<%- this.formatAsLiquibaseRemarks(field.documentation, true) %><% if (field.id && field.liquibaseAutoIncrement) { %> autoIncrement="true" startWith="1500"<%_ } %>>
    <%_ if (field.id) { _%>
                <constraints primaryKey="true" nullable="false"/>
    <%_ } else if (field.unique) { _%>
                <constraints nullable="<%= !field.columnRequired %>" <% if (!useMultiTenant || (useMultiTenant && entity.skipMultiTenant)) { %>unique="true" uniqueConstraintName="<%= field.uniqueConstraintName %>"<% } %> />
    <%_ } else { _%>
                <constraints nullable="<%= !field.columnRequired %>" />
    <%_ } _%>
            </column>
    <%_ if (field.shouldCreateContentType) { _%>
            <column name="<%= field.columnName %>_content_type" type="varchar(255)">
                <constraints nullable="<%= !field.columnRequired %>" />
            </column>
    <%_ } _%>
<%_ } _%>
<%_ for (relationship of relationships.filter(relationship => !(relationship.relationshipManyToOne && relationship?.bcConfig?.leftUnidirectional && relationship?.bcConfig?.leftRelateByIdEntity))) {
    if (((relationship.relationshipType === 'many-to-one') || (relationship.relationshipType === 'one-to-one' && relationship.ownerSide === true))
                && !relationship.id) {
        relationship.otherEntity.primaryKey.fields.forEach(idField => {
        const uniqueConstraintName = relationship.relationshipType === 'one-to-one' ? this.getUXConstraintName(entity.entityTableName, relationship.columnName + '_' + idField.columnName, entity.prodDatabaseType) : null;
         _%>
            <column name="<%= relationship.columnName %>_<%= idField.columnName %>" type="<%= idField.columnType %>"<%- this.formatAsLiquibaseRemarks(relationship.otherEntity.bcTitle, true) %>>
                <constraints nullable="<%= !relationship.columnRequired %>"<% if (uniqueConstraintName) { %> unique="true" uniqueConstraintName="<%= uniqueConstraintName %>"<% } %> />
            </column>
<%# add by begcode start _%>
    <%_ if (relationship.otherEntityField !== idField.fieldName) { _%>
            <column name="<%= relationship.columnName %>_<%= this._.snakeCase(relationship.otherEntityField) %>" type="varchar(255)">
                <constraints nullable="true" />
            </column>
    <%_ } _%>
<%# add by begcode end _%>
        <%_ });
    }
} _%>
            <!-- jhipster-needle-liquibase-add-column - JHipster will add columns here -->
        </createTable>
<%_ for (const field of fields) {
    if (field.shouldDropDefaultValue) { _%>
        <dropDefaultValue tableName="<%= entity.entityTableName %>" columnName="<%= field.columnName %>" columnDataType="${datetimeType}"/>
<%_ }
} _%>
    </changeSet>
    <%# add by begcode start %>
    <% const indexedFields = fields.filter(field => field.options?.indexed); %>
    <%_ if (indexedFields && indexedFields.length > 0) { _%>

    <changeSet id="<%= changelogDate %>-1-index" author="jhipster">
        <%_ for (field of fields) { _%>
        <createIndex tableName="<%= entity.entityTableName %>" indexName="index_<%= field.columnName %>">
            <column name="<%= field.columnName %>"></column>
        <%_ } _%>
        </createIndex>
    </changeSet>
    <%_ } _%>
    <%# add by begcode end _%>
<%_ const joinTableRelations = relationships.filter(rel => rel.shouldWriteJoinTable);
    if(joinTableRelations.length > 0) {
_%>

    <changeSet id="<%= changelogDate %>-1-relations" author="jhipster">
    <%_ for (relationship of joinTableRelations) { _%>

        <createTable tableName="<%= relationship.joinTable.name %>"<%- this.formatAsLiquibaseRemarks(relationship.bcTitle + '关联表', true) %>>
        <%_ for (field of relationship.otherEntity.primaryKey.fields) { _%>
            <column name="<%= relationship.columnName %>_<%= field.columnName %>" type="<%= field.columnType %>"<%- this.formatAsLiquibaseRemarks(relationship.otherEntity.bcTitle + field.columnName, true) %>>
                <constraints nullable="false"/>
            </column>
        <%_ } _%>
        <%_ for (field of entity.primaryKey.fields) { _%>
            <column name="<%= entity.entityTableName %>_<%= field.columnName %>" type="<%= field.columnType %>"<%- this.formatAsLiquibaseRemarks(entity.bcTitle + field.columnName, true) %>>
                <constraints nullable="false"/>
            </column>
        <%_ } _%>
        </createTable>

        <addPrimaryKey columnNames="<%= entity.primaryKey.fields.map(field => `${entity.entityTableName}_${field.columnName}`).join(', ') %>, <%= relationship.otherEntity.primaryKey.fields.map(field => `${relationship.columnName}_${field.columnName}`).join(', ') %>" tableName="<%= relationship.joinTable.name %>"/>
    <%_ } _%>
    </changeSet>
<%_ } _%>

    <!-- jhipster-needle-liquibase-add-changeset - JHipster will add changesets here -->
<%_ if (!skipFakeData || entity.importData) { _%>

    <!--
        Load sample data generated with Faker.js
        - This data can be easily edited using a CSV editor (or even MS Excel) and
          is located in the 'src/main/resources/config/liquibase/fake-data' directory
        - By default this data is applied when running with the JHipster 'dev' profile.
          This can be customized by adding or removing 'faker' in the 'spring.liquibase.contexts'
          Spring Boot configuration key.
    -->
    <changeSet id="<%= changelogDate %>-1-data" author="jhipster"<% if (!entity.importData) { %> context="faker"<% } %>>
        <loadData
                  file="config/liquibase/<%= entity.importData ? 'data' : 'fake-data' %>/<%= (!entity.incrementalChangelog || entity.importData) ? entity.entityTableName : databaseChangelog.changelogDate + '_entity_' + entity.entityTableName %>.csv"
                  separator=";"
                  tableName="<%= entity.entityTableName %>"
                  usePreparedStatements="true">
  <%_ const importFields = entity.importData ? fields.filter(item => item.id || item.options && item.options.importDataField) : fields; _%><%# add by begcode _%>
  <%_ for (field of importFields) { _%>
            <column name="<%= field.columnName %>" type="<%= field.loadColumnType %>"/>
    <%_ if (field.fieldType === 'byte[]' && field.fieldTypeBlobContent !== 'text') { _%>
            <column name="<%= field.columnName %>_content_type" type="string"/>
    <%_ } _%>
  <%_ } _%>
  <%_ for (relationship of relationships.filter(relationship => !relationship.id && relationship.columnRequired && relationship.persistableRelationship && !relationship.collection && !relationship.bcConfig?.unidirectionSkip)) { _%>
      <%_ for (field of relationship.otherEntity.primaryKey.fields) { _%>
            <column name="<%= relationship.columnName %>_<%= field.columnName %>" type="<%= field.loadColumnType %>"/>
      <%_ } _%>
  <%_  } _%>
            <!-- jhipster-needle-liquibase-add-loadcolumn - JHipster (and/or extensions) can add load columns here -->
        </loadData>
        <%# add by plus start %>
        <%_ for (relationship of importDataRelationships) { _%>
        <loadData
                file="config/liquibase/data/<%= relationship.joinTable.name %>.csv"
                separator=";"
                tableName="<%= relationship.joinTable.name %>"
                usePreparedStatements="true">
            <%_ for (field of relationship.otherEntity.primaryKey.fields) { _%>
                <column name="<%= relationship.columnName %>_<%= field.columnName %>" type="<%= field.loadColumnType %>"/>
            <%_ } _%>
            <%_ for (field of entity.primaryKey.fields) { _%>
                <column name="<%= entity.entityTableName %>_<%= field.columnName %>" type="<%= field.loadColumnType %>"/>
            <%_ } _%>
        </loadData>
        <%_  } _%><%# add by plus end %>
    </changeSet>
<%_ } _%>
</databaseChangeLog>
