azuresql-db-functions

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Serverless API + event-driven on the Azure SQL Database container with Azure Functions

Azure SQL Database 容器上的无服务器 API + 事件驱动方案(Azure Functions)

Build HTTP CRUD endpoints and change-driven handlers over the local Azure SQL Database container (Private Preview) using Azure Functions and the first-party Azure SQL bindings. Two capabilities:
  • API: HTTP-triggered functions with SQL input and output bindings (read and upsert with no ADO.NET boilerplate).
  • Event-driven (local): the SQL trigger binding fires a function when rows are inserted/updated/deleted. It is backed by Change Tracking, runs fully locally against the container, and needs no cloud services.
Event-driven note: Azure SQL Change Event Streaming (CES) is the cloud path for streaming row changes, and it cannot run against the local container (it is unsupported on the Linux engine and streams only to Azure Event Hubs public endpoints). Locally, use the SQL trigger below. Open references/event-driven.md when you need the reason CES cannot run here, or when a user asks for it by name.
The container supports what the bindings need: Change Tracking on a user database, compatibility level 130 or higher, and
OPENJSON
.
使用 Azure Functions 和第一方 Azure SQL bindings,在本地 Azure SQL Database 容器(私有预览版)上构建 HTTP CRUD 端点和变更驱动处理器。提供两项能力:
  • API: 使用 SQL input 和 output bindings 的 HTTP 触发函数(无需 ADO.NET 样板代码即可读取和 upsert)。
  • 事件驱动(本地): SQL trigger binding 会在插入、更新或删除行时触发函数。它基于 Change Tracking,完全在容器本地运行,且不需要云服务。
事件驱动说明:Azure SQL Change Event Streaming (CES) 是用于流式传输行变更的云端路径,无法在本地容器中运行(Linux 引擎不支持该功能,而且它仅可流向 Azure Event Hubs 的公共终结点)。在本地,请使用下文的 SQL trigger。当你需要了解 CES 无法在此运行的原因,或用户按名称询问 CES 时,请打开 references/event-driven.md。
容器支持 bindings 所需的功能:用户数据库上启用 Change Tracking、兼容级别为 130 或更高,以及
OPENJSON
。

Load-bearing facts (inlined; full engine detail in azuresql-db-container)

关键事实(已内联;完整的引擎详情见 azuresql-db-container)

  • This is the Azure SQL Database engine (Private Preview), not the SQL Server image
    mcr.microsoft.com/mssql/server
    .
    SERVERPROPERTY('EngineEdition')
    returns
    5
    ,
    SERVERPROPERTY('Edition')
    returns
    'SQL Azure'
    .
  • Image:
    sqldbpreview-dpgaeqhmgphzd4bk.azurecr.io/azure-sql/db-dev:latest
    (x64,
    linux/amd64
    ). Registry is private: sign in first with
    docker login sqldbpreview-dpgaeqhmgphzd4bk.azurecr.io
    using the shared pull-only credentials from https://aka.ms/sqldbcontainerpreview-signup (they may rotate). Registry and tag are provisional during Private Preview.
  • Required env:
    ACCEPT_EULA=Y
    and a complex
    MSSQL_SA_PASSWORD
    (8+ chars, upper/lower/digit/symbol). Engine listens on 1433.
  • The engine does NOT auto-create databases. Run
    CREATE DATABASE appdb
    on a master connection before the function app connects with
    Database=appdb
    . Do not use
    USE
    to switch databases; select it in the connection string.
  • On a non-x64 host add
    --platform linux/amd64
    .
