mirror of
https://github.com/djhackersdev/minime.git
synced 2026-08-21 18:04:04 -05:00
Heal the layer break around the Id<> type
This commit is contained in:
@@ -1,12 +1,23 @@
|
||||
import * as sql from "sql-bricks-postgres";
|
||||
|
||||
export type Id<T> = bigint & { __id: T };
|
||||
import { Id } from "../model";
|
||||
|
||||
export interface Row {
|
||||
[key: string]: string;
|
||||
}
|
||||
|
||||
export interface Transaction {
|
||||
/**
|
||||
* Generate a new random primary key.
|
||||
*
|
||||
* On SQLite this is a random 63-bit integer (the high bit is always zero
|
||||
* so that all IDs are positive, mostly for aesthetic reasons although this
|
||||
* may also usefully reserve a namespace for automated testing).
|
||||
*
|
||||
* On Postgres this might generate UUIDv4s instead.
|
||||
*/
|
||||
generateId<T>(): Id<T>;
|
||||
|
||||
modify(stmt: sql.Statement): Promise<void>;
|
||||
|
||||
fetchRow(stmt: sql.SelectStatement): Promise<Row | undefined>;
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
export * from "./api";
|
||||
export * from "./sqlite";
|
||||
export * from "./util";
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import Database from "better-sqlite3";
|
||||
import { randomBytes } from "crypto";
|
||||
import * as sql from "sql-bricks-postgres";
|
||||
|
||||
import { DataSource, Row, Transaction } from "./api";
|
||||
import { Id } from "../model";
|
||||
|
||||
type MixedRow = {
|
||||
[key: string]: any;
|
||||
@@ -52,6 +54,17 @@ function _postprocess(obj: MixedRow): Row {
|
||||
class SqliteTransaction implements Transaction {
|
||||
constructor(private readonly _db: Database.Database) {}
|
||||
|
||||
generateId<T>(): Id<T> {
|
||||
const buf = randomBytes(8);
|
||||
|
||||
buf[0] &= 0x7f; // Force number to be non-negative
|
||||
|
||||
const val = buf.readBigUInt64BE(0);
|
||||
const str = val.toString();
|
||||
|
||||
return str as Id<T>;
|
||||
}
|
||||
|
||||
modify(stmt: sql.Statement): Promise<void> {
|
||||
const params = _preprocess(stmt);
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
import { randomBytes } from "crypto";
|
||||
|
||||
export function generateId(): bigint {
|
||||
const buf = randomBytes(8);
|
||||
|
||||
buf[0] &= 0x7f; // Force number to be non-negative
|
||||
|
||||
// Let's not depend on Node v12 for the sake of 3 LoC just yet.
|
||||
|
||||
const hi = buf.readUInt32BE(0);
|
||||
const lo = buf.readUInt32BE(4);
|
||||
|
||||
return (BigInt(hi) << 32n) | BigInt(lo);
|
||||
}
|
||||
Reference in New Issue
Block a user