/* TShock, a server mod for Terraria Copyright (C) 2011-2025 Pryaxis & TShock Contributors This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ using System; using System.Collections.Generic; using System.Linq; using MySql.Data.MySqlClient; namespace TShockAPI.DB.Queries; /// /// Query Creator for Sqlite /// public class SqliteQueryBuilder : GenericQueryBuilder, IQueryBuilder { /// /// Creates a table from a SqlTable object. /// /// The SqlTable to create the table from /// The sql query for the table creation. public override string CreateTable(SqlTable table) { ValidateSqlColumnType(table.Columns); var columns = table.Columns.Select( c => "'{0}' {1} {2} {3} {4} {5}".SFormat(c.Name, DbTypeToString(c.Type, c.Length), c.Primary ? "PRIMARY KEY" : "", c.AutoIncrement ? "AUTOINCREMENT" : "", c.NotNull ? "NOT NULL" : "", c.DefaultCurrentTimestamp ? "DEFAULT CURRENT_TIMESTAMP" : "")); var uniques = table.Columns.Where(c => c.Unique).Select(c => c.Name); return "CREATE TABLE {0} ({1} {2})".SFormat(EscapeTableName(table.Name), string.Join(", ", columns), uniques.Any() ? ", UNIQUE({0})".SFormat(string.Join(", ", uniques)) : ""); } /// /// Renames the given table. /// /// Old name of the table /// New name of the table /// The sql query for renaming the table. public override string RenameTable(string from, string to) { return "ALTER TABLE {0} RENAME TO {1}".SFormat(from, to); } private static readonly Dictionary TypesAsStrings = new Dictionary { { MySqlDbType.VarChar, "TEXT" }, { MySqlDbType.String, "TEXT" }, { MySqlDbType.Text, "TEXT" }, { MySqlDbType.TinyText, "TEXT" }, { MySqlDbType.MediumText, "TEXT" }, { MySqlDbType.LongText, "TEXT" }, { MySqlDbType.Float, "REAL" }, { MySqlDbType.Double, "REAL" }, { MySqlDbType.Int32, "INTEGER" }, { MySqlDbType.Blob, "BLOB" }, { MySqlDbType.Int64, "BIGINT"}, { MySqlDbType.DateTime, "DATETIME"}, }; /// /// Converts the MySqlDbType enum to it's string representation. /// /// The MySqlDbType type /// The length of the datatype /// The string representation public override string DbTypeToString(MySqlDbType type, int? length) { if (TypesAsStrings.TryGetValue(type, out string ret)) { return ret; } throw new NotImplementedException(Enum.GetName(type)); } /// /// Escapes the table name /// /// The name of the table to be escaped /// protected override string EscapeTableName(string table) => $"\'{table}\'"; }