惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
有赞技术团队
有赞技术团队
J
Java Code Geeks
H
Hackread – Cybersecurity News, Data Breaches, AI and More
美团技术团队
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Hugging Face - Blog
Hugging Face - Blog
人人都是产品经理
人人都是产品经理
酷 壳 – CoolShell
酷 壳 – CoolShell
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
C
Check Point Blog
博客园 - 【当耐特】
The GitHub Blog
The GitHub Blog
Recent Announcements
Recent Announcements
The Cloudflare Blog
Microsoft Azure Blog
Microsoft Azure Blog
腾讯CDC
Vercel News
Vercel News
IT之家
IT之家
MyScale Blog
MyScale Blog
博客园_首页
Martin Fowler
Martin Fowler
WordPress大学
WordPress大学
罗磊的独立博客

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
PostgreSQL 2200S Error: Causes and Solutions Complete Guide
umzzil nng · 2026-06-16 · via DEV Community

umzzil nng

PostgreSQL Error 2200S: invalid xml comment

PostgreSQL error 2200S (invalid_xml_comment) is raised when an XML comment embedded in XML data violates the W3C XML 1.0 specification. This most commonly occurs when using XML-related functions such as xmlcomment(), XMLPARSE(), or when inserting data into an XML type column. Understanding the exact rules governing XML comments will save you significant debugging time in production environments.


Top 3 Causes

1. Double Hyphens (--) Inside an XML Comment

The XML 1.0 spec explicitly forbids the sequence -- anywhere inside an XML comment body. This catches many developers off guard, especially those accustomed to SQL-style -- comments.

-- This will FAIL: double hyphen inside comment
SELECT xmlcomment('this is -- invalid');
-- ERROR:  invalid xml comment  (SQLSTATE 2200S)

-- This works: replace '--' with '- -'
SELECT xmlcomment('this is - - valid');

-- Safe dynamic comment generation
SELECT xmlcomment(
    replace(user_input_value, '--', '- -')
)
FROM (SELECT 'status -- pending' AS user_input_value) t;

2. Malformed Comment Closing Tag

An XML comment must close with exactly -->. Using --->, ---->, or omitting the closing tag entirely causes the parser to throw 2200S.

-- FAIL: extra hyphen before closing '>'
SELECT XMLPARSE(DOCUMENT
    '<?xml version="1.0"?><!--- bad close --->
     <root/>');
-- ERROR:  invalid xml comment

-- PASS: standard well-formed comment
SELECT XMLPARSE(DOCUMENT
    '<?xml version="1.0"?><!-- good comment -->
     <root><item>data</item></root>');

-- Inserting a valid XML document with a comment
INSERT INTO reports (doc)
VALUES (XMLPARSE(DOCUMENT
    '<?xml version="1.0" encoding="UTF-8"?>
     <!-- Generated: 2024-01-15 -->
     <report><title>Q1</title></report>'));

3. Unsanitized User Input Injected into XML Comments

When raw user input or external API data is interpolated directly into XML comment strings, any embedded -- sequence will trigger this error. This is a common bug in ETL pipelines and dynamic XML builders.

-- Helper function to sanitize text before using in XML comments
CREATE OR REPLACE FUNCTION safe_xml_comment(p_text TEXT)
RETURNS XML
LANGUAGE plpgsql AS $$
BEGIN
    -- Strip double hyphens and trailing hyphens
    RETURN xmlcomment(
        rtrim(replace(p_text, '--', '- -'), '-')
    );
END;
$$;

-- Usage
SELECT safe_xml_comment('user note: value--123');
-- Returns: <!-- user note: value- -123 -->

-- Catch the error gracefully in PL/pgSQL
DO $$
BEGIN
    PERFORM xmlcomment('bad--input');
EXCEPTION
    WHEN invalid_xml_comment THEN
        RAISE NOTICE 'Caught SQLSTATE %, cleaning input...', SQLSTATE;
END;
$$;


Quick Fix Solutions

-- 1. Validate existing XML column for problematic comments
SELECT id
FROM xml_documents
WHERE content::TEXT ~ '--(?!>)';

-- 2. Bulk-fix stored XML by replacing double hyphens
UPDATE xml_documents
SET content = XMLPARSE(DOCUMENT
    replace(content::TEXT, '-->', ' -->')  -- adjust as needed
)
WHERE content::TEXT ~ '--(?!>)';

-- 3. Use xmlcomment() instead of manual string concat
-- BAD:
SELECT ('<!-- my comment -->'::XML);

-- GOOD:
SELECT xmlcomment('my comment');


Prevention Tips

1. Always use xmlcomment() for generating XML comments. Never build XML comment strings through raw concatenation. PostgreSQL's built-in xmlcomment() function still requires valid input, but pairing it with a sanitizer function makes the intent explicit and auditable.

2. Add a BEFORE INSERT/UPDATE trigger on XML columns. Let the database enforce XML validity as a last line of defense, independent of application logic.

CREATE OR REPLACE FUNCTION trg_validate_xml()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
    -- Force re-parse to catch any malformed XML including bad comments
    PERFORM XMLPARSE(DOCUMENT NEW.content::TEXT);
    RETURN NEW;
EXCEPTION
    WHEN invalid_xml_comment THEN
        RAISE EXCEPTION 'Invalid XML comment in input. SQLSTATE: 2200S';
END;
$$;

CREATE TRIGGER validate_xml_before_write
BEFORE INSERT OR UPDATE ON xml_documents
FOR EACH ROW EXECUTE FUNCTION trg_validate_xml();


Related Errors

SQLSTATE Name When It Occurs
2200M invalid_xml_document XML is not well-formed at the document level
2200N invalid_xml_content XML content (not comment) fails validation
2200T invalid_xml_processing_instruction Malformed <?target data?> PI node
22000 data_exception Parent class for all XML and data errors

📖 Want a more detailed guide?
Check out the full in-depth version (Korean) on oraerror.com — includes detailed analysis, additional SQL examples, and prevention tips.