Library Management System ER diagram and database schema

The Library Management System database schema is a DB Planner template with 24 tables, 164 columns and 45 relationships, free to use. Core tables include authors, book_contributors, book_subjects, books. It can be opened as an interactive ER diagram or exported as PostgreSQL, MySQL, or SQL Server DDL.

ER diagram of the Library Management System database schema, showing 24 tables and their relationships
FIG. 1: entity relationship diagram, 24 tables
Tables
24
Columns
164
Relationships
45
Category
Education
Exports
DBML, SQL, Prisma, C#
Price
Free

What this schema models

A complete library management system database design, modeled on how real integrated library systems work rather than how textbook diagrams draw them. 24 tables, 13 enums and 45 relationships covering the catalog (books, authors, subjects, series), physical holdings across branches, members and borrowing rules, circulation (loans, renewals, holds and transfers), fines and payments, and acquisitions. THE FOUR DESIGN RULES 1. A BOOK is not a COPY. books is the bibliographic record, one row per title and edition; copies are the physical items with barcodes. Holds are placed on the book, so any copy can fill them; loans are made on a copy. 2. Loans are history, not state. A loan row is never deleted. An open loan is simply returned_at IS NULL, and a partial unique index allows only one open loan per copy. 3. Rules are snapshotted. A loan copies the fine rate and due date it was made under, so changing a member type never rewrites past loans. 4. Fines are a ledger. Charges, payments and the allocations between them are separate rows, so partial payments and waivers are exact and auditable. Money is stored in integer cents. DETAILS WORTH STEALING - The hold queue is ordered by placed_at, with no stored position column to keep renumbering. - copies.status is a cached convenience for the public catalog; the authoritative answer to "is it out?" is an open row in loans. - Every renewal is its own row, so "why is this due on the 14th?" always has an answer. - book_contributors carries a role, so translators, editors and narrators are credited correctly. - Transfers track copies travelling between branches to fill holds. - Notifications record what was actually sent, for the member who says nobody told them. WHAT YOU GET Clean DBML that imports directly into DB Planner, and a laid-out board with zones color-coded and framed: catalog, titles and acquisitions, holdings, circulation, members, and fines, payments and staff. Every table carries a note. Postgres-flavoured types that port cleanly to MySQL or SQL Server. Useful for developers building an ILS or library app, students who need a realistic library management system ER diagram for a DBMS project, and anyone looking for a reference model of circulation and holds. This is a schema design reference, not a certified library system.

Tables (24)

Every table and its columns

publishers

Publishing houses. Kept separate from books so a rename or merger is one row.

Columns of the publishers table
ColumnTypeConstraintsReferencesDescription
iduuidPK
namevarchar(200)not null
cityvarchar(120)
countrychar(2)ISO 3166-1 alpha-2

authors

People and organizations credited on books, in any role.

Columns of the authors table
ColumnTypeConstraintsReferencesDescription
iduuidPK
sort_namevarchar(200)not nullSurname-first form used for shelving and browse, e.g. "Le Guin, Ursula K."
display_namevarchar(200)not null
birth_yearsmallint
death_yearsmallint

series

A named run of books, e.g. a trilogy. Order lives on the book (series_position).

Columns of the series table
ColumnTypeConstraintsReferences
iduuidPK
titlevarchar(300)not null

subjects

Controlled subject vocabulary. Free-text keywords belong in search, not here.

Columns of the subjects table
ColumnTypeConstraintsReferencesDescription
iduuidPK
headingvarchar(300)unique, not nullControlled heading, e.g. a Library of Congress subject heading
parent_iduuidFKsubjects.idBroader heading, for browsing narrower-to-broader

books

The BIBLIOGRAPHIC record: one row per title and edition, however many copies the library owns. Holds are placed here; loans are made on a copy.

Columns of the books table
ColumnTypeConstraintsReferencesDescription
iduuidPK
titlevarchar(500)not null
subtitlevarchar(500)
isbn13char(13)uniqueNull for items that predate ISBNs or never had one
editionvarchar(60)
publisher_iduuidFKpublishers.id
publication_yearsmallint
languagechar(3)not null, default 'eng'ISO 639-2 code
formatbook_formatnot null
call_numbervarchar(60)Classification shelf mark, e.g. Dewey 813.54 LEG
series_iduuidFKseries.id
series_positionsmallint
page_countinteger
summarytext
created_attimestamptznot null, default `now()`

Indexes: (title), (call_number)

book_contributors

Who is credited on a book and as what. A translator is not an author, and the catalog should say so.

Columns of the book_contributors table
ColumnTypeConstraintsReferencesDescription
book_iduuidFK, not nullbooks.id
author_iduuidFK, not nullauthors.id
rolecontributor_rolenot null, default 'author'
positionsmallintnot null, default 1Order of credit on the title page

book_subjects

Subject headings assigned to a book.

Columns of the book_subjects table
ColumnTypeConstraintsReferences
book_iduuidFK, not nullbooks.id
subject_iduuidFK, not nullsubjects.id

branches

Library locations. A single-site library still has exactly one row.

Columns of the branches table
ColumnTypeConstraintsReferences
iduuidPK
codevarchar(10)unique, not null
namevarchar(200)not null
address_line1varchar(200)
cityvarchar(120)
postal_codevarchar(20)
phonevarchar(30)

shelf_locations

Named collections within a branch.

Columns of the shelf_locations table
ColumnTypeConstraintsReferencesDescription
iduuidPK
branch_iduuidFK, not nullbranches.id
namevarchar(120)not nulle.g. "Adult Fiction", "Reference", "Picture Books"
loanablebooleannot null, default trueReference collections are on the shelf but never go home

copies

One physical item with a barcode. status is a cached convenience for the OPAC; the authoritative "is it out?" answer is an open row in loans.

Columns of the copies table
ColumnTypeConstraintsReferencesDescription
iduuidPK
barcodevarchar(30)unique, not nullWhat staff scan. The uuid is what foreign keys use.
book_iduuidFK, not nullbooks.id
branch_iduuidFK, not nullbranches.idOwning branch
shelf_location_iduuidFKshelf_locations.id
statuscopy_statusnot null, default 'available'
conditioncopy_conditionnot null, default 'good'
acquired_ondate
price_centsintegerReplacement cost, used when the copy is billed as lost
withdrawn_attimestamptz

Indexes: (book_id, status)

transfers

Copies in transit between branches, usually to fill a hold at the pickup branch.

Columns of the transfers table
ColumnTypeConstraintsReferencesDescription
iduuidPK
copy_iduuidFK, not nullcopies.id
from_branch_iduuidFK, not nullbranches.id
to_branch_iduuidFK, not nullbranches.id
hold_iduuidFKholds.idSet when the copy is travelling to fill a hold
sent_attimestamptznot null, default `now()`
received_attimestamptz

member_types

Borrowing rules by patron category. Loans copy the rules they were made under, so changing a rule never rewrites past loans.

Columns of the member_types table
ColumnTypeConstraintsReferencesDescription
iduuidPK
namevarchar(60)unique, not nulle.g. Adult, Child, Student, Staff
loan_limitsmallintnot null, default 20
loan_period_dayssmallintnot null, default 21
renewal_limitsmallintnot null, default 2
hold_limitsmallintnot null, default 10
daily_fine_centsintegernot null, default 0
max_fine_centsintegernot null, default 0Cap per loan; 0 with daily 0 means fine-free

members

Library patrons. A replacement card changes card_number and nothing else, so borrowing history survives.

Columns of the members table
ColumnTypeConstraintsReferences
iduuidPK
card_numbervarchar(30)unique, not null
member_type_iduuidFK, not nullmember_types.id
home_branch_iduuidFK, not nullbranches.id
first_namevarchar(100)not null
last_namevarchar(100)not null
emailvarchar(254)unique
phonevarchar(30)
date_of_birthdate
address_line1varchar(200)
cityvarchar(120)
postal_codevarchar(20)
statusmember_statusnot null, default 'active'
joined_ondatenot null, default `current_date`
expires_ondatenot null

loans

One row per checkout, kept forever as circulation history. An open loan is simply returned_at IS NULL.

Columns of the loans table
ColumnTypeConstraintsReferencesDescription
iduuidPK
copy_iduuidFK, not nullcopies.id
member_iduuidFK, not nullmembers.id
checkout_branch_iduuidFK, not nullbranches.id
checked_out_byuuidFKstaff.idNull for self-checkout kiosks
checked_out_attimestamptznot null, default `now()`
due_attimestamptznot nullComputed from member_types.loan_period_days at checkout
renewal_countsmallintnot null, default 0
returned_attimestamptzNull while the copy is out
return_branch_iduuidFKbranches.id
checked_in_byuuidFKstaff.id
daily_fine_centsintegernot nullSnapshot of the member type rule at checkout

Indexes: (member_id, returned_at), (copy_id, returned_at), (due_at)

loan_renewals

Every renewal, so "why is this due on the 14th?" has an answer. loans.due_at holds the current value.

Columns of the loan_renewals table
ColumnTypeConstraintsReferences
iduuidPK
loan_iduuidFK, not nullloans.id
renewed_attimestamptznot null, default `now()`
previous_due_attimestamptznot null
new_due_attimestamptznot null
sourcerenewal_sourcenot null

holds

Reservation queue for a title. When a copy comes back, the oldest waiting hold for that book gets it.

Columns of the holds table
ColumnTypeConstraintsReferencesDescription
iduuidPK
book_iduuidFK, not nullbooks.idHolds are on the TITLE: any copy can fill one
member_iduuidFK, not nullmembers.id
pickup_branch_iduuidFK, not nullbranches.id
placed_attimestamptznot null, default `now()`Queue order is placed_at; no stored position to keep renumbering
statushold_statusnot null, default 'waiting'
ready_copy_iduuidFKcopies.idThe copy set aside on the hold shelf
ready_attimestamptz
pickup_bydateLast day on the hold shelf before the hold expires
fulfilled_loan_iduuidFKloans.id
cancelled_attimestamptz

Indexes: (book_id, status, placed_at)

fines

Charges owed. A waiver is recorded on the row, never by deleting it. Balance = fines not waived minus payment allocations.

Columns of the fines table
ColumnTypeConstraintsReferencesDescription
iduuidPK
member_iduuidFK, not nullmembers.id
loan_iduuidFKloans.idNull for charges not tied to a loan, e.g. a lost card
reasonfine_reasonnot null
amount_centsintegernot null
assessed_attimestamptznot null, default `now()`
waived_attimestamptz
waived_byuuidFKstaff.id
waive_reasontext

payments

Money received from a member.

Columns of the payments table
ColumnTypeConstraintsReferencesDescription
iduuidPK
member_iduuidFK, not nullmembers.id
amount_centsintegernot null
methodpayment_methodnot null
paid_attimestamptznot null, default `now()`
received_byuuidFKstaff.idNull for online payments
external_referencevarchar(100)Card processor transaction id

payment_allocations

Which fines a payment paid, and how much of each. Makes partial payments and one payment across several fines exact.

Columns of the payment_allocations table
ColumnTypeConstraintsReferences
payment_iduuidFK, not nullpayments.id
fine_iduuidFK, not nullfines.id
amount_centsintegernot null

vendors

Suppliers the library orders from.

Columns of the vendors table
ColumnTypeConstraintsReferences
iduuidPK
namevarchar(200)not null
account_numbervarchar(60)
emailvarchar(254)

purchase_orders

An order to a vendor.

Columns of the purchase_orders table
ColumnTypeConstraintsReferencesDescription
iduuidPK
vendor_iduuidFK, not nullvendors.id
branch_iduuidFK, not nullbranches.idReceiving branch
ordered_byuuidFK, not nullstaff.id
statuspo_statusnot null, default 'draft'
ordered_attimestamptz

