001/**
002 * Copyright (c) 2022-2023, 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 */
016package com.mybatisflex.core.query;
017
018
019import com.mybatisflex.core.dialect.IDialect;
020
021import java.io.Serializable;
022import java.util.List;
023
024/**
025 * 排序字段
026 */
027public class QueryOrderBy implements Serializable {
028
029    private QueryColumn queryColumn;
030
031    private String orderType = "ASC"; //asc desc
032
033    private boolean nullsFirst = false;
034    private boolean nullsLast = false;
035
036    protected QueryOrderBy() {
037    }
038
039    public QueryOrderBy(QueryColumn queryColumn, String orderType) {
040        this.queryColumn = queryColumn;
041        this.orderType = orderType;
042    }
043
044
045    public QueryOrderBy(QueryColumn queryColumn) {
046        this.queryColumn = queryColumn;
047    }
048
049
050    public QueryOrderBy nullsFirst() {
051        this.nullsFirst = true;
052        this.nullsLast = false;
053        return this;
054    }
055
056
057    public QueryOrderBy nullsLast() {
058        this.nullsFirst = false;
059        this.nullsLast = true;
060        return this;
061    }
062
063
064    public String toSql(List<QueryTable> queryTables, IDialect dialect) {
065        String sql = queryColumn.toConditionSql(queryTables, dialect) + " " + orderType;
066        if (nullsFirst) {
067            sql = sql + " NULLS FIRST";
068        } else if (nullsLast) {
069            sql = sql + " NULLS LAST";
070        }
071        return sql;
072    }
073}