For the full engine model (readiness loop, vectors, troubleshooting) see the azuresql-db-container skill; to start the container and provision
appdb
, use azuresql-db-container or azuresql-db-scaffold.
  • 这是 Azure SQL Database 引擎(私有预览版),而不是 SQL Server 镜像
    mcr.microsoft.com/mssql/server
    。
    SERVERPROPERTY('EngineEdition')
    返回
    5
    ,
    SERVERPROPERTY('Edition')
    返回
    'SQL Azure'
    。
  • 镜像:
    sqldbpreview-dpgaeqhmgphzd4bk.azurecr.io/azure-sql/db-dev:latest
    (x64,
    linux/amd64
    )。注册表为私有:先使用 https://aka.ms/sqldbcontainerpreview-signup 提供的共享仅拉取凭据执行
    docker login sqldbpreview-dpgaeqhmgphzd4bk.azurecr.io
    (凭据可能会轮换)。私有预览期间,注册表和标签可能会变更。
  • 必需环境变量:
    ACCEPT_EULA=Y
    和复杂的
    MSSQL_SA_PASSWORD
    (至少 8 个字符,包含大写字母、小写字母、数字和符号)。引擎监听 1433 端口。
  • 引擎不会自动创建数据库。请先在 master 连接上运行
    CREATE DATABASE appdb
    ,然后函数应用才能使用
    Database=appdb
    进行连接。不要使用
    USE
    切换数据库;应在连接字符串中选择该数据库。
  • 在非 x64 主机上,请添加
    --platform linux/amd64
    。
有关完整的引擎模型(就绪循环、向量、故障排查),请参阅 azuresql-db-container skill;要启动容器并预配
appdb
,请使用 azuresql-db-container 或 azuresql-db-scaffold。

Step 1: the connection string setting

第 1 步:连接字符串设置

