001/*
002 *  Copyright (c) 2022-2025, Mybatis-Flex (fuhai999@gmail.com).
003 *  <p>
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *  <p>
008 *  http://www.apache.org/licenses/LICENSE-2.0
009 *  <p>
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016
017package com.mybatisflex.core.table;
018
019import com.mybatisflex.core.query.QueryTable;
020import com.mybatisflex.core.util.MapUtil;
021
022import java.util.Map;
023import java.util.concurrent.ConcurrentHashMap;
024import java.util.function.Function;
025
026/**
027 * 表定义,内包含字段。
028 *
029 * @author 王帅
030 * @since 2024-03-11
031 */
032public class TableDef extends QueryTable {
033
034    private static final Map<String, TableDef> CACHE = new ConcurrentHashMap<>();
035
036    @SuppressWarnings("unchecked")
037    protected static <V extends TableDef> V getCache(String key, Function<String, V> mappingFunction) {
038        return MapUtil.computeIfAbsent((Map<String, V>) CACHE, key, mappingFunction);
039    }
040
041    protected TableDef(String schema, String tableName) {
042        super(schema, tableName);
043    }
044
045    protected TableDef(String schema, String tableName, String alias) {
046        super(schema, tableName, alias);
047    }
048
049    /**
050     * 兼容方法,与 {@link #getName()} 相同。
051     *
052     * @return 表名
053     */
054    public String getTableName() {
055        return name;
056    }
057
058    public TableDef as(String alias) {
059        String key = getNameWithSchema() + "." + alias;
060        return getCache(key, k -> new TableDef(this.schema, this.name, alias));
061    }
062
063}