Skip to content

Commit b4e06b5

Browse files
[Phase 3] MSSQL JSON - test fixture + REST CRUD tests (#3720)
## What this PR does Adds the database test fixture and REST integration tests for SQL Server 2025 `JSON` columns. It builds on Phase 2 (which taught the engine to treat `JSON` as a normal `string`) and proves the behavior end-to-end through the REST API. This follows the exact pattern of the recently merged **vector data type** feature (#3677), and is unblocked by CI now running SQL Server 2025 (#3697). ## What's included - **Test table** — a `profiles` table with an `id` and a `metadata json` column, plus 5 seed rows covering a simple object, an array, a deeply nested object, unicode + emoji, and `NULL`. - **Entity** — a `Profile` entity (REST + GraphQL enabled) in the MsSql test config and config generator. - **REST tests** — `MsSqlRestJsonTypesTests`: read (list, by id, null, array, nested, unicode), insert, update (PUT/PATCH), clear-to-null, and delete. Because DAB treats `JSON` as a string, the tests parse `metadata` and compare it **semantically**, so they're robust to any whitespace / key-order normalization the engine applies. ## No gating needed Unlike the earlier plan, the table is created **unconditionally** (no server-version guard) — CI runs SQL Server 2025 and the schema already uses the 2025-only `vector` type the same way. ## Delivery plan | Phase | What | Status | |------|------|--------| | 1 | .NET 10 + SqlClient 6.x (prerequisite) | ✅ Merged (#3697/#3656) | | 2 | JSON type + error mapping (engine) | ✅ Merged (#3691) | | **3** | **Test fixture + REST CRUD tests (this PR)** | 🚧 In review | | 3b | GraphQL / OpenAPI / MCP schema-discovery tests | Next | | 4 | Error/filter edge cases + regression | After | ## Notes - Requires SQL Server 2025 / Azure SQL (native `json` type). - No changes to PostgreSQL, MySQL, DwSql, or CosmosDB. - Related issue: #2768. --------- Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
1 parent 2210289 commit b4e06b5

5 files changed

Lines changed: 390 additions & 0 deletions

File tree

‎config-generators/mssql-commands.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ add WebsiteUser_MM --config "dab-config.MsSql.json" --source website_users_mm --
1818
add SupportedType --config "dab-config.MsSql.json" --source type_table --permissions "anonymous:create,read,delete,update"
1919
add VectorType --config "dab-config.MsSql.json" --source vector_type_table --rest true --graphql false --permissions "anonymous:create,read,delete,update"
2020
update VectorType --config "dab-config.MsSql.json" --permissions "authenticated:create,read,delete,update"
21+
add Profile --config "dab-config.MsSql.json" --source profiles --rest true --graphql true --permissions "anonymous:create,read,delete,update"
22+
update Profile --config "dab-config.MsSql.json" --permissions "authenticated:create,read,delete,update"
2123
add stocks_price --config "dab-config.MsSql.json" --source stocks_price --permissions "authenticated:create,read,update,delete"
2224
update stocks_price --config "dab-config.MsSql.json" --permissions "anonymous:read"
2325
update stocks_price --config "dab-config.MsSql.json" --permissions "TestNestedFilterFieldIsNull_ColumnForbidden:read" --fields.exclude "price"

‎src/Service.Tests/DatabaseSchema-MsSql.sql‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ DROP TABLE IF EXISTS comics;
4141
DROP TABLE IF EXISTS brokers;
4242
DROP TABLE IF EXISTS type_table;
4343
DROP TABLE IF EXISTS vector_type_table;
44+
DROP TABLE IF EXISTS profiles;
4445
DROP TABLE IF EXISTS trees;
4546
DROP TABLE IF EXISTS fungi;
4647
DROP TABLE IF EXISTS empty_table;
@@ -241,6 +242,11 @@ CREATE TABLE vector_type_table(
241242
vector_data_max vector(1998)
242243
);
243244

245+
CREATE TABLE profiles(
246+
id int IDENTITY(5001, 1) PRIMARY KEY,
247+
metadata json NULL
248+
);
249+
244250
CREATE TABLE trees (
245251
treeId int PRIMARY KEY,
246252
species varchar(max),
@@ -640,6 +646,16 @@ VALUES (7, CAST('[' + (
640646
) + ']' AS vector(1998)));
641647
SET IDENTITY_INSERT vector_type_table OFF
642648

649+
SET IDENTITY_INSERT profiles ON
650+
INSERT INTO profiles(id, metadata)
651+
VALUES
652+
(1, N'{"role":"admin","tier":3}'),
653+
(2, N'{"tags":["a","b","c"]}'),
654+
(3, N'{"nested":{"key":{"deep":true}}}'),
655+
(4, N'{"unicode":"éü😀"}'),
656+
(5, NULL);
657+
SET IDENTITY_INSERT profiles OFF
658+
643659
SET IDENTITY_INSERT sales ON
644660
INSERT INTO sales(id, item_name, subtotal, tax) VALUES (1, 'Watch', 249.00, 20.59), (2, 'Montior', 120.50, 11.12);
645661
SET IDENTITY_INSERT sales OFF

‎src/Service.Tests/Snapshots/ConfigurationTests.TestReadingRuntimeConfigForMsSql.verified.txt‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1765,6 +1765,58 @@
17651765
]
17661766
}
17671767
},
1768+
{
1769+
Profile: {
1770+
Source: {
1771+
Object: profiles,
1772+
Type: Table
1773+
},
1774+
GraphQL: {
1775+
Singular: Profile,
1776+
Plural: Profiles,
1777+
Enabled: true
1778+
},
1779+
Rest: {
1780+
Enabled: true
1781+
},
1782+
Permissions: [
1783+
{
1784+
Role: anonymous,
1785+
Actions: [
1786+
{
1787+
Action: Create
1788+
},
1789+
{
1790+
Action: Read
1791+
},
1792+
{
1793+
Action: Delete
1794+
},
1795+
{
1796+
Action: Update
1797+
}
1798+
]
1799+
},
1800+
{
1801+
Role: authenticated,
1802+
Actions: [
1803+
{
1804+
Action: Create
1805+
},
1806+
{
1807+
Action: Read
1808+
},
1809+
{
1810+
Action: Delete
1811+
},
1812+
{
1813+
Action: Update
1814+
}
1815+
]
1816+
}
1817+
]
1818+
}
1819+
},
17681820
{
17691821
stocks_price: {
17701822
Source: {
Lines changed: 268 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,268 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT License.
3+
4+
using System.Net;
5+
using System.Net.Http;
6+
using System.Text;
7+
using System.Text.Json;
8+
using System.Threading.Tasks;
9+
using Microsoft.VisualStudio.TestTools.UnitTesting;
10+
11+
namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests
12+
{
13+
/// <summary>
14+
/// Tests for SQL Server native JSON column support via REST endpoints (read and write).
15+
/// DAB does nothing special for a JSON column - it is written from the request payload and
16+
/// read back with no custom handling, new scalar, or format. On read, SQL Server's
17+
/// FOR JSON PATH projection (which DAB uses to shape every result) inlines a native json
18+
/// column as a nested JSON value, so the metadata surfaces at the REST boundary as a JSON
19+
/// object rather than an escaped string. Writes still supply the payload as a JSON string,
20+
/// exactly as a normal string column would be written.
21+
/// Assertions compare the returned metadata semantically so they are robust to any
22+
/// whitespace / key-order normalization the engine applies to the JSON type.
23+
/// NOTE: The native JSON data type requires SQL Server 2025 / Azure SQL.
24+
/// </summary>
25+
[TestClass, TestCategory(TestCategory.MSSQL)]
26+
public class MsSqlRestJsonTypesTests : SqlTestBase
27+
{
28+
private const string JSON_TYPE_REST_PATH = "api/Profile";
29+
30+
[ClassInitialize]
31+
public static async Task SetupAsync(TestContext context)
32+
{
33+
DatabaseEngine = TestCategory.MSSQL;
34+
await InitializeTestFixture();
35+
}
36+
37+
#region Read Tests
38+
39+
/// <summary>
40+
/// GET /api/Profile - Verify the whole collection (5 seeded rows) is returned and that
41+
/// each metadata value renders either as a native JSON object payload or null (row 5).
42+
/// </summary>
43+
[TestMethod]
44+
public async Task GetJsonTypeList()
45+
{
46+
HttpResponseMessage response = await HttpClient.GetAsync(JSON_TYPE_REST_PATH);
47+
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
48+
49+
JsonElement items = JsonDocument.Parse(await response.Content.ReadAsStringAsync())
50+
.RootElement.GetProperty("value");
51+
Assert.AreEqual(5, items.GetArrayLength(), "Expected the 5 seeded profile rows.");
52+
53+
// Rows 1-4 carry a JSON payload (inlined as a native JSON object); row 5 is null.
54+
foreach (JsonElement record in items.EnumerateArray())
55+
{
56+
JsonValueKind metadataKind = record.GetProperty("metadata").ValueKind;
57+
Assert.IsTrue(
58+
metadataKind is JsonValueKind.Object or JsonValueKind.Null,
59+
$"Expected metadata to be a JSON object or null, but was {metadataKind}.");
60+
}
61+
}
62+
63+
/// <summary>
64+
/// GET /api/Profile/id/1 - Verify a simple object payload round-trips (verbatim value-equivalence).
65+
/// </summary>
66+
[TestMethod]
67+
public async Task GetJsonTypeByPrimaryKey()
68+
{
69+
JsonElement metadata = ParseMetadata(await GetRecordByIdAsync(1));
70+
Assert.AreEqual("admin", metadata.GetProperty("role").GetString());
71+
Assert.AreEqual(3, metadata.GetProperty("tier").GetInt32());
72+
}
73+
74+
/// <summary>
75+
/// GET /api/Profile/id/5 - Verify a SQL NULL metadata value is rendered as JSON null.
76+
/// </summary>
77+
[TestMethod]
78+
public async Task GetJsonTypeWithNull()
79+
{
80+
JsonElement record = await GetRecordByIdAsync(5);
81+
Assert.AreEqual(JsonValueKind.Null, record.GetProperty("metadata").ValueKind);
82+
}
83+
84+
/// <summary>
85+
/// GET /api/Profile/id/2 - Verify an array-bearing payload is preserved.
86+
/// </summary>
87+
[TestMethod]
88+
public async Task GetJsonTypeWithArrayPayload()
89+
{
90+
JsonElement metadata = ParseMetadata(await GetRecordByIdAsync(2));
91+
JsonElement tags = metadata.GetProperty("tags");
92+
Assert.AreEqual(JsonValueKind.Array, tags.ValueKind);
93+
Assert.AreEqual(3, tags.GetArrayLength());
94+
Assert.AreEqual("a", tags[0].GetString());
95+
Assert.AreEqual("b", tags[1].GetString());
96+
Assert.AreEqual("c", tags[2].GetString());
97+
}
98+
99+
/// <summary>
100+
/// GET /api/Profile/id/3 - Verify a deeply nested object payload is preserved.
101+
/// </summary>
102+
[TestMethod]
103+
public async Task GetJsonTypeWithNestedPayload()
104+
{
105+
JsonElement metadata = ParseMetadata(await GetRecordByIdAsync(3));
106+
Assert.IsTrue(metadata.GetProperty("nested").GetProperty("key").GetProperty("deep").GetBoolean());
107+
}
108+
109+
/// <summary>
110+
/// GET /api/Profile/id/4 - Verify unicode (including a multi-byte emoji) round-trips intact.
111+
/// </summary>
112+
[TestMethod]
113+
public async Task GetJsonTypeWithUnicode()
114+
{
115+
JsonElement metadata = ParseMetadata(await GetRecordByIdAsync(4));
116+
Assert.AreEqual("éü😀", metadata.GetProperty("unicode").GetString());
117+
}
118+
119+
#endregion
120+
121+
#region Write Tests
122+
123+
/// <summary>
124+
/// POST /api/Profile - Verify a new record with a JSON payload can be inserted, the value
125+
/// echoes back, and it is persisted (read-back). Also covers inserting a null payload.
126+
/// </summary>
127+
[DataTestMethod]
128+
[DataRow("{ \"metadata\": \"{\\\"role\\\":\\\"guest\\\"}\" }", false, DisplayName = "Insert profile with valid JSON object")]
129+
[DataRow("{ \"metadata\": null }", true, DisplayName = "Insert profile with null metadata")]
130+
public async Task InsertJsonType(string requestBody, bool expectNull)
131+
{
132+
HttpResponseMessage postResponse = await HttpClient.PostAsync(
133+
JSON_TYPE_REST_PATH,
134+
new StringContent(requestBody, Encoding.UTF8, "application/json"));
135+
Assert.AreEqual(HttpStatusCode.Created, postResponse.StatusCode);
136+
137+
JsonElement postElement = JsonDocument.Parse(await postResponse.Content.ReadAsStringAsync())
138+
.RootElement.GetProperty("value")[0];
139+
int newId = postElement.GetProperty("id").GetInt32();
140+
141+
JsonElement readBack = await GetRecordByIdAsync(newId);
142+
if (expectNull)
143+
{
144+
Assert.AreEqual(JsonValueKind.Null, readBack.GetProperty("metadata").ValueKind);
145+
}
146+
else
147+
{
148+
Assert.AreEqual("guest", ParseMetadata(readBack).GetProperty("role").GetString());
149+
}
150+
151+
await DeleteProfile(newId);
152+
}
153+
154+
/// <summary>
155+
/// PUT /api/Profile/id/1 - Verify a full update replaces the metadata payload, then restore it.
156+
/// </summary>
157+
[TestMethod]
158+
public async Task PutJsonType_Update()
159+
{
160+
try
161+
{
162+
HttpResponseMessage response = await HttpClient.PutAsync(
163+
$"{JSON_TYPE_REST_PATH}/id/1",
164+
new StringContent("{ \"metadata\": \"{\\\"role\\\":\\\"owner\\\"}\" }", Encoding.UTF8, "application/json"));
165+
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
166+
Assert.AreEqual("owner", ParseMetadata(await GetRecordByIdAsync(1)).GetProperty("role").GetString());
167+
}
168+
finally
169+
{
170+
// Restore original value so shared row 1 is left intact for other tests.
171+
HttpResponseMessage restore = await HttpClient.PutAsync(
172+
$"{JSON_TYPE_REST_PATH}/id/1",
173+
new StringContent("{ \"metadata\": \"{\\\"role\\\":\\\"admin\\\",\\\"tier\\\":3}\" }", Encoding.UTF8, "application/json"));
174+
Assert.AreEqual(HttpStatusCode.OK, restore.StatusCode);
175+
}
176+
}
177+
178+
/// <summary>
179+
/// PATCH /api/Profile/id/1 - Verify a partial update sets a new metadata payload, then restore it.
180+
/// </summary>
181+
[TestMethod]
182+
public async Task PatchJsonType_Update()
183+
{
184+
try
185+
{
186+
HttpResponseMessage response = await HttpClient.PatchAsync(
187+
$"{JSON_TYPE_REST_PATH}/id/1",
188+
new StringContent("{ \"metadata\": \"{\\\"role\\\":\\\"editor\\\"}\" }", Encoding.UTF8, "application/json"));
189+
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
190+
Assert.AreEqual("editor", ParseMetadata(await GetRecordByIdAsync(1)).GetProperty("role").GetString());
191+
}
192+
finally
193+
{
194+
// Restore original value so shared row 1 is left intact for other tests.
195+
HttpResponseMessage restore = await HttpClient.PutAsync(
196+
$"{JSON_TYPE_REST_PATH}/id/1",
197+
new StringContent("{ \"metadata\": \"{\\\"role\\\":\\\"admin\\\",\\\"tier\\\":3}\" }", Encoding.UTF8, "application/json"));
198+
Assert.AreEqual(HttpStatusCode.OK, restore.StatusCode);
199+
}
200+
}
201+
202+
/// <summary>
203+
/// PATCH /api/Profile/id/2 - Verify metadata can be cleared to null.
204+
/// </summary>
205+
[TestMethod]
206+
public async Task PatchJsonType_ToNull()
207+
{
208+
try
209+
{
210+
HttpResponseMessage response = await HttpClient.PatchAsync(
211+
$"{JSON_TYPE_REST_PATH}/id/2",
212+
new StringContent("{ \"metadata\": null }", Encoding.UTF8, "application/json"));
213+
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
214+
Assert.AreEqual(JsonValueKind.Null, (await GetRecordByIdAsync(2)).GetProperty("metadata").ValueKind);
215+
}
216+
finally
217+
{
218+
// Restore original array payload so shared row 2 is left intact for other tests.
219+
HttpResponseMessage restore = await HttpClient.PutAsync(
220+
$"{JSON_TYPE_REST_PATH}/id/2",
221+
new StringContent("{ \"metadata\": \"{\\\"tags\\\":[\\\"a\\\",\\\"b\\\",\\\"c\\\"]}\" }", Encoding.UTF8, "application/json"));
222+
Assert.AreEqual(HttpStatusCode.OK, restore.StatusCode);
223+
}
224+
}
225+
226+
#endregion
227+
228+
#region Helpers
229+
230+
/// <summary>
231+
/// DELETE /api/Profile/id/{id} - Verify a record can be deleted.
232+
/// </summary>
233+
private static async Task DeleteProfile(int id)
234+
{
235+
HttpResponseMessage deleteResponse = await HttpClient.DeleteAsync($"{JSON_TYPE_REST_PATH}/id/{id}");
236+
Assert.AreEqual(HttpStatusCode.NoContent, deleteResponse.StatusCode);
237+
}
238+
239+
/// <summary>
240+
/// Fetches a single Profile record by its primary key and returns the record element.
241+
/// </summary>
242+
private static async Task<JsonElement> GetRecordByIdAsync(int id)
243+
{
244+
HttpResponseMessage response = await HttpClient.GetAsync($"{JSON_TYPE_REST_PATH}/id/{id}");
245+
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
246+
string body = await response.Content.ReadAsStringAsync();
247+
return JsonDocument.Parse(body).RootElement.GetProperty("value")[0].Clone();
248+
}
249+
250+
/// <summary>
251+
/// Returns the metadata field as a JSON element. DAB applies no special handling to a JSON
252+
/// column, so SQL Server's FOR JSON PATH projection inlines it as a native JSON object at the
253+
/// REST boundary. This helper asserts the value is a JSON object and returns it for inspection.
254+
/// </summary>
255+
private static JsonElement ParseMetadata(JsonElement record)
256+
{
257+
JsonElement metadata = record.GetProperty("metadata");
258+
Assert.AreEqual(
259+
JsonValueKind.Object,
260+
metadata.ValueKind,
261+
"A native JSON column is inlined as a JSON object at the REST boundary via FOR JSON PATH.");
262+
263+
return metadata.Clone();
264+
}
265+
266+
#endregion
267+
}
268+
}

0 commit comments

Comments
 (0)