feat(sql): SQL Injection

This commit is contained in:
Björn Benouarets
2025-11-06 16:44:28 +01:00
parent 10110071eb
commit 59d6c911f9
14 changed files with 430 additions and 483 deletions

166
build/alter.go Normal file
View File

@@ -0,0 +1,166 @@
package build
import (
"fmt"
"strings"
"git.secnex.io/secnex/pgson/schema"
"git.secnex.io/secnex/pgson/sql"
)
func AlterTable(s *schema.Table) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
var ddlParts, comments []string
for _, f := range s.Schema {
if err := sql.ValidateIdent(f.Name); err != nil {
return nil, err
}
pgType, err := sql.ValidateType(f.Type)
if err != nil {
return nil, err
}
colParts := []string{sql.QuoteIdent(f.Name), pgType}
if f.Nullable != nil && !*f.Nullable {
colParts = append(colParts, "NOT NULL")
}
if f.Unique != nil && *f.Unique {
colParts = append(colParts, "UNIQUE")
}
if f.Default != nil && *f.Default != "" {
def, err := sql.ValidateDefault(*f.Default)
if err != nil {
return nil, err
}
colParts = append(colParts, "DEFAULT "+def)
}
if f.References != nil {
if err := sql.ValidateIdent(f.References.Table); err != nil {
return nil, err
}
if err := sql.ValidateIdent(f.References.Column); err != nil {
return nil, err
}
onDelete, err := sql.ValidateAction(f.References.OnDelete)
if err != nil {
return nil, err
}
onUpdate, err := sql.ValidateAction(f.References.OnUpdate)
if err != nil {
return nil, err
}
fk := fmt.Sprintf("REFERENCES %s(%s) ON DELETE %s ON UPDATE %s", sql.QuoteIdent(f.References.Table), sql.QuoteIdent(f.References.Column), onDelete, onUpdate)
colParts = append(colParts, fk)
}
ddlParts = append(ddlParts, strings.Join(colParts, " "))
if f.Comment != nil {
comments = append(comments, fmt.Sprintf("COMMENT ON COLUMN %s.%s IS '%s'", sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name), *f.Comment))
}
}
ddl := fmt.Sprintf(sql.DDL_ALTER_TABLE, sql.QuoteIdent(s.Name), strings.Join(ddlParts, " "))
return &ddl, nil
}
func AddColumn(s *schema.Table, f *schema.Field) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if err := sql.ValidateIdent(f.Name); err != nil {
return nil, err
}
ddl := fmt.Sprintf(sql.DDL_ADD_COLUMN, sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name))
return &ddl, nil
}
func DropColumn(s *schema.Table, f *schema.Field) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if err := sql.ValidateIdent(f.Name); err != nil {
return nil, err
}
ddl := fmt.Sprintf(sql.DDL_DROP_COLUMN, sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name))
return &ddl, nil
}
func AlterColumn(s *schema.Table, f *schema.Field) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
pgType, err := sql.ValidateType(f.Type)
if err != nil {
return nil, err
}
colParts := []string{sql.QuoteIdent(f.Name), pgType}
if f.Nullable != nil && !*f.Nullable {
colParts = append(colParts, "NOT NULL")
}
ddl := fmt.Sprintf(sql.DDL_ALTER_COLUMN, sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name), strings.Join(colParts, " "))
if f.Default != nil && *f.Default != "" {
def, err := sql.ValidateDefault(*f.Default)
if err != nil {
return nil, err
}
colParts = append(colParts, "DEFAULT "+def)
}
return &ddl, nil
}
func AddForeignKey(s *schema.Table, f *schema.Field) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if err := sql.ValidateIdent(f.Name); err != nil {
return nil, err
}
ddl := fmt.Sprintf(sql.DDL_ADD_FOREIGN_KEY, sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name))
return &ddl, nil
}
func DropForeignKey(s *schema.Table, f *schema.Field) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if err := sql.ValidateIdent(f.Name); err != nil {
return nil, err
}
ddl := fmt.Sprintf(sql.DDL_DROP_FOREIGN_KEY, sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name))
return &ddl, nil
}
func AddConstraint(s *schema.Table, f *schema.Field) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if err := sql.ValidateIdent(f.Name); err != nil {
return nil, err
}
ddl := fmt.Sprintf(sql.DDL_ADD_CONSTRAINT, sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name))
return &ddl, nil
}
func DropConstraint(s *schema.Table, f *schema.Field) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if err := sql.ValidateIdent(f.Name); err != nil {
return nil, err
}
ddl := fmt.Sprintf(sql.DDL_DROP_CONSTRAINT, sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name))
return &ddl, nil
}

