unknown 6 godzin temu
rodzic
commit
9c324e4533

+ 19 - 89
.obsidian/workspace.json

@@ -4,109 +4,39 @@
     "type": "split",
     "children": [
       {
-        "id": "c5ca57fb4db777a9",
+        "id": "0d514b8a15319f53",
         "type": "tabs",
         "children": [
           {
-            "id": "8e66644a45b88361",
+            "id": "d71e50b2479be430",
             "type": "leaf",
             "state": {
               "type": "markdown",
               "state": {
-                "file": "c/c common.md",
+                "file": "hardcore web development/11. SQL/SQL настройка.md",
                 "mode": "source",
                 "source": false
               },
               "icon": "lucide-file",
-              "title": "c common"
+              "title": "SQL настройка"
             }
           },
           {
-            "id": "544a83d173b1de2e",
+            "id": "93f97d4cb4342e03",
             "type": "leaf",
             "state": {
               "type": "markdown",
               "state": {
-                "file": "c/macros.md",
+                "file": "hardcore web development/11. SQL/Типы данных.md",
                 "mode": "source",
                 "source": false
               },
               "icon": "lucide-file",
-              "title": "macros"
-            }
-          },
-          {
-            "id": "d479cd788600828d",
-            "type": "leaf",
-            "state": {
-              "type": "markdown",
-              "state": {
-                "file": "c/c common.md",
-                "mode": "source",
-                "source": false
-              },
-              "icon": "lucide-file",
-              "title": "c common"
-            }
-          },
-          {
-            "id": "08bfc9b99c85d9b0",
-            "type": "leaf",
-            "state": {
-              "type": "markdown",
-              "state": {
-                "file": "linux/vim.md",
-                "mode": "source",
-                "source": false
-              },
-              "icon": "lucide-file",
-              "title": "vim"
-            }
-          },
-          {
-            "id": "6ae03aa62c3b1078",
-            "type": "leaf",
-            "state": {
-              "type": "markdown",
-              "state": {
-                "file": "c/gcc.md",
-                "mode": "source",
-                "source": false
-              },
-              "icon": "lucide-file",
-              "title": "gcc"
-            }
-          },
-          {
-            "id": "7cf999cd87add41d",
-            "type": "leaf",
-            "state": {
-              "type": "markdown",
-              "state": {
-                "file": "c/pointer.md",
-                "mode": "source",
-                "source": false
-              },
-              "icon": "lucide-file",
-              "title": "pointer"
-            }
-          },
-          {
-            "id": "35a870091f7d30bf",
-            "type": "leaf",
-            "state": {
-              "type": "markdown",
-              "state": {
-                "file": "Text 10.md",
-                "mode": "source",
-                "source": false
-              },
-              "icon": "lucide-file",
-              "title": "Text 10"
+              "title": "Типы данных"
             }
           }
         ],
-        "currentTab": 6
+        "currentTab": 1
       }
     ],
     "direction": "vertical"
@@ -236,20 +166,25 @@
       "markdown-importer:Open format converter": false
     }
   },
