askrobots / postblob Public

An experimental web framework where PostgreSQL does everything: routing, HTML, file storage, jobs and sessions.

0 downloads

postblob/init_postblob_simple.sql
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/postblob.git
HTTPS
https://gitstable.com/git/askrobots/postblob.git
SSH
ssh://git@gitstable.com:2222/askrobots/postblob.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 docs: Add screenshots to README ae44e69 1 year, 2 months ago History
init_postblob_simple.sql · 17.8 KB · 580 lines
1-- PostBlob Database: PostgreSQL-powered application (No PL/Python Required)
2-- Create database: createdb postblob
3-- Initialize: psql postblob < init_postblob_simple.sql
4
5-- Enable extensions
6CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
7CREATE EXTENSION IF NOT EXISTS "pgcrypto";
8
9-- =============================================
10-- CORE TABLES
11-- =============================================
12
13-- File/blob storage
14CREATE TABLE IF NOT EXISTS blobs (
15 id uuid DEFAULT uuid_generate_v4() PRIMARY KEY,
16 filename text NOT NULL,
17 mimetype text NOT NULL,
18 data bytea NOT NULL,
19 size bigint NOT NULL,
20 metadata jsonb DEFAULT '{}'::jsonb,
21 created_at timestamptz DEFAULT now(),
22 updated_at timestamptz DEFAULT now()
23);
24
25-- Job queue
26CREATE TABLE IF NOT EXISTS jobs (
27 id serial PRIMARY KEY,
28 type text NOT NULL,
29 payload jsonb DEFAULT '{}'::jsonb,
30 status text DEFAULT 'pending' CHECK (status IN ('pending', 'processing', 'completed', 'failed')),
31 result jsonb,
32 attempts integer DEFAULT 0,
33 created_at timestamptz DEFAULT now(),
34 started_at timestamptz,
35 completed_at timestamptz
36);
37
38-- Exception storage
39CREATE TABLE IF NOT EXISTS exceptions (
40 id serial PRIMARY KEY,
41 error_type text NOT NULL,
42 message text NOT NULL,
43 traceback text,
44 context jsonb DEFAULT '{}'::jsonb,
45 function_name text,
46 occurred_at timestamptz DEFAULT now(),
47 resolved boolean DEFAULT false
48);
49
50-- Sessions
51CREATE TABLE IF NOT EXISTS sessions (
52 id uuid DEFAULT uuid_generate_v4() PRIMARY KEY,
53 data jsonb DEFAULT '{}'::jsonb,
54 created_at timestamptz DEFAULT now(),
55 expires_at timestamptz DEFAULT (now() + interval '24 hours'),
56 last_access timestamptz DEFAULT now()
57);
58
59-- Key-value cache
60CREATE TABLE IF NOT EXISTS cache (
61 key text PRIMARY KEY,
62 value jsonb NOT NULL,
63 expires_at timestamptz,
64 created_at timestamptz DEFAULT now()
65);
66
67-- Circuit breakers
68CREATE TABLE IF NOT EXISTS circuit_breakers (
69 function_name text PRIMARY KEY,
70 state text DEFAULT 'closed' CHECK (state IN ('closed', 'open', 'half_open')),
71 failure_count integer DEFAULT 0,
72 last_failure timestamptz,
73 last_success timestamptz
74);
75
76-- =============================================
77-- API Routes Table (Instead of PL/Python)
78-- =============================================
79
80CREATE TABLE IF NOT EXISTS routes (
81 id serial PRIMARY KEY,
82 method text NOT NULL,
83 path_pattern text NOT NULL,
84 handler text NOT NULL,
85 description text,
86 UNIQUE(method, path_pattern)
87);
88
89-- Insert default routes
90INSERT INTO routes (method, path_pattern, handler, description) VALUES
91('GET', '/', 'home', 'Welcome page'),
92('GET', '/stats', 'stats', 'Database statistics'),
93('GET', '/blobs', 'list_blobs', 'List all blobs'),
94('GET', '/blob/:id', 'get_blob', 'Get specific blob'),
95('POST', '/blob', 'create_blob', 'Upload new blob'),
96('DELETE', '/blob/:id', 'delete_blob', 'Delete blob'),
97('GET', '/jobs', 'list_jobs', 'List all jobs'),
98('POST', '/job', 'create_job', 'Create new job'),
99('GET', '/job/:id', 'get_job', 'Get job status')
100ON CONFLICT DO NOTHING;
101
102-- =============================================
103-- PL/pgSQL FUNCTIONS (No Python needed)
104-- =============================================
105
106-- Main request handler using PL/pgSQL
107CREATE OR REPLACE FUNCTION handle_request(
108 p_method text,
109 p_path text,
110 p_headers jsonb DEFAULT '{}'::jsonb,
111 p_body jsonb DEFAULT '{}'::jsonb,
112 p_session_id uuid DEFAULT NULL
113) RETURNS jsonb AS $$
114DECLARE
115 v_response jsonb;
116 v_route record;
117 v_blob_id uuid;
118 v_job_id integer;
119 v_stats jsonb;
120BEGIN
121 -- Default response
122 v_response := jsonb_build_object(
123 'status', 404,
124 'body', jsonb_build_object('error', 'Not found')
125 );
126
127 -- Route: GET /
128 IF p_method = 'GET' AND p_path = '/' THEN
129 v_response := jsonb_build_object(
130 'status', 200,
131 'body', jsonb_build_object(
132 'message', 'Welcome to PostBlob!',
133 'endpoints', jsonb_build_array(
134 '/blobs', '/jobs', '/stats'
135 )
136 )
137 );
138
139 -- Route: GET /stats
140 ELSIF p_method = 'GET' AND p_path = '/stats' THEN
141 SELECT jsonb_build_object(
142 'blob_count', (SELECT COUNT(*) FROM blobs),
143 'total_size', COALESCE((SELECT SUM(size) FROM blobs), 0),
144 'jobs_completed', (SELECT COUNT(*) FROM jobs WHERE status = 'completed'),
145 'total_exceptions', (SELECT COUNT(*) FROM exceptions),
146 'active_sessions', (SELECT COUNT(*) FROM sessions WHERE expires_at > now())
147 ) INTO v_stats;
148
149 v_response := jsonb_build_object(
150 'status', 200,
151 'body', v_stats
152 );
153
154 -- Route: GET /blobs
155 ELSIF p_method = 'GET' AND p_path = '/blobs' THEN
156 v_response := jsonb_build_object(
157 'status', 200,
158 'body', (
159 SELECT COALESCE(jsonb_agg(
160 jsonb_build_object(
161 'id', id,
162 'filename', filename,
163 'size', size,
164 'mimetype', mimetype,
165 'created_at', created_at
166 ) ORDER BY created_at DESC
167 ), '[]'::jsonb)
168 FROM blobs
169 LIMIT 100
170 )
171 );
172
173 -- Route: GET /blob/{id}
174 ELSIF p_method = 'GET' AND p_path LIKE '/blob/%' THEN
175 v_blob_id := substring(p_path from '/blob/(.+)')::uuid;
176
177 SELECT jsonb_build_object(
178 'id', id,
179 'filename', filename,
180 'size', size,
181 'mimetype', mimetype,
182 'metadata', metadata,
183 'created_at', created_at
184 ) INTO v_response
185 FROM blobs
186 WHERE id = v_blob_id;
187
188 IF v_response IS NOT NULL THEN
189 v_response := jsonb_build_object(
190 'status', 200,
191 'body', v_response
192 );
193 ELSE
194 v_response := jsonb_build_object(
195 'status', 404,
196 'body', jsonb_build_object('error', 'Blob not found')
197 );
198 END IF;
199
200 -- Route: POST /blob
201 ELSIF p_method = 'POST' AND p_path = '/blob' THEN
202 INSERT INTO blobs (filename, mimetype, data, size, metadata)
203 VALUES (
204 COALESCE(p_body->>'filename', 'unnamed'),
205 COALESCE(p_body->>'mimetype', 'application/octet-stream'),
206 decode(p_body->>'data', 'base64'),
207 length(decode(p_body->>'data', 'base64')),
208 COALESCE(p_body->'metadata', '{}'::jsonb)
209 )
210 RETURNING id INTO v_blob_id;
211
212 v_response := jsonb_build_object(
213 'status', 201,
214 'body', jsonb_build_object(
215 'id', v_blob_id,
216 'url', '/blob/' || v_blob_id
217 )
218 );
219
220 -- Route: DELETE /blob/{id}
221 ELSIF p_method = 'DELETE' AND p_path LIKE '/blob/%' THEN
222 v_blob_id := substring(p_path from '/blob/(.+)')::uuid;
223
224 DELETE FROM blobs WHERE id = v_blob_id;
225
226 IF FOUND THEN
227 v_response := jsonb_build_object(
228 'status', 200,
229 'body', jsonb_build_object('deleted', v_blob_id)
230 );
231 ELSE
232 v_response := jsonb_build_object(
233 'status', 404,
234 'body', jsonb_build_object('error', 'Blob not found')
235 );
236 END IF;
237
238 -- Route: GET /jobs
239 ELSIF p_method = 'GET' AND p_path = '/jobs' THEN
240 v_response := jsonb_build_object(
241 'status', 200,
242 'body', (
243 SELECT COALESCE(jsonb_agg(
244 jsonb_build_object(
245 'id', id,
246 'type', type,
247 'status', status,
248 'created_at', created_at,
249 'completed_at', completed_at
250 ) ORDER BY created_at DESC
251 ), '[]'::jsonb)
252 FROM jobs
253 LIMIT 100
254 )
255 );
256
257 -- Route: POST /job
258 ELSIF p_method = 'POST' AND p_path = '/job' THEN
259 INSERT INTO jobs (type, payload)
260 VALUES (
261 COALESCE(p_body->>'type', 'default'),
262 COALESCE(p_body->'payload', '{}'::jsonb)
263 )
264 RETURNING id INTO v_job_id;
265
266 -- Notify job worker
267 PERFORM pg_notify('new_job', v_job_id::text);
268
269 v_response := jsonb_build_object(
270 'status', 201,
271 'body', jsonb_build_object(
272 'job_id', v_job_id,
273 'status', 'pending'
274 )
275 );
276
277 -- Route: GET /job/{id}
278 ELSIF p_method = 'GET' AND p_path LIKE '/job/%' THEN
279 v_job_id := substring(p_path from '/job/(\d+)')::integer;
280
281 SELECT jsonb_build_object(
282 'id', id,
283 'type', type,
284 'status', status,
285 'payload', payload,
286 'result', result,
287 'created_at', created_at,
288 'completed_at', completed_at
289 ) INTO v_response
290 FROM jobs
291 WHERE id = v_job_id;
292
293 IF v_response IS NOT NULL THEN
294 v_response := jsonb_build_object(
295 'status', 200,
296 'body', v_response
297 );
298 ELSE
299 v_response := jsonb_build_object(
300 'status', 404,
301 'body', jsonb_build_object('error', 'Job not found')
302 );
303 END IF;
304 END IF;
305
306 RETURN v_response;
307END;
308$$ LANGUAGE plpgsql;
309
310-- =============================================
311-- JOB PROCESSOR (PL/pgSQL version)
312-- =============================================
313
314CREATE OR REPLACE FUNCTION process_job(p_job_id integer)
315RETURNS void AS $$
316DECLARE
317 v_job record;
318 v_result jsonb;
319BEGIN
320 -- Get job details
321 SELECT * INTO v_job FROM jobs WHERE id = p_job_id FOR UPDATE;
322
323 IF NOT FOUND OR v_job.status != 'pending' THEN
324 RETURN;
325 END IF;
326
327 -- Mark as processing
328 UPDATE jobs
329 SET status = 'processing', started_at = now()
330 WHERE id = p_job_id;
331
332 -- Process different job types
333 BEGIN
334 CASE v_job.type
335 WHEN 'cleanup' THEN
336 -- Clean old sessions and cache
337 DELETE FROM sessions WHERE expires_at < now();
338 DELETE FROM cache WHERE expires_at < now();
339 v_result := jsonb_build_object(
340 'status', 'success',
341 'message', 'Cleanup completed'
342 );
343
344 WHEN 'compute' THEN
345 -- Simple computation
346 v_result := jsonb_build_object(
347 'result', (COALESCE((v_job.payload->>'value')::integer, 0) * 2)
348 );
349
350 WHEN 'analyze_blobs' THEN
351 -- Analyze blob storage
352 v_result := jsonb_build_object(
353 'total_blobs', (SELECT COUNT(*) FROM blobs),
354 'total_size', (SELECT COALESCE(SUM(size), 0) FROM blobs),
355 'avg_size', (SELECT COALESCE(AVG(size), 0) FROM blobs)
356 );
357
358 ELSE
359 -- Unknown job type
360 v_result := jsonb_build_object(
361 'error', format('Unknown job type: %s', v_job.type)
362 );
363 END CASE;
364
365 -- Mark as completed
366 UPDATE jobs
367 SET status = 'completed',
368 result = v_result,
369 completed_at = now()
370 WHERE id = p_job_id;
371
372 EXCEPTION WHEN OTHERS THEN
373 -- Mark as failed
374 UPDATE jobs
375 SET status = 'failed',
376 result = jsonb_build_object(
377 'error', SQLERRM,
378 'detail', SQLSTATE
379 ),
380 attempts = attempts + 1
381 WHERE id = p_job_id;
382
383 -- Log exception
384 INSERT INTO exceptions (error_type, message, context, function_name)
385 VALUES (
386 SQLSTATE,
387 SQLERRM,
388 jsonb_build_object('job_id', p_job_id, 'job_type', v_job.type),
389 'process_job'
390 );
391 END;
392END;
393$$ LANGUAGE plpgsql;
394
395-- =============================================
396-- CACHE FUNCTIONS
397-- =============================================
398
399CREATE OR REPLACE FUNCTION cache_get(p_key text)
400RETURNS jsonb AS $$
401BEGIN
402 -- Clean expired entries
403 DELETE FROM cache WHERE expires_at < now();
404
405 RETURN (SELECT value FROM cache WHERE key = p_key);
406END;
407$$ LANGUAGE plpgsql;
408
409CREATE OR REPLACE FUNCTION cache_set(
410 p_key text,
411 p_value jsonb,
412 p_ttl_seconds integer DEFAULT 3600
413) RETURNS void AS $$
414BEGIN
415 INSERT INTO cache (key, value, expires_at)
416 VALUES (p_key, p_value, now() + (p_ttl_seconds || ' seconds')::interval)
417 ON CONFLICT (key) DO UPDATE
418 SET value = EXCLUDED.value,
419 expires_at = EXCLUDED.expires_at,
420 created_at = now();
421END;
422$$ LANGUAGE plpgsql;
423
424-- =============================================
425-- NATURAL LANGUAGE QUERY (PL/pgSQL version)
426-- =============================================
427
428CREATE OR REPLACE FUNCTION ask(question text)
429RETURNS jsonb AS $$
430DECLARE
431 sql_query text;
432 result jsonb;
433 word_count integer;
434BEGIN
435 -- Normalize input
436 question := lower(trim(question));
437
438 -- Simple pattern matching for common queries
439 sql_query := CASE
440 -- "show blobs" or "list blobs"
441 WHEN question ~ '^(show|list)\s+blobs?$' THEN
442 'SELECT * FROM blobs ORDER BY created_at DESC LIMIT 10'
443
444 -- "count blobs"
445 WHEN question ~ '^count\s+blobs?$' THEN
446 'SELECT COUNT(*) as count FROM blobs'
447
448 -- "show jobs" or "list jobs"
449 WHEN question ~ '^(show|list)\s+jobs?$' THEN
450 'SELECT * FROM jobs ORDER BY created_at DESC LIMIT 10'
451
452 -- "pending jobs"
453 WHEN question ~ '^pending\s+jobs?$' THEN
454 'SELECT * FROM jobs WHERE status = ''pending'''
455
456 -- "failed jobs"
457 WHEN question ~ '^failed\s+jobs?$' THEN
458 'SELECT * FROM jobs WHERE status = ''failed'''
459
460 -- "completed jobs"
461 WHEN question ~ '^completed\s+jobs?$' THEN
462 'SELECT * FROM jobs WHERE status = ''completed'''
463
464 -- "show stats" or "statistics"
465 WHEN question ~ '^(show\s+)?stats|statistics$' THEN
466 'SELECT
467 (SELECT COUNT(*) FROM blobs) as blob_count,
468 (SELECT COUNT(*) FROM jobs) as job_count,
469 (SELECT COUNT(*) FROM sessions WHERE expires_at > now()) as active_sessions'
470
471 -- "biggest blob" or "largest file"
472 WHEN question ~ '^(biggest|largest)\s+(blob|file)$' THEN
473 'SELECT * FROM blobs ORDER BY size DESC LIMIT 1'
474
475 -- "newest blob" or "latest file"
476 WHEN question ~ '^(newest|latest)\s+(blob|file)$' THEN
477 'SELECT * FROM blobs ORDER BY created_at DESC LIMIT 1'
478
479 -- "show 5 blobs" (with number)
480 WHEN question ~ '^show\s+(\d+)\s+blobs?$' THEN
481 format('SELECT * FROM blobs ORDER BY created_at DESC LIMIT %s',
482 (regexp_match(question, 'show\s+(\d+)', 'i'))[1])
483
484 ELSE
485 NULL
486 END;
487
488 IF sql_query IS NULL THEN
489 RETURN jsonb_build_object(
490 'error', 'Could not understand query',
491 'original', question,
492 'hint', 'Try: "show blobs", "count jobs", "failed jobs", "show stats"'
493 );
494 END IF;
495
496 -- Execute the query
497 BEGIN
498 EXECUTE 'SELECT jsonb_agg(row_to_json(t)) FROM (' || sql_query || ') t' INTO result;
499
500 IF result IS NULL THEN
501 result := '[]'::jsonb;
502 END IF;
503
504 RETURN jsonb_build_object(
505 'success', true,
506 'sql', sql_query,
507 'data', result
508 );
509 EXCEPTION WHEN OTHERS THEN
510 RETURN jsonb_build_object(
511 'error', SQLERRM,
512 'sql', sql_query,
513 'original', question
514 );
515 END;
516END;
517$$ LANGUAGE plpgsql;
518
519-- =============================================
520-- INDEXES
521-- =============================================
522
523CREATE INDEX IF NOT EXISTS idx_jobs_status ON jobs(status, created_at);
524CREATE INDEX IF NOT EXISTS idx_blobs_created ON blobs(created_at DESC);
525CREATE INDEX IF NOT EXISTS idx_exceptions_occurred ON exceptions(occurred_at DESC);
526CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at);
527CREATE INDEX IF NOT EXISTS idx_cache_expires ON cache(expires_at);
528
529-- =============================================
530-- TRIGGERS
531-- =============================================
532
533-- Job notification trigger
534CREATE OR REPLACE FUNCTION notify_new_job() RETURNS trigger AS $$
535BEGIN
536 PERFORM pg_notify('new_job', NEW.id::text);
537 RETURN NEW;
538END;
539$$ LANGUAGE plpgsql;
540
541DROP TRIGGER IF EXISTS job_created ON jobs;
542CREATE TRIGGER job_created
543 AFTER INSERT ON jobs
544 FOR EACH ROW
545 EXECUTE FUNCTION notify_new_job();
546
547-- =============================================
548-- INITIAL DATA
549-- =============================================
550
551-- Create a welcome blob
552INSERT INTO blobs (filename, mimetype, data, size, metadata)
553VALUES (
554 'welcome.txt',
555 'text/plain',
556 'Welcome to PostBlob - PostgreSQL powers everything!'::bytea,
557 length('Welcome to PostBlob - PostgreSQL powers everything!'),
558 '{"type": "system", "description": "Welcome message"}'::jsonb
559) ON CONFLICT DO NOTHING;
560
561-- Create sample jobs
562INSERT INTO jobs (type, payload, status) VALUES
563 ('cleanup', '{"description": "Initial cleanup"}'::jsonb, 'pending'),
564 ('analyze_blobs', '{"description": "Analyze storage"}'::jsonb, 'pending')
565ON CONFLICT DO NOTHING;
566
567-- Success message
568DO $$
569BEGIN
570 RAISE NOTICE '';
571 RAISE NOTICE '========================================';
572 RAISE NOTICE 'PostBlob database initialized!';
573 RAISE NOTICE '========================================';
574 RAISE NOTICE 'Tables created: blobs, jobs, sessions, cache, exceptions';
575 RAISE NOTICE 'Functions ready: handle_request(), process_job(), ask()';
576 RAISE NOTICE '';
577 RAISE NOTICE 'Try: SELECT ask(''show blobs'');';
578 RAISE NOTICE ' SELECT ask(''count jobs'');';
579 RAISE NOTICE ' SELECT ask(''show stats'');';
580END $$;