View File

@@ -2,21 +2,109 @@ package build
import (
"fmt"
"log"
"strings"
"git.secnex.io/secnex/pgson/schema"
"git.secnex.io/secnex/pgson/utils"
"git.secnex.io/secnex/pgson/sql"
)
func CreateSQL(s *schema.Table) (string, error) {
schemaParts := make([]string, len(s.Schema))
for i, field := range s.Schema {
schemaParts[i] = field.SQL()
func CreateTable(s *schema.Table) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
schemaParts = append(schemaParts, "\"created_at\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP")
schemaParts = append(schemaParts, "\"updated_at\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP")
schemaParts = append(schemaParts, "\"deleted_at\" TIMESTAMP NULL")
query := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (%s)", utils.SQLQuoteIdent(s.Name), strings.Join(schemaParts, ", "))
return query, nil
var cols, comments, pks []string
for _, f := range s.Schema {
if err := sql.ValidateIdent(f.Name); err != nil {
log.Printf("Invalid identifier: %s", f.Name)
return nil, err
}
pgType, err := sql.ValidateType(f.Type)
if err != nil {
log.Printf("Invalid type: %s", f.Type)
return nil, err
}
if f.Type == "hash" {
if _, ok := sql.AlgorithmMap[strings.ToLower(*f.Algorithm)]; !ok {
log.Printf("Invalid algorithm: %s", *f.Algorithm)
return nil, fmt.Errorf("invalid algorithm: %s", *f.Algorithm)
}
}
colParts := []string{sql.QuoteIdent(f.Name), pgType}
if f.Nullable != nil && !*f.Nullable {
colParts = append(colParts, "NOT NULL")
}
if f.Unique != nil && *f.Unique {
colParts = append(colParts, "UNIQUE")
}
// Auto-generate UUID for UUID primary keys if no default is specified
if f.Primary != nil && *f.Primary && f.Type == "uuid" {
if f.Default == nil || *f.Default == "" {
colParts = append(colParts, "DEFAULT gen_random_uuid()")
} else {
def, err := sql.ValidateDefault(*f.Default)
if err != nil {
return nil, err
}
colParts = append(colParts, "DEFAULT "+def)
}
} else if f.Default != nil && *f.Default != "" {
def, err := sql.ValidateDefault(*f.Default)
if err != nil {
return nil, err
}
colParts = append(colParts, "DEFAULT "+def)
}
if f.References != nil {
if err := sql.ValidateIdent(f.References.Table); err != nil {
log.Printf("Invalid references table: %s", f.References.Table)
return nil, err
}
if err := sql.ValidateIdent(f.References.Column); err != nil {
log.Printf("Invalid references column: %s", f.References.Column)
return nil, err
}
onDelete, err := sql.ValidateAction(f.References.OnDelete)
if err != nil {
log.Printf("Invalid on delete: %s", f.References.OnDelete)
return nil, err
}
onUpdate, err := sql.ValidateAction(f.References.OnUpdate)
if err != nil {
log.Printf("Invalid on update: %s", f.References.OnUpdate)
return nil, err
}
fk := fmt.Sprintf("REFERENCES %s(%s) ON DELETE %s ON UPDATE %s", sql.QuoteIdent(f.References.Table), sql.QuoteIdent(f.References.Column), onDelete, onUpdate)
colParts = append(colParts, fk)
}
cols = append(cols, strings.Join(colParts, " "))
if f.Primary != nil && *f.Primary {
pks = append(pks, sql.QuoteIdent(f.Name))
}
if f.Comment != nil {
comments = append(comments, fmt.Sprintf("COMMENT ON COLUMN %s.%s IS '%s'", sql.QuoteIdent(s.Name), sql.QuoteIdent(f.Name), *f.Comment))
}
}
if len(pks) > 0 {
cols = append(cols, "PRIMARY KEY ("+strings.Join(pks, ", ")+")")
}
ddl := fmt.Sprintf(sql.DDL_CREATE_TABLE, sql.QuoteIdent(s.Name), strings.Join(cols, ",\n "))
if len(comments) > 0 {
ddl += "\n" + strings.Join(comments, "\n")
}
log.Printf("DDL: %s", ddl)
return &ddl, nil
}

View File

@@ -1,64 +0,0 @@
package build
import (
"fmt"
"git.secnex.io/secnex/pgson/schema"
"git.secnex.io/secnex/pgson/utils"
)
func DeleteSQL(s *schema.Table, where any) (string, error) {
if s == nil {
return "", fmt.Errorf("nil table provided")
}
if s.Name == "" || !utils.IsValidIdentifier(s.Name) {
return "", fmt.Errorf("invalid table name: %q", s.Name)
}
if s.PrimaryKey == "" || !utils.IsValidIdentifier(s.PrimaryKey) {
return "", fmt.Errorf("invalid primary key: %q", s.PrimaryKey)
}
found := false
for i := range s.Schema {
if s.Schema[i].Name == s.PrimaryKey {
found = true
break
}
}
if !found {
return "", fmt.Errorf("primary key %q not found in schema", s.PrimaryKey)
}
return fmt.Sprintf("UPDATE %s SET deleted_at = CURRENT_TIMESTAMP WHERE %s = %s",
utils.SQLQuoteIdent(s.Name),
utils.SQLQuoteIdent(s.PrimaryKey),
utils.SQLQuoteValue(where),
), nil
}
func HardDeleteSQL(s *schema.Table, where any) (string, error) {
if s == nil {
return "", fmt.Errorf("nil table provided")
}
if s.Name == "" || !utils.IsValidIdentifier(s.Name) {
return "", fmt.Errorf("invalid table name: %q", s.Name)
}
if s.PrimaryKey == "" || !utils.IsValidIdentifier(s.PrimaryKey) {
return "", fmt.Errorf("invalid primary key: %q", s.PrimaryKey)
}
found := false
for i := range s.Schema {
if s.Schema[i].Name == s.PrimaryKey {
found = true
break
}
}
if !found {
return "", fmt.Errorf("primary key %q not found in schema", s.PrimaryKey)
}
return fmt.Sprintf("DELETE FROM %s WHERE %s = %s",
utils.SQLQuoteIdent(s.Name),
utils.SQLQuoteIdent(s.PrimaryKey),
utils.SQLQuoteValue(where),
), nil
}

View File

@@ -4,15 +4,13 @@ import (
"fmt"
"git.secnex.io/secnex/pgson/schema"
"git.secnex.io/secnex/pgson/utils"
"git.secnex.io/secnex/pgson/sql"
)
func DropSQL(s *schema.Table) (string, error) {
if s == nil {
return "", fmt.Errorf("nil table provided")
func DropTable(s *schema.Table) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if s.Name == "" || !utils.IsValidIdentifier(s.Name) {
return "", fmt.Errorf("invalid table name: %q", s.Name)
}
return fmt.Sprintf("DROP TABLE IF EXISTS %s", utils.SQLQuoteIdent(s.Name)), nil
ddl := fmt.Sprintf(sql.DDL_DROP_TABLE, sql.QuoteIdent(s.Name))
return &ddl, nil
}

View File

@@ -5,67 +5,24 @@ import (
"strings"
"git.secnex.io/secnex/pgson/schema"
"git.secnex.io/secnex/pgson/utils"
"git.secnex.io/secnex/pgson/sql"
)
func InsertManySQL(s *schema.Table, data []map[string]any, returning bool) (string, error) {
if s == nil || len(data) == 0 {
return "", fmt.Errorf("invalid input: no table or data provided")
func Insert(s *schema.Table) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if !utils.IsValidIdentifier(s.Name) {
return "", fmt.Errorf("invalid table name: %q", s.Name)
}
var cols, values []string
columnNames := make([]string, 0, len(data[0]))
for column := range data[0] {
if !utils.IsValidIdentifier(column) {
return "", fmt.Errorf("invalid column name: %q", column)
for _, f := range s.Schema {
if err := sql.ValidateIdent(f.Name); err != nil {
return nil, err
}
columnNames = append(columnNames, column)
cols = append(cols, sql.QuoteIdent(f.Name))
values = append(values, "?")
}
columns := make([]string, len(columnNames))
for i, col := range columnNames {
columns[i] = utils.SQLQuoteIdent(col)
}
fieldMap := make(map[string]*schema.Field)
for i := range s.Schema {
fieldMap[s.Schema[i].Name] = &s.Schema[i]
}
values := make([]string, len(data))
for i, row := range data {
rowValues := make([]string, len(columnNames))
for j, colName := range columnNames {
value := row[colName]
if field, exists := fieldMap[colName]; exists && field.Type == "hash" && field.Algorithm != nil {
valueStr := fmt.Sprintf("%v", value)
hashed, err := utils.Hash(valueStr, *field.Algorithm)
if err != nil {
return "", fmt.Errorf("hashing error for column %q: %w", colName, err)
}
value = hashed
}
rowValues[j] = utils.SQLQuoteValue(value)
}
values[i] = fmt.Sprintf("(%s)", strings.Join(rowValues, ", "))
}
query := fmt.Sprintf("INSERT INTO %s (%s) VALUES %s", utils.SQLQuoteIdent(s.Name), strings.Join(columns, ", "), strings.Join(values, ", "))
if returning {
if !utils.IsValidIdentifier(s.PrimaryKey) {
return "", fmt.Errorf("invalid primary key column: %q", s.PrimaryKey)
}
query += " RETURNING " + utils.SQLQuoteIdent(s.PrimaryKey)
}
return query, nil
}
func InsertSQL(s *schema.Table, data map[string]any, returning bool) (string, error) {
return InsertManySQL(s, []map[string]any{data}, returning)
dmlParts := fmt.Sprintf(sql.DML_INSERT_INTO, sql.QuoteIdent(s.Name), strings.Join(cols, ", "), strings.Join(values, ", "))
return &dmlParts, nil
}

View File

@@ -4,23 +4,13 @@ import (
"fmt"
"git.secnex.io/secnex/pgson/schema"
"git.secnex.io/secnex/pgson/utils"
"git.secnex.io/secnex/pgson/sql"
)
func TruncateSQL(s *schema.Table, cascade bool, restartIdentity bool) (string, error) {
if s == nil {
return "", fmt.Errorf("nil table provided")
func TruncateTable(s *schema.Table) (*string, error) {
if err := sql.ValidateIdent(s.Name); err != nil {
return nil, err
}
if s.Name == "" || !utils.IsValidIdentifier(s.Name) {
return "", fmt.Errorf("invalid table name: %q", s.Name)
}
query := fmt.Sprintf("TRUNCATE TABLE %s", utils.SQLQuoteIdent(s.Name))
if restartIdentity {
query += " RESTART IDENTITY"
}
if cascade {
query += " CASCADE"
}
return query, nil
ddl := fmt.Sprintf(sql.DDL_TRUNCATE_TABLE, sql.QuoteIdent(s.Name))
return &ddl, nil
}

View File

@@ -1,56 +0,0 @@
package build
import (
"fmt"
"strings"
"git.secnex.io/secnex/pgson/schema"
"git.secnex.io/secnex/pgson/utils"
)
func UpdateSQL(s *schema.Table, data map[string]any, where string) (string, error) {
if s == nil {
return "", fmt.Errorf("nil table provided")
}
if s.Name == "" || !utils.IsValidIdentifier(s.Name) {
return "", fmt.Errorf("invalid table name: %q", s.Name)
}
if s.PrimaryKey == "" || !utils.IsValidIdentifier(s.PrimaryKey) {
return "", fmt.Errorf("invalid primary key: %q", s.PrimaryKey)
}
fieldMap := make(map[string]*schema.Field)
for i := range s.Schema {
fieldMap[s.Schema[i].Name] = &s.Schema[i]
}
setClause := make([]string, 0, len(data))
for field, value := range data {
if !utils.IsValidIdentifier(field) {
return "", fmt.Errorf("invalid field name: %q", field)
}
if schemaField, exists := fieldMap[field]; exists && schemaField.Type == "hash" && schemaField.Algorithm != nil {
valueStr := fmt.Sprintf("%v", value)
hashed, err := utils.Hash(valueStr, *schemaField.Algorithm)
if err != nil {
return "", err
}
value = hashed
}
setClause = append(setClause, fmt.Sprintf("%s = %s", utils.SQLQuoteIdent(field), utils.SQLQuoteValue(value)))
}
setClause = append(setClause, "updated_at = CURRENT_TIMESTAMP")
query := fmt.Sprintf(
"UPDATE %s SET %s WHERE %s = %s",
utils.SQLQuoteIdent(s.Name),
strings.Join(setClause, ", "),
utils.SQLQuoteIdent(s.PrimaryKey),
utils.SQLQuoteValue(where),
)
return query, nil
}

View File

@@ -5,37 +5,6 @@ import (
"git.secnex.io/secnex/pgson/schema"
)
func Create(s *schema.Table) (string, error) {
if err := s.Validate(); err != nil {
return "", err
}
return build.CreateSQL(s)
}
func Drop(s *schema.Table) (string, error) {
return build.DropSQL(s)
}
func InsertMany(s *schema.Table, data []map[string]any, returning bool) (string, error) {
return build.InsertManySQL(s, data, returning)
}
func Insert(s *schema.Table, data map[string]any, returning bool) (string, error) {
return build.InsertSQL(s, data, returning)
}
func Update(s *schema.Table, data map[string]any, where string) (string, error) {
return build.UpdateSQL(s, data, where)
}
func Delete(s *schema.Table, where string) (string, error) {
return build.DeleteSQL(s, where)
}
func HardDelete(s *schema.Table, where string) (string, error) {
return build.HardDeleteSQL(s, where)
}
func Truncate(s *schema.Table, cascade bool, restartIdentity bool) (string, error) {
return build.TruncateSQL(s, cascade, restartIdentity)
func CreateTable(schema *schema.Table) (*string, error) {
return build.CreateTable(schema)
}

View File

@@ -1,66 +0,0 @@
package schema
import (
"fmt"
"slices"
)
var (
requiredAttributes = [2]string{"name", "type"}
onlySupportedTypes = []string{"string", "int", "float", "bool", "date", "time", "datetime", "uuid", "json", "hash"}
)
func ValidateField(field *Field) error {
if err := ValidateHashAlgorithm(field); err != nil {
return err
}
if err := ValidateAttributes(field); err != nil {
return err
}
if err := ValidateFieldType(field); err != nil {
return err
}
return nil
}
func ValidateAttributes(field *Field) error {
// Check if the field has keys that are necessary for the field
for _, attribute := range requiredAttributes {
if _, ok := map[string]any{field.Name: field.Type}[attribute]; !ok {
return fmt.Errorf("attribute %s is required", attribute)
}
}
return nil
}
func ValidateFieldType(field *Field) error {
if !slices.Contains(onlySupportedTypes, field.Type) {
return fmt.Errorf("unsupported type: %s", field.Type)
}
return nil
}
func ValidateHashAlgorithm(field *Field) error {
if field.Type != "hash" {
return nil
}
if field.Algorithm == nil {
return fmt.Errorf("algorithm is required for hash field")
}
var hashAlgorithms = []string{"argon2", "bcrypt", "md5", "sha256", "sha512"}
for _, algorithm := range hashAlgorithms {
if *field.Algorithm == algorithm {
return nil
}
}
return fmt.Errorf("unsupported hash algorithm: %s", *field.Algorithm)
}
func (t *Table) Validate() error {
for _, field := range t.Schema {
if err := ValidateField(&field); err != nil {
return err
}
}
return nil
}

View File

@@ -2,9 +2,6 @@ package schema
import (
"encoding/json"
"fmt"
"git.secnex.io/secnex/pgson/utils"
)
type Table struct {
@@ -32,19 +29,6 @@ type Reference struct {
OnUpdate string `json:"on_update"`
}
var fieldTypeToSQLType = map[string]string{
"string": "VARCHAR",
"int": "INTEGER",
"float": "FLOAT",
"bool": "BOOLEAN",
"date": "DATE",
"time": "TIME",
"datetime": "TIMESTAMP",
"uuid": "UUID",
"json": "JSONB",
"hash": "VARCHAR",
}
func NewTable(data []byte) (*Table, error) {
var table Table
err := json.Unmarshal(data, &table)
@@ -57,82 +41,3 @@ func NewTable(data []byte) (*Table, error) {
func (t *Table) JSON() ([]byte, error) {
return json.Marshal(t)
}
func (f *Field) SQL() string {
if !utils.IsValidIdentifier(f.Name) {
return ""
}
sqlType := fieldTypeToSQLType[f.Type]
if sqlType == "" {
return ""
}
quotedName := utils.SQLQuoteIdent(f.Name)
sql := fmt.Sprintf("%s %s", quotedName, sqlType)
if f.Nullable != nil && !*f.Nullable {
sql += " NOT NULL"
}
if f.Primary != nil && *f.Primary {
sql += " PRIMARY KEY"
if f.Default == nil && f.Type == "uuid" {
sql += " DEFAULT uuid_generate_v4()"
}
}
if f.Unique != nil && *f.Unique {
sql += " UNIQUE"
}
if f.Default != nil && f.Primary == nil {
def := *f.Default
if utils.IsValidDefault(def) {
switch {
case utils.IsValidDefault(def):
if utils.IsValidDefault(def) && (def == "CURRENT_TIMESTAMP" || def == "now()" || def == "uuid_generate_v4()") {
sql += fmt.Sprintf(" DEFAULT %s", def)
} else {
sql += fmt.Sprintf(" DEFAULT %s", utils.SQLQuoteValue(def))
}
}
} else {
return ""
}
}
if f.References != nil {
ref := f.References
if !utils.IsValidIdentifier(ref.Table) || !utils.IsValidIdentifier(ref.Column) {
return ""
}
sql += fmt.Sprintf(" REFERENCES %s(%s)", utils.SQLQuoteIdent(ref.Table), utils.SQLQuoteIdent(ref.Column))
if ref.OnDelete != "" {
action, err := utils.SanitizeOnAction(ref.OnDelete)
if err == nil && action != "" {
sql += fmt.Sprintf(" ON DELETE %s", action)
}
}
if ref.OnUpdate != "" {
action, err := utils.SanitizeOnAction(ref.OnUpdate)
if err == nil && action != "" {
sql += fmt.Sprintf(" ON UPDATE %s", action)
}
}
}
return sql
}
func (f *Field) SQLReferences() string {
if f.References == nil {
return ""
}
ref := f.References
if !utils.IsValidIdentifier(ref.Table) || !utils.IsValidIdentifier(ref.Column) {
return ""
}
return fmt.Sprintf(" REFERENCES %s(%s)", utils.SQLQuoteIdent(ref.Table), utils.SQLQuoteIdent(ref.Column))
}

15
sql/ddl.go Normal file
View File

@@ -0,0 +1,15 @@
package sql
var (
DDL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS %s (\n %s\n);"
DDL_DROP_TABLE = "DROP TABLE IF EXISTS %s;"
DDL_TRUNCATE_TABLE = "TRUNCATE TABLE %s;"
DDL_ALTER_TABLE = "ALTER TABLE %s %s;"
DDL_ADD_COLUMN = "ALTER TABLE %s ADD COLUMN %s;"
DDL_DROP_COLUMN = "ALTER TABLE %s DROP COLUMN %s;"
DDL_ALTER_COLUMN = "ALTER TABLE %s ALTER COLUMN %s %s;"
DDL_ADD_FOREIGN_KEY = "ALTER TABLE %s ADD FOREIGN KEY (%s) REFERENCES %s (%s);"
DDL_DROP_FOREIGN_KEY = "ALTER TABLE %s DROP FOREIGN KEY %s;"
DDL_ADD_CONSTRAINT = "ALTER TABLE %s ADD CONSTRAINT %s %s;"
DDL_DROP_CONSTRAINT = "ALTER TABLE %s DROP CONSTRAINT %s;"
)

5
sql/dml.go Normal file
View File

@@ -0,0 +1,5 @@
package sql
var (
DML_INSERT_INTO = "INSERT INTO %s (%s) VALUES (%s);"
)

120
sql/validate.go Normal file
View File

@@ -0,0 +1,120 @@
package sql
import (
"fmt"
"regexp"
"strings"
"git.secnex.io/secnex/pgson/schema"
)
var (
IdentifierRegex = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)
TypeMap = map[string]string{
"string": "VARCHAR",
"int": "INTEGER",
"float": "FLOAT",
"bool": "BOOLEAN",
"date": "DATE",
"time": "TIME",
"datetime": "TIMESTAMP",
"uuid": "UUID",
"json": "JSONB",
"hash": "VARCHAR",
}
FkActions = map[string]struct{}{
"CASCADE": {},
"RESTRICT": {},
"SET NULL": {},
"NO ACTION": {},
"SET DEFAULT": {},
}
DefaultFunctions = map[string]struct{}{
"CURRENT_TIMESTAMP": {},
"now()": {},
"uuid_generate_v4()": {},
}
AlgorithmMap = map[string]struct{}{
"argon2": {},
"bcrypt": {},
"md5": {},
"sha256": {},
"sha512": {},
}
)
func ValidateIdent(name string) error {
if !IdentifierRegex.MatchString(name) {
return fmt.Errorf("invalid identifier: %s", name)
}
return nil
}
func ValidateType(name string) (string, error) {
pg, ok := TypeMap[name]
if !ok {
return "", fmt.Errorf("invalid type: %s", name)
}
return pg, nil
}
func ValidateAction(act string) (string, error) {
a := strings.ToUpper(act)
if _, ok := FkActions[a]; !ok {
return "", fmt.Errorf("invalid action: %s", act)
}
return a, nil
}
func ValidateDefault(def string) (string, error) {
if regexp.MustCompile(`^\d+(\.\d+)?$`).MatchString(def) || regexp.MustCompile(`^'.*'$`).MatchString(def) {
return def, nil
}
if _, ok := DefaultFunctions[strings.ToLower(def)]; ok {
return def, nil
}
return "", fmt.Errorf("invalid default: %s", def)
}
func ValidateReferences(refs *schema.Reference) error {
if err := ValidateIdent(refs.Table); err != nil {
return err
}
if err := ValidateIdent(refs.Column); err != nil {
return err
}
return nil
}
func ValidateAlgorithm(algo string) error {
a := strings.ToUpper(algo)
if _, ok := AlgorithmMap[a]; !ok {
return fmt.Errorf("invalid algorithm: %s", algo)
}
return nil
}
func ValidatePrimary(primary bool) error {
if primary {
return nil
}
return fmt.Errorf("primary is required")
}
func ValidateUnique(unique bool) error {
if unique {
return nil
}
return fmt.Errorf("unique is required")
}
func ValidateComment(comment *string) error {
if comment == nil {
return nil
}
return ValidateIdent(*comment)
}
func QuoteIdent(name string) string {
return `"` + strings.ReplaceAll(name, `"`, `""`) + `"`
}

View File

@@ -1,80 +0,0 @@
package utils
import (
"fmt"
"regexp"
"strings"
)
func SQLQuoteIdent(id string) string {
return `"` + strings.ReplaceAll(id, `"`, `""`) + `"`
}
func SQLQuoteValue(value any) string {
switch v := value.(type) {
case string:
escaped := strings.ReplaceAll(v, "'", "''")
return fmt.Sprintf("'%s'", escaped)
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return fmt.Sprintf("%v", value)
case float32, float64:
return fmt.Sprintf("%v", value)
case bool:
return fmt.Sprintf("%v", value)
case nil:
return "NULL"
}
str := fmt.Sprintf("%v", value)
escaped := strings.ReplaceAll(str, "'", "''")
return fmt.Sprintf("'%s'", escaped)
}
var identifierRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]{0,62}$`)
func IsValidIdentifier(id string) bool {
return identifierRe.MatchString(id)
}
var allowedOnActions = map[string]bool{
"CASCADE": true,
"SET NULL": true,
"NO ACTION": true,
"RESTRICT": true,
"SET DEFAULT": true,
}
func SanitizeOnAction(s string) (string, error) {
if strings.TrimSpace(s) == "" {
return "", nil
}
u := strings.ToUpper(strings.Join(strings.Fields(s), " "))
if allowedOnActions[u] {
return u, nil
}
return "", fmt.Errorf("invalid action: %q", s)
}
var allowedDefaultFuncs = map[string]bool{
"CURRENT_TIMESTAMP": true,
"NOW()": true,
"UUID_GENERATE_V4()": true,
}
func IsValidDefault(val string) bool {
v := strings.TrimSpace(val)
if v == "" {
return false
}
if regexp.MustCompile(`^[+-]?\d+(\.\d+)?$`).MatchString(v) {
return true
}
if strings.HasPrefix(v, "'") && strings.HasSuffix(v, "'") {
return true
}
if allowedDefaultFuncs[strings.ToUpper(v)] {
return true
}
return false
}