0

I’m trying to insert rows into Azure SQL Database using Azure Functions SQL Output Binding (Node.js).

const { app, output } = require('@azure/functions');
const { z } = require('zod');

// SQL Output Binding
const sqlOutput = output.sql({
  commandText: 'dbo.coach_profile',
  connectionStringSetting: 'SqlConnectionString',
});

const coachSchema = z.object({
  first_name: z.string().nullable().optional(),
  last_name: z.string().nullable().optional(),
  bio: z.string().nullable().optional(),
  email: z.string().nullable().optional(),
});

app.http('create_coach_profile', {
  route: 'coach/create_profile',
  methods: ['POST'],
  authLevel: 'function',
  extraOutputs: [sqlOutput],
  handler: async (req, ctx) => {
    try {
      const user_id = req.headers['x-user-id'];
      const email = req.headers['x-user-email'];

      if (!user_id || !email) {
        return { status: 401, jsonBody: { error: 'Missing identity headers' } };
      }

      const body = await req.json();
      const validated = coachSchema.parse(body);

      const coach = {
        ...validated,
        user_id,
        email
        // not sending created_at / updated_at (SQL defaults handle these)
      };

      ctx.extraOutputs.set(sqlOutput, coach);
      return { status: 201, jsonBody: { success: true, coach } };
    } catch (err) {
      return { status: 500, jsonBody: { error: err.message } };
    }
  },
});
CREATE TABLE [dbo].[coach_profile](
  [coach_id] INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
  [user_id] NVARCHAR(100) NOT NULL,
  [first_name] NVARCHAR(100) NULL,
  [last_name] NVARCHAR(100) NULL,
  [bio] NVARCHAR(MAX) NULL,
  [email] NVARCHAR(256) NULL,
  [created_at] DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME(),
  [updated_at] DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME(),
  CONSTRAINT [UQ_coach_profile_user] UNIQUE ([user_id])
);

Executed 'Functions.create_coach_profile' (Failed, Duration=240001ms)
Error: Failed to fetch

Why does Azure SQL Output Binding work for one table but hang for another?

Do I need to explicitly include the PK even when it’s IDENTITY?

Could the UNIQUE constraint on user_id cause a silent failure?

How can I enable more detailed logging for SQL Output Bindings?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.