Skip to content

Commit 1f2b56d

Browse files
authored
orm: add check for invalid index field name (#26142)
1 parent 61d4364 commit 1f2b56d

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

vlib/orm/orm.v

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,8 @@ pub fn orm_table_gen(sql_dialect SQLDialect, table Table, q string, defaults boo
473473
mut field_comments := map[string]string{}
474474
mut index_fields := []string{}
475475

476+
valid_sql_field_names := fields.map(sql_field_name(it))
477+
476478
for attr in table.attrs {
477479
match attr.name {
478480
'comment' {
@@ -485,6 +487,9 @@ pub fn orm_table_gen(sql_dialect SQLDialect, table Table, q string, defaults boo
485487
index_strings := attr.arg.split(',')
486488
for i in index_strings {
487489
x := i.trim_space()
490+
if x !in valid_sql_field_names {
491+
return error("table `${table.name}` has no field's name: `${x}`")
492+
}
488493
if x.len > 0 && x !in index_fields {
489494
index_fields << x
490495
}

vlib/orm/orm_func_test.v

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -583,3 +583,49 @@ fn test_orm_func_f32_f64() {
583583
assert data.age_f32 == p.age_f32
584584
assert data.age_f64 == p.age_f64
585585
}
586+
587+
@[index: 'age_f33, age_f64']
588+
struct InvalidIndexFieldName1 {
589+
age_f32 f32
590+
age_f64 f64
591+
}
592+
593+
fn test_orm_func_invalid_index_field_name1() {
594+
p := InvalidIndexFieldName1{
595+
age_f32: 10.33
596+
age_f64: 10.343
597+
}
598+
599+
db := sqlite.connect(':memory:')!
600+
601+
mut qb := orm.new_query[InvalidIndexFieldName1](db)
602+
603+
qb.create() or {
604+
assert err.msg() == "table `InvalidIndexFieldName1` has no field's name: `age_f33`"
605+
return
606+
}
607+
assert false, 'should not be here'
608+
}
609+
610+
@[index: 'age_f32, age_f64']
611+
struct InvalidIndexFieldName2 {
612+
age_f32 f32 @[sql: abc]
613+
age_f64 f64
614+
}
615+
616+
fn test_orm_func_invalid_index_field_name2() {
617+
p := InvalidIndexFieldName2{
618+
age_f32: 10.33
619+
age_f64: 10.343
620+
}
621+
622+
db := sqlite.connect(':memory:')!
623+
624+
mut qb := orm.new_query[InvalidIndexFieldName2](db)
625+
626+
qb.create() or {
627+
assert err.msg() == "table `InvalidIndexFieldName2` has no field's name: `age_f32`"
628+
return
629+
}
630+
assert false, 'should not be here'
631+
}

0 commit comments

Comments
 (0)