Skip to content

Commit b41c709

Browse files
tags script fixed / tester script updated.
1 parent 6613d20 commit b41c709

File tree

7 files changed

+119
-61
lines changed

7 files changed

+119
-61
lines changed

docs/PuddySqlTags.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ Sets the alias used in `EXISTS` subqueries (commonly `'value'`).
190190
Sets the SQL expression used for `json_each()` parsing, such as:
191191

192192
```sql
193-
json_array_elements_text(tags)
193+
json_each(tags)
194194
```
195195

196196
---

package-lock.json

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
"prettier": "3.6.2",
6262
"rollup": "^4.44.1",
6363
"rollup-preserve-directives": "^1.1.3",
64+
"safe-stable-stringify": "^2.5.0",
6465
"tslib": "^2.8.1",
6566
"typescript": "^5.8.3",
6667
"webpack": "^5.99.6",

src/PuddySqlQuery.mjs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,9 +142,9 @@ import PuddySqlTags from './PuddySqlTags.mjs';
142142
*
143143
* @typedef {Object} BoostValue
144144
* @property {string[]} [columns] - List of columns to apply the boost on.
145-
* @property {string} operator - Operator used in the condition (e.g., '=', 'LIKE').
146-
* @property {string|string[]} value - Value to match in the condition.
147-
* @property {number} weight - Weight factor to boost results matching the condition.
145+
* @property {string} [operator='LIKE'] - Operator used in the condition (e.g., '=', 'LIKE').
146+
* @property {string|string[]} [value] - Value to match in the condition.
147+
* @property {number} [weight=1] - Weight factor to boost results matching the condition.
148148
*/
149149

150150
/**
@@ -619,13 +619,15 @@ class PuddySqlQuery {
619619

620620
// Boost
621621
for (const boost of boostArray) {
622+
// Validator
622623
const { columns, operator = 'LIKE', value, weight = 1 } = boost;
623624
if (typeof operator !== 'string')
624625
throw new Error(`operator requires an string value. Got: ${typeof operator}`);
625626
const opValue = operator.toUpperCase();
626627
if (typeof weight !== 'number' || Number.isNaN(weight))
627628
throw new Error(`Boost 'weight' must be a valid number. Got: ${weight}`);
628629

630+
// No columns mode
629631
if (!columns) {
630632
if (typeof value !== 'string')
631633
throw new Error(
@@ -637,9 +639,11 @@ class PuddySqlQuery {
637639
continue;
638640
}
639641

642+
// Check columns
640643
if (!Array.isArray(columns) || columns.some((col) => typeof col !== 'string'))
641644
throw new Error(`Boost 'columns' must be a string or array of strings. Got: ${columns}`);
642645

646+
// In mode
643647
if (opValue === 'IN') {
644648
if (!Array.isArray(value))
645649
throw new Error(`'${opValue}' operator requires an array value. Got: ${typeof value}`);
@@ -649,7 +653,10 @@ class PuddySqlQuery {
649653
return `${col} IN (${inList})`;
650654
});
651655
cases.push(`WHEN ${conditions.join(' OR ')} THEN ${weight}`);
652-
} else {
656+
}
657+
658+
// Other modes
659+
else {
653660
if (typeof value !== 'string')
654661
throw new Error(`'${opValue}' operator requires an string value. Got: ${typeof value}`);
655662

src/PuddySqlTags.mjs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ class PuddySqlTags {
6969
*
7070
* @type {string|null}
7171
*/
72-
#jsonEach = 'json_array_elements_text';
72+
#jsonEach = 'json_each';
7373

7474
/** @type {SpecialQuery[]} */
7575
#specialQueries = [];

