Skip to content

Commit

Permalink
Added "save" fix and return entity feature (+ readme updates)
Browse files Browse the repository at this point in the history
- Added sqlite files to gitignore
  • Loading branch information
deadlinecode committed Mar 23, 2023
1 parent c69fc07 commit 3af65ea
Show file tree
Hide file tree
Showing 5 changed files with 66 additions and 38 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
BunORM*.tgz
yarn-error.log
*.sqlite
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,8 @@ Please! Please! Please! Please! Please use the dev branch when making changes an
- [ ] Cleaning up the messy shit i call "code"
- [ ] Adding support for multiple relation types (one-to-many, one-to-one, etc.)
- [ ] Support relations both ways if one is set
- [ ] `db.tables.[table].save` should return the saved entity
- [ ] Bulk actions for everything
- [x] `db.tables.[table].save` should return the saved or updated entity
<br/>
<br/>

Expand Down
11 changes: 9 additions & 2 deletions src/example/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,12 +179,19 @@ db.tables[TableName].create({
// Save a row in the database
// Parameter can be a object containing the data or the result of the create function
db.tables[TableName].save({
name: "admin",
username: "admin",
});

// Call save with id parameter to update
// It also makes all properties partial/optional
db.tables[TableName].save({
id: 1,
username: "newAdmin",
});

// Delete a row from the database based on the parameters
db.tables.users.delete({
username: "admin",
username: "newAdmin",
});
```

Expand Down
7 changes: 6 additions & 1 deletion src/example/example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,11 @@ const onlyUsernameAdmins = db.tables.users.find({
// everything except username and the default attributes (id, createdAt, updatedAt and functions) will be undefined
onlyUsernameAdmins[0].username;

db.tables.users.save({
id: 1,
username: "newAdmin",
});

db.tables.users.delete({
username: "admin",
username: "newAdmin",
});
83 changes: 49 additions & 34 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,11 @@ type Or<A, TA, B, TB> = A extends TA ? true : B extends TB ? true : false;

interface _TableFunctions<TT extends Tables, T extends Tables[string]> {
create: (cols: _Columns<TT, T, true>) => AddTableFx<T, _Columns<TT, T, true>>;
save: (cols: { id?: number } & _Columns<TT, T, true>) => void;
save: (
cols:
| _Columns<TT, T, true>
| ({ id: number } & Partial<_Columns<TT, T, true>>)
) => AddTableFx<T, AddColumnDefaults<_Columns<TT, T, true>>>[];
delete: (opts: Partial<_Columns<TT, T, true>>) => void;
find: <
S extends (keyof T["columns"])[] | undefined,
Expand Down Expand Up @@ -354,41 +358,52 @@ export class BunORM<T extends Narrow<Tables>> {
.filter(([_, v]) => typeof v !== "function")
.map(([col, val]) => [
col,
Table.columns[col].type === "JSON" ? JSON.stringify(val) : val,
!["id", "createdAt", "updatedAt"].includes(col) &&
Table.columns[col].type === "JSON"
? JSON.stringify(val)
: val,
])
);
cols.id &&
(
this.db
.query(`SELECT COUNT(*) AS count FROM ${table} WHERE id = $id;`)
.get({ $id: cols.id }) as any
).count !== 0
? this.db
.query(
`UPDATE ${table} SET ${Object.keys(cols)
.filter((x) => x !== "id")
.map((x, i) => `${x} = $S_${x}`)
.join()} WHERE id = $id;`
)
.run(
Object.fromEntries([
...Object.entries(cols)
.filter(([k]) => k !== "id")
.map(([k, v]) => [`$S_${k}`, v]),
["$id", cols.id],
])
)
: this.db
.query(
`INSERT INTO ${table} ` +
(Object.keys(cols).length === 0
? "DEFAULT VALUES;"
: `('${Object.keys(cols).join("','")}') VALUES (${arr(
Object.keys(cols).length,
(i) => `?${i}`
).join()});`)
)
.all(...(Object.values(cols) as any));
return executeGetMiddleware(
injectFx(
parseJSON(
(cols.id &&
(
this.db
.query(
`SELECT COUNT(*) AS count FROM ${table} WHERE id = $id;`
)
.get({ $id: cols.id }) as any
).count !== 0
? this.db
.query(
`UPDATE ${table} SET ${Object.keys(cols)
.filter((x) => x !== "id")
.map((x, i) => `${x} = $S_${x}`)
.join()} WHERE id = $id RETURNING *;`
)
.all(
Object.fromEntries([
...Object.entries(cols)
.filter(([k]) => k !== "id")
.map(([k, v]) => [`$S_${k}`, v]),
["$id", cols.id],
])
)
: this.db
.query(
`INSERT INTO ${table} ` +
(Object.keys(cols).length === 0
? "DEFAULT VALUES;"
: `('${Object.keys(cols).join("','")}') VALUES (${arr(
Object.keys(cols).length,
(i) => `?${i}`
).join()}) RETURNING *;`)
)
.all(...(Object.values(cols) as any))) as any
)
)
);
},
delete: (opts) =>
this.db
Expand Down

0 comments on commit 3af65ea

Please sign in to comment.