Skip to content

Commit

Permalink
Respect max name length (#5463)
Browse files Browse the repository at this point in the history
Fixes #5460

(cherry picked from commit 5ba1592)
  • Loading branch information
NinoFloris committed Nov 28, 2023
1 parent 5e2f829 commit 8bc38b3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/Npgsql/Internal/Postgres/DataTypeName.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ namespace Npgsql.Internal.Postgres;
/// We need to respect this to get to valid names when deriving them (for multirange/arrays etc).
/// This does not include the namespace.
/// </remarks>
const int NAMEDATALEN = 64 - 1; // Minus null terminator.
internal const int NAMEDATALEN = 64 - 1; // Minus null terminator.

readonly string _value;

Expand All @@ -32,10 +32,11 @@ namespace Npgsql.Internal.Postgres;
if (fullyQualifiedDataTypeName.AsSpan(schemaEndIndex).EndsWith("[]".AsSpan()))
fullyQualifiedDataTypeName = NormalizeName(fullyQualifiedDataTypeName);

var typeNameLength = fullyQualifiedDataTypeName.Length - schemaEndIndex + 1;
var typeNameLength = fullyQualifiedDataTypeName.Length - (schemaEndIndex + 1);
if (typeNameLength > NAMEDATALEN)
throw new ArgumentException(
$"Name is too long and would be truncated to: {fullyQualifiedDataTypeName.Substring(0, fullyQualifiedDataTypeName.Length - typeNameLength + NAMEDATALEN)}");
$"Name is too long and would be truncated to: {fullyQualifiedDataTypeName.Substring(0,
fullyQualifiedDataTypeName.Length - typeNameLength + NAMEDATALEN)}");
}

_value = fullyQualifiedDataTypeName;
Expand Down
26 changes: 26 additions & 0 deletions test/Npgsql.Tests/DataTypeNameTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System;
using Npgsql.Internal.Postgres;
using NUnit.Framework;

namespace Npgsql.Tests;

public class DataTypeNameTests
{
[Test]
public void MaxLengthDataTypeName()
{
var name = new string('a', DataTypeName.NAMEDATALEN);
var fullyQualifiedDataTypeName= $"public.{name}";
Assert.DoesNotThrow(() => new DataTypeName(fullyQualifiedDataTypeName));
Assert.AreEqual(new DataTypeName(fullyQualifiedDataTypeName).Value, fullyQualifiedDataTypeName);
}

[Test]
public void TooLongDataTypeName()
{
var name = new string('a', DataTypeName.NAMEDATALEN + 1);
var fullyQualifiedDataTypeName= $"public.{name}";
var exception = Assert.Throws<ArgumentException>(() => new DataTypeName(fullyQualifiedDataTypeName));
Assert.That(exception!.Message, Does.EndWith($": public.{new string('a', DataTypeName.NAMEDATALEN)}"));
}
}

0 comments on commit 8bc38b3

Please sign in to comment.