src/old/tag.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ class TinySqlTags {
5151
this.parseLimit = -1;
5252

5353
// json_each
54-
this.jsonEach = 'json_array_elements_text';
54+
this.jsonEach = 'json_each';
5555
this.specialQueries = [];
5656

5757
this.wildcardA = '*';

test/index.mjs

Lines changed: 93 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@
33
// This test script initializes a SQLite3 database in memory,
44
// creates a small test table, and runs various queries to demonstrate functionality.
55

6-
// import path from 'path';
7-
// import { fileURLToPath } from 'url';
6+
import stringify from 'safe-stable-stringify';
7+
import { ColorSafeStringify } from 'tiny-essentials';
88
import PuddySql from '../dist/index.mjs';
99

10-
// 🌐 Path Setup
11-
// const __filename = fileURLToPath(import.meta.url);
12-
// const __dirname = path.dirname(__filename);
10+
const colorJsonSafe = new ColorSafeStringify();
11+
const colorSafeStringify = (json, space = 0) =>
12+
colorJsonSafe.colorize(stringify(json, null, space));
1313

1414
// 🚀 Create SQL Engine Instance
1515
const db = new PuddySql.Instance();
@@ -38,90 +38,129 @@ const db = new PuddySql.Instance();
3838

3939
// 📤 Fetching All Records
4040
console.log('\n📃 All Records:\n');
41-
const allItems = await table.getAll();
42-
console.table(allItems);
41+
console.table(await table.getAll());
4342

4443
// 🔍 Find by ID
4544
console.log('\n🔍 Getting record with ID = 1\n');
46-
const oneItem = await table.get('1');
47-
console.dir(oneItem);
45+
console.log(colorSafeStringify(await table.get('1')));
4846

4947
// 🔁 Update an Entry
5048
console.log('\n📝 Updating ID = 4 (yay = true)\n');
5149
await table.set('4', { yay: true });
52-
const updated = await table.get('4');
53-
console.dir(updated);
50+
console.log(colorSafeStringify(await table.get('4')));
5451

5552
console.log('\n📝 Updating ID = 4 (yay = false)\n');
5653
await table.set('4', { yay: false });
57-
const updated2 = await table.get('4');
58-
console.dir(updated2);
54+
console.log(colorSafeStringify(await table.get('4')));
5955

6056
// ❌ Delete an Entry
6157
console.log('\n🗑️ Deleting ID = 2\n');
6258
await table.delete('2');
63-
const afterDelete = await table.getAll();
64-
console.table(afterDelete);
59+
console.table(await table.getAll());
6560

6661
// 🔎 Advanced Search: prompt = pudding
6762
console.log('\n🔎 Search: prompt = pudding\n');
68-
const search1 = await table.search({
69-
q: {
70-
group: 'AND',
71-
conditions: [{ column: 'prompt', value: '🍮 pudding' }],
72-
},
73-
});
74-
console.dir(search1);
63+
console.log(
64+
colorSafeStringify(
65+
await table.search({
66+
q: {
67+
group: 'AND',
68+
conditions: [{ column: 'prompt', value: '🍮 pudding' }],
69+
},
70+
}),
71+
1,
72+
),
73+
);
7574

7675
// 🔎 OR Search: prompt = pudding OR yay = false
7776
console.log('\n🔎 OR Search: pudding or yay = false\n');
78-
const search2 = await table.search({
79-
q: {
80-
group: 'OR',
81-
conditions: [
82-
{ column: 'prompt', value: '🍮 pudding' },
83-
{ column: 'yay', value: false },
84-
],
85-
},
86-
});
87-
console.dir(search2);
77+
console.log(
78+
colorSafeStringify(
79+
await table.search({
80+
q: {
81+
group: 'OR',
82+
conditions: [
83+
{ column: 'prompt', value: '🍮 pudding' },
84+
{ column: 'yay', value: false },
85+
],
86+
},
87+
}),
88+
1,
89+
),
90+
);
8891

8992
// 📚 Paginated Search
9093
console.log('\n📚 Paginated Search (2 per page)\n');
91-
const paged = await table.search({
92-
q: {},
93-
perPage: 2,
94-
page: 1,
95-
order: 'id ASC',
96-
});
97-
console.table(paged.items);
94+
const page1 = await table.search({ q: {}, perPage: 2, page: 1, order: 'id ASC' });
95+
console.table(page1.items);
9896

9997
console.log('\n📚 Paginated Search (Page 2)\n');
100-
const paged2 = await table.search({
101-
q: {},
102-
perPage: 2,
103-
page: 2,
104-
order: 'id ASC',
105-
});
106-
console.table(paged2.items);
107-
console.table(paged2);
98+
const page2 = await table.search({ q: {}, perPage: 2, page: 2, order: 'id ASC' });
99+
console.table(page2.items);
100+
console.table({ totalPages: page2.totalPages, totalItems: page2.totalItems });
108101

109102
// 📌 Get amount (first 3)
110103
console.log('\n📌 Getting first 3 records\n');
111-
const few = await table.getAmount(3);
112-
console.table(few);
104+
console.table(await table.getAmount(3));
113105

114106
// 🧹 Advanced delete: delete all yay = false
115107
console.log('\n🧹 Deleting all yay = false...\n');
116-
const deleted = await table.advancedDelete({
117-
yay: { value: false },
118-
});
108+
const deleted = await table.advancedDelete({ yay: { value: false } });
119109
console.log(`Deleted rows: ${deleted}`);
120110

121111
// 🧾 Final state
122112
console.log('\n🧾 Final Records:\n');
123-
const final = await table.getAll();
124-
console.table(final);
113+
console.table(await table.getAll());
125114

115+
// 🏷️ Tags System Tests
116+
console.log('\n🏷️ Creating tagged_posts table...\n');
117+
const tagTable = await db.initTable({ name: 'tagged_posts', id: 'id' }, [
118+
['id', 'TEXT', 'PRIMARY KEY'],
119+
['title', 'TEXT'],
120+
['tags', 'TAGS'],
121+
]);
122+
123+
const tagManager = tagTable.getTagEditor('tags');
124+
125+
await tagTable.set('a1', { title: 'Post 1', tags: ['cute', 'funny'] });
126+
await tagTable.set('a2', { title: 'Post 2', tags: ['serious'] });
127+
await tagTable.set('a3', { title: 'Post 3', tags: ['cute', 'deep'] });
128+
const tagItems = await tagTable.getAll();
129+
console.table(tagItems);
130+
131+
console.log('\n🔖 Search: has tag "cute"\n');
132+
console.table(
133+
await tagTable.search({
134+
tagsQ: { column: 'tags', include: ['cute'] },
135+
}),
136+
);
137+
138+
console.log('\n🧠 Advanced Tag Search: cute AND not serious\n');
139+
console.table(
140+
await tagTable.search({
141+
tagsQ: { column: 'tags', include: ['cute', '!serious'] }
142+
}),
143+
);
144+
145+
console.log('\n⚡ Boosted Tag Search (cute *2, deep *3)\n');
146+
console.table(
147+
await tagTable.search({
148+
select: {
149+
boost: {
150+
alias: 'p',
151+
value: [
152+
{ columns: ['tags'], value: 'deep', weight: 3 },
153+
{ columns: ['tags'], value: 'cute', weight: 2 },
154+
]
155+
}
156+
},
157+
tagsQ: {
158+
column: 'tags',
159+
include: ['cute', 'deep'],
160+
},
161+
}),
162+
);
163+
164+
console.log('\n✅ All tag tests done.\n');
126165
console.log('\n✅ Done.\n');
127166
})();

0 commit comments

Comments
 (0)