// Package parser extracts named SQL queries from text content. // It recognizes query blocks introduced by a line comment of the form: // // -- name: // // The content from that marker up to the next marker (or end of input) is // captured as a Query. The API is intended to remain stable as the format // evolves. package parser import ( "regexp" "strings" ) // Query represents a single named SQL query extracted from input. // Name is the identifier provided after the "name:" marker, // and SQL is the associated SQL text trimmed of surrounding whitespace. type Query struct { Name string SQL string } var ( queryNamePattern = regexp.MustCompile(`(?m)^--\s+name:\s+(\w+)`) ) // Parse scans content for named query markers and returns the discovered // queries in order of appearance. The marker format is: // // -- name: // // SQL included in each query spans from its marker to the next marker or end of input, // with surrounding whitespace trimmed. Currently, Parse always returns a nil error. func Parse(content string) ([]Query, error) { indices := queryNamePattern.FindAllStringSubmatchIndex(content, -1) queries := make([]Query, 0, len(indices)) for index, queryIndices := range indices { endOfQueryIndex := len(content) if index < len(indices)-1 { endOfQueryIndex = indices[index+1][0] } queryName := content[queryIndices[2]:queryIndices[3]] querySQL := content[queryIndices[1]:endOfQueryIndex] queries = append(queries, Query{ Name: strings.TrimSpace(queryName), SQL: strings.TrimSpace(querySQL), }) } return queries, nil }