MySQL · Create

Ids that aren't numbers: text and uuid

Ids that aren't numbers, in three scenarios: a text id you supply (a country code), a uuid the database would generate (MySQL can't hand one back, so ARX refuses it), and a uuid your code generates.

Set up for this page

Besides the sample itself, it uses SampleContext.cs (the dbContext every sample is given); SampleOutput.cs (Step and Show, which print), in the files below.

1 Text id you supply

A text id you supply: the country code. Supplied means you always set it.

Already in scope: connectionString (string)

C#
var schema = ArxSchemaCatalog.Create()
    .Table("country", ArxIdColumn.Supplied<string>("code"))
    .Build();

var service = new ArxMySqlDbService(connectionString, schema);

var country = new ArxEntity("country");
country["code"] = "PT";
country["name"] = "Portugal";

ArxRecordId id = await service.CreateAsync(country);

// A text id is read with AsString().
Console.WriteLine($"created country {id.AsString()}");

Check it in the database

SQL

Run it in any SQL tool connected to the database, after the code has run.

SELECT code, name
FROM country
WHERE code = 'PT';

Expect: 1 row, Portugal.

2 Uuid the database makes: refused on MySQL

A uuid the database generates (a DEFAULT (UUID()) column): MySQL hands back only generated integer ids (LAST_INSERT_ID()), so ARX can't return it. Declaring such an id Generated is refused before any SQL is sent.

Already in scope: connectionString (string)

C#
var schema = ArxSchemaCatalog.Create()
    .Table("device", ArxIdColumn.Generated<Guid>("id"))
    .Build();

var service = new ArxMySqlDbService(connectionString, schema);

var device = new ArxEntity("device");
device["serial_number"] = "DEV-0001";

try
{
    await service.CreateAsync(device);
}
catch (ArxNotSupportedException error)
{
    // ARX8001: declare the id Supplied and set it (scenario 3).
    Console.WriteLine($"{error.Code}: nothing written");
}

Check it in the database

SQL

Run it in any SQL tool connected to the database, after the code has run.

SELECT count(*)
FROM device
WHERE serial_number = 'DEV-0001';

Expect: 0.

3 Uuid your code makes

A uuid your code generates: set the id, and it's written as given.

Already in scope: connectionString (string)

C#
// Supplied: your code sets the id on every record, and ARX writes it as given (CHAR(36), lower-case text).
var schema = ArxSchemaCatalog.Create()
    .Table("device", ArxIdColumn.Supplied<Guid>("id"))
    .Build();

var service = new ArxMySqlDbService(connectionString, schema);

var myId = Guid.Parse("e4a7c2d1-9b3f-4e8a-a5c6-7d8e9f0a1b2c");

var device = new ArxEntity("device");
device["id"] = myId;
device["serial_number"] = "DEV-0002";

ArxRecordId id = await service.CreateAsync(device);

Console.WriteLine($"created device {id.AsGuid()} (the same as myId: {id.AsGuid() == myId})");

Check it in the database

SQL

Run it in any SQL tool connected to the database, after the code has run.

SELECT id, serial_number
FROM device
WHERE serial_number = 'DEV-0002';

Expect: 1 row, id e4a7c2d1-9b3f-4e8a-a5c6-7d8e9f0a1b2c.

Run the complete sample

The code above comes from one program, built in a fresh project and run against the database. To run it yourself, here is every file and step.

The program, its files and how to run it

Run it locally

  1. .NET SDK: .NET SDK 10.0.100 or later 10.0.x (target net10.0).
  2. Create the project:
    Terminal
    dotnet new console -n ArxSample -f net10.0
    cd ArxSample
  3. Install the packages:
    Terminal
    dotnet add package ARX.SDK.MySQL --version 1.0.0-rc.1
  4. Database: a MySQL 8.4 (tested with 8.4.13) database with the sample schema.
  5. Configuration: set ARX_SAMPLES_MYSQL to its connection string. Nothing is hard-coded.
  6. Source code: replace Program.cs and add the 3 other files below, with the file names shown.
  7. Run it:
    Terminal
    dotnet run
  8. Expected output: below.

The files

Program.cs

Runs the sample. Generated for this page; it reads the connection string from the environment.

using ArxSamples.MySQL;
using ArxSamples.MySQL.Operations.Create.Basics;

// The connection string comes from the environment, never from the code (see "Configure the connection").
var connectionString = Environment.GetEnvironmentVariable("ARX_SAMPLES_MYSQL")
    ?? throw new InvalidOperationException("Set the ARX_SAMPLES_MYSQL environment variable to your MySQL connection string.");

await new Basic4_TextAndUuidIds().RunAsync(new SampleContext(connectionString));
Basic4_TextAndUuidIds.cs

The sample, as it is in the repository.

using ARX.SDK;
using ARX.SDK.MySQL.Services;
using ARX.SDK.Services;

using static ArxSamples.MySQL.SampleOutput;

namespace ArxSamples.MySQL.Operations.Create.Basics;

/// <summary>
/// Ids that aren't numbers, in three scenarios: a text id you supply (a country code), a uuid the database would
/// generate (MySQL can't hand one back, so ARX refuses it), and a uuid your code generates.
/// </summary>
public sealed class Basic4_TextAndUuidIds : ISample
{
    public string Name => "create-basics-4-text-and-uuid-ids";

    public string Title => "Ids that aren't numbers: text and uuid";

