Using PostgreSQL、Golang
、Docker to implement simple bank API.
bigserial
: a big auto increment integers(8-byte/64-bit)now()
: PosgresSQL
default function to get current timetext
and varchar
are both used to store strings of variable length. The main difference is that varchar
has a limit on the maximum length of the string that can be stored, whereas text
does not have a limit. text
is generally used when the length of the string is unknown or could be very long, while varchar
is used when the length of the string is expected to be relatively short and can be specified in advance.owner
name to find account
Table accounts as A {
id bigserial [pk]
owner varchar [not null]
balance bigint [not null]
currency varchar [not null]
created_at timestamptz [not null,default: `now()`]
Indexes {
owner
}
}
account
// one-to-many: each account can have many entries
Table entries {
id bigserial [pk] // auto-increment
account_id bigint [ref: > A.id, not null]
amount bigint [not null, note: 'can be negative or positive']
created_at timestamptz [not null,default: `now()`]
Indexes {
account_id
}
}
// one-to-many
Table transfers {
id bigserial [pk] // auto-increment
from_account_id bigint [ref: > A.id, not null]
to_account_id bigint [ref: > A.id, not null]
amount bigint [not null, note: 'must be positive']
created_at timestamptz [not null,default: `now()`]
Indexes {
from_account_id
to_account_id
(from_account_id, to_account_id)
}
}
以下為完整的Postgresql Simple_Back_diagram.sql
CREATE TABLE "accounts" (
"id" bigserial PRIMARY KEY,
"owner" varchar NOT NULL,
"balance" bigint NOT NULL,
"currency" varchar NOT NULL,
"created_at" timestamptz NOT NULL DEFAULT (now())
);
CREATE TABLE "entries" (
"id" bigserial PRIMARY KEY,
"account_id" bigint NOT NULL,
"amount" bigint NOT NULL,
"created_at" timestamptz NOT NULL DEFAULT (now())
);
CREATE TABLE "transfers" (
"id" bigserial PRIMARY KEY,
"from_account_id" bigint NOT NULL,
"to_account_id" bigint NOT NULL,
"amount" bigint NOT NULL,
"created_at" timestamptz NOT NULL DEFAULT (now())
);
CREATE INDEX ON "accounts" ("owner");
CREATE INDEX ON "entries" ("account_id");
CREATE INDEX ON "transfers" ("from_account_id");
CREATE INDEX ON "transfers" ("to_account_id");
CREATE INDEX ON "transfers" ("from_account_id", "to_account_id");
COMMENT ON COLUMN "entries"."amount" IS 'can be negative or positive';
COMMENT ON COLUMN "transfers"."amount" IS 'must be positive';
ALTER TABLE "entries" ADD FOREIGN KEY ("account_id") REFERENCES "accounts" ("id");
ALTER TABLE "transfers" ADD FOREIGN KEY ("from_account_id") REFERENCES "accounts" ("id");
ALTER TABLE "transfers" ADD FOREIGN KEY ("to_account_id") REFERENCES "accounts" ("id");