diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6f799f8 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +migrations/atlas.sum binary diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md new file mode 100644 index 0000000..25f1449 --- /dev/null +++ b/DEVELOPMENT.md @@ -0,0 +1,10 @@ +# Development + +## Migrations + +If you make changes to the database schema, you need to generate a new migration. +To do this you need to install [atlas](https://atlasgo.io/). + +```shell +atlas migrate diff --env=local +``` diff --git a/atlas.hcl b/atlas.hcl new file mode 100644 index 0000000..fffe3a0 --- /dev/null +++ b/atlas.hcl @@ -0,0 +1,21 @@ +data "external_schema" "peewee" { + program = [ + "helpers/db_schema.sh" + ] +} + +env "local" { + src = data.external_schema.peewee.url + dev = "sqlite://dev?mode=memory" + url = "sqlite://whoisdevices.db" + + migration { + dir = "file://migrations" + } + + format { + migrate { + diff = format("{{ sql . \" \" }}") + } + } +} diff --git a/helpers/db_schema.sh b/helpers/db_schema.sh new file mode 100755 index 0000000..64e3801 --- /dev/null +++ b/helpers/db_schema.sh @@ -0,0 +1,4 @@ +#!/bin/bash +export PYTHONPATH=. + +poetry run python whois/db_schema.py diff --git a/migrations/20240321230454_init.sql b/migrations/20240321230454_init.sql new file mode 100644 index 0000000..cfbefea --- /dev/null +++ b/migrations/20240321230454_init.sql @@ -0,0 +1,19 @@ +-- Create "device" table +CREATE TABLE `device` ( + `mac_address` char NOT NULL, + `hostname` varchar NULL, + `last_seen` datetime NOT NULL, + `user_id` integer NULL, + `flags` integer NULL, + PRIMARY KEY (`mac_address`), + CONSTRAINT `0` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION +); +-- Create "user" table +CREATE TABLE `user` ( + `id` integer NOT NULL, + `username` varchar NOT NULL, + `password` varchar NOT NULL, + `display_name` varchar NOT NULL, + `flags` integer NULL, + PRIMARY KEY (`id`) +); diff --git a/migrations/atlas.sum b/migrations/atlas.sum new file mode 100644 index 0000000..31bdf80 --- /dev/null +++ b/migrations/atlas.sum @@ -0,0 +1,2 @@ +h1:EMRfUNLQLucjfPsImSG2fyQeY/BZRZ/LVYOtJAfHzf8= +20240321230454_init.sql h1:+0SqLh3omTCq19IGAYbyECsORj2cicbwW9rOqVwh6VQ= diff --git a/whois/db_schema.py b/whois/db_schema.py new file mode 100644 index 0000000..b266146 --- /dev/null +++ b/whois/db_schema.py @@ -0,0 +1,14 @@ +import peewee +from playhouse.reflection import print_table_sql + +from whois.database import Device, User + + +def print_schema(): + for model in [Device, User]: + print_table_sql(model) + print(";") + + +if __name__ == "__main__": + print_schema()