Sample code for 30+ languages & platforms
Lua Requires Chilkat v11.6.0+

Azure Table: Insert Two Entities in an Atomic Batch

See more Azure Table Service Examples

Inserts two distinct entities in a single atomic changeset. Existing entities cause conflict and roll back the transaction. Disabled by default. Uses exactly two entities with one fixed table/partition, unique Content-IDs, CRLF multipart framing, and a byte-count check against the 4 MiB request limit. Dynamic batches must additionally preserve the 100-operation, single-partition and unique-entity constraints.

Parses nested MIME responses using Chilkat.Mime, validates inner HTTP status and Content-ID uniqueness/completeness, and requires 204 for both operations. Outer 202 alone is not success. A lost or malformed response has an uncertain outcome; inspect state before replaying. Separate batches are not atomic together.

Targets Azure Storage Table service in the public cloud, not Azure Cosmos DB for Table. Uses Chilkat 11.6.0 or later and an unlocked library. Direct data requests pin x-ms-version 2026-04-06 and OData 3.0. Shared Key examples read private qa_data/azure/storage.json with account and access_key string fields. Authentication examples explain their additional fields. Create private local directories before running; keep credentials, tokens, SAS, entity values, checkpoints and diagnostics outside public content and source control.

HTTPS certificates are verified. Transport completion and HTTP status are checked separately. Writes are not automatically retried after an uncertain outcome. Entity keys, ETags and continuation tokens remain strings. Examples operate on the existing ExampleCustomers table unless noted; review the targets before adapting them. Microsoft Entra ID with suitable Table data roles is preferred where available.

Microsoft reference.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- StringBuilder compares text by value in every generated language.
local textCompare = chilkat.StringBuilder.new()
local applyChange = false
if not applyChange then
    print("This example writes an atomic transaction. Review the target and deliberately enable applyChange.")
    return
end

-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
local config = chilkat.JsonObject.new()
config.strict = true
success = config:load_file("qa_data/azure/storage.json")
if not success then
    print("Could not load private Azure configuration.")
    return
end

textCompare:clear()
textCompare:set_string(config:string_of("account"))
local sameText1 = textCompare:contents_equal("", true)
if (config:json_type_of("account") ~= 1) or (sameText1) then
    print("Supply the storage account name.")
    return
end

-- access_key is the base64 account key, not a connection string or SAS.
textCompare:clear()
textCompare:set_string(config:string_of("access_key"))
local sameText2 = textCompare:contents_equal("", true)
if (config:json_type_of("access_key") ~= 1) or (sameText2) then
    print("Supply the base64 account access key.")
    return
end

local accountText = chilkat.StringBuilder.new()
success = accountText:append(config:string_of("account"))
if not success then
    print("Could not prepare the request.")
    return
end

if (accountText.length < 3) or (accountText.length > 24) then
    print("Storage account names need 3-24 lowercase letters or digits.")
    return
end

local allowedAccountChars = chilkat.StringBuilder.new()
success = allowedAccountChars:append("abcdefghijklmnopqrstuvwxyz0123456789")
if not success then
    print("Could not prepare the request.")
    return
end

local charIndex = 0
while charIndex < accountText.length do
    if not allowedAccountChars:contains(accountText:get_range(charIndex, 1, false), true) then
        print("Storage account names need lowercase letters or digits.")
        return
    end

    charIndex = charIndex + 1
end

local endpoint = chilkat.StringBuilder.new()
success = endpoint:append(config:string_of("account"))
if not success then
    print("Could not prepare the request.")
    return
end

success = endpoint:append(".table.core.windows.net")
if not success then
    print("Could not prepare the request.")
    return
end

-- Table names contain only letters and digits and are case-insensitive.
-- Entity PartitionKey and RowKey values are case-sensitive.
local resourcePath = "/$batch"
local rest = chilkat.Rest.new()
rest.connect_timeout_ms = 20000
rest.idle_timeout_ms = 60000
local azAuth = chilkat.AuthAzureStorage.new()
azAuth.account = config:string_of("account")
azAuth.access_key = config:string_of("access_key")
azAuth.service = "Table"
azAuth.scheme = "SharedKey"
azAuth.xms_version = "2026-04-06"
success = rest:set_auth_azure_storage(azAuth)
if not success then
    print("Could not configure Shared Key signing.")
    return
end

local connection = chilkat.Socket.new()
connection.require_ssl_cert_verify = true
connection.max_read_idle_ms = 60000
connection.max_send_idle_ms = 60000
success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
if not success then
    print("TLS connection failed; inspect diagnostics privately.")
    return
end