purchase_order_lines

Titles on an order. Receiving a line creates rows in copies.

Columns of the purchase_order_lines table
ColumnTypeConstraintsReferences
iduuidPK
purchase_order_iduuidFK, not nullpurchase_orders.id
book_iduuidFK, not nullbooks.id
quantitysmallintnot null
unit_price_centsintegernot null
received_quantitysmallintnot null, default 0

staff

Library employees. Referenced from every action that needs an audit trail.

Columns of the staff table
ColumnTypeConstraintsReferences
iduuidPK
branch_iduuidFK, not nullbranches.id
first_namevarchar(100)not null
last_namevarchar(100)not null
emailvarchar(254)unique, not null
rolestaff_rolenot null
activebooleannot null, default true

notifications

Due-soon, overdue and hold-ready notices actually sent, so a member who says "nobody told me" can be answered.

Columns of the notifications table
ColumnTypeConstraintsReferences
iduuidPK
member_iduuidFK, not nullmembers.id
kindnotification_kindnot null
channelnotification_channelnot null
loan_iduuidFKloans.id
hold_iduuidFKholds.id
sent_attimestamptznot null, default `now()`

Enums (13)

book_format
print, large_print, ebook, audiobook, dvd, periodical
contributor_role
author, editor, translator, illustrator, narrator
copy_status
available, on_loan, on_hold_shelf, in_transit, in_repair, lost, withdrawn
copy_condition
new, good, worn, damaged
member_status
active, suspended, expired
renewal_source
member, staff, automatic
hold_status
waiting, in_transit, ready, fulfilled, cancelled, expired
fine_reason
overdue, lost_item, damaged_item, replacement_card, processing
payment_method
cash, card, online
po_status
draft, ordered, partially_received, received, cancelled
staff_role
librarian, library_assistant, branch_manager, administrator
notification_kind
due_soon, overdue, hold_ready, hold_expiring, fine_assessed
notification_channel
email, sms

Relationships (45)

  • book_contributors.author_id references authors.id many to one
  • book_contributors.book_id references books.id many to one
  • book_subjects.book_id references books.id many to one
  • book_subjects.subject_id references subjects.id many to one
  • books.publisher_id references publishers.id many to one
  • books.series_id references series.id many to one
  • copies.book_id references books.id many to one
  • copies.branch_id references branches.id many to one
  • copies.shelf_location_id references shelf_locations.id many to one
  • fines.loan_id references loans.id many to one
  • fines.member_id references members.id many to one
  • fines.waived_by references staff.id many to one
  • holds.book_id references books.id many to one
  • holds.fulfilled_loan_id references loans.id many to one
  • holds.member_id references members.id many to one
  • holds.pickup_branch_id references branches.id many to one
  • holds.ready_copy_id references copies.id many to one
  • loan_renewals.loan_id references loans.id many to one
  • loans.checked_in_by references staff.id many to one
  • loans.checked_out_by references staff.id many to one
  • loans.checkout_branch_id references branches.id many to one
  • loans.copy_id references copies.id many to one
  • loans.member_id references members.id many to one
  • loans.return_branch_id references branches.id many to one
  • members.home_branch_id references branches.id many to one
  • members.member_type_id references member_types.id many to one
  • notifications.hold_id references holds.id many to one
  • notifications.loan_id references loans.id many to one
  • notifications.member_id references members.id many to one
  • payment_allocations.fine_id references fines.id many to one
  • payment_allocations.payment_id references payments.id many to one
  • payments.member_id references members.id many to one
  • payments.received_by references staff.id many to one
  • purchase_order_lines.book_id references books.id many to one
  • purchase_order_lines.purchase_order_id references purchase_orders.id many to one
  • purchase_orders.branch_id references branches.id many to one
  • purchase_orders.ordered_by references staff.id many to one
  • purchase_orders.vendor_id references vendors.id many to one
  • shelf_locations.branch_id references branches.id many to one
  • staff.branch_id references branches.id many to one
  • subjects.parent_id references subjects.id many to one
  • transfers.copy_id references copies.id many to one
  • transfers.from_branch_id references branches.id many to one
  • transfers.hold_id references holds.id many to one
  • transfers.to_branch_id references branches.id many to one

Library Management System database schema in DBML

The schema as it is written: DBML, the text format DB Planner draws its diagrams from. Copy it into any DBML tool, or open it in the diagram above.

library-management.dbml dbml
// Library Management System
// Zones (header colors): catalog (blue), holdings (teal), members (green),
// circulation (amber), fines and payments (purple), acquisitions (gray),
// staff and notifications (coral).

// ---------------------------------------------------------------------------
// CATALOG: what the library knows about a title, independent of any copy
// ---------------------------------------------------------------------------

Table publishers [headercolor: #4c8bf5] {
  id uuid [pk]
  name varchar(200) [not null]
  city varchar(120)
  country char(2) [note: 'ISO 3166-1 alpha-2']
  Note: 'Publishing houses. Kept separate from books so a rename or merger is one row.'
}

Table authors [headercolor: #4c8bf5] {
  id uuid [pk]
  sort_name varchar(200) [not null, note: 'Surname-first form used for shelving and browse, e.g. "Le Guin, Ursula K."']
  display_name varchar(200) [not null]
  birth_year smallint
  death_year smallint
  Note: 'People and organizations credited on books, in any role.'
}

Table series [headercolor: #4c8bf5] {
  id uuid [pk]
  title varchar(300) [not null]
  Note: 'A named run of books, e.g. a trilogy. Order lives on the book (series_position).'
}

Table subjects [headercolor: #4c8bf5] {
  id uuid [pk]
  heading varchar(300) [not null, unique, note: 'Controlled heading, e.g. a Library of Congress subject heading']
  parent_id uuid [ref: > subjects.id, note: 'Broader heading, for browsing narrower-to-broader']
  Note: 'Controlled subject vocabulary. Free-text keywords belong in search, not here.'
}

Table books [headercolor: #4c8bf5] {
  id uuid [pk]
  title varchar(500) [not null]
  subtitle varchar(500)
  isbn13 char(13) [unique, note: 'Null for items that predate ISBNs or never had one']
  edition varchar(60)
  publisher_id uuid [ref: > publishers.id]
  publication_year smallint
  language char(3) [not null, default: 'eng', note: 'ISO 639-2 code']
  format book_format [not null]
  call_number varchar(60) [note: 'Classification shelf mark, e.g. Dewey 813.54 LEG']
  series_id uuid [ref: > series.id]
  series_position smallint
  page_count integer
  summary text
  created_at timestamptz [not null, default: `now()`]

  indexes {
    title
    call_number
  }

  Note: '''
  The BIBLIOGRAPHIC record: one row per title and edition, however many copies the
  library owns. Holds are placed here; loans are made on a copy.
  '''
}

Table book_contributors [headercolor: #4c8bf5] {
  book_id uuid [not null, ref: > books.id]
  author_id uuid [not null, ref: > authors.id]
  role contributor_role [not null, default: 'author']
  position smallint [not null, default: 1, note: 'Order of credit on the title page']

  indexes {
    (book_id, author_id, role) [pk]
  }

  Note: 'Who is credited on a book and as what. A translator is not an author, and the catalog should say so.'
}

Table book_subjects [headercolor: #4c8bf5] {
  book_id uuid [not null, ref: > books.id]
  subject_id uuid [not null, ref: > subjects.id]

  indexes {
    (book_id, subject_id) [pk]
  }

  Note: 'Subject headings assigned to a book.'
}

// ---------------------------------------------------------------------------
// HOLDINGS: the physical things on shelves
// ---------------------------------------------------------------------------

Table branches [headercolor: #4cd0b0] {
  id uuid [pk]
  code varchar(10) [not null, unique]
  name varchar(200) [not null]
  address_line1 varchar(200)
  city varchar(120)
  postal_code varchar(20)
  phone varchar(30)
  Note: 'Library locations. A single-site library still has exactly one row.'
}

Table shelf_locations [headercolor: #4cd0b0] {
  id uuid [pk]
  branch_id uuid [not null, ref: > branches.id]
  name varchar(120) [not null, note: 'e.g. "Adult Fiction", "Reference", "Picture Books"']
  loanable boolean [not null, default: true, note: 'Reference collections are on the shelf but never go home']
  Note: 'Named collections within a branch.'
}

Table copies [headercolor: #4cd0b0] {
  id uuid [pk]
  barcode varchar(30) [not null, unique, note: 'What staff scan. The uuid is what foreign keys use.']
  book_id uuid [not null, ref: > books.id]
  branch_id uuid [not null, ref: > branches.id, note: 'Owning branch']
  shelf_location_id uuid [ref: > shelf_locations.id]
  status copy_status [not null, default: 'available']
  condition copy_condition [not null, default: 'good']
  acquired_on date
  price_cents integer [note: 'Replacement cost, used when the copy is billed as lost']
  withdrawn_at timestamptz

  indexes {
    (book_id, status)
  }

  Note: '''
  One physical item with a barcode. status is a cached convenience for the OPAC; the
  authoritative "is it out?" answer is an open row in loans.
  '''
}

Table transfers [headercolor: #4cd0b0] {
  id uuid [pk]
  copy_id uuid [not null, ref: > copies.id]
  from_branch_id uuid [not null, ref: > branches.id]
  to_branch_id uuid [not null, ref: > branches.id]
  hold_id uuid [ref: > holds.id, note: 'Set when the copy is travelling to fill a hold']
  sent_at timestamptz [not null, default: `now()`]
  received_at timestamptz
  Note: 'Copies in transit between branches, usually to fill a hold at the pickup branch.'
}

// ---------------------------------------------------------------------------
// MEMBERS: patrons and the rules that apply to them
// ---------------------------------------------------------------------------

Table member_types [headercolor: #8bc34a] {
  id uuid [pk]
  name varchar(60) [not null, unique, note: 'e.g. Adult, Child, Student, Staff']
  loan_limit smallint [not null, default: 20]
  loan_period_days smallint [not null, default: 21]
  renewal_limit smallint [not null, default: 2]
  hold_limit smallint [not null, default: 10]
  daily_fine_cents integer [not null, default: 0]
  max_fine_cents integer [not null, default: 0, note: 'Cap per loan; 0 with daily 0 means fine-free']
  Note: 'Borrowing rules by patron category. Loans copy the rules they were made under, so changing a rule never rewrites past loans.'
}

Table members [headercolor: #8bc34a] {
  id uuid [pk]
  card_number varchar(30) [not null, unique]
  member_type_id uuid [not null, ref: > member_types.id]
  home_branch_id uuid [not null, ref: > branches.id]
  first_name varchar(100) [not null]
  last_name varchar(100) [not null]
  email varchar(254) [unique]
  phone varchar(30)
  date_of_birth date
  address_line1 varchar(200)
  city varchar(120)
  postal_code varchar(20)
  status member_status [not null, default: 'active']
  joined_on date [not null, default: `current_date`]
  expires_on date [not null]
  Note: 'Library patrons. A replacement card changes card_number and nothing else, so borrowing history survives.'
}

// ---------------------------------------------------------------------------
// CIRCULATION: loans, renewals and holds
// ---------------------------------------------------------------------------

Table loans [headercolor: #f5b74c] {
  id uuid [pk]
  copy_id uuid [not null, ref: > copies.id]
  member_id uuid [not null, ref: > members.id]
  checkout_branch_id uuid [not null, ref: > branches.id]
  checked_out_by uuid [ref: > staff.id, note: 'Null for self-checkout kiosks']
  checked_out_at timestamptz [not null, default: `now()`]
  due_at timestamptz [not null, note: 'Computed from member_types.loan_period_days at checkout']
  renewal_count smallint [not null, default: 0]
  returned_at timestamptz [note: 'Null while the copy is out']
  return_branch_id uuid [ref: > branches.id]
  checked_in_by uuid [ref: > staff.id]
  daily_fine_cents integer [not null, note: 'Snapshot of the member type rule at checkout']

  indexes {
    (member_id, returned_at)
    (copy_id, returned_at) [note: 'Enforce ONE open loan per copy with a partial unique index WHERE returned_at IS NULL']
    due_at
  }

  Note: 'One row per checkout, kept forever as circulation history. An open loan is simply returned_at IS NULL.'
}