The bindings read the connection string from an app setting. Use the name
SqlConnectionString
(the docs' convention). In
local.settings.json
:
json
{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
    "SqlConnectionString": "Server=localhost,1433;Database=appdb;User Id=sa;Password=<sa-password>;TrustServerCertificate=true"
  }
}
Replace
<sa-password>
with the container's
MSSQL_SA_PASSWORD
;
local.settings.json
stays out of source control.
TrustServerCertificate=true
is required for the container's self-signed cert. Set
FUNCTIONS_WORKER_RUNTIME
to your language (
dotnet-isolated
,
node
,
python
,
powershell
,
java
). Bindings reference this setting name via
ConnectionStringSetting
(C#/Java),
connectionStringSetting
(function.json), or
connection_string_setting
(Python v2 decorator) - not
Connection
(that keyword is for Storage/Event Hubs bindings).
Bindings 从应用设置中读取连接字符串。使用名称
SqlConnectionString
(文档约定)。在
local.settings.json
中:
json
{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
    "SqlConnectionString": "Server=localhost,1433;Database=appdb;User Id=sa;Password=<sa-password>;TrustServerCertificate=true"
  }
}
将
<sa-password>
替换为容器的
MSSQL_SA_PASSWORD
;
local.settings.json
不应纳入源代码管理。
容器使用自签名证书,因此必须设置
TrustServerCertificate=true
。将
FUNCTIONS_WORKER_RUNTIME
设置为你的语言(
dotnet-isolated
、
node
、
python
、
powershell
、
java
)。Bindings 通过
ConnectionStringSetting
(C#/Java)、
connectionStringSetting
(function.json)或
connection_string_setting
(Python v2 decorator)引用此设置名称,而不是
Connection
(该关键字用于 Storage/Event Hubs bindings)。

Step 2: install the SQL extension

第 2 步:安装 SQL 扩展

  • .NET isolated worker: add the NuGet package.
    bash
    dotnet add package Microsoft.Azure.Functions.Worker.Extensions.Sql
  • JavaScript / TypeScript / Python / PowerShell / Java: use the extension bundle in
    host.json
    (Java also adds the
    azure-functions-java-library-sql
    Maven package):
    json
    {
      "version": "2.0",
      "extensionBundle": {
        "id": "Microsoft.Azure.Functions.ExtensionBundle",
        "version": "[4.0.0, 5.0.0)"
      }
    }
  • .NET isolated worker: 添加 NuGet 包。
    bash
    dotnet add package Microsoft.Azure.Functions.Worker.Extensions.Sql
  • JavaScript / TypeScript / Python / PowerShell / Java: 在
    host.json
    中使用扩展捆绑包(Java 还需添加
    azure-functions-java-library-sql
    Maven 包):
    json
    {
      "version": "2.0",
      "extensionBundle": {
        "id": "Microsoft.Azure.Functions.ExtensionBundle",
        "version": "[4.0.0, 5.0.0)"
      }
    }

Step 3: HTTP API with SQL input/output bindings

第 3 步:使用 SQL input/output bindings 构建 HTTP API

Template: choose one supported worker runtime. This example uses
dotnet-isolated
, but Node.js, Python, and other runtimes are also available.
bash
func init MyApi --worker-runtime dotnet-isolated
cd MyApi || exit 1
func new --name Books                              # pick an HTTP trigger template
Then wire the SQL bindings into the function. Per-language snippets (HTTP GET via input binding, HTTP POST upsert via output binding) are in references/functions-snippets.md; open it once you know your language. Open references/functions-bindings-reference.md when a binding attribute or a
function.json
field is rejected.
Output-binding requirements: the target table must have a primary key (the binding upserts via
MERGE
), and the database compatibility level must be 130+ (the binding uses
OPENJSON
). The engine is fully capable; just ensure the table has a PK.
Run it:
bash
func start        # HTTP endpoints on http://localhost:7071/api/<name>
模板:选择一种受支持的 worker runtime。此示例使用
dotnet-isolated
,但也可以使用 Node.js、Python 和其他运行时。
bash
func init MyApi --worker-runtime dotnet-isolated
cd MyApi || exit 1
func new --name Books                              # pick an HTTP trigger template
接下来,将 SQL bindings 接入函数。按语言划分的代码片段(通过 input binding 实现 HTTP GET,通过 output binding 实现 HTTP POST upsert)位于 references/functions-snippets.md;确定所用语言后再打开它。当 binding 属性或
function.json
字段被拒绝时,请打开 references/functions-bindings-reference.md。
Output binding 要求:目标表必须具有主键(binding 通过
MERGE
执行 upsert),并且数据库兼容级别必须为 130+(binding 使用
OPENJSON
)。引擎完全具备所需能力;只需确保表具有 PK。
运行:
bash
func start        # HTTP endpoints on http://localhost:7071/api/<name>

Step 4: event-driven with the SQL trigger (the local mechanism)

第 4 步:使用 SQL trigger 实现事件驱动(本地机制)

The SQL trigger fires your function when rows change.
There is no SQL trigger template to scaffold from, even though the tooling lists one. With Azure Functions Core Tools 4.12.0,
func templates list
advertises a
SQL Trigger
entry, but
func new --template SqlTrigger
exits non-zero with
Unknown template 'SqlTrigger'
: the listing and the scaffolder disagree, and no flag reconciles them. Scaffold an HTTP trigger instead (
func new --name ToDoTrigger --template HttpTrigger
, which succeeds in the same project) and write the trigger binding in by hand, as below.
The trigger requires Change Tracking on the database and table. Enable it once (on
appdb
, not
master
):
sql
ALTER DATABASE appdb
  SET CHANGE_TRACKING = ON (CHANGE_RETENTION = 2 DAYS, AUTO_CLEANUP = ON);
ALTER TABLE dbo.ToDo ENABLE CHANGE_TRACKING;
The function binds to a list of changes, each with an
Item
and an
Operation
(
Insert
/
Update
/
Delete
). C# isolated example:
csharp
[Function("ToDoTrigger")]
public static void Run(
    [SqlTrigger("[dbo].[ToDo]", "SqlConnectionString")]
    IReadOnlyList<SqlChange<ToDoItem>> changes,
    FunctionContext context)
{
    foreach (var change in changes)
        context.GetLogger("ToDoTrigger")
            .LogInformation($"{change.Operation}: {change.Item.Id}");
}
The trigger creates an internal
az_func
schema plus a
Leases_{FunctionId}_{TableId}
table (it makes these itself if the principal can). Behavior, permission grants, and the CES-is-cloud-only detail are in references/event-driven.md; open it when configuring the trigger or its least-privilege grants. Since you connect as
sa
locally, the permission grants are already satisfied; they matter when you move to least privilege or to the cloud.
SQL trigger 会在行发生变更时触发你的函数。
尽管工具列出了 SQL trigger 模板,但实际上没有可用于搭建的模板。 在 Azure Functions Core Tools 4.12.0 中,
func templates list
会显示一个
SQL Trigger
条目,但执行
func new --template SqlTrigger
时会以非零状态退出并显示
Unknown template 'SqlTrigger'
:模板列表与脚手架生成器不一致,并且没有任何参数可以消除这种不一致。请改为搭建 HTTP trigger(
func new --name ToDoTrigger --template HttpTrigger
,该命令在同一项目中可以成功执行),然后如下手动编写 trigger binding。
Trigger 要求在数据库和表上启用 Change Tracking。请在
appdb
(而不是
master
)上一次性启用:
sql
ALTER DATABASE appdb
  SET CHANGE_TRACKING = ON (CHANGE_RETENTION = 2 DAYS, AUTO_CLEANUP = ON);
ALTER TABLE dbo.ToDo ENABLE CHANGE_TRACKING;
函数绑定到变更列表,每项包含一个
Item
和一个
Operation
(
Insert
/
Update
/
Delete
)。C# isolated 示例:
csharp
[Function("ToDoTrigger")]
public static void Run(
    [SqlTrigger("[dbo].[ToDo]", "SqlConnectionString")]
    IReadOnlyList<SqlChange<ToDoItem>> changes,
    FunctionContext context)
{
    foreach (var change in changes)
        context.GetLogger("ToDoTrigger")
            .LogInformation($"{change.Operation}: {change.Item.Id}");
}
Trigger 会创建内部的
az_func
schema 以及
Leases_{FunctionId}_{TableId}
表(如果主体具备相应权限,它会自行创建这些对象)。具体行为、权限授予以及 CES 仅适用于云端的详细信息见 references/event-driven.md;配置 trigger 或其最小权限授权时,请打开该文档。由于本地使用
sa
身份连接,权限授予条件已经得到满足;迁移到最小权限配置或云端时,这些授权才会发挥作用。

Validation rules

验证规则

  • The database engine is the container image above (EngineEdition=5), never
    mcr.microsoft.com/mssql/server
    .
  • appdb
    exists (created on a master connection) before the function app runs;
    SqlConnectionString
    uses
    Database=appdb
    and
    TrustServerCertificate=true
    .
  • The connection string lives in
    local.settings.json
    (or app settings), not in code; bindings reference it via
    ConnectionStringSetting
    /
    connectionStringSetting
    .
  • Output-binding target tables have a primary key; the database compat level is 130+.
  • The SQL trigger has Change Tracking enabled on both the database and the table; event-driven is done with the trigger locally, not CES.
  • If a validation rule above fails, or you had to deviate from this skill to make the task work, that is a bug in this skill: load the azuresql-db-feedback skill and offer to file a report.
  • When every rule above passes and the task is done, close with ONE line, once per session, and do not ask a question or wait for a reply: "That worked. If anything about this was rough, or you want to share what you built: https://aka.ms/sql-agent-skills-feedback"
  • 数据库引擎必须是上述容器镜像(EngineEdition=5),绝不能使用
    mcr.microsoft.com/mssql/server
    。
  • 在函数应用运行前,
    appdb
    必须已经存在(通过 master 连接创建);
    SqlConnectionString
    使用
    Database=appdb
    和
    TrustServerCertificate=true
    。
  • 连接字符串必须位于
    local.settings.json
    (或应用设置)中,而不能写在代码里;bindings 通过
    ConnectionStringSetting
    /
    connectionStringSetting
    引用它。
  • Output binding 的目标表必须具有主键;数据库兼容级别必须为 130+。
  • SQL trigger 必须在数据库和表上同时启用 Change Tracking;本地事件驱动使用 trigger,而不是 CES。
  • 如果上述任一验证规则失败,或你不得不偏离此 skill 才能让任务正常运行,则说明此 skill 存在 bug:加载 azuresql-db-feedback skill,并主动提出提交报告。
  • 当上述所有规则均通过且任务完成时,每个会话只以以下一行结束一次,不要提问或等待回复:"That worked. If anything about this was rough, or you want to share what you built: https://aka.ms/sql-agent-skills-feedback"

Check it worked

验证是否成功

  • Positive verification: Insert and update a tracked row, confirm the SQL trigger receives the event, then invoke the HTTP function and verify the output row.
  • Cleanup verification: Stop the Functions host and remove test rows, generated state tables, and temporary local settings.
  • Report success only after both observations pass.
  • 正向验证: 插入并更新一条受跟踪的行,确认 SQL trigger 收到事件,然后调用 HTTP 函数并验证输出行。
  • 清理验证: 停止 Functions host,并删除测试行、生成的状态表和临时本地设置。
  • 只有在两项观察均通过后才能报告成功。

Do not

禁止事项

  • Do not use the SQL Server image
    mcr.microsoft.com/mssql/server
    ; this is the Azure SQL engine.
  • Do not expect the function app to create
    appdb
    ; provision it on a master connection first.
  • Do not try to make Change Event Streaming (CES) work locally - it is unsupported on the local (Linux) engine and streams only to Azure Event Hubs. Use the SQL trigger locally.
  • Do not use an output binding against a table with no primary key, or below compatibility level 130.
  • Do not scaffold with
    func new --template SqlTrigger
    ; the template is listed but cannot be created. Create an HTTP trigger and add the binding by hand.
  • Do not use the
    Connection
    binding keyword for SQL bindings; it is
    ConnectionStringSetting
    /
    connectionStringSetting
    .
  • Do not commit
    local.settings.json
    (it holds the connection string / SA password) or drop
    TrustServerCertificate=true
    /
    --platform linux/amd64
    on a non-x64 host.
  • 不要使用 SQL Server 镜像
    mcr.microsoft.com/mssql/server
    ;这是 Azure SQL 引擎。
  • 不要指望函数应用创建
    appdb
    ;请先通过 master 连接进行预配。
  • 不要尝试让 Change Event Streaming(CES)在本地运行——本地(Linux)引擎不支持它,并且它仅可流向 Azure Event Hubs。本地请使用 SQL trigger。
  • 不要对没有主键或兼容级别低于 130 的表使用 output binding。
  • 不要使用
    func new --template SqlTrigger
    搭建项目;虽然模板会被列出,但无法创建。请创建 HTTP trigger,然后手动添加 binding。
  • 不要对 SQL bindings 使用
    Connection
    binding 关键字;应使用
    ConnectionStringSetting
    /
    connectionStringSetting
    。
  • 不要提交
    local.settings.json
    (其中包含连接字符串和 SA 密码),也不要在非 x64 主机上删除
    TrustServerCertificate=true
    或
    --platform linux/amd64
    。

References

参考资料

  • references/functions-bindings-reference.md: open it when you need binding fields, the
    SqlConnectionString
    setting, or
    host.json
    trigger tuning.
  • references/functions-snippets.md: open it when you need copyable project setup, per-language function bodies,
    func
    commands, or a local verification loop.
  • references/event-driven.md: open it when implementing a SQL trigger, granting its permissions, or replacing cloud-only CES locally.
  • references/functions-bindings-reference.md:需要 binding 字段、
    SqlConnectionString
    设置或
    host.json
    trigger 调优时打开。
  • references/functions-snippets.md:需要可复制的项目设置、按语言划分的函数体、
    func
    命令或本地验证循环时打开。
  • references/event-driven.md:实现 SQL trigger、授予其权限或在本地替代仅支持云端的 CES 时打开。

Staying current

保持内容最新

Authoritative, version-pinned references for the tools this skill uses (read the one you need):
If the Microsoft Learn MCP server is configured, use
mcp__microsoft-learn__microsoft_docs_search
or
mcp__microsoft-learn__microsoft_docs_fetch
to fetch the current version of any of these on demand. It is optional; when it is unavailable, the references above are authoritative.
此 skill 所用工具的权威且版本固定的参考资料(按需读取所需的一份):
如果已配置 Microsoft Learn MCP server,请使用
mcp__microsoft-learn__microsoft_docs_search
或
mcp__microsoft-learn__microsoft_docs_fetch
按需获取上述资料的当前版本。这是可选项;不可用时,以上参考资料即为权威来源。