在这里工作(第 9.1 页):
-- Domain with only values 1 ... 9 allowed,
-- used for both the {x,y,z} coordinates and the cell values.
CREATE DOMAIN one_nine
AS INTEGER
CHECK (value >= 1 AND value <= 9)
;
CREATE DOMAIN one_nine_notnull
AS INTEGER NOT NULL
CHECK (value >= 1 AND value <= 9)
;
CREATE TABLE all_numbers
(val one_nine_notnull PRIMARY KEY
);
INSERT INTO all_numbers(val)
SELECT nn FROM generate_series(1,9) AS nn;
-- Table containing exactly one sudoku puzzle.
-- The zzz coordinate (the "box number") is formally redundant
-- (since it is functionally dependant on {xxx,yyy})
DROP TABLE IF EXISTS sudoku3 CASCADE;
CREATE TABLE sudoku3
( yyy one_nine_notnull
, xxx one_nine_notnull
, zzz one_nine_notnull
, val one_nine
);
INSERT INTO sudoku3 (yyy,xxx,zzz,val) VALUES ( NULL, 3, 1, 4);
INSERT INTO sudoku3 (yyy,xxx,zzz,val) VALUES ( 1, 3, 1, 14);
-- Conveniance view with 3-width horizontal and vertical bands
CREATE VIEW v_sudoku AS (
SELECT yyy,xxx,zzz
, val
, (xxx+2)/ 3 as x3
, (yyy+2)/ 3 as y3
FROM sudoku3
)
;
-- First constraint: (x,y) is unique
ALTER TABLE sudoku3 ADD PRIMARY KEY (xxx,yyy);
-- Three constraints for unique values for {rows,columns,boxes}
CREATE UNIQUE INDEX sudoku_xv ON sudoku3 (xxx,val);
CREATE UNIQUE INDEX sudoku_yv ON sudoku3 (yyy,val);
CREATE UNIQUE INDEX sudoku_zv ON sudoku3 (zzz,val);
输出:
drop cascades to type w00t.one_nine_notnull
drop cascades to table w00t.all_numbers
drop cascades to table w00t.sudoku3
drop cascades to view w00t.v_sudoku
drop cascades to view w00t.sudoku_row
drop cascades to view w00t.valid_moves
drop cascades to view w00t.low_hanging_fruit
drop cascades to view w00t.magic_moves
drop cascades to function w00t.sudoku_magic()
DROP SCHEMA
CREATE SCHEMA
SET
CREATE DOMAIN
CREATE DOMAIN
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "all_numbers_pkey" for table "all_numbers"
CREATE TABLE
INSERT 0 9
NOTICE: table "sudoku3" does not exist, skipping
DROP TABLE
CREATE TABLE
ERROR: domain one_nine_notnull does not allow null values
ERROR: value for domain one_nine violates check constraint "one_nine_check"
CREATE VIEW
NOTICE: ALTER TABLE / ADD PRIMARY KEY will create implicit index "sudoku3_pkey" for table "sudoku3"
ALTER TABLE
CREATE INDEX
CREATE INDEX
CREATE INDEX
INSERT 0 81
...