Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/server/templates/go.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,16 @@ function formatForGoTypeName(name: string): string {
.join('')
}

// Go raw string literals cannot contain a backtick, so a column name with one
// has to be emitted as an interpreted literal instead.
function formatGoStructTag(name: string): string {
const tag = `json:"${name}"`
if (!tag.includes('`')) {
return `\`${tag}\``
}
return `"${tag.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
}

function generateTableStruct(
schema: PostgresSchema,
table: PostgresTable | PostgresView | PostgresMaterializedView,
Expand Down Expand Up @@ -157,7 +167,7 @@ function generateTableStruct(
const formattedColumnEntries = columnEntries.map(([formattedName, type, name]) => {
return ` ${formattedName.padEnd(maxFormattedNameLength)} ${type.padEnd(
maxTypeLength
)} \`json:"${name}"\``
)} ${formatGoStructTag(name)}`
})

return `
Expand Down Expand Up @@ -215,7 +225,7 @@ function generateCompositeTypeStruct(
const formattedAttributeEntries = attributeEntries.map(([formattedName, type, name]) => {
return ` ${formattedName.padEnd(maxFormattedNameLength)} ${type.padEnd(
maxTypeLength
)} \`json:"${name}"\``
)} ${formatGoStructTag(name)}`
})

return `
Expand Down
21 changes: 21 additions & 0 deletions test/server/templates/go.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,24 @@ describe('go typegen pgTypeToGoType array fallback', () => {
expect(result).toMatch(/Tags\s+\[]string\b/)
})
})

describe('go typegen struct tags', () => {
test('a column name containing a backtick is emitted as an interpreted literal', () => {
const result = apply(buildMetadata([baseColumn({ name: 'bad`tag' })]))

expect(result).toContain('"json:\\"bad`tag\\""')
expect(result).not.toContain('`json:"bad`tag"`')
})

test('double quotes are escaped alongside the backtick', () => {
const result = apply(buildMetadata([baseColumn({ name: 'a"b`c' })]))

expect(result).toContain('"json:\\"a\\"b`c\\""')
})

test('ordinary column names keep the raw literal form', () => {
const result = apply(buildMetadata([baseColumn({ name: 'title' })]))

expect(result).toContain('`json:"title"`')
})
})