--- a/engine.sql
+++ b/engine.sql
@@ -165,16 +165,22 @@
     -- disconnect all previously opened connections
     PERFORM dblink_disconnect(unnest(dblink_get_connections()));
 
-    -- start parallel jobs
-    FOR i IN 1 .. jobs LOOP
-        connname := 'job' || i;
-        PERFORM dblink_connect(connname, current_setting('gen.connstr'));
-        res := CASE dblink_send_query(connname, format('CALL process_queue(%L)',end_date))
-            WHEN 1 THEN 'ok' ELSE 'FAILED'
-        END CASE;
-        CALL log_message(0, format('Job %s (connname=%s): %s', i, connname, res));
-        RAISE NOTICE 'Starting job %: %', i, res;
-    END LOOP;
+    IF jobs = 1 THEN
+        -- jobs=1: синхронно, чтобы не убивать dblink-сессию при выходе из psql
+        CALL process_queue(end_date);
+        CALL log_message(0, 'Job 1 (local): ok');
+    ELSE
+        -- start parallel jobs
+        FOR i IN 1 .. jobs LOOP
+            connname := 'job' || i;
+            PERFORM dblink_connect(connname, current_setting('gen.connstr'));
+            res := CASE dblink_send_query(connname, format('CALL process_queue(%L)',end_date))
+                WHEN 1 THEN 'ok' ELSE 'FAILED'
+            END CASE;
+            CALL log_message(0, format('Job %s (connname=%s): %s', i, connname, res));
+            RAISE NOTICE 'Starting job %: %', i, res;
+        END LOOP;
+    END IF;
 
     -- re-create booking.now()
     EXECUTE format(
@@ -230,7 +236,8 @@
     SELECT count(*) > 0
     FROM pg_stat_activity
     WHERE application_name = 'Airlines processor'
-      AND state != 'idle';
+      AND state != 'idle'
+      AND pid <> pg_backend_pid();
 END;
 
 /*
