Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support more data types and add relevant docs #226

Merged
merged 1 commit into from
Mar 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CodeGenerator/Generators/CsprojGen.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace SqlcGenCsharp.Generators;

internal class CsprojGen(string outputDirectory, string projectName, string namespaceName, Options options)
{
private const string DefaultDapperVersion = "2.1.35";
private const string DefaultDapperVersion = "2.1.66";
private const string DefaultNpgsqlVersion = "8.0.6";
private const string DefaultMysqlConnectorVersion = "2.4.0";
private const string DefaultSqliteVersion = "9.0.0";
Expand Down
21 changes: 19 additions & 2 deletions CodeGenerator/Generators/UtilsGen.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,31 @@ public static string TransformQueryForSqliteBatch(string originalSql, int cntRec

var optionalNullToNStringConverter = dbDriver.Options.DriverName is DriverName.MySqlConnector
? $$"""
public class NullToNStringConverter : DefaultTypeConverter
public class NullToStringConverter : DefaultTypeConverter
{
public override {{dbDriver.AddNullableSuffixIfNeeded("string", true)}} ConvertToString(
{{dbDriver.AddNullableSuffixIfNeeded("object", true)}} value, IWriterRow row, MemberMapData memberMapData)
{{dbDriver.AddNullableSuffixIfNeeded("object", false)}} value, IWriterRow row, MemberMapData memberMapData)
{
return value == null ? @"\N" : base.ConvertToString(value, row, memberMapData);
}
}

public class BoolToBitConverter : DefaultTypeConverter
{
public override {{dbDriver.AddNullableSuffixIfNeeded("string", true)}} ConvertToString(
{{dbDriver.AddNullableSuffixIfNeeded("object", false)}} value, IWriterRow row, MemberMapData memberMapData)
{
switch (value)
{
case null:
return @"\N";
case bool b:
return b ? "1" : "0";
default:
return base.ConvertToString(value, row, memberMapData);
}
}
}
"""
: string.Empty;

Expand Down
8 changes: 6 additions & 2 deletions Drivers/ColumnMapping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@

namespace SqlcGenCsharp.Drivers;

public class ColumnMapping(string csharpType, Dictionary<string, string?> dbTypes, Func<int, string> readerFn, Func<int, string>? readerArrayFn = null)
public record DbTypeInfo(int? Length = null, string? NpgsqlTypeOverride = null);

public class ColumnMapping(
string csharpType,
Dictionary<string, DbTypeInfo> dbTypes, Func<int, string> readerFn, Func<int, string>? readerArrayFn = null)
{
public string CsharpType { get; } = csharpType;
public Func<int, string> ReaderFn { get; } = readerFn;
public Func<int, string>? ReaderArrayFn { get; } = readerArrayFn;
public Dictionary<string, string?> DbTypes { get; } = dbTypes;
public Dictionary<string, DbTypeInfo> DbTypes { get; } = dbTypes;
}
20 changes: 14 additions & 6 deletions Drivers/DbDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public abstract class DbDriver

private HashSet<string> NullableTypesInDotnetCore { get; } = ["string", "object"];

private HashSet<string> NullableTypes { get; } = ["bool", "short", "int", "long", "float", "double", "decimal", "DateTime"];
private HashSet<string> NullableTypes { get; } = ["bool", "byte", "short", "int", "long", "float", "double", "decimal", "DateTime"];

protected abstract List<ColumnMapping> ColumnMappings { get; }

Expand Down Expand Up @@ -64,9 +64,8 @@ public string GetCsharpType(Column column)

string GetTypeWithoutNullableSuffix()
{
var columnType = column.Type.Name.ToLower();
foreach (var columnMapping in ColumnMappings
.Where(columnMapping => columnMapping.DbTypes.ContainsKey(columnType)))
.Where(columnMapping => DoesColumnMappingApply(columnMapping, column)))
{
if (column.IsArray || column.IsSqlcSlice) return $"{columnMapping.CsharpType}[]";
return columnMapping.CsharpType;
Expand All @@ -75,11 +74,20 @@ string GetTypeWithoutNullableSuffix()
}
}

public string GetColumnReader(Column column, int ordinal)
private static bool DoesColumnMappingApply(ColumnMapping columnMapping, Column column)
{
var columnType = column.Type.Name.ToLower();
if (!columnMapping.DbTypes.TryGetValue(columnType, out var typeInfo))
return false;
if (typeInfo.Length is null)
return true;
return typeInfo.Length.Value == column.Length;
}

public string GetColumnReader(Column column, int ordinal)
{
foreach (var columnMapping in ColumnMappings
.Where(columnMapping => columnMapping.DbTypes.ContainsKey(columnType)))
.Where(columnMapping => DoesColumnMappingApply(columnMapping, column)))
{
if (column.IsArray)
return columnMapping.ReaderArrayFn?.Invoke(ordinal) ?? throw new InvalidOperationException("ReaderArrayFn is null");
Expand All @@ -94,7 +102,7 @@ public string GetColumnReader(Column column, int ordinal)
foreach (var columnMapping in ColumnMappings)
{
if (columnMapping.DbTypes.TryGetValue(columnType, out var dbTypeOverride))
return dbTypeOverride;
return dbTypeOverride.NpgsqlTypeOverride;
}
throw new NotSupportedException($"Column {column.Name} has unsupported column type: {column.Type.Name}");
}
Expand Down
118 changes: 64 additions & 54 deletions Drivers/MySqlConnectorDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,70 +14,73 @@ public partial class MySqlConnectorDriver(Options options, Dictionary<string, Ta
{
protected override List<ColumnMapping> ColumnMappings { get; } =
[
new("bool",
new Dictionary<string, DbTypeInfo>
{
{ "tinyint", new DbTypeInfo(Length: 1) }
}, ordinal => $"reader.GetBoolean({ordinal})"),
new("short",
new Dictionary<string, DbTypeInfo>
{
{ "tinyint", new DbTypeInfo() },
{ "smallint", new DbTypeInfo() },
{ "year", new DbTypeInfo() }
}, ordinal => $"reader.GetInt16({ordinal})"),
new("long",
new Dictionary<string, string?>
new Dictionary<string, DbTypeInfo>
{
{ "bigint", null }
{ "bigint", new DbTypeInfo() }
}, ordinal => $"reader.GetInt64({ordinal})"),
new("byte",
new Dictionary<string, DbTypeInfo>
{
{ "bit", new DbTypeInfo() }
}, ordinal => $"reader.GetFieldValue<byte>({ordinal})"),
new("byte[]",
new Dictionary<string, string?>
new Dictionary<string, DbTypeInfo>
{
{ "binary", null },
{ "blob", null },
{ "longblob", null },
{ "mediumblob", null },
{ "tinyblob", null },
{ "varbinary", null }
{ "binary", new DbTypeInfo() },
{ "blob", new DbTypeInfo() },
{ "longblob", new DbTypeInfo() },
{ "mediumblob", new DbTypeInfo() },
{ "tinyblob", new DbTypeInfo() },
{ "varbinary", new DbTypeInfo() }
}, ordinal => $"reader.GetFieldValue<byte[]>({ordinal})"),
new("string",
new Dictionary<string, string?>
new Dictionary<string, DbTypeInfo>
{
{ "char", null },
{ "decimal", null },
{ "longtext", null },
{ "mediumtext", null },
{ "text", null },
{ "time", null },
{ "tinytext", null },
{ "varchar", null },
{ "var_string", null },
{ "json", null }
{ "char", new DbTypeInfo() },
{ "decimal", new DbTypeInfo() },
{ "longtext", new DbTypeInfo() },
{ "mediumtext", new DbTypeInfo() },
{ "text", new DbTypeInfo() },
{ "time", new DbTypeInfo() },
{ "tinytext", new DbTypeInfo() },
{ "varchar", new DbTypeInfo() },
{ "var_string", new DbTypeInfo() },
{ "json", new DbTypeInfo() }
}, ordinal => $"reader.GetString({ordinal})"),
new("DateTime",
new Dictionary<string, string?>
new Dictionary<string, DbTypeInfo>
{
{ "date", null },
{ "datetime", null },
{ "timestamp", null }
{ "date", new DbTypeInfo() },
{ "datetime", new DbTypeInfo() },
{ "timestamp", new DbTypeInfo() }
}, ordinal => $"reader.GetDateTime({ordinal})"),
new("short",
new Dictionary<string, string?>
{
{ "smallint", null },
{ "year", null }
}, ordinal => $"reader.GetInt16({ordinal})"),
new("int",
new Dictionary<string, string?>
new Dictionary<string, DbTypeInfo>
{
{ "int", null },
{ "mediumint", null },
{ "int", new DbTypeInfo() },
{ "mediumint", new DbTypeInfo() },
}, ordinal => $"reader.GetInt32({ordinal})"),
new("bool",
new Dictionary<string, string?>
{
{ "bit", null },
{ "tinyint", null },
{ "bool", null },
{ "boolean", null }
}, ordinal => $"reader.GetBoolean({ordinal})"),
new("double",
new Dictionary<string, string?>
new Dictionary<string, DbTypeInfo>
{
{ "double", null },
{ "float", null }
{ "double", new DbTypeInfo() },
{ "float", new DbTypeInfo() }
}, ordinal => $"reader.GetDouble({ordinal})"),
new("object",
new Dictionary<string, string?>(), ordinal => $"reader.GetValue({ordinal})")
new Dictionary<string, DbTypeInfo>(), ordinal => $"reader.GetValue({ordinal})")
];

public override UsingDirectiveSyntax[] GetUsingDirectives()
Expand Down Expand Up @@ -170,24 +173,31 @@ public string GetCopyFromImpl(Query query, string queryTextConstant)
var csvWriterVar = Variable.CsvWriter.AsVarName();
var loaderVar = Variable.Loader.AsVarName();
var connectionVar = Variable.Connection.AsVarName();
var nullConverterFn = Variable.NullConverterFn.AsVarName();

var loaderColumns = query.Params.Select(p => $"\"{p.Column.Name}\"").JoinByComma();
var (establishConnection, connectionOpen) = EstablishConnection(query);
return $$"""
const string supportedDateTimeFormat = "yyyy-MM-dd H:mm:ss";
var {{Variable.Config.AsVarName()}} = new CsvConfiguration(CultureInfo.CurrentCulture) { Delimiter = "{{csvDelimiter}}" };
var {{nullConverterFn}} = new Utils.NullToStringConverter();
using (var {{Variable.Writer.AsVarName()}} = new StreamWriter("{{tempCsvFilename}}", false, new UTF8Encoding(false)))
using (var {{csvWriterVar}} = new CsvWriter({{Variable.Writer.AsVarName()}}, {{Variable.Config.AsVarName()}}))
{
var options = new TypeConverterOptions { Formats = new[] { supportedDateTimeFormat } };
{{csvWriterVar}}.Context.TypeConverterOptionsCache.AddOptions<DateTime>(options);
{{csvWriterVar}}.Context.TypeConverterOptionsCache.AddOptions<DateTime?>(options);
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<bool?>(new Utils.NullToNStringConverter());
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<short?>(new Utils.NullToNStringConverter());
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<int?>(new Utils.NullToNStringConverter());
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<long?>(new Utils.NullToNStringConverter());
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<DateTime?>(new Utils.NullToNStringConverter());
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<string>(new Utils.NullToNStringConverter());
var {{Variable.Options}} = new TypeConverterOptions { Formats = new[] { supportedDateTimeFormat } };
{{csvWriterVar}}.Context.TypeConverterOptionsCache.AddOptions<DateTime>({{Variable.Options}});
{{csvWriterVar}}.Context.TypeConverterOptionsCache.AddOptions<DateTime?>({{Variable.Options}});
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<bool?>(new Utils.BoolToBitConverter());
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<byte?>({{nullConverterFn}});
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<short?>({{nullConverterFn}});
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<int?>({{nullConverterFn}});
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<long?>({{nullConverterFn}});
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<float?>({{nullConverterFn}});
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<decimal?>({{nullConverterFn}});
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<double?>({{nullConverterFn}});
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<DateTime?>({{nullConverterFn}});
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<{{AddNullableSuffixIfNeeded("string", false)}}>({{nullConverterFn}});
{{csvWriterVar}}.Context.TypeConverterCache.AddConverter<{{AddNullableSuffixIfNeeded("object", false)}}>({{nullConverterFn}});
await {{csvWriterVar}}.WriteRecordsAsync({{Variable.Args.AsVarName()}});
}

Expand Down
Loading