-  "active": "35a870091f7d30bf",
+  "active": "93f97d4cb4342e03",
   "lastOpenFiles": [
-    "c/pointer.md",
-    "Text 10.md",
+    "hardcore web development/11. SQL/Сортировка данных.md",
+    "hardcore web development/11. SQL/Типы данных.md",
+    "hardcore web development/11. SQL/SQL настройка.md",
+    "hardcore web development/11. SQL/Создание таблиц.md",
+    "hardcore web development/11. SQL/Дата и время.md",
+    "English/Texts/Text 10.md",
     "c/c common.md",
-    "hardcore web development/11. SQL/JOIN/INNER JOIN.md",
+    "c/macros.md",
+    "linux/vim.md",
     "c/gcc.md",
+    "c/pointer.md",
+    "hardcore web development/11. SQL/JOIN/INNER JOIN.md",
     "lua/main.md",
     "lua",
-    "linux/vim.md",
     "Кодинг.md",
     "c/printf scanf.md",
     "c/misc.md",
-    "c/macros.md",
     "Greenstar/ethernet stm32.md",
     "ROTEK/allwinner 069 070.md",
     "linux/server.md",
@@ -261,9 +196,6 @@
     "ROTEK/Arbiter.md",
     "ROTEK/universal IO/universal IO.md",
     "ROTEK/universal IO/tasks.md",
-    "ROTEK/universal IO/Test HV.md",
-    "ROTEK/bt67xx/common.md",
-    "ROTEK/bt67xx/Команды.md",
     "English/img/34-10.jpg",
     "English/img/34-9.jpg",
     "English/img/34-8.jpg",
@@ -274,8 +206,6 @@
     "English/img/34-3.jpg",
     "English/img/34-2.jpg",
     "English/img/34-1.jpg",
-    "proGit.md",
-    "hardcore web development/11. SQL/Создание таблиц.md",
     "docs/Galleon.pdf",
     "docs/~$alleon.doc",
     "docs/Galleon.doc",

+ 0 - 0
Text 10.md → English/Texts/Text 10.md


+ 1 - 1
hardcore web development/11. SQL/SQL настройка.md

@@ -26,7 +26,7 @@ $ psql -U <user name> -h <host ip> -W -d <data base name>
 
 $ psql rroom -h 94.232.244.161 -W -d rroom_db
 
-$ psql -U bird -h 94.232.244.161 -W -d berd_db
+$ psql -U bird -h 94.232.244.161 -W -d bird_db
 ```
 
 ```sql

+ 95 - 0
hardcore web development/11. SQL/quiz_1.sql

@@ -210,3 +210,98 @@ select email from employees
 where extract('month' from birthday)=4
 order by email;
 
+-- -----------------------------------------------------------------
+-- 11.31 Работа с массивами
+
+drop table if exists log;
+table log;
+
+create temp table log (
+	log_id bigint generated always as identity,
+	created_at timestamp not null default current_timestamp,
+	messages text not null
+);
+
+insert into log (created_at, messages) values(
+	'2024-08-01 00:47:28.821', 'кажется, всё пропало|или нет, пытаемся восстановить связь|нет, точно всё пропало'
+);
+
+insert into log (created_at, messages) values(
+	'2024-08-01 01:06:21.581', 'id=128|ничоси, опять всё сломалось, никогда такого не было и вот опять'
+);
+
+select log_id, created_at, (string_to_array(messages, '|'))
+[array_length(string_to_array(messages, '|'), 1)] as last_message 
+from log;
+
+select log_id, created_at,
+	split_part(messages, '|', array_length(string_to_array(messages, '|'), 1)) as last_message
+from log;
+
+select log_id, created_at, split_part(messages, '|', -1) as last_message from log;
+
+--
+select unnest(string_to_array(messages, '|')) as messages from log;
+
+select int_array from some_entity where 777=any(int_array);
+
+select unnest(string_to_array(messages, '|')) from log;
+
+select unnest as messages from (select unnest(string_to_array(messages, '|')) from log) 
+where unnest like '%всё%';
+
+-- более короткое решение
+select t.* from (
+	select unnest(string_to_array(messages, '|') messages
+	from log
+) t where t.messages '%всё%';
+
+-- -----------------------------------------------------------------
+-- 11.33 Работа с JSON и JSONB
+
+drop table if exists book_json;
+
+create temp table book_json (
+	book_id bigint generated always as identity primary key,
+	data jsonb not null
+);
+
+-- Данные в поле data (jsonb) могут различаться
+insert into book_json (data) values 
+	('{"name": null}'),
+	('{"name": ""}'),
+	('{"name": "Тихий Дон"}'),
+	('{"name": 777}'),
+	('{}');
+
+table book_json;
+
+select book_id, data from book_json where data ? 'name';
+
+select book_id, data from book_json where data->>'name' is not null;
+
+select book_id, data from book_json where length(data->>'name') > 0;
+
+-- или вот такой вариант
+select * from book_json
+where data->>'name' is not null and data->>'name' != '';
+
+-- Создание таблицы с ограничениями по jsonb
+create table book_json(
+	book_id bigint generated always as identity primary key,
+	data jsonb not null check (
+		data->>'name' is not null and
+		data->>'pages' is not null and
+		(data->>'pages')::int > 0
+	)
+);
+
+
+
+
+
+
+
+
+
+

+ 66 - 0
hardcore web development/11. SQL/Типы данных.md

@@ -158,3 +158,69 @@ create table color (
 
 ~={yellow}Boolean=~
 
+~={yellow}Массивы=~
+Применяются редко. Использование массивов является нарушением принципов нормализации.
+
+```sql
+drop table if exists some_entity;
+
+create temp table some_entity (
+	entity_id bigint generated always as identity primary key,
+	int_array INT[],
+	text_array TEXT[],
+	date_array DATE[]
+);
+
+insert into some_entity (int_array, text_array, date_array) values (
+	'{100, 255, 328}',
+	'{"Алексей", "Петр", "Василий"}',
+	'{"2024-06-25", "2024-06-26", "2024-01-01"}'
+);
+
+select * from some_entity;
+
+-- Достать элементы по индексу
+select int_array[1], text_array[1], date_array[1] from some_entity;
+
+-- Добавить данные
+update some_entity set int_array = array_append(int_array, 777);
+
+select int_array from some_entity;
+
+-- Посмотреть количество значений
+select array_length(int_array, 1) from some_entity;
+
+-- Проверить наличие значений
+select int_array from some_entity where 777=any(int_array);
+
+select int_array from some_entity where 12345=any(int_array);
+
+-- Преобразовать строку в массив и взять второе значение
+select '{10, 20, 30}'::integer[][2];
+
+-- Преобразование массива в строку с разделением элементов :::
+select array_to_string('{10, 20, 30}'::integer[], ':::');
+
+-- Можно объединить с другой строкой
+select 'Список: ' || array_to_string('{10, 20, 30}'::integer[], ', ');
+
+-- Разбить строку на массив
+select (string_to_array('100, 200, 333', ', '))
+
+-- Разбить строку на массив взять нужный элемент
+select (string_to_array('100, 200, 333', ', '))[1];
+
+--
+select '{"Алексей", "Петр", "Василий"}'::text[];
+
+-- Преобразует массив в таблицу
+select unnest('{"Алексей", "Петр", "Василий"}'::text[]);
+
+-- Преобразует массив в таблицу. Можно сортировать и т.п.
+select unnest('{"Алексей", "Петр", "Василий"}'::text[]) as t order by t;
+```
+
+~={yellow}JSON и JSONB=~
+Что это дает?
+Получаем гибкую схему данных. Т.к. в json может содержаться разный набор данных в рамке одной колонки.
+Формат JSON в отличие от формата JSONB не будет парсить данные.