Files
2026-07-10 17:07:54 +01:00

152 lines
2.9 KiB
Go

package sqimple
import (
"fmt"
"regexp"
"strings"
)
var (
insertTableRegexp = regexp.MustCompile("^into ([A-Za-z0-9_]+)( (as) ([A-Za-z0-9_]+))?$")
selectTableRegexp = regexp.MustCompile("^(from|left join|inner join|right join) ([A-Za-z0-9_]+)( (as) ([A-Za-z0-9_]+))?( (on) ([^ ]+) (=|!=|>|>=|<|<=) ([^ ]+)( (and) ([^ ]+) (=|!=|>|>=|<|<=) ([^ ]+))*)?$")
updateTableRegexp = regexp.MustCompile("^(.+)( (as) ([A-Za-z0-9_]+))?$")
)
type InsertTable string
func (t InsertTable) IsValid() bool {
return insertTableRegexp.MatchString(string(t))
}
func (t InsertTable) Parse() (table, as string, ok bool) {
if insertTableRegexp.MatchString(string(t)) {
ok = true
result := insertTableRegexp.FindAllStringSubmatch(string(t), -1)
for _, r := range result {
table = r[1]
if r[3] == "as" {
as = r[4]
}
}
}
return
}
func (t InsertTable) String() string {
return string(t)
}
func Into(def string) InsertTable {
if strings.Index(def, "into ") == 0 {
return InsertTable(def)
}
return InsertTable(fmt.Sprintf("into %s", def))
}
type SelectTable string
func (t SelectTable) IsValid() bool {
return selectTableRegexp.MatchString(string(t))
}
func (t SelectTable) Parse() (selectType, table, as string, on *OnClause, ok bool) {
if selectTableRegexp.MatchString(string(t)) {
ok = true
result := selectTableRegexp.FindAllStringSubmatch(string(t), -1)
for i, r := range result {
// for j, c := range r {
// fmt.Println(i, j, c)
// }
if i == 0 {
selectType, table = r[1], r[2]
if r[4] == "as" {
as = r[5]
}
if r[7] == "on" {
on = On(r[8], r[9], r[10])
}
}
if r[12] == "and" {
on.And(r[13], r[14], r[15])
}
}
}
return
}
func (t SelectTable) String() string {
return string(t)
}
func From(def string) SelectTable {
if strings.Index(def, "from ") == 0 {
return SelectTable(def)
}
return SelectTable(fmt.Sprintf("from %s", def))
}
func InnerJoin(def string) SelectTable {
if strings.Index(def, "inner join ") == 0 {
return SelectTable(def)
}
return SelectTable(fmt.Sprintf("inner join %s", def))
}
func LeftJoin(def string) SelectTable {
if strings.Index(def, "left join ") == 0 {
return SelectTable(def)
}
return SelectTable(fmt.Sprintf("left join %s", def))
}
func RightJoin(def string) SelectTable {
if strings.Index(def, "right join ") == 0 {
return SelectTable(def)
}
return SelectTable(fmt.Sprintf("right join %s", def))
}
type UpdateTable string
func (t UpdateTable) IsValid() bool {
return updateTableRegexp.MatchString(string(t))
}
func (t UpdateTable) Parse() (table, as string, ok bool) {
if insertTableRegexp.MatchString(string(t)) {
ok = true
result := updateTableRegexp.FindAllStringSubmatch(string(t), -1)
for _, r := range result {
table = r[1]
if r[3] == "as" {
as = r[4]
}
}
}
return
}
func (t UpdateTable) String() string {
return string(t)
}