-- Do not replay a write automatically after losing its response.
success = rest:use_connection(connection, false)
if not success then
    print("Could not prepare the request.")
    return
end

local result = chilkat.JsonObject.new()
result.strict = true
success = rest:add_header("DataServiceVersion", "3.0;NetFx")
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_header("MaxDataServiceVersion", "3.0;NetFx")
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_header("Content-Type", "application/json")
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_header("Accept", "application/json;odata=minimalmetadata")
if not success then
    print("Could not prepare the request.")
    return
end

-- Exactly two distinct entities in the same table and partition, by construction.
-- Dynamic plans must also enforce <=100 operations, one operation per entity, and one partition.
local random = chilkat.Prng.new()
local nonce = random:gen_random(16, "hex")
if not random.last_method_success then
    print("Could not create MIME boundaries.")
    return
end

local batchBoundary = chilkat.StringBuilder.new()
local changesetBoundary = chilkat.StringBuilder.new()
success = batchBoundary:append("batch_")
if not success then
    print("Could not prepare the request.")
    return
end

success = batchBoundary:append(nonce)
if not success then
    print("Could not prepare the request.")
    return
end

success = changesetBoundary:append("changeset_")
if not success then
    print("Could not prepare the request.")
    return
end

success = changesetBoundary:append(nonce)
if not success then
    print("Could not prepare the request.")
    return
end

local wire = chilkat.StringBuilder.new()
success = wire:append("--")
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append(batchBoundary:get_as_string())
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append("\r\nContent-Type: multipart/mixed; boundary=")
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append(changesetBoundary:get_as_string())
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append("\r\n\r\n")
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append("--")
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append(changesetBoundary:get_as_string())
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append("\r\nContent-Type: application/http\r\nContent-Transfer-Encoding: binary\r\nContent-ID: 1\r\n\r\nPOST https://")
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append(endpoint:get_as_string())
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append("/ExampleCustomers HTTP/1.1\r\nAccept: application/json;odata=minimalmetadata\r\nDataServiceVersion: 3.0;NetFx\r\nMaxDataServiceVersion: 3.0;NetFx\r\n")
if not success then
    print("Could not prepare the request.")
    return
end

local item1 = chilkat.JsonObject.new()
success = item1:update_string("PartitionKey", "customers-west")
if not success then
    print("Could not prepare the request.")
    return
end

success = item1:update_string("RowKey", "customer-001")
if not success then
    print("Could not prepare the request.")
    return
end

success = item1:update_string("Address", "Batch address 1")
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append("Content-Type: application/json\r\nPrefer: return-no-content\r\n\r\n")
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append(item1:emit())
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append("\r\n")
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append("--")
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append(changesetBoundary:get_as_string())
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append("\r\nContent-Type: application/http\r\nContent-Transfer-Encoding: binary\r\nContent-ID: 2\r\n\r\nPOST https://")
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append(endpoint:get_as_string())
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append("/ExampleCustomers HTTP/1.1\r\nAccept: application/json;odata=minimalmetadata\r\nDataServiceVersion: 3.0;NetFx\r\nMaxDataServiceVersion: 3.0;NetFx\r\n")
if not success then
    print("Could not prepare the request.")
    return
end

local item2 = chilkat.JsonObject.new()
success = item2:update_string("PartitionKey", "customers-west")
if not success then
    print("Could not prepare the request.")
    return
end

success = item2:update_string("RowKey", "customer-002")
if not success then
    print("Could not prepare the request.")
    return
end

success = item2:update_string("Address", "Batch address 2")
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append("Content-Type: application/json\r\nPrefer: return-no-content\r\n\r\n")
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append(item2:emit())
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append("\r\n")
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append("--")
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append(changesetBoundary:get_as_string())
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append("--\r\n")
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append("--")
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append(batchBoundary:get_as_string())
if not success then
    print("Could not prepare the request.")
    return
end

success = wire:append("--\r\n")
if not success then
    print("Could not prepare the request.")
    return
end

local payloadBytes = chilkat.BinData.new()
success = payloadBytes:append_string(wire:get_as_string(), "utf-8")
if not success then
    print("Could not prepare the request.")
    return
end

if payloadBytes.num_bytes > 4194304 then
    print("Batch exceeds the 4 MiB limit including multipart overhead.")
    return
end

local contentType = chilkat.StringBuilder.new()
success = contentType:append("multipart/mixed; boundary=")
if not success then
    print("Could not prepare the request.")
    return
end

success = contentType:append(batchBoundary:get_as_string())
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_header("Content-Type", contentType:get_as_string())
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_header("Accept", "multipart/mixed")
if not success then
    print("Could not prepare the request.")
    return
end

