Skip to content

Commit

Permalink
feat: support check constraints in sqlite
Browse files Browse the repository at this point in the history
  • Loading branch information
taozhi8833998 committed Jun 14, 2024
1 parent 2fe22fd commit 5f8a7e3
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
3 changes: 1 addition & 2 deletions pegjs/mysql.pegjs
Original file line number Diff line number Diff line change
Expand Up @@ -1467,8 +1467,7 @@ create_constraint_definition
/ create_constraint_check

constraint_name
= kc:KW_CONSTRAINT __
c:ident? {
= kc:KW_CONSTRAINT __ c:ident? {
return {
keyword: kc.toLowerCase(),
constraint: c
Expand Down
19 changes: 18 additions & 1 deletion pegjs/sqlite.pegjs
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,9 @@ column_definition_opt
/ re:reference_definition {
return { reference_definition: re }
}
/ ck:check_constraint_definition {
return { check: ck }
}
/ t:create_option_character_set_kw __ s:KW_ASSIGIN_EQUAL? __ v:ident_name {
return { character_set: { type: t, value: v, symbol: s }}
}
Expand Down Expand Up @@ -868,7 +871,7 @@ create_constraint_unique
}

create_constraint_check
= kc:constraint_name? __ u:'CHECK'i __ nfr:('NOT'i __ 'FOR'i __ 'REPLICATION'i __)? LPAREN __ c:expr __ RPAREN {
= kc:constraint_name? __ u:'CHECK'i __ nfr:('NOT'i __ 'FOR'i __ 'REPLICATION'i __)? LPAREN __ c:or_and_expr __ RPAREN {
return {
constraint_type: u.toLowerCase(),
keyword: kc && kc.keyword,
Expand Down Expand Up @@ -896,6 +899,20 @@ create_constraint_foreign
}
}

check_constraint_definition
= kc:constraint_name? __ u:'CHECK'i __ LPAREN __ c:or_and_expr __ RPAREN __ ne:(KW_NOT? __ 'ENFORCED'i)? {
const enforced = []
if (ne) enforced.push(ne[0], ne[2])
return {
constraint_type: u.toLowerCase(),
keyword: kc && kc.keyword,
constraint: kc && kc.constraint,
definition: [c],
enforced: enforced.filter(v => v).join(' ').toLowerCase(),
resource: 'constraint',
}
}

reference_definition
= kc:KW_REFERENCES __
t:table_name __
Expand Down
4 changes: 3 additions & 1 deletion test/sqlite.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,11 +165,13 @@ describe('sqlite', () => {
})

it('should create table', () => {
const sql = `CREATE TABLE IF NOT EXISTS posts (
let sql = `CREATE TABLE IF NOT EXISTS posts (
user_id INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(user_id)
);
`
expect(getParsedSql(sql)).to.be.equal('CREATE TABLE IF NOT EXISTS `posts` (`user_id` INTEGER NOT NULL, FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`))')
sql = 'CREATE TABLE users (age INTEGER CHECK(age >= 18));'
expect(getParsedSql(sql)).to.be.equal('CREATE TABLE `users` (`age` INTEGER CHECK (`age` >= 18))')
})
})

0 comments on commit 5f8a7e3

Please sign in to comment.