Initial Entity stuff commit...

This commit is contained in:
Alex Stevenson 2025-07-31 00:03:16 -04:00
parent fb7a98e823
commit 380153ec39
3 changed files with 54 additions and 16 deletions

66
main.go
View file

@ -9,20 +9,22 @@ import (
_ "github.com/mattn/go-sqlite3"
)
// Panic and crash if an error shows up, and print the error
func check(e error) {
if e != nil {
panic(e)
}
}
// Convert a query into an executable statement.
func prep_query(db *sql.DB, q string) (*sql.Stmt){
statement, err := db.Prepare(q)
check(err)
return statement
}
// User record management stuff. Eventually want to abstract
// this out to store any sort of record...
type User struct {
id int64
name string
@ -31,13 +33,11 @@ type User struct {
func create_user(db *sql.DB, name string) (User) {
s := prep_query(db, "INSERT INTO users (name) VALUES (?)")
res, err := s.Exec(name)
check(err)
var u User
id, _ := res.LastInsertId()
u.id = id
u.name = name
@ -68,10 +68,44 @@ func get_user(db *sql.DB, name string) (User) {
type Entity struct {
id int64
user_id int64
name string
spawn_line string
}
func create_entity(db *sql.DB, user_id int64, spawn_line string) (Entity) {
s := prep_query(db, "INSERT INTO entities (user_id, spawn_line) VALUES (?, ?)")
res, err := s.Exec(user_id, spawn_line)
check(err)
var ent Entity
id, _ := res.LastInsertId()
ent.id = id
ent.user_id = user_id
ent.spawn_line = spawn_line
return ent
}
func get_entity(db *sql.DB, id int64) (Entity) {
s := prep_query(db, "SELECT * FROM entities WHERE id = ? LIMIT 1")
res, err := s.Query(id)
check(err)
var e Entity
res.Next()
res.Scan(&e.id, &e.user_id, &e.spawn_line)
res.Close()
if e.id != 0 {
return e
} else {
log.Printf("Entity id %d doesn't exist!", id)
panic("!")
}
}
func reset_database(db *sql.DB) {
dat, _ := os.ReadFile("setup.sql")
queries := strings.Split(string(dat), ";")
@ -82,19 +116,21 @@ func reset_database(db *sql.DB) {
}
}
func main() {
db, _ := sql.Open("sqlite3", "rpgqui.db")
reset_database(db)
var u User
u = get_user(db, "Monqui")
log.Printf("ID: %d, name: %s", u.id, u.name)
u = get_user(db, "dug")
log.Printf("ID: %d, name: %s", u.id, u.name)
u = get_user(db, "Gary")
log.Printf("ID: %d, name: %s", u.id, u.name)
u = get_user(db, "Jimbo")
log.Printf("ID: %d, name: %s", u.id, u.name)
log.Println("Reset db...")
// spin up a user...
u := get_user(db, "Monqui")
// make an entity for the user...
e := create_entity(db, u.id, "hello im monqui")
log.Printf("ID: %d, user_id: %d, spawn_line: %s", e.id, e.user_id, e.spawn_line)
// this should fail...
e = create_entity(db, 2, "hello im monqui???")
log.Printf("ID: %d, user_id: %d, spawn_line: %s", e.id, e.user_id, e.spawn_line)
}

BIN
rpgqui.db

Binary file not shown.

View file

@ -1,9 +1,11 @@
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS entities;
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name VARCHAR(64)
name VARCHAR(64) UNIQUE
);
CREATE TABLE IF NOT EXISTS entities (