SQL parser syntax error in Golang

I’m stuck on Stage #AZ9

I’ve tried to parse sql field from sqlite_schema table. I am using golang and it is suggested to use “GitHub - xwb1989/sqlparser: SQL Parser implemented in Go” package for SQL parsing. However, parsing this field is failed due to incorrect syntax. sql field from tables contains autoincrement keyword which causes the problem. Autoincrement is valid keyword from sqlite, but it is not the case in MySQL. And suggested parser is only parsing MySQL queries. However, this parser is probably one of the most popular ones for golang. I am not sure what to do.

Here are my logs:

Logs from your program will appear here!
2024/11/16 04:39:35 ignoring error parsing DDL 'CREATE TABLE apples
(
        id integer primary key autoincrement,
        name text,
        color text
)': syntax error at position 60 near 'autoincrement'
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0x2be3e0]

goroutine 1 [running]:
main.readRow(0xc00000a170, {0xc000030460, 0x3, 0xffffffffffffffff?}, {0xc00000a0e0, 0xb}, {0xc00000a2e0, 0x6}, {0xc00000a2d8, 0x4})
        C:/Users/nsmir/dev/go/codecrafters/codecrafters-sqlite-go/app/main.go:202 +0x160
main.main()
        C:/Users/nsmir/dev/go/codecrafters/codecrafters-sqlite-go/app/main.go:390 +0x62d
exit status 2

And here’s a snippet of my code:

func readRow(header *databaseHeader, schemas []*sqliteSchema, path, table, column string) []string {
	schema := findSchema(schemas, table)
	sql := schema.sql
	stmt, err := sqlparser.Parse(sql) // <-- issue is here
	if err != nil {
		log.Fatal(err)
	}
        ...

Hi @silentstranger5, here’s an idea to experiment with:

How about manually removing “autoincrement” from the CREATE TABLE statement before parsing it with the MySQL parser? Does it parse correctly?

Hi. I have tried it. The problem is that it is messing up with column sizes, because as soon as you remove ‘autoincrement’ keyword, column sizes provided in record header are no longer valid. But those values are crucial to correctly find column values and their boundaries.

Thinking more on your idea, I replaced ‘autoincrement’ keyword with spaces. It is a little weird, but it works now.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.