local responseText = rest:full_request_string("POST", resourcePath, wire:get_as_string())
if not rest.last_method_success then
    print("Request did not complete; inspect the target before retrying a write.")
    return
end

if rest.response_status_code ~= 202 then
    print("HTTP status: " .. rest.response_status_code)
    print("Request ID: " .. rest:response_hdr_by_name("x-ms-request-id"))
    -- 404 is missing, 409 is conflict, and 412 is a stale ETag: none are success.
    -- Keep response bodies private. Reconcile uncertain writes before retrying.
    return
end

-- Outer 202 only acknowledges the batch envelope, not transaction success.
local responseMimeText = chilkat.StringBuilder.new()
success = responseMimeText:append("Content-Type: ")
if not success then
    print("Could not prepare the request.")
    return
end

success = responseMimeText:append(rest:response_hdr_by_name("Content-Type"))
if not success then
    print("Could not prepare the request.")
    return
end

success = responseMimeText:append("\r\nMIME-Version: 1.0\r\n\r\n")
if not success then
    print("Could not prepare the request.")
    return
end

success = responseMimeText:append(responseText)
if not success then
    print("Could not prepare the request.")
    return
end

local envelope = chilkat.Mime.new()
local changeset = chilkat.Mime.new()
local part = chilkat.Mime.new()
success = envelope:load_mime(responseMimeText:get_as_string())
if not success then
    print("Invalid MIME batch response; reconcile before retrying.")
    return
end

textCompare:clear()
textCompare:set_string(envelope.content_type)
local sameText3 = textCompare:contents_equal("multipart/mixed", true)
if (not sameText3) or (envelope.num_parts ~= 1) then
    print("Expected one changeset response.")
    return
end

success = envelope:part_at(0, changeset)
if not success then
    print("Could not prepare the request.")
    return
end

textCompare:clear()
textCompare:set_string(changeset.content_type)
local sameText4 = textCompare:contents_equal("multipart/mixed", true)
if (not sameText4) or ((changeset.num_parts < 1) or (changeset.num_parts > 2)) then
    print("Invalid changeset response.")
    return
end

local responseIds = chilkat.Hashtable.new()
local inner = chilkat.StringBuilder.new()
local statusLine = chilkat.StringBuilder.new()
local innerHeaders = chilkat.Mime.new()
local partIndex = 0
while partIndex < changeset.num_parts do
    success = changeset:part_at(partIndex, part)
    if not success then
        print("Could not prepare the request.")
        return
    end

    textCompare:clear()
    textCompare:set_string(part.content_type)
    local sameText5 = textCompare:contents_equal("application/http", true)
    if not sameText5 then
        print("Expected application/http response part.")
        return
    end

    success = inner:set_string(part:get_body_decoded())
    if not success then
        print("Could not prepare the request.")
        return
    end

    if not inner:contains("\r\n\r\n", true) then
        print("Incomplete inner HTTP response.")
        return
    end

    success = statusLine:set_string(inner:get_before("\r\n", true))
    if not success then
        print("Could not prepare the request.")
        return
    end

    if not statusLine:starts_with("HTTP/1.1 ", true) then
        print("Invalid inner HTTP status line.")
        return
    end

    success = innerHeaders:load_mime(inner:get_as_string())
    if not success then
        print("Invalid inner response headers.")
        return
    end

    local contentId = innerHeaders:get_header_field("Content-ID")
    textCompare:clear()
    textCompare:set_string(contentId)
    local sameText6 = textCompare:contents_equal("1", true)
    textCompare:clear()
    textCompare:set_string(contentId)
    local sameText7 = textCompare:contents_equal("2", true)
    if (not sameText6) and (not sameText7) then
        print("Unexpected or missing response Content-ID.")
        return
    end

    if responseIds:contains(contentId) then
        print("Duplicate response Content-ID.")
        return
    end

    success = responseIds:add_str(contentId, "seen")
    if not success then
        print("Could not prepare the request.")
        return
    end

    textCompare:clear()
    textCompare:set_string(statusLine:get_nth(1, " ", false, false))
    local sameText8 = textCompare:contents_equal("204", true)
    if not sameText8 then
        print("Atomic transaction did not report success. Operation Content-ID: " .. contentId)
        print("Inner HTTP status: " .. statusLine:get_nth(1, " ", false, false))
        -- Keep the full error body private. A service-reported operation failure rolls back the changeset.
        return
    end

    partIndex = partIndex + 1
end

if (changeset.num_parts ~= 2) or ((not responseIds:contains("1")) or (not responseIds:contains("2"))) then
    print("Incomplete success response; inspect state before replaying.")
    return
end

print("Both operations succeeded in one atomic transaction.")