Table loan_renewals [headercolor: #f5b74c] {
  id uuid [pk]
  loan_id uuid [not null, ref: > loans.id]
  renewed_at timestamptz [not null, default: `now()`]
  previous_due_at timestamptz [not null]
  new_due_at timestamptz [not null]
  source renewal_source [not null]
  Note: 'Every renewal, so "why is this due on the 14th?" has an answer. loans.due_at holds the current value.'
}

Table holds [headercolor: #f5b74c] {
  id uuid [pk]
  book_id uuid [not null, ref: > books.id, note: 'Holds are on the TITLE: any copy can fill one']
  member_id uuid [not null, ref: > members.id]
  pickup_branch_id uuid [not null, ref: > branches.id]
  placed_at timestamptz [not null, default: `now()`, note: 'Queue order is placed_at; no stored position to keep renumbering']
  status hold_status [not null, default: 'waiting']
  ready_copy_id uuid [ref: > copies.id, note: 'The copy set aside on the hold shelf']
  ready_at timestamptz
  pickup_by date [note: 'Last day on the hold shelf before the hold expires']
  fulfilled_loan_id uuid [ref: > loans.id]
  cancelled_at timestamptz

  indexes {
    (book_id, status, placed_at)
  }

  Note: 'Reservation queue for a title. When a copy comes back, the oldest waiting hold for that book gets it.'
}

// ---------------------------------------------------------------------------
// FINES AND PAYMENTS: a ledger, never an editable balance
// ---------------------------------------------------------------------------

Table fines [headercolor: #b98cf0] {
  id uuid [pk]
  member_id uuid [not null, ref: > members.id]
  loan_id uuid [ref: > loans.id, note: 'Null for charges not tied to a loan, e.g. a lost card']
  reason fine_reason [not null]
  amount_cents integer [not null]
  assessed_at timestamptz [not null, default: `now()`]
  waived_at timestamptz
  waived_by uuid [ref: > staff.id]
  waive_reason text
  Note: 'Charges owed. A waiver is recorded on the row, never by deleting it. Balance = fines not waived minus payment allocations.'
}

Table payments [headercolor: #b98cf0] {
  id uuid [pk]
  member_id uuid [not null, ref: > members.id]
  amount_cents integer [not null]
  method payment_method [not null]
  paid_at timestamptz [not null, default: `now()`]
  received_by uuid [ref: > staff.id, note: 'Null for online payments']
  external_reference varchar(100) [note: 'Card processor transaction id']
  Note: 'Money received from a member.'
}

Table payment_allocations [headercolor: #b98cf0] {
  payment_id uuid [not null, ref: > payments.id]
  fine_id uuid [not null, ref: > fines.id]
  amount_cents integer [not null]

  indexes {
    (payment_id, fine_id) [pk]
  }

  Note: 'Which fines a payment paid, and how much of each. Makes partial payments and one payment across several fines exact.'
}

// ---------------------------------------------------------------------------
// ACQUISITIONS: buying new material
// ---------------------------------------------------------------------------

Table vendors [headercolor: #90a4ae] {
  id uuid [pk]
  name varchar(200) [not null]
  account_number varchar(60)
  email varchar(254)
  Note: 'Suppliers the library orders from.'
}

Table purchase_orders [headercolor: #90a4ae] {
  id uuid [pk]
  vendor_id uuid [not null, ref: > vendors.id]
  branch_id uuid [not null, ref: > branches.id, note: 'Receiving branch']
  ordered_by uuid [not null, ref: > staff.id]
  status po_status [not null, default: 'draft']
  ordered_at timestamptz
  Note: 'An order to a vendor.'
}

Table purchase_order_lines [headercolor: #90a4ae] {
  id uuid [pk]
  purchase_order_id uuid [not null, ref: > purchase_orders.id]
  book_id uuid [not null, ref: > books.id]
  quantity smallint [not null]
  unit_price_cents integer [not null]
  received_quantity smallint [not null, default: 0]
  Note: 'Titles on an order. Receiving a line creates rows in copies.'
}

// ---------------------------------------------------------------------------
// STAFF AND NOTIFICATIONS
// ---------------------------------------------------------------------------

Table staff [headercolor: #f07178] {
  id uuid [pk]
  branch_id uuid [not null, ref: > branches.id]
  first_name varchar(100) [not null]
  last_name varchar(100) [not null]
  email varchar(254) [not null, unique]
  role staff_role [not null]
  active boolean [not null, default: true]
  Note: 'Library employees. Referenced from every action that needs an audit trail.'
}

Table notifications [headercolor: #f07178] {
  id uuid [pk]
  member_id uuid [not null, ref: > members.id]
  kind notification_kind [not null]
  channel notification_channel [not null]
  loan_id uuid [ref: > loans.id]
  hold_id uuid [ref: > holds.id]
  sent_at timestamptz [not null, default: `now()`]
  Note: 'Due-soon, overdue and hold-ready notices actually sent, so a member who says "nobody told me" can be answered.'
}

// ---------------------------------------------------------------------------
// ENUMS
// ---------------------------------------------------------------------------

Enum book_format {
  print
  large_print
  ebook
  audiobook
  dvd
  periodical
}

Enum contributor_role {
  author
  editor
  translator
  illustrator
  narrator
}

Enum copy_status {
  available
  on_loan
  on_hold_shelf
  in_transit
  in_repair
  lost
  withdrawn
}

Enum copy_condition {
  new
  good
  worn
  damaged
}

Enum member_status {
  active
  suspended
  expired
}

Enum renewal_source {
  member
  staff
  automatic
}

Enum hold_status {
  waiting
  in_transit
  ready
  fulfilled
  cancelled
  expired
}

Enum fine_reason {
  overdue
  lost_item
  damaged_item
  replacement_card
  processing
}

Enum payment_method {
  cash
  card
  online
}

Enum po_status {
  draft
  ordered
  partially_received
  received
  cancelled
}

Enum staff_role {
  librarian
  library_assistant
  branch_manager
  administrator
}

Enum notification_kind {
  due_soon
  overdue
  hold_ready
  hold_expiring
  fine_assessed
}

Enum notification_channel {
  email
  sms
}

Library Management System database schema as SQL

The same schema as CREATE TABLE statements, exported by DB Planner. PostgreSQL is shown first; MySQL and SQL Server are below it.

PostgreSQL
postgresql.sql PostgreSQL
CREATE TYPE "book_format" AS ENUM (
  'print',
  'large_print',
  'ebook',
  'audiobook',
  'dvd',
  'periodical'
);

CREATE TYPE "contributor_role" AS ENUM (
  'author',
  'editor',
  'translator',
  'illustrator',
  'narrator'
);

CREATE TYPE "copy_status" AS ENUM (
  'available',
  'on_loan',
  'on_hold_shelf',
  'in_transit',
  'in_repair',
  'lost',
  'withdrawn'
);

CREATE TYPE "copy_condition" AS ENUM (
  'new',
  'good',
  'worn',
  'damaged'
);

CREATE TYPE "member_status" AS ENUM (
  'active',
  'suspended',
  'expired'
);

CREATE TYPE "renewal_source" AS ENUM (
  'member',
  'staff',
  'automatic'
);

CREATE TYPE "hold_status" AS ENUM (
  'waiting',
  'in_transit',
  'ready',
  'fulfilled',
  'cancelled',
  'expired'
);

CREATE TYPE "fine_reason" AS ENUM (
  'overdue',
  'lost_item',
  'damaged_item',
  'replacement_card',
  'processing'
);

CREATE TYPE "payment_method" AS ENUM (
  'cash',
  'card',
  'online'
);

CREATE TYPE "po_status" AS ENUM (
  'draft',
  'ordered',
  'partially_received',
  'received',
  'cancelled'
);

CREATE TYPE "staff_role" AS ENUM (
  'librarian',
  'library_assistant',
  'branch_manager',
  'administrator'
);

CREATE TYPE "notification_kind" AS ENUM (
  'due_soon',
  'overdue',
  'hold_ready',
  'hold_expiring',
  'fine_assessed'
);

CREATE TYPE "notification_channel" AS ENUM (
  'email',
  'sms'
);

CREATE TABLE "publishers" (
  "id" uuid PRIMARY KEY,
  "name" varchar(200) NOT NULL,
  "city" varchar(120),
  "country" char(2)
);

CREATE TABLE "authors" (
  "id" uuid PRIMARY KEY,
  "sort_name" varchar(200) NOT NULL,
  "display_name" varchar(200) NOT NULL,
  "birth_year" smallint,
  "death_year" smallint
);

CREATE TABLE "series" (
  "id" uuid PRIMARY KEY,
  "title" varchar(300) NOT NULL
);

CREATE TABLE "subjects" (
  "id" uuid PRIMARY KEY,
  "heading" varchar(300) UNIQUE NOT NULL,
  "parent_id" uuid
);