    public async Task RunAsync(SampleContext dbContext)
    {
        await Scenario1_ATextIdYouSupplyAsync(dbContext.ConnectionString);

        await Scenario2_AUuidTheDatabaseGeneratesAsync(dbContext.ConnectionString);

        await Scenario3_AUuidYourCodeGeneratesAsync(dbContext.ConnectionString);
    }

    /// <summary>1. A text id you supply: the country code. Supplied means you always set it.</summary>
    private static async Task Scenario1_ATextIdYouSupplyAsync(string connectionString)
    {
        Step("1. Text id you supply");

        var schema = ArxSchemaCatalog.Create()
            .Table("country", ArxIdColumn.Supplied<string>("code"))
            .Build();

        var service = new ArxMySqlDbService(connectionString, schema);

        var country = new ArxEntity("country");
        country["code"] = "PT";
        country["name"] = "Portugal";

        ArxRecordId id = await service.CreateAsync(country);

        // A text id is read with AsString().
        Show($"created country {id.AsString()}");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT code, name
         * FROM country
         * WHERE code = 'PT';
         * -- Expect: 1 row, Portugal.
         * ===========================================================
         */
    }

    /// <summary>
    /// 2. A uuid the database generates (a <c>DEFAULT (UUID())</c> column): MySQL hands back only generated integer ids
    /// (<c>LAST_INSERT_ID()</c>), so ARX can't return it. Declaring such an id Generated is refused before any SQL is sent.
    /// </summary>
    private static async Task Scenario2_AUuidTheDatabaseGeneratesAsync(string connectionString)
    {
        Step("2. Uuid the database makes: refused on MySQL");

        var schema = ArxSchemaCatalog.Create()
            .Table("device", ArxIdColumn.Generated<Guid>("id"))
            .Build();

        var service = new ArxMySqlDbService(connectionString, schema);

        var device = new ArxEntity("device");
        device["serial_number"] = "DEV-0001";

        try
        {
            await service.CreateAsync(device);
        }
        catch (ArxNotSupportedException error)
        {
            // ARX8001: declare the id Supplied and set it (scenario 3).
            Show($"{error.Code}: nothing written");
        }

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT count(*)
         * FROM device
         * WHERE serial_number = 'DEV-0001';
         * -- Expect: 0.
         * ===========================================================
         */
    }

    /// <summary>3. A uuid your code generates: set the id, and it's written as given.</summary>
    private static async Task Scenario3_AUuidYourCodeGeneratesAsync(string connectionString)
    {
        Step("3. Uuid your code makes");

        // Supplied: your code sets the id on every record, and ARX writes it as given (CHAR(36), lower-case text).
        var schema = ArxSchemaCatalog.Create()
            .Table("device", ArxIdColumn.Supplied<Guid>("id"))
            .Build();

        var service = new ArxMySqlDbService(connectionString, schema);

        var myId = Guid.Parse("e4a7c2d1-9b3f-4e8a-a5c6-7d8e9f0a1b2c");

        var device = new ArxEntity("device");
        device["id"] = myId;
        device["serial_number"] = "DEV-0002";

        ArxRecordId id = await service.CreateAsync(device);

        Show($"created device {id.AsGuid()} (the same as myId: {id.AsGuid() == myId})");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT id, serial_number
         * FROM device
         * WHERE serial_number = 'DEV-0002';
         * -- Expect: 1 row, id e4a7c2d1-9b3f-4e8a-a5c6-7d8e9f0a1b2c.
         * ===========================================================
         */
    }
}
SampleContext.cs

What every sample is given: the connection string (and the ISample interface the samples implement).

namespace ArxSamples.MySQL;

/// <summary>One documentation sample: a scenario a real application has, shown end to end.</summary>
public interface ISample
{
    /// <summary>The name to run it alone: <c>dotnet run -- &lt;name&gt;</c>.</summary>
    string Name { get; }

    /// <summary>One line on what it shows.</summary>
    string Title { get; }

    Task RunAsync(SampleContext dbContext);
}

/// <summary>
/// What a sample is given. Every sample gets the connection string; the application's service and catalog
/// (SampleContext.Application.cs) and the plain MySqlConnector read-back helper (SampleContext.Direct.cs) live in their own
/// files, so a sample needs only the files it uses.
/// </summary>
public sealed partial class SampleContext
{
    public SampleContext(string connectionString)
    {
        ConnectionString = connectionString;
    }

    public string ConnectionString { get; }
}
SampleOutput.cs

How the samples print: Step for each scenario, Show for what it did, ShowError for an error caught on purpose.

using ARX.SDK;

namespace ArxSamples.MySQL;

/// <summary>How the samples print: a numbered step for each scenario, then what it did.</summary>
public static class SampleOutput
{
    /// <summary>The start of a scenario: <c>Step("1. By the id Create returned")</c>.</summary>
    public static void Step(string text) => Console.WriteLine($"  > {text}");

    /// <summary>What the scenario did.</summary>
    public static void Show(string text) => Console.WriteLine($"      {text}");

    /// <summary>An ARX error the scenario caught on purpose.</summary>
    public static void ShowError(ArxException exception)
        => Console.WriteLine($"      caught {exception.GetType().Name}: {exception.Message}");
}

Expected output

What dotnet run printed when the sample was verified, on a freshly created sample schema. Ids differ when the tables already hold rows.

Output
  > 1. Text id you supply
      created country PT
  > 2. Uuid the database makes: refused on MySQL
      NotSupported: nothing written
  > 3. Uuid your code makes
      created device e4a7c2d1-9b3f-4e8a-a5c6-7d8e9f0a1b2c (the same as myId: True)