CREATE TABLE "books" (
  "id" uuid PRIMARY KEY,
  "title" varchar(500) NOT NULL,
  "subtitle" varchar(500),
  "isbn13" char(13) UNIQUE,
  "edition" varchar(60),
  "publisher_id" uuid,
  "publication_year" smallint,
  "language" char(3) NOT NULL DEFAULT 'eng',
  "format" book_format NOT NULL,
  "call_number" varchar(60),
  "series_id" uuid,
  "series_position" smallint,
  "page_count" integer,
  "summary" text,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "book_contributors" (
  "book_id" uuid NOT NULL,
  "author_id" uuid NOT NULL,
  "role" contributor_role NOT NULL DEFAULT 'author',
  "position" smallint NOT NULL DEFAULT 1,
  PRIMARY KEY ("book_id", "author_id", "role")
);

CREATE TABLE "book_subjects" (
  "book_id" uuid NOT NULL,
  "subject_id" uuid NOT NULL,
  PRIMARY KEY ("book_id", "subject_id")
);

CREATE TABLE "branches" (
  "id" uuid PRIMARY KEY,
  "code" varchar(10) UNIQUE NOT NULL,
  "name" varchar(200) NOT NULL,
  "address_line1" varchar(200),
  "city" varchar(120),
  "postal_code" varchar(20),
  "phone" varchar(30)
);

CREATE TABLE "shelf_locations" (
  "id" uuid PRIMARY KEY,
  "branch_id" uuid NOT NULL,
  "name" varchar(120) NOT NULL,
  "loanable" boolean NOT NULL DEFAULT true
);

CREATE TABLE "copies" (
  "id" uuid PRIMARY KEY,
  "barcode" varchar(30) UNIQUE NOT NULL,
  "book_id" uuid NOT NULL,
  "branch_id" uuid NOT NULL,
  "shelf_location_id" uuid,
  "status" copy_status NOT NULL DEFAULT 'available',
  "condition" copy_condition NOT NULL DEFAULT 'good',
  "acquired_on" date,
  "price_cents" integer,
  "withdrawn_at" timestamptz
);

CREATE TABLE "transfers" (
  "id" uuid PRIMARY KEY,
  "copy_id" uuid NOT NULL,
  "from_branch_id" uuid NOT NULL,
  "to_branch_id" uuid NOT NULL,
  "hold_id" uuid,
  "sent_at" timestamptz NOT NULL DEFAULT (now()),
  "received_at" timestamptz
);

CREATE TABLE "member_types" (
  "id" uuid PRIMARY KEY,
  "name" varchar(60) UNIQUE NOT NULL,
  "loan_limit" smallint NOT NULL DEFAULT 20,
  "loan_period_days" smallint NOT NULL DEFAULT 21,
  "renewal_limit" smallint NOT NULL DEFAULT 2,
  "hold_limit" smallint NOT NULL DEFAULT 10,
  "daily_fine_cents" integer NOT NULL DEFAULT 0,
  "max_fine_cents" integer NOT NULL DEFAULT 0
);

CREATE TABLE "members" (
  "id" uuid PRIMARY KEY,
  "card_number" varchar(30) UNIQUE NOT NULL,
  "member_type_id" uuid NOT NULL,
  "home_branch_id" uuid NOT NULL,
  "first_name" varchar(100) NOT NULL,
  "last_name" varchar(100) NOT NULL,
  "email" varchar(254) UNIQUE,
  "phone" varchar(30),
  "date_of_birth" date,
  "address_line1" varchar(200),
  "city" varchar(120),
  "postal_code" varchar(20),
  "status" member_status NOT NULL DEFAULT 'active',
  "joined_on" date NOT NULL DEFAULT (current_date),
  "expires_on" date NOT NULL
);

CREATE TABLE "loans" (
  "id" uuid PRIMARY KEY,
  "copy_id" uuid NOT NULL,
  "member_id" uuid NOT NULL,
  "checkout_branch_id" uuid NOT NULL,
  "checked_out_by" uuid,
  "checked_out_at" timestamptz NOT NULL DEFAULT (now()),
  "due_at" timestamptz NOT NULL,
  "renewal_count" smallint NOT NULL DEFAULT 0,
  "returned_at" timestamptz,
  "return_branch_id" uuid,
  "checked_in_by" uuid,
  "daily_fine_cents" integer NOT NULL
);

CREATE TABLE "loan_renewals" (
  "id" uuid PRIMARY KEY,
  "loan_id" uuid NOT NULL,
  "renewed_at" timestamptz NOT NULL DEFAULT (now()),
  "previous_due_at" timestamptz NOT NULL,
  "new_due_at" timestamptz NOT NULL,
  "source" renewal_source NOT NULL
);

CREATE TABLE "holds" (
  "id" uuid PRIMARY KEY,
  "book_id" uuid NOT NULL,
  "member_id" uuid NOT NULL,
  "pickup_branch_id" uuid NOT NULL,
  "placed_at" timestamptz NOT NULL DEFAULT (now()),
  "status" hold_status NOT NULL DEFAULT 'waiting',
  "ready_copy_id" uuid,
  "ready_at" timestamptz,
  "pickup_by" date,
  "fulfilled_loan_id" uuid,
  "cancelled_at" timestamptz
);

CREATE TABLE "fines" (
  "id" uuid PRIMARY KEY,
  "member_id" uuid NOT NULL,
  "loan_id" uuid,
  "reason" fine_reason NOT NULL,
  "amount_cents" integer NOT NULL,
  "assessed_at" timestamptz NOT NULL DEFAULT (now()),
  "waived_at" timestamptz,
  "waived_by" uuid,
  "waive_reason" text
);

CREATE TABLE "payments" (
  "id" uuid PRIMARY KEY,
  "member_id" uuid NOT NULL,
  "amount_cents" integer NOT NULL,
  "method" payment_method NOT NULL,
  "paid_at" timestamptz NOT NULL DEFAULT (now()),
  "received_by" uuid,
  "external_reference" varchar(100)
);

CREATE TABLE "payment_allocations" (
  "payment_id" uuid NOT NULL,
  "fine_id" uuid NOT NULL,
  "amount_cents" integer NOT NULL,
  PRIMARY KEY ("payment_id", "fine_id")
);

CREATE TABLE "vendors" (
  "id" uuid PRIMARY KEY,
  "name" varchar(200) NOT NULL,
  "account_number" varchar(60),
  "email" varchar(254)
);

CREATE TABLE "purchase_orders" (
  "id" uuid PRIMARY KEY,
  "vendor_id" uuid NOT NULL,
  "branch_id" uuid NOT NULL,
  "ordered_by" uuid NOT NULL,
  "status" po_status NOT NULL DEFAULT 'draft',
  "ordered_at" timestamptz
);

CREATE TABLE "purchase_order_lines" (
  "id" uuid PRIMARY KEY,
  "purchase_order_id" uuid NOT NULL,
  "book_id" uuid NOT NULL,
  "quantity" smallint NOT NULL,
  "unit_price_cents" integer NOT NULL,
  "received_quantity" smallint NOT NULL DEFAULT 0
);

CREATE TABLE "staff" (
  "id" uuid PRIMARY KEY,
  "branch_id" uuid NOT NULL,
  "first_name" varchar(100) NOT NULL,
  "last_name" varchar(100) NOT NULL,
  "email" varchar(254) UNIQUE NOT NULL,
  "role" staff_role NOT NULL,
  "active" boolean NOT NULL DEFAULT true
);

CREATE TABLE "notifications" (
  "id" uuid PRIMARY KEY,
  "member_id" uuid NOT NULL,
  "kind" notification_kind NOT NULL,
  "channel" notification_channel NOT NULL,
  "loan_id" uuid,
  "hold_id" uuid,
  "sent_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE INDEX ON "books" ("title");

CREATE INDEX ON "books" ("call_number");

CREATE INDEX ON "copies" ("book_id", "status");

CREATE INDEX ON "loans" ("member_id", "returned_at");

CREATE INDEX ON "loans" ("copy_id", "returned_at");

CREATE INDEX ON "loans" ("due_at");

CREATE INDEX ON "holds" ("book_id", "status", "placed_at");

COMMENT ON TABLE "publishers" IS 'Publishing houses. Kept separate from books so a rename or merger is one row.';

COMMENT ON COLUMN "publishers"."country" IS 'ISO 3166-1 alpha-2';

COMMENT ON TABLE "authors" IS 'People and organizations credited on books, in any role.';

COMMENT ON COLUMN "authors"."sort_name" IS 'Surname-first form used for shelving and browse, e.g. "Le Guin, Ursula K."';

COMMENT ON TABLE "series" IS 'A named run of books, e.g. a trilogy. Order lives on the book (series_position).';

COMMENT ON TABLE "subjects" IS 'Controlled subject vocabulary. Free-text keywords belong in search, not here.';

COMMENT ON COLUMN "subjects"."heading" IS 'Controlled heading, e.g. a Library of Congress subject heading';

COMMENT ON COLUMN "subjects"."parent_id" IS 'Broader heading, for browsing narrower-to-broader';

COMMENT ON TABLE "books" IS 'The BIBLIOGRAPHIC record: one row per title and edition, however many copies the
library owns. Holds are placed here; loans are made on a copy.
';

COMMENT ON COLUMN "books"."isbn13" IS 'Null for items that predate ISBNs or never had one';

COMMENT ON COLUMN "books"."language" IS 'ISO 639-2 code';

COMMENT ON COLUMN "books"."call_number" IS 'Classification shelf mark, e.g. Dewey 813.54 LEG';

COMMENT ON TABLE "book_contributors" IS 'Who is credited on a book and as what. A translator is not an author, and the catalog should say so.';

COMMENT ON COLUMN "book_contributors"."position" IS 'Order of credit on the title page';

COMMENT ON TABLE "book_subjects" IS 'Subject headings assigned to a book.';

COMMENT ON TABLE "branches" IS 'Library locations. A single-site library still has exactly one row.';

COMMENT ON TABLE "shelf_locations" IS 'Named collections within a branch.';

COMMENT ON COLUMN "shelf_locations"."name" IS 'e.g. "Adult Fiction", "Reference", "Picture Books"';

COMMENT ON COLUMN "shelf_locations"."loanable" IS 'Reference collections are on the shelf but never go home';

COMMENT ON TABLE "copies" IS 'One physical item with a barcode. status is a cached convenience for the OPAC; the
authoritative "is it out?" answer is an open row in loans.
';

COMMENT ON COLUMN "copies"."barcode" IS 'What staff scan. The uuid is what foreign keys use.';

COMMENT ON COLUMN "copies"."branch_id" IS 'Owning branch';

COMMENT ON COLUMN "copies"."price_cents" IS 'Replacement cost, used when the copy is billed as lost';

COMMENT ON TABLE "transfers" IS 'Copies in transit between branches, usually to fill a hold at the pickup branch.';

COMMENT ON COLUMN "transfers"."hold_id" IS 'Set when the copy is travelling to fill a hold';

COMMENT ON TABLE "member_types" IS 'Borrowing rules by patron category. Loans copy the rules they were made under, so changing a rule never rewrites past loans.';

COMMENT ON COLUMN "member_types"."name" IS 'e.g. Adult, Child, Student, Staff';

COMMENT ON COLUMN "member_types"."max_fine_cents" IS 'Cap per loan; 0 with daily 0 means fine-free';

COMMENT ON TABLE "members" IS 'Library patrons. A replacement card changes card_number and nothing else, so borrowing history survives.';

COMMENT ON TABLE "loans" IS 'One row per checkout, kept forever as circulation history. An open loan is simply returned_at IS NULL.';

COMMENT ON COLUMN "loans"."checked_out_by" IS 'Null for self-checkout kiosks';

COMMENT ON COLUMN "loans"."due_at" IS 'Computed from member_types.loan_period_days at checkout';

COMMENT ON COLUMN "loans"."returned_at" IS 'Null while the copy is out';

COMMENT ON COLUMN "loans"."daily_fine_cents" IS 'Snapshot of the member type rule at checkout';

COMMENT ON TABLE "loan_renewals" IS 'Every renewal, so "why is this due on the 14th?" has an answer. loans.due_at holds the current value.';

COMMENT ON TABLE "holds" IS 'Reservation queue for a title. When a copy comes back, the oldest waiting hold for that book gets it.';

COMMENT ON COLUMN "holds"."book_id" IS 'Holds are on the TITLE: any copy can fill one';

COMMENT ON COLUMN "holds"."placed_at" IS 'Queue order is placed_at; no stored position to keep renumbering';

COMMENT ON COLUMN "holds"."ready_copy_id" IS 'The copy set aside on the hold shelf';

COMMENT ON COLUMN "holds"."pickup_by" IS 'Last day on the hold shelf before the hold expires';

COMMENT ON TABLE "fines" IS 'Charges owed. A waiver is recorded on the row, never by deleting it. Balance = fines not waived minus payment allocations.';

COMMENT ON COLUMN "fines"."loan_id" IS 'Null for charges not tied to a loan, e.g. a lost card';

COMMENT ON TABLE "payments" IS 'Money received from a member.';

COMMENT ON COLUMN "payments"."received_by" IS 'Null for online payments';

COMMENT ON COLUMN "payments"."external_reference" IS 'Card processor transaction id';

COMMENT ON TABLE "payment_allocations" IS 'Which fines a payment paid, and how much of each. Makes partial payments and one payment across several fines exact.';

COMMENT ON TABLE "vendors" IS 'Suppliers the library orders from.';

COMMENT ON TABLE "purchase_orders" IS 'An order to a vendor.';

COMMENT ON COLUMN "purchase_orders"."branch_id" IS 'Receiving branch';

COMMENT ON TABLE "purchase_order_lines" IS 'Titles on an order. Receiving a line creates rows in copies.';

COMMENT ON TABLE "staff" IS 'Library employees. Referenced from every action that needs an audit trail.';

COMMENT ON TABLE "notifications" IS 'Due-soon, overdue and hold-ready notices actually sent, so a member who says "nobody told me" can be answered.';

ALTER TABLE "subjects" ADD FOREIGN KEY ("parent_id") REFERENCES "subjects" ("id");

ALTER TABLE "books" ADD FOREIGN KEY ("publisher_id") REFERENCES "publishers" ("id");

ALTER TABLE "books" ADD FOREIGN KEY ("series_id") REFERENCES "series" ("id");

ALTER TABLE "book_contributors" ADD FOREIGN KEY ("book_id") REFERENCES "books" ("id");

ALTER TABLE "book_contributors" ADD FOREIGN KEY ("author_id") REFERENCES "authors" ("id");

ALTER TABLE "book_subjects" ADD FOREIGN KEY ("book_id") REFERENCES "books" ("id");

ALTER TABLE "book_subjects" ADD FOREIGN KEY ("subject_id") REFERENCES "subjects" ("id");

ALTER TABLE "shelf_locations" ADD FOREIGN KEY ("branch_id") REFERENCES "branches" ("id");

ALTER TABLE "copies" ADD FOREIGN KEY ("book_id") REFERENCES "books" ("id");

ALTER TABLE "copies" ADD FOREIGN KEY ("branch_id") REFERENCES "branches" ("id");

ALTER TABLE "copies" ADD FOREIGN KEY ("shelf_location_id") REFERENCES "shelf_locations" ("id");

ALTER TABLE "transfers" ADD FOREIGN KEY ("copy_id") REFERENCES "copies" ("id");

ALTER TABLE "transfers" ADD FOREIGN KEY ("from_branch_id") REFERENCES "branches" ("id");

ALTER TABLE "transfers" ADD FOREIGN KEY ("to_branch_id") REFERENCES "branches" ("id");

ALTER TABLE "transfers" ADD FOREIGN KEY ("hold_id") REFERENCES "holds" ("id");

ALTER TABLE "members" ADD FOREIGN KEY ("member_type_id") REFERENCES "member_types" ("id");

ALTER TABLE "members" ADD FOREIGN KEY ("home_branch_id") REFERENCES "branches" ("id");

ALTER TABLE "loans" ADD FOREIGN KEY ("copy_id") REFERENCES "copies" ("id");

ALTER TABLE "loans" ADD FOREIGN KEY ("member_id") REFERENCES "members" ("id");

ALTER TABLE "loans" ADD FOREIGN KEY ("checkout_branch_id") REFERENCES "branches" ("id");

ALTER TABLE "loans" ADD FOREIGN KEY ("checked_out_by") REFERENCES "staff" ("id");

ALTER TABLE "loans" ADD FOREIGN KEY ("return_branch_id") REFERENCES "branches" ("id");

ALTER TABLE "loans" ADD FOREIGN KEY ("checked_in_by") REFERENCES "staff" ("id");

ALTER TABLE "loan_renewals" ADD FOREIGN KEY ("loan_id") REFERENCES "loans" ("id");

ALTER TABLE "holds" ADD FOREIGN KEY ("book_id") REFERENCES "books" ("id");

ALTER TABLE "holds" ADD FOREIGN KEY ("member_id") REFERENCES "members" ("id");

ALTER TABLE "holds" ADD FOREIGN KEY ("pickup_branch_id") REFERENCES "branches" ("id");

ALTER TABLE "holds" ADD FOREIGN KEY ("ready_copy_id") REFERENCES "copies" ("id");

ALTER TABLE "holds" ADD FOREIGN KEY ("fulfilled_loan_id") REFERENCES "loans" ("id");

ALTER TABLE "fines" ADD FOREIGN KEY ("member_id") REFERENCES "members" ("id");

ALTER TABLE "fines" ADD FOREIGN KEY ("loan_id") REFERENCES "loans" ("id");

ALTER TABLE "fines" ADD FOREIGN KEY ("waived_by") REFERENCES "staff" ("id");

ALTER TABLE "payments" ADD FOREIGN KEY ("member_id") REFERENCES "members" ("id");

ALTER TABLE "payments" ADD FOREIGN KEY ("received_by") REFERENCES "staff" ("id");

ALTER TABLE "payment_allocations" ADD FOREIGN KEY ("payment_id") REFERENCES "payments" ("id");

ALTER TABLE "payment_allocations" ADD FOREIGN KEY ("fine_id") REFERENCES "fines" ("id");

ALTER TABLE "purchase_orders" ADD FOREIGN KEY ("vendor_id") REFERENCES "vendors" ("id");

ALTER TABLE "purchase_orders" ADD FOREIGN KEY ("branch_id") REFERENCES "branches" ("id");

ALTER TABLE "purchase_orders" ADD FOREIGN KEY ("ordered_by") REFERENCES "staff" ("id");

ALTER TABLE "purchase_order_lines" ADD FOREIGN KEY ("purchase_order_id") REFERENCES "purchase_orders" ("id");

ALTER TABLE "purchase_order_lines" ADD FOREIGN KEY ("book_id") REFERENCES "books" ("id");

ALTER TABLE "staff" ADD FOREIGN KEY ("branch_id") REFERENCES "branches" ("id");

ALTER TABLE "notifications" ADD FOREIGN KEY ("member_id") REFERENCES "members" ("id");

ALTER TABLE "notifications" ADD FOREIGN KEY ("loan_id") REFERENCES "loans" ("id");

ALTER TABLE "notifications" ADD FOREIGN KEY ("hold_id") REFERENCES "holds" ("id");
MySQL
mysql.sql MySQL
CREATE TABLE `publishers` (
  `id` uuid PRIMARY KEY,
  `name` varchar(200) NOT NULL,
  `city` varchar(120),
  `country` char(2) COMMENT 'ISO 3166-1 alpha-2'
);

CREATE TABLE `authors` (
  `id` uuid PRIMARY KEY,
  `sort_name` varchar(200) NOT NULL COMMENT 'Surname-first form used for shelving and browse, e.g. "Le Guin, Ursula K."',
  `display_name` varchar(200) NOT NULL,
  `birth_year` smallint,
  `death_year` smallint
);

CREATE TABLE `series` (
  `id` uuid PRIMARY KEY,
  `title` varchar(300) NOT NULL
);

CREATE TABLE `subjects` (
  `id` uuid PRIMARY KEY,
  `heading` varchar(300) UNIQUE NOT NULL COMMENT 'Controlled heading, e.g. a Library of Congress subject heading',
  `parent_id` uuid COMMENT 'Broader heading, for browsing narrower-to-broader'
);

CREATE TABLE `books` (
  `id` uuid PRIMARY KEY,
  `title` varchar(500) NOT NULL,
  `subtitle` varchar(500),
  `isbn13` char(13) UNIQUE COMMENT 'Null for items that predate ISBNs or never had one',
  `edition` varchar(60),
  `publisher_id` uuid,
  `publication_year` smallint,
  `language` char(3) NOT NULL DEFAULT 'eng' COMMENT 'ISO 639-2 code',
  `format` ENUM ('print', 'large_print', 'ebook', 'audiobook', 'dvd', 'periodical') NOT NULL,
  `call_number` varchar(60) COMMENT 'Classification shelf mark, e.g. Dewey 813.54 LEG',
  `series_id` uuid,
  `series_position` smallint,
  `page_count` integer,
  `summary` text,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `book_contributors` (
  `book_id` uuid NOT NULL,
  `author_id` uuid NOT NULL,
  `role` ENUM ('author', 'editor', 'translator', 'illustrator', 'narrator') NOT NULL DEFAULT 'author',
  `position` smallint NOT NULL DEFAULT 1 COMMENT 'Order of credit on the title page',
  PRIMARY KEY (`book_id`, `author_id`, `role`)
);

CREATE TABLE `book_subjects` (
  `book_id` uuid NOT NULL,
  `subject_id` uuid NOT NULL,
  PRIMARY KEY (`book_id`, `subject_id`)
);

CREATE TABLE `branches` (
  `id` uuid PRIMARY KEY,
  `code` varchar(10) UNIQUE NOT NULL,
  `name` varchar(200) NOT NULL,
  `address_line1` varchar(200),
  `city` varchar(120),
  `postal_code` varchar(20),
  `phone` varchar(30)
);

CREATE TABLE `shelf_locations` (
  `id` uuid PRIMARY KEY,
  `branch_id` uuid NOT NULL,
  `name` varchar(120) NOT NULL COMMENT 'e.g. "Adult Fiction", "Reference", "Picture Books"',
  `loanable` boolean NOT NULL DEFAULT true COMMENT 'Reference collections are on the shelf but never go home'
);

CREATE TABLE `copies` (
  `id` uuid PRIMARY KEY,
  `barcode` varchar(30) UNIQUE NOT NULL COMMENT 'What staff scan. The uuid is what foreign keys use.',
  `book_id` uuid NOT NULL,
  `branch_id` uuid NOT NULL COMMENT 'Owning branch',
  `shelf_location_id` uuid,
  `status` ENUM ('available', 'on_loan', 'on_hold_shelf', 'in_transit', 'in_repair', 'lost', 'withdrawn') NOT NULL DEFAULT 'available',
  `condition` ENUM ('new', 'good', 'worn', 'damaged') NOT NULL DEFAULT 'good',
  `acquired_on` date,
  `price_cents` integer COMMENT 'Replacement cost, used when the copy is billed as lost',
  `withdrawn_at` timestamptz
);

CREATE TABLE `transfers` (
  `id` uuid PRIMARY KEY,
  `copy_id` uuid NOT NULL,
  `from_branch_id` uuid NOT NULL,
  `to_branch_id` uuid NOT NULL,
  `hold_id` uuid COMMENT 'Set when the copy is travelling to fill a hold',
  `sent_at` timestamptz NOT NULL DEFAULT (now()),
  `received_at` timestamptz
);

CREATE TABLE `member_types` (
  `id` uuid PRIMARY KEY,
  `name` varchar(60) UNIQUE NOT NULL COMMENT 'e.g. Adult, Child, Student, Staff',
  `loan_limit` smallint NOT NULL DEFAULT 20,
  `loan_period_days` smallint NOT NULL DEFAULT 21,
  `renewal_limit` smallint NOT NULL DEFAULT 2,
  `hold_limit` smallint NOT NULL DEFAULT 10,
  `daily_fine_cents` integer NOT NULL DEFAULT 0,
  `max_fine_cents` integer NOT NULL DEFAULT 0 COMMENT 'Cap per loan; 0 with daily 0 means fine-free'
);

CREATE TABLE `members` (
  `id` uuid PRIMARY KEY,
  `card_number` varchar(30) UNIQUE NOT NULL,
  `member_type_id` uuid NOT NULL,
  `home_branch_id` uuid NOT NULL,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `email` varchar(254) UNIQUE,
  `phone` varchar(30),
  `date_of_birth` date,
  `address_line1` varchar(200),
  `city` varchar(120),
  `postal_code` varchar(20),
  `status` ENUM ('active', 'suspended', 'expired') NOT NULL DEFAULT 'active',
  `joined_on` date NOT NULL DEFAULT (current_date),
  `expires_on` date NOT NULL
);

CREATE TABLE `loans` (
  `id` uuid PRIMARY KEY,
  `copy_id` uuid NOT NULL,
  `member_id` uuid NOT NULL,
  `checkout_branch_id` uuid NOT NULL,
  `checked_out_by` uuid COMMENT 'Null for self-checkout kiosks',
  `checked_out_at` timestamptz NOT NULL DEFAULT (now()),
  `due_at` timestamptz NOT NULL COMMENT 'Computed from member_types.loan_period_days at checkout',
  `renewal_count` smallint NOT NULL DEFAULT 0,
  `returned_at` timestamptz COMMENT 'Null while the copy is out',
  `return_branch_id` uuid,
  `checked_in_by` uuid,
  `daily_fine_cents` integer NOT NULL COMMENT 'Snapshot of the member type rule at checkout'
);

CREATE TABLE `loan_renewals` (
  `id` uuid PRIMARY KEY,
  `loan_id` uuid NOT NULL,
  `renewed_at` timestamptz NOT NULL DEFAULT (now()),
  `previous_due_at` timestamptz NOT NULL,
  `new_due_at` timestamptz NOT NULL,
  `source` ENUM ('member', 'staff', 'automatic') NOT NULL
);

CREATE TABLE `holds` (
  `id` uuid PRIMARY KEY,
  `book_id` uuid NOT NULL COMMENT 'Holds are on the TITLE: any copy can fill one',
  `member_id` uuid NOT NULL,
  `pickup_branch_id` uuid NOT NULL,
  `placed_at` timestamptz NOT NULL DEFAULT (now()) COMMENT 'Queue order is placed_at; no stored position to keep renumbering',
  `status` ENUM ('waiting', 'in_transit', 'ready', 'fulfilled', 'cancelled', 'expired') NOT NULL DEFAULT 'waiting',
  `ready_copy_id` uuid COMMENT 'The copy set aside on the hold shelf',
  `ready_at` timestamptz,
  `pickup_by` date COMMENT 'Last day on the hold shelf before the hold expires',
  `fulfilled_loan_id` uuid,
  `cancelled_at` timestamptz
);

CREATE TABLE `fines` (
  `id` uuid PRIMARY KEY,
  `member_id` uuid NOT NULL,
  `loan_id` uuid COMMENT 'Null for charges not tied to a loan, e.g. a lost card',
  `reason` ENUM ('overdue', 'lost_item', 'damaged_item', 'replacement_card', 'processing') NOT NULL,
  `amount_cents` integer NOT NULL,
  `assessed_at` timestamptz NOT NULL DEFAULT (now()),
  `waived_at` timestamptz,
  `waived_by` uuid,
  `waive_reason` text
);

CREATE TABLE `payments` (
  `id` uuid PRIMARY KEY,
  `member_id` uuid NOT NULL,
  `amount_cents` integer NOT NULL,
  `method` ENUM ('cash', 'card', 'online') NOT NULL,
  `paid_at` timestamptz NOT NULL DEFAULT (now()),
  `received_by` uuid COMMENT 'Null for online payments',
  `external_reference` varchar(100) COMMENT 'Card processor transaction id'
);

CREATE TABLE `payment_allocations` (
  `payment_id` uuid NOT NULL,
  `fine_id` uuid NOT NULL,
  `amount_cents` integer NOT NULL,
  PRIMARY KEY (`payment_id`, `fine_id`)
);

CREATE TABLE `vendors` (
  `id` uuid PRIMARY KEY,
  `name` varchar(200) NOT NULL,
  `account_number` varchar(60),
  `email` varchar(254)
);

CREATE TABLE `purchase_orders` (
  `id` uuid PRIMARY KEY,
  `vendor_id` uuid NOT NULL,
  `branch_id` uuid NOT NULL COMMENT 'Receiving branch',
  `ordered_by` uuid NOT NULL,
  `status` ENUM ('draft', 'ordered', 'partially_received', 'received', 'cancelled') NOT NULL DEFAULT 'draft',
  `ordered_at` timestamptz
);

CREATE TABLE `purchase_order_lines` (
  `id` uuid PRIMARY KEY,
  `purchase_order_id` uuid NOT NULL,
  `book_id` uuid NOT NULL,
  `quantity` smallint NOT NULL,
  `unit_price_cents` integer NOT NULL,
  `received_quantity` smallint NOT NULL DEFAULT 0
);

CREATE TABLE `staff` (
  `id` uuid PRIMARY KEY,
  `branch_id` uuid NOT NULL,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `email` varchar(254) UNIQUE NOT NULL,
  `role` ENUM ('librarian', 'library_assistant', 'branch_manager', 'administrator') NOT NULL,
  `active` boolean NOT NULL DEFAULT true
);

CREATE TABLE `notifications` (
  `id` uuid PRIMARY KEY,
  `member_id` uuid NOT NULL,
  `kind` ENUM ('due_soon', 'overdue', 'hold_ready', 'hold_expiring', 'fine_assessed') NOT NULL,
  `channel` ENUM ('email', 'sms') NOT NULL,
  `loan_id` uuid,
  `hold_id` uuid,
  `sent_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE INDEX `books_index_0` ON `books` (`title`);

CREATE INDEX `books_index_1` ON `books` (`call_number`);

CREATE INDEX `copies_index_2` ON `copies` (`book_id`, `status`);

CREATE INDEX `loans_index_3` ON `loans` (`member_id`, `returned_at`);

CREATE INDEX `loans_index_4` ON `loans` (`copy_id`, `returned_at`);

CREATE INDEX `loans_index_5` ON `loans` (`due_at`);

CREATE INDEX `holds_index_6` ON `holds` (`book_id`, `status`, `placed_at`);

ALTER TABLE `publishers` COMMENT = 'Publishing houses. Kept separate from books so a rename or merger is one row.';

ALTER TABLE `authors` COMMENT = 'People and organizations credited on books, in any role.';

ALTER TABLE `series` COMMENT = 'A named run of books, e.g. a trilogy. Order lives on the book (series_position).';

ALTER TABLE `subjects` COMMENT = 'Controlled subject vocabulary. Free-text keywords belong in search, not here.';

ALTER TABLE `books` COMMENT = 'The BIBLIOGRAPHIC record: one row per title and edition, however many copies the
library owns. Holds are placed here; loans are made on a copy.
';

ALTER TABLE `book_contributors` COMMENT = 'Who is credited on a book and as what. A translator is not an author, and the catalog should say so.';

ALTER TABLE `book_subjects` COMMENT = 'Subject headings assigned to a book.';

ALTER TABLE `branches` COMMENT = 'Library locations. A single-site library still has exactly one row.';

ALTER TABLE `shelf_locations` COMMENT = 'Named collections within a branch.';

ALTER TABLE `copies` COMMENT = 'One physical item with a barcode. status is a cached convenience for the OPAC; the
authoritative "is it out?" answer is an open row in loans.
';

ALTER TABLE `transfers` COMMENT = 'Copies in transit between branches, usually to fill a hold at the pickup branch.';

ALTER TABLE `member_types` COMMENT = 'Borrowing rules by patron category. Loans copy the rules they were made under, so changing a rule never rewrites past loans.';

ALTER TABLE `members` COMMENT = 'Library patrons. A replacement card changes card_number and nothing else, so borrowing history survives.';

ALTER TABLE `loans` COMMENT = 'One row per checkout, kept forever as circulation history. An open loan is simply returned_at IS NULL.';

ALTER TABLE `loan_renewals` COMMENT = 'Every renewal, so "why is this due on the 14th?" has an answer. loans.due_at holds the current value.';

ALTER TABLE `holds` COMMENT = 'Reservation queue for a title. When a copy comes back, the oldest waiting hold for that book gets it.';

ALTER TABLE `fines` COMMENT = 'Charges owed. A waiver is recorded on the row, never by deleting it. Balance = fines not waived minus payment allocations.';

ALTER TABLE `payments` COMMENT = 'Money received from a member.';

ALTER TABLE `payment_allocations` COMMENT = 'Which fines a payment paid, and how much of each. Makes partial payments and one payment across several fines exact.';

ALTER TABLE `vendors` COMMENT = 'Suppliers the library orders from.';

ALTER TABLE `purchase_orders` COMMENT = 'An order to a vendor.';

ALTER TABLE `purchase_order_lines` COMMENT = 'Titles on an order. Receiving a line creates rows in copies.';

ALTER TABLE `staff` COMMENT = 'Library employees. Referenced from every action that needs an audit trail.';

ALTER TABLE `notifications` COMMENT = 'Due-soon, overdue and hold-ready notices actually sent, so a member who says "nobody told me" can be answered.';

ALTER TABLE `subjects` ADD FOREIGN KEY (`parent_id`) REFERENCES `subjects` (`id`);

ALTER TABLE `books` ADD FOREIGN KEY (`publisher_id`) REFERENCES `publishers` (`id`);

ALTER TABLE `books` ADD FOREIGN KEY (`series_id`) REFERENCES `series` (`id`);

ALTER TABLE `book_contributors` ADD FOREIGN KEY (`book_id`) REFERENCES `books` (`id`);

ALTER TABLE `book_contributors` ADD FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`);

ALTER TABLE `book_subjects` ADD FOREIGN KEY (`book_id`) REFERENCES `books` (`id`);

ALTER TABLE `book_subjects` ADD FOREIGN KEY (`subject_id`) REFERENCES `subjects` (`id`);

ALTER TABLE `shelf_locations` ADD FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`);

ALTER TABLE `copies` ADD FOREIGN KEY (`book_id`) REFERENCES `books` (`id`);

ALTER TABLE `copies` ADD FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`);

ALTER TABLE `copies` ADD FOREIGN KEY (`shelf_location_id`) REFERENCES `shelf_locations` (`id`);

ALTER TABLE `transfers` ADD FOREIGN KEY (`copy_id`) REFERENCES `copies` (`id`);

ALTER TABLE `transfers` ADD FOREIGN KEY (`from_branch_id`) REFERENCES `branches` (`id`);

ALTER TABLE `transfers` ADD FOREIGN KEY (`to_branch_id`) REFERENCES `branches` (`id`);

ALTER TABLE `transfers` ADD FOREIGN KEY (`hold_id`) REFERENCES `holds` (`id`);

ALTER TABLE `members` ADD FOREIGN KEY (`member_type_id`) REFERENCES `member_types` (`id`);

ALTER TABLE `members` ADD FOREIGN KEY (`home_branch_id`) REFERENCES `branches` (`id`);

ALTER TABLE `loans` ADD FOREIGN KEY (`copy_id`) REFERENCES `copies` (`id`);

ALTER TABLE `loans` ADD FOREIGN KEY (`member_id`) REFERENCES `members` (`id`);

ALTER TABLE `loans` ADD FOREIGN KEY (`checkout_branch_id`) REFERENCES `branches` (`id`);

ALTER TABLE `loans` ADD FOREIGN KEY (`checked_out_by`) REFERENCES `staff` (`id`);

ALTER TABLE `loans` ADD FOREIGN KEY (`return_branch_id`) REFERENCES `branches` (`id`);

ALTER TABLE `loans` ADD FOREIGN KEY (`checked_in_by`) REFERENCES `staff` (`id`);

ALTER TABLE `loan_renewals` ADD FOREIGN KEY (`loan_id`) REFERENCES `loans` (`id`);

ALTER TABLE `holds` ADD FOREIGN KEY (`book_id`) REFERENCES `books` (`id`);

ALTER TABLE `holds` ADD FOREIGN KEY (`member_id`) REFERENCES `members` (`id`);

ALTER TABLE `holds` ADD FOREIGN KEY (`pickup_branch_id`) REFERENCES `branches` (`id`);

ALTER TABLE `holds` ADD FOREIGN KEY (`ready_copy_id`) REFERENCES `copies` (`id`);

ALTER TABLE `holds` ADD FOREIGN KEY (`fulfilled_loan_id`) REFERENCES `loans` (`id`);

ALTER TABLE `fines` ADD FOREIGN KEY (`member_id`) REFERENCES `members` (`id`);

ALTER TABLE `fines` ADD FOREIGN KEY (`loan_id`) REFERENCES `loans` (`id`);

ALTER TABLE `fines` ADD FOREIGN KEY (`waived_by`) REFERENCES `staff` (`id`);

ALTER TABLE `payments` ADD FOREIGN KEY (`member_id`) REFERENCES `members` (`id`);

ALTER TABLE `payments` ADD FOREIGN KEY (`received_by`) REFERENCES `staff` (`id`);

ALTER TABLE `payment_allocations` ADD FOREIGN KEY (`payment_id`) REFERENCES `payments` (`id`);

ALTER TABLE `payment_allocations` ADD FOREIGN KEY (`fine_id`) REFERENCES `fines` (`id`);

ALTER TABLE `purchase_orders` ADD FOREIGN KEY (`vendor_id`) REFERENCES `vendors` (`id`);

ALTER TABLE `purchase_orders` ADD FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`);

ALTER TABLE `purchase_orders` ADD FOREIGN KEY (`ordered_by`) REFERENCES `staff` (`id`);

ALTER TABLE `purchase_order_lines` ADD FOREIGN KEY (`purchase_order_id`) REFERENCES `purchase_orders` (`id`);

ALTER TABLE `purchase_order_lines` ADD FOREIGN KEY (`book_id`) REFERENCES `books` (`id`);

ALTER TABLE `staff` ADD FOREIGN KEY (`branch_id`) REFERENCES `branches` (`id`);

ALTER TABLE `notifications` ADD FOREIGN KEY (`member_id`) REFERENCES `members` (`id`);

ALTER TABLE `notifications` ADD FOREIGN KEY (`loan_id`) REFERENCES `loans` (`id`);

ALTER TABLE `notifications` ADD FOREIGN KEY (`hold_id`) REFERENCES `holds` (`id`);
SQL Server
sql-server.sql SQL Server
CREATE TABLE [publishers] (
  [id] uuid PRIMARY KEY,
  [name] varchar(200) NOT NULL,
  [city] varchar(120),
  [country] char(2)
)
GO

CREATE TABLE [authors] (
  [id] uuid PRIMARY KEY,
  [sort_name] varchar(200) NOT NULL,
  [display_name] varchar(200) NOT NULL,
  [birth_year] smallint,
  [death_year] smallint
)
GO

CREATE TABLE [series] (
  [id] uuid PRIMARY KEY,
  [title] varchar(300) NOT NULL
)
GO

CREATE TABLE [subjects] (
  [id] uuid PRIMARY KEY,
  [heading] varchar(300) UNIQUE NOT NULL,
  [parent_id] uuid
)
GO

CREATE TABLE [books] (
  [id] uuid PRIMARY KEY,
  [title] varchar(500) NOT NULL,
  [subtitle] varchar(500),
  [isbn13] char(13) UNIQUE,
  [edition] varchar(60),
  [publisher_id] uuid,
  [publication_year] smallint,
  [language] char(3) NOT NULL DEFAULT 'eng',
  [format] nvarchar(255) NOT NULL CHECK ([format] IN ('print', 'large_print', 'ebook', 'audiobook', 'dvd', 'periodical')),
  [call_number] varchar(60),
  [series_id] uuid,
  [series_position] smallint,
  [page_count] integer,
  [summary] text,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [book_contributors] (
  [book_id] uuid NOT NULL,
  [author_id] uuid NOT NULL,
  [role] nvarchar(255) NOT NULL CHECK ([role] IN ('author', 'editor', 'translator', 'illustrator', 'narrator')) DEFAULT 'author',
  [position] smallint NOT NULL DEFAULT (1),
  PRIMARY KEY ([book_id], [author_id], [role])
)
GO

CREATE TABLE [book_subjects] (
  [book_id] uuid NOT NULL,
  [subject_id] uuid NOT NULL,
  PRIMARY KEY ([book_id], [subject_id])
)
GO

CREATE TABLE [branches] (
  [id] uuid PRIMARY KEY,
  [code] varchar(10) UNIQUE NOT NULL,
  [name] varchar(200) NOT NULL,
  [address_line1] varchar(200),
  [city] varchar(120),
  [postal_code] varchar(20),
  [phone] varchar(30)
)
GO

CREATE TABLE [shelf_locations] (
  [id] uuid PRIMARY KEY,
  [branch_id] uuid NOT NULL,
  [name] varchar(120) NOT NULL,
  [loanable] boolean NOT NULL DEFAULT (true)
)
GO

CREATE TABLE [copies] (
  [id] uuid PRIMARY KEY,
  [barcode] varchar(30) UNIQUE NOT NULL,
  [book_id] uuid NOT NULL,
  [branch_id] uuid NOT NULL,
  [shelf_location_id] uuid,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('available', 'on_loan', 'on_hold_shelf', 'in_transit', 'in_repair', 'lost', 'withdrawn')) DEFAULT 'available',
  [condition] nvarchar(255) NOT NULL CHECK ([condition] IN ('new', 'good', 'worn', 'damaged')) DEFAULT 'good',
  [acquired_on] date,
  [price_cents] integer,
  [withdrawn_at] timestamptz
)
GO

CREATE TABLE [transfers] (
  [id] uuid PRIMARY KEY,
  [copy_id] uuid NOT NULL,
  [from_branch_id] uuid NOT NULL,
  [to_branch_id] uuid NOT NULL,
  [hold_id] uuid,
  [sent_at] timestamptz NOT NULL DEFAULT (now()),
  [received_at] timestamptz
)
GO

CREATE TABLE [member_types] (
  [id] uuid PRIMARY KEY,
  [name] varchar(60) UNIQUE NOT NULL,
  [loan_limit] smallint NOT NULL DEFAULT (20),
  [loan_period_days] smallint NOT NULL DEFAULT (21),
  [renewal_limit] smallint NOT NULL DEFAULT (2),
  [hold_limit] smallint NOT NULL DEFAULT (10),
  [daily_fine_cents] integer NOT NULL DEFAULT (0),
  [max_fine_cents] integer NOT NULL DEFAULT (0)
)
GO

CREATE TABLE [members] (
  [id] uuid PRIMARY KEY,
  [card_number] varchar(30) UNIQUE NOT NULL,
  [member_type_id] uuid NOT NULL,
  [home_branch_id] uuid NOT NULL,
  [first_name] varchar(100) NOT NULL,
  [last_name] varchar(100) NOT NULL,
  [email] varchar(254) UNIQUE,
  [phone] varchar(30),
  [date_of_birth] date,
  [address_line1] varchar(200),
  [city] varchar(120),
  [postal_code] varchar(20),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('active', 'suspended', 'expired')) DEFAULT 'active',
  [joined_on] date NOT NULL DEFAULT (current_date),
  [expires_on] date NOT NULL
)
GO

CREATE TABLE [loans] (
  [id] uuid PRIMARY KEY,
  [copy_id] uuid NOT NULL,
  [member_id] uuid NOT NULL,
  [checkout_branch_id] uuid NOT NULL,
  [checked_out_by] uuid,
  [checked_out_at] timestamptz NOT NULL DEFAULT (now()),
  [due_at] timestamptz NOT NULL,
  [renewal_count] smallint NOT NULL DEFAULT (0),
  [returned_at] timestamptz,
  [return_branch_id] uuid,
  [checked_in_by] uuid,
  [daily_fine_cents] integer NOT NULL
)
GO

CREATE TABLE [loan_renewals] (
  [id] uuid PRIMARY KEY,
  [loan_id] uuid NOT NULL,
  [renewed_at] timestamptz NOT NULL DEFAULT (now()),
  [previous_due_at] timestamptz NOT NULL,
  [new_due_at] timestamptz NOT NULL,
  [source] nvarchar(255) NOT NULL CHECK ([source] IN ('member', 'staff', 'automatic'))
)
GO

CREATE TABLE [holds] (
  [id] uuid PRIMARY KEY,
  [book_id] uuid NOT NULL,
  [member_id] uuid NOT NULL,
  [pickup_branch_id] uuid NOT NULL,
  [placed_at] timestamptz NOT NULL DEFAULT (now()),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('waiting', 'in_transit', 'ready', 'fulfilled', 'cancelled', 'expired')) DEFAULT 'waiting',
  [ready_copy_id] uuid,
  [ready_at] timestamptz,
  [pickup_by] date,
  [fulfilled_loan_id] uuid,
  [cancelled_at] timestamptz
)
GO

CREATE TABLE [fines] (
  [id] uuid PRIMARY KEY,
  [member_id] uuid NOT NULL,
  [loan_id] uuid,
  [reason] nvarchar(255) NOT NULL CHECK ([reason] IN ('overdue', 'lost_item', 'damaged_item', 'replacement_card', 'processing')),
  [amount_cents] integer NOT NULL,
  [assessed_at] timestamptz NOT NULL DEFAULT (now()),
  [waived_at] timestamptz,
  [waived_by] uuid,
  [waive_reason] text
)
GO

CREATE TABLE [payments] (
  [id] uuid PRIMARY KEY,
  [member_id] uuid NOT NULL,
  [amount_cents] integer NOT NULL,
  [method] nvarchar(255) NOT NULL CHECK ([method] IN ('cash', 'card', 'online')),
  [paid_at] timestamptz NOT NULL DEFAULT (now()),
  [received_by] uuid,
  [external_reference] varchar(100)
)
GO

CREATE TABLE [payment_allocations] (
  [payment_id] uuid NOT NULL,
  [fine_id] uuid NOT NULL,
  [amount_cents] integer NOT NULL,
  PRIMARY KEY ([payment_id], [fine_id])
)
GO

CREATE TABLE [vendors] (
  [id] uuid PRIMARY KEY,
  [name] varchar(200) NOT NULL,
  [account_number] varchar(60),
  [email] varchar(254)
)
GO

CREATE TABLE [purchase_orders] (
  [id] uuid PRIMARY KEY,
  [vendor_id] uuid NOT NULL,
  [branch_id] uuid NOT NULL,
  [ordered_by] uuid NOT NULL,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('draft', 'ordered', 'partially_received', 'received', 'cancelled')) DEFAULT 'draft',
  [ordered_at] timestamptz
)
GO

CREATE TABLE [purchase_order_lines] (
  [id] uuid PRIMARY KEY,
  [purchase_order_id] uuid NOT NULL,
  [book_id] uuid NOT NULL,
  [quantity] smallint NOT NULL,
  [unit_price_cents] integer NOT NULL,
  [received_quantity] smallint NOT NULL DEFAULT (0)
)
GO

CREATE TABLE [staff] (
  [id] uuid PRIMARY KEY,
  [branch_id] uuid NOT NULL,
  [first_name] varchar(100) NOT NULL,
  [last_name] varchar(100) NOT NULL,
  [email] varchar(254) UNIQUE NOT NULL,
  [role] nvarchar(255) NOT NULL CHECK ([role] IN ('librarian', 'library_assistant', 'branch_manager', 'administrator')),
  [active] boolean NOT NULL DEFAULT (true)
)
GO

CREATE TABLE [notifications] (
  [id] uuid PRIMARY KEY,
  [member_id] uuid NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('due_soon', 'overdue', 'hold_ready', 'hold_expiring', 'fine_assessed')),
  [channel] nvarchar(255) NOT NULL CHECK ([channel] IN ('email', 'sms')),
  [loan_id] uuid,
  [hold_id] uuid,
  [sent_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE INDEX [books_index_0] ON [books] ("title")
GO

CREATE INDEX [books_index_1] ON [books] ("call_number")
GO

CREATE INDEX [copies_index_2] ON [copies] ("book_id", "status")
GO

CREATE INDEX [loans_index_3] ON [loans] ("member_id", "returned_at")
GO

CREATE INDEX [loans_index_4] ON [loans] ("copy_id", "returned_at")
GO

CREATE INDEX [loans_index_5] ON [loans] ("due_at")
GO

CREATE INDEX [holds_index_6] ON [holds] ("book_id", "status", "placed_at")
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Publishing houses. Kept separate from books so a rename or merger is one row.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'publishers';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'ISO 3166-1 alpha-2',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'publishers',
@level2type = N'Column', @level2name = 'country';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'People and organizations credited on books, in any role.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'authors';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Surname-first form used for shelving and browse, e.g. "Le Guin, Ursula K."',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'authors',
@level2type = N'Column', @level2name = 'sort_name';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A named run of books, e.g. a trilogy. Order lives on the book (series_position).',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'series';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Controlled subject vocabulary. Free-text keywords belong in search, not here.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'subjects';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Controlled heading, e.g. a Library of Congress subject heading',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'subjects',
@level2type = N'Column', @level2name = 'heading';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Broader heading, for browsing narrower-to-broader',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'subjects',
@level2type = N'Column', @level2name = 'parent_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The BIBLIOGRAPHIC record: one row per title and edition, however many copies the
library owns. Holds are placed here; loans are made on a copy.
',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'books';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for items that predate ISBNs or never had one',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'books',
@level2type = N'Column', @level2name = 'isbn13';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'ISO 639-2 code',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'books',
@level2type = N'Column', @level2name = 'language';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Classification shelf mark, e.g. Dewey 813.54 LEG',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'books',
@level2type = N'Column', @level2name = 'call_number';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Who is credited on a book and as what. A translator is not an author, and the catalog should say so.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'book_contributors';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Order of credit on the title page',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'book_contributors',
@level2type = N'Column', @level2name = 'position';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Subject headings assigned to a book.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'book_subjects';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Library locations. A single-site library still has exactly one row.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'branches';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Named collections within a branch.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'shelf_locations';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. "Adult Fiction", "Reference", "Picture Books"',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'shelf_locations',
@level2type = N'Column', @level2name = 'name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Reference collections are on the shelf but never go home',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'shelf_locations',
@level2type = N'Column', @level2name = 'loanable';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'One physical item with a barcode. status is a cached convenience for the OPAC; the
authoritative "is it out?" answer is an open row in loans.
',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'copies';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'What staff scan. The uuid is what foreign keys use.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'copies',
@level2type = N'Column', @level2name = 'barcode';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Owning branch',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'copies',
@level2type = N'Column', @level2name = 'branch_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Replacement cost, used when the copy is billed as lost',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'copies',
@level2type = N'Column', @level2name = 'price_cents';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Copies in transit between branches, usually to fill a hold at the pickup branch.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'transfers';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Set when the copy is travelling to fill a hold',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'transfers',
@level2type = N'Column', @level2name = 'hold_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Borrowing rules by patron category. Loans copy the rules they were made under, so changing a rule never rewrites past loans.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'member_types';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. Adult, Child, Student, Staff',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'member_types',
@level2type = N'Column', @level2name = 'name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Cap per loan; 0 with daily 0 means fine-free',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'member_types',
@level2type = N'Column', @level2name = 'max_fine_cents';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Library patrons. A replacement card changes card_number and nothing else, so borrowing history survives.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'members';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'One row per checkout, kept forever as circulation history. An open loan is simply returned_at IS NULL.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'loans';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for self-checkout kiosks',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'loans',
@level2type = N'Column', @level2name = 'checked_out_by';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Computed from member_types.loan_period_days at checkout',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'loans',
@level2type = N'Column', @level2name = 'due_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null while the copy is out',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'loans',
@level2type = N'Column', @level2name = 'returned_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Snapshot of the member type rule at checkout',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'loans',
@level2type = N'Column', @level2name = 'daily_fine_cents';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Every renewal, so "why is this due on the 14th?" has an answer. loans.due_at holds the current value.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'loan_renewals';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Reservation queue for a title. When a copy comes back, the oldest waiting hold for that book gets it.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'holds';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Holds are on the TITLE: any copy can fill one',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'holds',
@level2type = N'Column', @level2name = 'book_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Queue order is placed_at; no stored position to keep renumbering',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'holds',
@level2type = N'Column', @level2name = 'placed_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The copy set aside on the hold shelf',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'holds',
@level2type = N'Column', @level2name = 'ready_copy_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Last day on the hold shelf before the hold expires',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'holds',
@level2type = N'Column', @level2name = 'pickup_by';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Charges owed. A waiver is recorded on the row, never by deleting it. Balance = fines not waived minus payment allocations.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'fines';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for charges not tied to a loan, e.g. a lost card',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'fines',
@level2type = N'Column', @level2name = 'loan_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Money received from a member.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'payments';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for online payments',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'payments',
@level2type = N'Column', @level2name = 'received_by';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Card processor transaction id',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'payments',
@level2type = N'Column', @level2name = 'external_reference';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Which fines a payment paid, and how much of each. Makes partial payments and one payment across several fines exact.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'payment_allocations';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Suppliers the library orders from.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'vendors';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'An order to a vendor.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'purchase_orders';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Receiving branch',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'purchase_orders',
@level2type = N'Column', @level2name = 'branch_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Titles on an order. Receiving a line creates rows in copies.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'purchase_order_lines';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Library employees. Referenced from every action that needs an audit trail.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'staff';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Due-soon, overdue and hold-ready notices actually sent, so a member who says "nobody told me" can be answered.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'notifications';
GO

ALTER TABLE [subjects] ADD FOREIGN KEY ([parent_id]) REFERENCES [subjects] ([id])
GO

ALTER TABLE [books] ADD FOREIGN KEY ([publisher_id]) REFERENCES [publishers] ([id])
GO

ALTER TABLE [books] ADD FOREIGN KEY ([series_id]) REFERENCES [series] ([id])
GO

ALTER TABLE [book_contributors] ADD FOREIGN KEY ([book_id]) REFERENCES [books] ([id])
GO

ALTER TABLE [book_contributors] ADD FOREIGN KEY ([author_id]) REFERENCES [authors] ([id])
GO

ALTER TABLE [book_subjects] ADD FOREIGN KEY ([book_id]) REFERENCES [books] ([id])
GO

ALTER TABLE [book_subjects] ADD FOREIGN KEY ([subject_id]) REFERENCES [subjects] ([id])
GO

ALTER TABLE [shelf_locations] ADD FOREIGN KEY ([branch_id]) REFERENCES [branches] ([id])
GO

ALTER TABLE [copies] ADD FOREIGN KEY ([book_id]) REFERENCES [books] ([id])
GO

ALTER TABLE [copies] ADD FOREIGN KEY ([branch_id]) REFERENCES [branches] ([id])
GO

ALTER TABLE [copies] ADD FOREIGN KEY ([shelf_location_id]) REFERENCES [shelf_locations] ([id])
GO

ALTER TABLE [transfers] ADD FOREIGN KEY ([copy_id]) REFERENCES [copies] ([id])
GO

ALTER TABLE [transfers] ADD FOREIGN KEY ([from_branch_id]) REFERENCES [branches] ([id])
GO

ALTER TABLE [transfers] ADD FOREIGN KEY ([to_branch_id]) REFERENCES [branches] ([id])
GO

ALTER TABLE [transfers] ADD FOREIGN KEY ([hold_id]) REFERENCES [holds] ([id])
GO

ALTER TABLE [members] ADD FOREIGN KEY ([member_type_id]) REFERENCES [member_types] ([id])
GO

ALTER TABLE [members] ADD FOREIGN KEY ([home_branch_id]) REFERENCES [branches] ([id])
GO

ALTER TABLE [loans] ADD FOREIGN KEY ([copy_id]) REFERENCES [copies] ([id])
GO

ALTER TABLE [loans] ADD FOREIGN KEY ([member_id]) REFERENCES [members] ([id])
GO

ALTER TABLE [loans] ADD FOREIGN KEY ([checkout_branch_id]) REFERENCES [branches] ([id])
GO

ALTER TABLE [loans] ADD FOREIGN KEY ([checked_out_by]) REFERENCES [staff] ([id])
GO

ALTER TABLE [loans] ADD FOREIGN KEY ([return_branch_id]) REFERENCES [branches] ([id])
GO

ALTER TABLE [loans] ADD FOREIGN KEY ([checked_in_by]) REFERENCES [staff] ([id])
GO

ALTER TABLE [loan_renewals] ADD FOREIGN KEY ([loan_id]) REFERENCES [loans] ([id])
GO

ALTER TABLE [holds] ADD FOREIGN KEY ([book_id]) REFERENCES [books] ([id])
GO

ALTER TABLE [holds] ADD FOREIGN KEY ([member_id]) REFERENCES [members] ([id])
GO

ALTER TABLE [holds] ADD FOREIGN KEY ([pickup_branch_id]) REFERENCES [branches] ([id])
GO

ALTER TABLE [holds] ADD FOREIGN KEY ([ready_copy_id]) REFERENCES [copies] ([id])
GO

ALTER TABLE [holds] ADD FOREIGN KEY ([fulfilled_loan_id]) REFERENCES [loans] ([id])
GO

ALTER TABLE [fines] ADD FOREIGN KEY ([member_id]) REFERENCES [members] ([id])
GO

ALTER TABLE [fines] ADD FOREIGN KEY ([loan_id]) REFERENCES [loans] ([id])
GO

ALTER TABLE [fines] ADD FOREIGN KEY ([waived_by]) REFERENCES [staff] ([id])
GO

ALTER TABLE [payments] ADD FOREIGN KEY ([member_id]) REFERENCES [members] ([id])
GO

ALTER TABLE [payments] ADD FOREIGN KEY ([received_by]) REFERENCES [staff] ([id])
GO

ALTER TABLE [payment_allocations] ADD FOREIGN KEY ([payment_id]) REFERENCES [payments] ([id])
GO

ALTER TABLE [payment_allocations] ADD FOREIGN KEY ([fine_id]) REFERENCES [fines] ([id])
GO

ALTER TABLE [purchase_orders] ADD FOREIGN KEY ([vendor_id]) REFERENCES [vendors] ([id])
GO

ALTER TABLE [purchase_orders] ADD FOREIGN KEY ([branch_id]) REFERENCES [branches] ([id])
GO

ALTER TABLE [purchase_orders] ADD FOREIGN KEY ([ordered_by]) REFERENCES [staff] ([id])
GO

ALTER TABLE [purchase_order_lines] ADD FOREIGN KEY ([purchase_order_id]) REFERENCES [purchase_orders] ([id])
GO

ALTER TABLE [purchase_order_lines] ADD FOREIGN KEY ([book_id]) REFERENCES [books] ([id])
GO

ALTER TABLE [staff] ADD FOREIGN KEY ([branch_id]) REFERENCES [branches] ([id])
GO

ALTER TABLE [notifications] ADD FOREIGN KEY ([member_id]) REFERENCES [members] ([id])
GO

ALTER TABLE [notifications] ADD FOREIGN KEY ([loan_id]) REFERENCES [loans] ([id])
GO

ALTER TABLE [notifications] ADD FOREIGN KEY ([hold_id]) REFERENCES [holds] ([id])
GO

How to use this template

  1. Open the ER diagram to see the tables and how they relate.
  2. Copy it into your workspace. You get your own editable copy, in DBML.
  3. Export it as PostgreSQL, MySQL, or SQL Server DDL, or as Prisma, Drizzle, SQLAlchemy, TypeScript, Zod or C# models.

The copy opens in DB Planner’s ER diagram tool, with the schema as text in the DBML editor beside it. Have a database already? Turn its SQL into an ER diagram instead.

Frequently asked questions

Which table is at the centre of the Library Management System database schema?
branches. It is referenced by 8 other tables: copies, holds, loans, members, purchase_orders and 3 more.
How is copies related to branches?
copies.branch_id references branches.id, a many to one relationship. All 45 relationships in the schema are listed on this page.
Which table in the Library Management System database schema has the most columns?
books, with 15 columns, followed by members (15) and loans (12). The schema has 164 columns across 24 tables.
Can I export it to PostgreSQL or MySQL?
Yes. Every DB Planner template exports as DBML, as PostgreSQL, MySQL, or SQL Server DDL, and as C# models.
Is this template free?
Yes. You can open it in the browser without an account, and copy it into your own workspace with a free DB Planner account.
Can I change it after copying it?
Yes. A copy is yours: you can rename tables, add columns, and export it. Changes the author makes later do not affect your copy.