Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1142585f84 | ||
|
|
40ce8d334b | ||
|
|
c770d08b7f | ||
|
|
374b4b22c9 | ||
|
|
7c60f4c57b | ||
|
|
25c4866515 | ||
|
|
66ba2b8874 | ||
|
|
d673df0ca1 | ||
|
|
f0c0c55e89 | ||
|
|
49a1d24660 | ||
|
|
188c5a1be1 | ||
|
|
45f9ac558f | ||
|
|
1547f8c736 | ||
|
|
29144f54bd | ||
|
|
6e91f84750 | ||
|
|
7599b8b856 | ||
|
|
99b36e577e | ||
|
|
cba3e326e8 | ||
|
|
9625489583 | ||
|
|
b4679a154f | ||
|
|
cca6601bea | ||
|
|
7a48d336e7 | ||
|
|
37d867930b |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -16,6 +16,7 @@
|
|||||||
|
|
||||||
!README.md
|
!README.md
|
||||||
!LICENSE
|
!LICENSE
|
||||||
|
!COPYING
|
||||||
|
|
||||||
!Makefile
|
!Makefile
|
||||||
|
|
||||||
|
|||||||
56
.test/activity.json
Normal file
56
.test/activity.json
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
{
|
||||||
|
"_group": "system_collections",
|
||||||
|
"_name": "activity",
|
||||||
|
"_version": "202507",
|
||||||
|
"singular": "activity",
|
||||||
|
"plural": "activities",
|
||||||
|
"idPrefix": "act",
|
||||||
|
"system": true,
|
||||||
|
"indexSpecs": [{
|
||||||
|
"name": "name_1",
|
||||||
|
"keys": { "name": 1 },
|
||||||
|
"unique": true
|
||||||
|
}],
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"_id": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"person": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"createdAt": {
|
||||||
|
"bsonType": "date"
|
||||||
|
},
|
||||||
|
"updatedAt": {
|
||||||
|
"bsonType": "date"
|
||||||
|
},
|
||||||
|
"archivedAt": {
|
||||||
|
"bsonType": "date"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"views": {
|
||||||
|
"activityExpanded": {
|
||||||
|
"viewOn": "activity",
|
||||||
|
"pipeline": [{
|
||||||
|
"$lookup": {
|
||||||
|
"from": "person",
|
||||||
|
"localField": "person",
|
||||||
|
"foreignField": "_id",
|
||||||
|
"as": "refPerson"
|
||||||
|
}
|
||||||
|
}, {
|
||||||
|
"$unwind": "$refPerson"
|
||||||
|
}, {
|
||||||
|
"$set": { "person": "$refPerson" }
|
||||||
|
}, {
|
||||||
|
"$unset": "refPerson"
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
28
.test/event.json
Normal file
28
.test/event.json
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
{
|
||||||
|
"_group": "system_collections",
|
||||||
|
"_name": "event",
|
||||||
|
"_version": "202507",
|
||||||
|
"singular": "event",
|
||||||
|
"plural": "events",
|
||||||
|
"idPrefix": "e",
|
||||||
|
"indexSpecs": [],
|
||||||
|
"timeseries": {
|
||||||
|
"timeField": "createdAt",
|
||||||
|
"metaField": "name",
|
||||||
|
"granularity": "minutes"
|
||||||
|
},
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"_id": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"createdAt": {
|
||||||
|
"bsonType": "timestamp"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
35
.test/offer.json
Normal file
35
.test/offer.json
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
"_group": "system_collections",
|
||||||
|
"_name": "offer",
|
||||||
|
"_version": "202507",
|
||||||
|
"singular": "offer",
|
||||||
|
"plural": "offers",
|
||||||
|
"idPrefix": "ofr",
|
||||||
|
"indexSpecs": [{
|
||||||
|
"name": "name_1",
|
||||||
|
"keys": { "name": 1 },
|
||||||
|
"unique": true
|
||||||
|
}],
|
||||||
|
"discriminator": {
|
||||||
|
"field": "store",
|
||||||
|
"ctxField": "store",
|
||||||
|
"collection": "store"
|
||||||
|
},
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"_id": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"store": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"createdAt": {
|
||||||
|
"bsonType": "date"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
37
.test/person.json
Normal file
37
.test/person.json
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
{
|
||||||
|
"_group": "system_collections",
|
||||||
|
"_name": "person",
|
||||||
|
"_version": "202507",
|
||||||
|
"singular": "person",
|
||||||
|
"plural": "persons",
|
||||||
|
"idPrefix": "prs",
|
||||||
|
"system": true,
|
||||||
|
"indexSpecs": [{
|
||||||
|
"name": "name_1",
|
||||||
|
"keys": { "name": 1 },
|
||||||
|
"unique": true
|
||||||
|
}],
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"_id": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"age": {
|
||||||
|
"bsonType": "number"
|
||||||
|
},
|
||||||
|
"createdAt": {
|
||||||
|
"bsonType": "date"
|
||||||
|
},
|
||||||
|
"updatedAt": {
|
||||||
|
"bsonType": "date"
|
||||||
|
},
|
||||||
|
"archivedAt": {
|
||||||
|
"bsonType": "date"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
20
.test/sample.json
Normal file
20
.test/sample.json
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
[{
|
||||||
|
"name": "PKCELL Ultra Alkaline Batteries Size D LR20-2B (2-Pack)",
|
||||||
|
"sku": "ALK-PK-LR202B-01",
|
||||||
|
"price": {
|
||||||
|
"value": 288,
|
||||||
|
"currency": "cad"
|
||||||
|
},
|
||||||
|
"active": true,
|
||||||
|
"tags": ["alkaline", "size-d", "pkcell"]
|
||||||
|
}, {
|
||||||
|
"name": "Shimano Cleats SH-11 Yellow 6 degrees",
|
||||||
|
"sku": "BK-SM-SH51",
|
||||||
|
"active": true,
|
||||||
|
"tags": ["shimano", "cleats", "sh11", "cycling"]
|
||||||
|
}, {
|
||||||
|
"name": "OSRAM Light Bulbs H7 Original Classic 12V 55W Spare Part Replacement",
|
||||||
|
"sku": "LT-OSR-H712V35W",
|
||||||
|
"active": false,
|
||||||
|
"tags": ["osram", "h7", "halogen-bulb", "12v", "55w"]
|
||||||
|
}]
|
||||||
36
.test/store.json
Normal file
36
.test/store.json
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
{
|
||||||
|
"_group": "system_collections",
|
||||||
|
"_name": "store",
|
||||||
|
"_version": "202507",
|
||||||
|
"singular": "store",
|
||||||
|
"plural": "stores",
|
||||||
|
"idPrefix": "str",
|
||||||
|
"indexSpecs": [{
|
||||||
|
"name": "code_1",
|
||||||
|
"keys": { "code": 1 },
|
||||||
|
"unique": true
|
||||||
|
}],
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"_id": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"code": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"created_at": {
|
||||||
|
"bsonType": "date"
|
||||||
|
},
|
||||||
|
"updated_at": {
|
||||||
|
"bsonType": "date"
|
||||||
|
},
|
||||||
|
"archived_at": {
|
||||||
|
"bsonType": "date"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
53
.test/user.json
Normal file
53
.test/user.json
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
{
|
||||||
|
"_group": "system_collections",
|
||||||
|
"_name": "user",
|
||||||
|
"_version": "202507",
|
||||||
|
"singular": "user",
|
||||||
|
"plural": "users",
|
||||||
|
"idPrefix": "usr",
|
||||||
|
"system": true,
|
||||||
|
"indexSpecs": [{
|
||||||
|
"name": "username_1",
|
||||||
|
"keys": { "username": 1 },
|
||||||
|
"unique": true
|
||||||
|
}, {
|
||||||
|
"name": "email_1",
|
||||||
|
"keys": { "email": 1 },
|
||||||
|
"unique": true
|
||||||
|
}],
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"_id": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"fullname": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"firstname": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"username": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"password": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"email": {
|
||||||
|
"bsonType": "string"
|
||||||
|
},
|
||||||
|
"credentials": {
|
||||||
|
"bsonType": ["object", "null"]
|
||||||
|
},
|
||||||
|
"createdAt": {
|
||||||
|
"bsonType": "date"
|
||||||
|
},
|
||||||
|
"updatedAt": {
|
||||||
|
"bsonType": "date"
|
||||||
|
},
|
||||||
|
"archivedAt": {
|
||||||
|
"bsonType": "date"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
674
COPYING
Normal file
674
COPYING
Normal file
@@ -0,0 +1,674 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
18
LICENSE
Normal file
18
LICENSE
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Volts & Amps Batteries
|
||||||
|
*
|
||||||
|
* This file is part of boxtep.
|
||||||
|
*
|
||||||
|
* This library is free software: you can redistribute it and/or
|
||||||
|
* modify it under the terms of the GNU Lesser General Public License
|
||||||
|
* as published by the Free Software Foundation, either version 3
|
||||||
|
* of the License, or (at your option) any later version.
|
||||||
|
*
|
||||||
|
* This library is distributed in the hope that it will be useful,
|
||||||
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
* GNU Lesser General Public License for more details.
|
||||||
|
*
|
||||||
|
* You should have received a copy of the GNU Lesser General Public License
|
||||||
|
* along with this library. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
3
README.md
Normal file
3
README.md
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
This project is licensed under the GNU Lesser General Public License v3.0.
|
||||||
|
You may use this library in proprietary applications, provided that
|
||||||
|
modifications to the library itself remain open source.
|
||||||
22
audit.go
Normal file
22
audit.go
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
package mongo
|
||||||
|
|
||||||
|
type Op string
|
||||||
|
|
||||||
|
const (
|
||||||
|
OpUpdate Op = "update"
|
||||||
|
OpDelete Op = "delete"
|
||||||
|
OpInsert Op = "insert"
|
||||||
|
OpArchive Op = "archive"
|
||||||
|
OpRestore Op = "restore"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AuditResult struct {
|
||||||
|
Op Op `bson:"op" json:"op"`
|
||||||
|
Entity string `bson:"entity,omitempty" json:"entity,omitempty"`
|
||||||
|
Data any `bson:"data,omitempty" json:"data,omitempty",`
|
||||||
|
Before any `bson:"before,omitempty" json:"before,omitempty"`
|
||||||
|
After any `bson:"after,omitempty" json:"after,omitempty"`
|
||||||
|
Context any `bson:"context,omitempty" json:"context,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type OnAudit func(audit *AuditResult) error
|
||||||
53
delete.go
Normal file
53
delete.go
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
package mongo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"slices"
|
||||||
|
|
||||||
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
|
|
||||||
|
"git.gsuntres.com/general/commons"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DeleteOne will delete the first document that matches the filter.
|
||||||
|
func (c *MongoClient) DeleteOne(ctx context.Context, database, name string, filter bson.M) error {
|
||||||
|
var err error
|
||||||
|
|
||||||
|
// 1. Prepare query.
|
||||||
|
collection := c.GetCollection(database, name)
|
||||||
|
|
||||||
|
// 2. Check discriminator and mongofy
|
||||||
|
if err := c.DiscriminatorCheckAndApplyToFilter(ctx, name, filter); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
f := Mongofy(&Query{ Filter: filter })
|
||||||
|
|
||||||
|
var found bson.M
|
||||||
|
if c.WithAudit {
|
||||||
|
err = collection.FindOne(ctx, f).Decode(&found)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Delete
|
||||||
|
_, err = collection.DeleteOne(ctx, f)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.WithAudit && !slices.Contains(c.IgnoreAudit, name) {
|
||||||
|
contx := commons.ContextSerialize(ctx, c.ContextFields)
|
||||||
|
audit := &AuditResult {
|
||||||
|
Entity: name,
|
||||||
|
Op: OpDelete,
|
||||||
|
Before: found,
|
||||||
|
Context: contx,
|
||||||
|
}
|
||||||
|
|
||||||
|
(*c.OnAudit)(audit)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
package mongo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"go.mongodb.org/mongo-driver/v2/bson"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DeleteOne will delete the first document that matches the filter.
|
|
||||||
func (c *MongoClient) DeleteOne(ctx context.Context, database, name string, filter bson.M) error {
|
|
||||||
|
|
||||||
// 1. Prepare query.
|
|
||||||
collection := c.GetCollection(database, name)
|
|
||||||
|
|
||||||
// 2. Query
|
|
||||||
_, err := collection.DeleteOne(ctx, filter)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
236
delete_test.go
Normal file
236
delete_test.go
Normal file
@@ -0,0 +1,236 @@
|
|||||||
|
package mongo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"fmt"
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
|
|
||||||
|
"git.gsuntres.com/general/commons"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDeleteOne(t *testing.T) {
|
||||||
|
client := GetMongoClient()
|
||||||
|
|
||||||
|
data := map[string]any {
|
||||||
|
"_id": "su_123458",
|
||||||
|
"name": "MyNameTODelete",
|
||||||
|
"age": int32(25),
|
||||||
|
}
|
||||||
|
|
||||||
|
o, err := client.InsertOne(context.Background(), "mydb", "mycollection", data)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
// now delete it
|
||||||
|
err = client.DeleteOne(context.Background(), "mydb", "mycollection", bson.M{"_id": o["_id"].(string)})
|
||||||
|
if err != nil { t.Fatalf("Failed to deleteOne %#v", err) }
|
||||||
|
|
||||||
|
// raw query
|
||||||
|
var results bson.M
|
||||||
|
filter := bson.M{ "name": "MyName" }
|
||||||
|
|
||||||
|
c := client.Client.Database("mydb").Collection("mycollection")
|
||||||
|
c.FindOne(context.Background(), filter).Decode(&results)
|
||||||
|
|
||||||
|
if results != nil {
|
||||||
|
t.Fatalf("Should have no results not %v", results)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDelete_Discriminator(t *testing.T) {
|
||||||
|
// 1. Register schemas
|
||||||
|
schemaStore, err := os.ReadFile("./.test/store.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
schemaOffer, err := os.ReadFile("./.test/offer.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
var store bson.M
|
||||||
|
if err := json.Unmarshal(schemaStore, &store); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaStore), schemaStore[:4])
|
||||||
|
}
|
||||||
|
|
||||||
|
var offer bson.M
|
||||||
|
if err := json.Unmarshal(schemaOffer, &offer); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaOffer), schemaOffer[:4])
|
||||||
|
}
|
||||||
|
|
||||||
|
client := GetMongoClient()
|
||||||
|
client.AddDefinition(store)
|
||||||
|
client.AddDefinition(offer)
|
||||||
|
|
||||||
|
// Store str_1234 has BOOMRAW 1.
|
||||||
|
ctx1 := context.Background()
|
||||||
|
ctx1 = context.WithValue(ctx1, "store", "str_1234")
|
||||||
|
offer1 := map[string]any { "name": "BOOMRAW 1" }
|
||||||
|
_, err = client.InsertOne(ctx1, "mydb", "offer", offer1)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
// Store str_4321 has BOOMRAW 2
|
||||||
|
ctx2 := context.Background()
|
||||||
|
ctx2 = context.WithValue(ctx2, "store", "str_4321")
|
||||||
|
offer2 := map[string]any { "name": "BOOMRAW 2" }
|
||||||
|
_, err = client.InsertOne(ctx2, "mydb", "offer", offer2)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
// Attempt to delete BOOMRAW2 in str_1234
|
||||||
|
err = client.DeleteOne(ctx1, "mydb", "offer", bson.M{"name": "BOOMRAW2"})
|
||||||
|
|
||||||
|
// Within store str_4321 searching for BOOMRAW should return one result
|
||||||
|
filter := bson.M{"name": bson.M{"$regex": "BOOMRAW*"}}
|
||||||
|
findResult, err := client.Find(ctx2, "mydb", "offer", filter, &FindOptions{ Offset: int64(0) })
|
||||||
|
if err != nil { t.Fatalf("Failed to find %#v", err) }
|
||||||
|
|
||||||
|
dataAny, hasData := findResult["data"]
|
||||||
|
if !hasData { t.Fatal("no data") }
|
||||||
|
|
||||||
|
data := dataAny.(bson.A)
|
||||||
|
|
||||||
|
if len(data) != 1 {
|
||||||
|
t.Fatalf("Expected to return 1 document but got %d", len(data))
|
||||||
|
}
|
||||||
|
|
||||||
|
arr, _ := commons.BsonAToSlice(data)
|
||||||
|
|
||||||
|
o := arr[0]
|
||||||
|
|
||||||
|
name := o["name"]
|
||||||
|
|
||||||
|
if name != "BOOMRAW 2" {
|
||||||
|
t.Fatalf("Expected BOOMRAW 2 not %s", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeleteOne_WithAudit(t *testing.T) {
|
||||||
|
client := GetMongoClient()
|
||||||
|
|
||||||
|
data := map[string]any {
|
||||||
|
"_id": "su_123458",
|
||||||
|
"name": "MyNameTODelete",
|
||||||
|
"age": int32(25),
|
||||||
|
}
|
||||||
|
|
||||||
|
o, err := client.InsertOne(context.Background(), "mydb", "mycollection", data)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
// now delete it
|
||||||
|
|
||||||
|
var (
|
||||||
|
onAudit_calls int
|
||||||
|
onAudit_before any
|
||||||
|
onAudit_context any
|
||||||
|
)
|
||||||
|
|
||||||
|
cancel := client.Subscribe(func(audit *AuditResult) error {
|
||||||
|
onAudit_calls++
|
||||||
|
onAudit_before = audit.Before
|
||||||
|
onAudit_context = audit.Context
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
ctx = context.WithValue(ctx, "account", "xxxxxx")
|
||||||
|
ctx = context.WithValue(ctx, "store", "str_4321")
|
||||||
|
err = client.DeleteOne(ctx, "mydb", "mycollection", bson.M{"_id": o["_id"].(string)})
|
||||||
|
if err != nil { t.Fatalf("Failed to deleteOne %#v", err) }
|
||||||
|
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
// raw query
|
||||||
|
var results bson.M
|
||||||
|
filter := bson.M{ "name": "MyName" }
|
||||||
|
|
||||||
|
c := client.Client.Database("mydb").Collection("mycollection")
|
||||||
|
c.FindOne(context.Background(), filter).Decode(&results)
|
||||||
|
|
||||||
|
if results != nil {
|
||||||
|
t.Fatalf("Should have no results not %v", results)
|
||||||
|
}
|
||||||
|
|
||||||
|
if onAudit_calls != 1 {
|
||||||
|
t.Fatalf("ondelete should have been called once, not %d", onAudit_calls)
|
||||||
|
}
|
||||||
|
|
||||||
|
if onAudit_before != nil {
|
||||||
|
tp := fmt.Sprintf("%T", onAudit_before)
|
||||||
|
if tp != "bson.M" {
|
||||||
|
t.Fatalf("before has the wrong type %s", tp)
|
||||||
|
}
|
||||||
|
|
||||||
|
before := onAudit_before.(bson.M)
|
||||||
|
|
||||||
|
AssertSubset(t, before, o, "Should have been equal")
|
||||||
|
}
|
||||||
|
|
||||||
|
if onAudit_context != nil {
|
||||||
|
ctx := onAudit_context.(map[string]any)
|
||||||
|
AssertSubset(t, ctx, map[string]any{"account": "xxxxxx", "store": "str_4321"}, "Should have been equal")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeleteOne_WithAuditButIgnored(t *testing.T) {
|
||||||
|
client := GetMongoClient()
|
||||||
|
client.IgnoreAudit = []string{"mycollection"}
|
||||||
|
|
||||||
|
data := map[string]any {
|
||||||
|
"_id": "su_123458",
|
||||||
|
"name": "MyNameTODelete",
|
||||||
|
"age": int32(25),
|
||||||
|
}
|
||||||
|
|
||||||
|
o, err := client.InsertOne(context.Background(), "mydb", "mycollection", data)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
// now delete it
|
||||||
|
|
||||||
|
var (
|
||||||
|
onAudit_calls int
|
||||||
|
onAudit_before any
|
||||||
|
)
|
||||||
|
|
||||||
|
cancel := client.Subscribe(func(audit *AuditResult) error {
|
||||||
|
onAudit_calls++
|
||||||
|
onAudit_before = audit.Before
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
ctx = context.WithValue(ctx, "account", "xxxxxx")
|
||||||
|
ctx = context.WithValue(ctx, "store", "str_4321")
|
||||||
|
err = client.DeleteOne(ctx, "mydb", "mycollection", bson.M{"_id": o["_id"].(string)})
|
||||||
|
if err != nil { t.Fatalf("Failed to deleteOne %#v", err) }
|
||||||
|
|
||||||
|
cancel()
|
||||||
|
client.IgnoreAudit = []string{"event"}
|
||||||
|
|
||||||
|
// raw query
|
||||||
|
var results bson.M
|
||||||
|
filter := bson.M{ "name": "MyName" }
|
||||||
|
|
||||||
|
c := client.Client.Database("mydb").Collection("mycollection")
|
||||||
|
c.FindOne(context.Background(), filter).Decode(&results)
|
||||||
|
|
||||||
|
if results != nil {
|
||||||
|
t.Fatalf("Should have no results not %v", results)
|
||||||
|
}
|
||||||
|
|
||||||
|
if onAudit_calls != 0 {
|
||||||
|
t.Fatalf("ondelete should have not been called. [%d]", onAudit_calls)
|
||||||
|
}
|
||||||
|
|
||||||
|
if onAudit_before != nil {
|
||||||
|
tp := fmt.Sprintf("%T", onAudit_before)
|
||||||
|
if tp != "bson.M" {
|
||||||
|
t.Fatalf("before has the wrong type %s", tp)
|
||||||
|
}
|
||||||
|
|
||||||
|
before := onAudit_before.(bson.M)
|
||||||
|
|
||||||
|
AssertSubset(t, before, o, "Should have been equal")
|
||||||
|
}
|
||||||
|
}
|
||||||
80
discrimination.go
Normal file
80
discrimination.go
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
package mongo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"fmt"
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
|
|
||||||
|
"git.gsuntres.com/general/commons"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (c *MongoClient) DiscriminatorCheckAndApplyToData(ctx context.Context, name string, data map[string]any) error {
|
||||||
|
cdef, ok := c.Registry[name]
|
||||||
|
if ok && cdef.Discriminator != nil {
|
||||||
|
if data == nil {
|
||||||
|
data = map[string]any{}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Discriminator found for %s; will use it", name)
|
||||||
|
|
||||||
|
// get from context
|
||||||
|
vAny := ctx.Value(cdef.Discriminator.CtxField)
|
||||||
|
if vAny == nil {
|
||||||
|
return fmt.Errorf("discriminator field required for %s", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// update payload
|
||||||
|
v := vAny.(string)
|
||||||
|
data[cdef.Discriminator.Field] = v
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *MongoClient) DiscriminatorOmitInData(name string, data bson.M) error {
|
||||||
|
cdef, ok := c.Registry[name]
|
||||||
|
if ok && cdef.Discriminator != nil {
|
||||||
|
if data == nil {
|
||||||
|
data = map[string]any{}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Making sure discriminator is not in data for %s", name)
|
||||||
|
|
||||||
|
_, ok := data[cdef.Discriminator.Field]
|
||||||
|
if ok {
|
||||||
|
delete(data, cdef.Discriminator.Field)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *MongoClient) DiscriminatorCheckAndApplyToFilter(ctx context.Context, name string, filter bson.M) error {
|
||||||
|
cdef, ok := c.Registry[name]
|
||||||
|
if ok && cdef.Discriminator != nil {
|
||||||
|
if filter == nil {
|
||||||
|
filter = bson.M{}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Discriminator found for %s; will use it", name)
|
||||||
|
|
||||||
|
// get from context
|
||||||
|
vAny := ctx.Value(cdef.Discriminator.CtxField)
|
||||||
|
if vAny == nil {
|
||||||
|
return fmt.Errorf("discriminator field required for %s", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// update payload
|
||||||
|
v := vAny.(string)
|
||||||
|
if commons.StringIsBlank(v) {
|
||||||
|
return fmt.Errorf("discriminator field required for %s", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
filter[cdef.Discriminator.Field] = bson.M{"eq": v}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
72
ensure.go
Normal file
72
ensure.go
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
package mongo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
|
"github.com/matoous/go-nanoid/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const alphabet = "0123456789abcdefghijclmnopqrstuvwxyz"
|
||||||
|
|
||||||
|
const maxLen = 10
|
||||||
|
|
||||||
|
// ensureId adds the id property when missing or when it's an empty string.
|
||||||
|
func ensureId(data bson.M, idPrefix string) string {
|
||||||
|
maybeId, hasId := data["_id"]
|
||||||
|
|
||||||
|
var id, finalId string
|
||||||
|
if !hasId || maybeId == "" {
|
||||||
|
id, _ = gonanoid.Generate(alphabet, maxLen)
|
||||||
|
if idPrefix != "" {
|
||||||
|
finalId = fmt.Sprintf("%s_%s", idPrefix, id)
|
||||||
|
} else {
|
||||||
|
finalId = id
|
||||||
|
}
|
||||||
|
|
||||||
|
data["_id"] = finalId
|
||||||
|
}
|
||||||
|
|
||||||
|
return finalId
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureNoId(data bson.M) {
|
||||||
|
if _, ok := data["_id"]; ok {
|
||||||
|
delete(data, "_id")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureExistingCreatedAt(data bson.M, old bson.M) time.Time {
|
||||||
|
var cAt time.Time
|
||||||
|
cAtAny, ok := old["createdAt"]
|
||||||
|
if ok {
|
||||||
|
switch cAtAny.(type) {
|
||||||
|
case bson.DateTime:
|
||||||
|
cAtBson := cAtAny.(bson.DateTime)
|
||||||
|
cAt = cAtBson.Time()
|
||||||
|
default:
|
||||||
|
cAt = cAtAny.(time.Time)
|
||||||
|
}
|
||||||
|
|
||||||
|
data["createdAt"] = cAt
|
||||||
|
}
|
||||||
|
|
||||||
|
return cAt
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureCreatedAt(data bson.M) time.Time {
|
||||||
|
now := time.Now().UTC().Truncate(time.Millisecond)
|
||||||
|
|
||||||
|
data["createdAt"] = now
|
||||||
|
|
||||||
|
return now
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureUpdatedAt(data bson.M) time.Time {
|
||||||
|
now := time.Now().UTC().Truncate(time.Millisecond)
|
||||||
|
|
||||||
|
data["updatedAt"] = now
|
||||||
|
|
||||||
|
return now
|
||||||
|
}
|
||||||
90
ensure_test.go
Normal file
90
ensure_test.go
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
package mongo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
"testing/synctest"
|
||||||
|
|
||||||
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestEnsureId(t *testing.T) {
|
||||||
|
data := map[string]any {
|
||||||
|
"Name": "My Name Is",
|
||||||
|
}
|
||||||
|
|
||||||
|
ensureId(data, "")
|
||||||
|
|
||||||
|
if id, okid := data["_id"]; !okid || id == "" {
|
||||||
|
t.Fatal("Failed to add Id")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureId_EmptyId(t *testing.T) {
|
||||||
|
data := map[string]any {
|
||||||
|
"_id": "myidxxxxxx",
|
||||||
|
"name": "My Name Is",
|
||||||
|
}
|
||||||
|
|
||||||
|
ensureId(data, "")
|
||||||
|
|
||||||
|
if data["_id"] == "" {
|
||||||
|
t.Fatal("Id was updated")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureId_ExistingId(t *testing.T) {
|
||||||
|
data := map[string]any {
|
||||||
|
"_id": "",
|
||||||
|
"name": "My Name Is",
|
||||||
|
}
|
||||||
|
|
||||||
|
ensureId(data, "")
|
||||||
|
|
||||||
|
if id, okid := data["_id"]; !okid || id == "" {
|
||||||
|
t.Fatal("Failed to add Id")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureCreatedAt(t *testing.T) {
|
||||||
|
data := map[string]any {
|
||||||
|
"name": "My Name Is",
|
||||||
|
}
|
||||||
|
|
||||||
|
synctest.Test(t, func(t *testing.T) {
|
||||||
|
now := ensureCreatedAt(data)
|
||||||
|
|
||||||
|
if createdAt, _ := data["createdAt"]; createdAt != now {
|
||||||
|
t.Fatal("Failed to add CreatedAt")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureExistingCreatedAt(t *testing.T) {
|
||||||
|
tm, err := time.Parse(time.RFC3339, "2025-12-24T13:00:11Z")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
// t.Fatalf("==> %T", tm)
|
||||||
|
|
||||||
|
old := bson.M{"createdAt": tm}
|
||||||
|
|
||||||
|
data := bson.M{}
|
||||||
|
|
||||||
|
ensureExistingCreatedAt(data, old)
|
||||||
|
|
||||||
|
if data["createdAt"] != tm {
|
||||||
|
t.Fatal("wrong date")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsureExistingCreatedAt_NoField(t *testing.T) {
|
||||||
|
old := bson.M{"name": "I have no created at"}
|
||||||
|
|
||||||
|
data := bson.M{}
|
||||||
|
|
||||||
|
ensureExistingCreatedAt(data, old)
|
||||||
|
|
||||||
|
if _, ok := data["createdAt"]; ok {
|
||||||
|
t.Fatal("Should had no createdAt")
|
||||||
|
}
|
||||||
|
}
|
||||||
108
filter.go
Normal file
108
filter.go
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
package mongo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Query struct {
|
||||||
|
Filter map[string]any `json:"filter"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Filter struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Op string `json:"op"`
|
||||||
|
Value string `json:"value"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func makeFilter(name string, value any) *Filter {
|
||||||
|
var op string
|
||||||
|
|
||||||
|
var v string
|
||||||
|
|
||||||
|
switch value.(type) {
|
||||||
|
case string:
|
||||||
|
op = "eq"
|
||||||
|
v = value.(string)
|
||||||
|
case bson.M:
|
||||||
|
vMap := value.(bson.M)
|
||||||
|
|
||||||
|
for kk, vv := range vMap {
|
||||||
|
op = kk
|
||||||
|
v = vv.(string)
|
||||||
|
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
case map[string]any:
|
||||||
|
vMap := value.(map[string]any)
|
||||||
|
|
||||||
|
for kk, vv := range vMap {
|
||||||
|
op = kk
|
||||||
|
v = vv.(string)
|
||||||
|
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
op = "eq"
|
||||||
|
}
|
||||||
|
|
||||||
|
o := &Filter{
|
||||||
|
Name: name,
|
||||||
|
Op: op,
|
||||||
|
Value: v,
|
||||||
|
}
|
||||||
|
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
func Mongofy(q *Query) map[string]any {
|
||||||
|
|
||||||
|
conditions := make([]map[string]interface{}, 0)
|
||||||
|
|
||||||
|
logic := "and"
|
||||||
|
|
||||||
|
for k, v := range q.Filter {
|
||||||
|
if k == "_logic" {
|
||||||
|
logic = v.(string)
|
||||||
|
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
f := makeFilter(k, v)
|
||||||
|
|
||||||
|
mongoOp := mapToOp(f.Op)
|
||||||
|
|
||||||
|
conditions = append(conditions, map[string]any{ k: map[string]any{ mongoOp: f.Value }})
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(conditions) == 0 {
|
||||||
|
return map[string]any{}
|
||||||
|
}
|
||||||
|
|
||||||
|
if logic == "or" {
|
||||||
|
return map[string]any{
|
||||||
|
"$or": conditions,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return map[string]any{
|
||||||
|
"$and": conditions,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mapToOp(v string) string {
|
||||||
|
switch v {
|
||||||
|
case "eq":
|
||||||
|
return "$eq"
|
||||||
|
case "le":
|
||||||
|
return "$le"
|
||||||
|
case "includes":
|
||||||
|
return "$regex"
|
||||||
|
default:
|
||||||
|
log.Printf("WARN: no conversion for %v", v)
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
}
|
||||||
174
find.go
174
find.go
@@ -1,37 +1,55 @@
|
|||||||
package mongo
|
package mongo
|
||||||
|
|
||||||
import (
|
import (
|
||||||
// "log"
|
|
||||||
"context"
|
"context"
|
||||||
// "fmt"
|
|
||||||
// "encoding/base64"
|
|
||||||
|
|
||||||
// "go.mongodb.org/mongo-driver/v2/mongo/options"
|
|
||||||
"go.mongodb.org/mongo-driver/v2/bson"
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
|
"git.gsuntres.com/general/commons"
|
||||||
// "git.gsuntres.com/boxtep/boxtep/core"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type FindOptions struct {
|
||||||
|
Offset int64 `json:"offset"`
|
||||||
|
Limit int64 `json:"limit"`
|
||||||
|
Alias string `json:"alias"`
|
||||||
|
Sort [][]any `json:"sort"`
|
||||||
|
}
|
||||||
|
|
||||||
// Find is used to fetch the first page of data.
|
// Find is used to fetch the first page of data.
|
||||||
func (c *MongoClient) Find(ctx context.Context, database, name string, filter bson.M, limit int64) (bson.M, error) {
|
func (c *MongoClient) Find(ctx context.Context, database, name string, filter bson.M, opts *FindOptions) (bson.M, error) {
|
||||||
|
|
||||||
|
var limit int64
|
||||||
|
|
||||||
|
if opts != nil {
|
||||||
|
limit = opts.Limit
|
||||||
|
}
|
||||||
|
|
||||||
// 1. Prepare to query.
|
// 1. Prepare to query.
|
||||||
collection := c.GetCollection(database, name)
|
finalName := name
|
||||||
|
if opts != nil && commons.StringIsNotBlank(opts.Alias) {
|
||||||
|
finalName = opts.Alias
|
||||||
|
}
|
||||||
|
collection := c.GetCollection(database, finalName)
|
||||||
|
|
||||||
pageSize := max(limit, c.Limit)
|
pageSize := max(limit, c.Limit)
|
||||||
|
|
||||||
|
sortOpts := commons.BsonDFromSlice(opts.Sort)
|
||||||
|
var sort bson.D
|
||||||
|
|
||||||
// id := DecodeCursor(nextCursor)
|
if len(sortOpts) == 0 {
|
||||||
|
sort = sortOpts
|
||||||
|
} else {
|
||||||
|
sort = bson.D{{Key: "_id", Value: 1}}
|
||||||
|
}
|
||||||
|
|
||||||
// filter["_id"] = bson.M{"_id": bson.M{"$gt": id}}
|
if err := c.DiscriminatorCheckAndApplyToFilter(ctx, name, filter); err != nil {
|
||||||
// opts := options.Find().
|
return nil, err
|
||||||
// SetLimit(pageSize + 1).
|
}
|
||||||
// SetSort(bson.M{"_id": 1})
|
|
||||||
// id := DecodeCursor(nextCursor)
|
|
||||||
sort := bson.M{"_id": 1}
|
|
||||||
// filter["_id"] = bson.M{"_id": bson.M{"$gt": id}}
|
|
||||||
|
|
||||||
pipeline := BuildPaginationPipeline(0, pageSize + 1, filter, sort)
|
f := Mongofy(&Query{
|
||||||
|
Filter: filter,
|
||||||
|
})
|
||||||
|
|
||||||
|
pipeline := BuildPaginationPipeline(0, pageSize + 1, f, sort)
|
||||||
|
|
||||||
// 2. Query
|
// 2. Query
|
||||||
cursor, err := collection.Aggregate(ctx, pipeline)
|
cursor, err := collection.Aggregate(ctx, pipeline)
|
||||||
@@ -54,9 +72,15 @@ func (c *MongoClient) Find(ctx context.Context, database, name string, filter bs
|
|||||||
|
|
||||||
var totalValue any
|
var totalValue any
|
||||||
if len(metadata) != 0 {
|
if len(metadata) != 0 {
|
||||||
|
switch metadata[0].(type) {
|
||||||
|
case bson.D:
|
||||||
|
metadataRoot := metadata[0].(bson.D)
|
||||||
|
totalValue, _ = commons.BsonDGetAny(metadataRoot, "total")
|
||||||
|
case bson.M:
|
||||||
metadataRoot := metadata[0].(bson.M)
|
metadataRoot := metadata[0].(bson.M)
|
||||||
totalValue = metadataRoot["total"]
|
totalValue = metadataRoot["total"]
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var total int64
|
var total int64
|
||||||
switch v := totalValue.(type) {
|
switch v := totalValue.(type) {
|
||||||
@@ -91,37 +115,101 @@ func (c *MongoClient) Find(ctx context.Context, database, name string, filter bs
|
|||||||
out["next_cursor"] = nextCursor
|
out["next_cursor"] = nextCursor
|
||||||
}
|
}
|
||||||
|
|
||||||
// _data, err := bson.Marshal(out)
|
|
||||||
// if err != nil {
|
|
||||||
// return nil, err
|
|
||||||
// }
|
|
||||||
|
|
||||||
// var r bson.M
|
|
||||||
// if err := bson.Unmarshal(_data, &r); err != nil {
|
|
||||||
// return nil, err
|
|
||||||
// }
|
|
||||||
|
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// func (c *MongoClient) FindNext(ctx context.Context, database, name string, filter bson.M, nextCursor string, limit int64) ([]bson.M, error) {
|
func (c *MongoClient) FindOffset(ctx context.Context, database, name string, filter bson.M, opts *FindOptions) (bson.M, error) {
|
||||||
// collection := c.GetCollection(database, name)
|
var offset int64
|
||||||
|
var limit int64
|
||||||
|
|
||||||
// opts := options.Find().
|
if opts != nil {
|
||||||
// SetLimit(max(limit, c.Limit)).
|
limit = opts.Limit
|
||||||
// SetSort()
|
}
|
||||||
|
|
||||||
// cursor, err := collection.Find(ctx, filter)
|
if opts != nil {
|
||||||
// if err != nil {
|
offset = opts.Offset
|
||||||
// return nil, err
|
}
|
||||||
// }
|
|
||||||
|
|
||||||
// var results []bson.M
|
// 1. Prepare to query.
|
||||||
// if err = cursor.All(ctx, &results); err != nil {
|
finalName := name
|
||||||
// return nil, err
|
if opts != nil && commons.StringIsNotBlank(opts.Alias) {
|
||||||
// }
|
finalName = opts.Alias
|
||||||
|
}
|
||||||
|
collection := c.GetCollection(database, finalName)
|
||||||
|
|
||||||
// return results, err
|
finalLimit := max(limit, c.Limit)
|
||||||
// }
|
|
||||||
|
|
||||||
// func EncodeCursor()
|
if err := c.DiscriminatorCheckAndApplyToFilter(ctx, name, filter); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
f := Mongofy(&Query{
|
||||||
|
Filter: filter,
|
||||||
|
})
|
||||||
|
|
||||||
|
sort := commons.BsonDFromSlice(opts.Sort)
|
||||||
|
|
||||||
|
pipeline := BuildPaginationPipeline(offset, finalLimit, f, sort)
|
||||||
|
|
||||||
|
// 2. Query
|
||||||
|
cursor, err := collection.Aggregate(ctx, pipeline)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer cursor.Close(ctx)
|
||||||
|
|
||||||
|
// 3. Build results
|
||||||
|
var facetResults []bson.M
|
||||||
|
if err = cursor.All(ctx, &facetResults); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
root := facetResults[0]
|
||||||
|
|
||||||
|
data := root["data"].(bson.A)
|
||||||
|
|
||||||
|
metadata := root["metadata"].(bson.A)
|
||||||
|
|
||||||
|
var totalValue any
|
||||||
|
if len(metadata) != 0 {
|
||||||
|
switch metadata[0].(type) {
|
||||||
|
case bson.D:
|
||||||
|
metadataRoot := metadata[0].(bson.D)
|
||||||
|
totalValue, _ = commons.BsonDGetAny(metadataRoot, "total")
|
||||||
|
case bson.M:
|
||||||
|
metadataRoot := metadata[0].(bson.M)
|
||||||
|
totalValue = metadataRoot["total"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var total int64
|
||||||
|
switch v := totalValue.(type) {
|
||||||
|
case int32:
|
||||||
|
total = int64(v)
|
||||||
|
case int64:
|
||||||
|
total = v
|
||||||
|
default:
|
||||||
|
total = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
hasMore := false
|
||||||
|
if total > offset + finalLimit {
|
||||||
|
hasMore = true
|
||||||
|
}
|
||||||
|
|
||||||
|
hasPrevious := false
|
||||||
|
if finalLimit - offset < 0 {
|
||||||
|
hasPrevious = true
|
||||||
|
}
|
||||||
|
|
||||||
|
out := bson.M{
|
||||||
|
"data": data,
|
||||||
|
"offset": offset,
|
||||||
|
"limit": finalLimit,
|
||||||
|
"has_more": hasMore,
|
||||||
|
"has_previous": hasPrevious,
|
||||||
|
"total": total,
|
||||||
|
}
|
||||||
|
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|||||||
69
find_test.go
69
find_test.go
@@ -1,17 +1,23 @@
|
|||||||
package mongo
|
package mongo
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"os"
|
||||||
"context"
|
"context"
|
||||||
"testing"
|
"testing"
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
"go.mongodb.org/mongo-driver/v2/bson"
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
|
|
||||||
|
"git.gsuntres.com/general/commons"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestFind_Default(t *testing.T) {
|
func TestFind_Default(t *testing.T) {
|
||||||
client := GetMongoClient()
|
client := GetMongoClient()
|
||||||
|
|
||||||
filter := bson.M{"name": bson.M{"$regex": "OSRAM"}}
|
filter := bson.M{"name": bson.M{"$regex": "OSRAM"}}
|
||||||
findResult, err := client.Find(context.Background(), "mydb", "mycollection", filter, 0)
|
findResult, err := client.Find(context.Background(), "mydb", "mycollection", filter, &FindOptions{
|
||||||
|
Offset: int64(0),
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to insertOne %#v", err)
|
t.Fatalf("Failed to insertOne %#v", err)
|
||||||
}
|
}
|
||||||
@@ -49,3 +55,64 @@ func TestFind_Default(t *testing.T) {
|
|||||||
t.Fatalf("Expected total to be 1 but found %d", total)
|
t.Fatalf("Expected total to be 1 but found %d", total)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestFind_Discriminator(t *testing.T) {
|
||||||
|
// 1. Register schemas
|
||||||
|
schemaStore, err := os.ReadFile("./.test/store.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
schemaOffer, err := os.ReadFile("./.test/offer.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
var store bson.M
|
||||||
|
if err := json.Unmarshal(schemaStore, &store); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaStore), schemaStore[:4])
|
||||||
|
}
|
||||||
|
|
||||||
|
var offer bson.M
|
||||||
|
if err := json.Unmarshal(schemaOffer, &offer); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaOffer), schemaOffer[:4])
|
||||||
|
}
|
||||||
|
|
||||||
|
client := GetMongoClient()
|
||||||
|
client.AddDefinition(store)
|
||||||
|
client.AddDefinition(offer)
|
||||||
|
|
||||||
|
// Store str_1234 has OSRAM 1.
|
||||||
|
ctx1 := context.Background()
|
||||||
|
ctx1 = context.WithValue(ctx1, "store", "str_1234")
|
||||||
|
offer1 := map[string]any { "name": "OSRAM 1" }
|
||||||
|
_, err = client.InsertOne(ctx1, "mydb", "offer", offer1)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
// Store str_4321 has OSRAM 2
|
||||||
|
ctx2 := context.Background()
|
||||||
|
ctx2 = context.WithValue(ctx2, "store", "str_4321")
|
||||||
|
offer2 := map[string]any { "name": "OSRAM 2" }
|
||||||
|
_, err = client.InsertOne(ctx2, "mydb", "offer", offer2)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
// Within store str_1234 searching for OSRAM should return one result
|
||||||
|
filter := bson.M{"name": bson.M{"$regex": "OSRAM*"}}
|
||||||
|
findResult, err := client.Find(ctx1, "mydb", "offer", filter, &FindOptions{ Offset: int64(0) })
|
||||||
|
if err != nil { t.Fatalf("Failed to find %#v", err) }
|
||||||
|
|
||||||
|
dataAny, hasData := findResult["data"]
|
||||||
|
if !hasData { t.Fatal("no data") }
|
||||||
|
|
||||||
|
data := dataAny.(bson.A)
|
||||||
|
|
||||||
|
if len(data) != 1 {
|
||||||
|
t.Fatalf("Expected to return 1 document but got %d", len(data))
|
||||||
|
}
|
||||||
|
|
||||||
|
arr, _ := commons.BsonAToSlice(data)
|
||||||
|
|
||||||
|
o := arr[0]
|
||||||
|
|
||||||
|
name := o["name"]
|
||||||
|
|
||||||
|
if name != "OSRAM 1" {
|
||||||
|
t.Fatalf("Expected OSRAM 1 not %s", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package mongo
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"log"
|
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"go.mongodb.org/mongo-driver/v2/bson"
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
@@ -26,8 +25,6 @@ func (c *MongoClient) GenericFind(ctx context.Context, payload *FindRequest) (*D
|
|||||||
|
|
||||||
collection := c.GetCollection(database, name)
|
collection := c.GetCollection(database, name)
|
||||||
|
|
||||||
log.Printf("%v", collection)
|
|
||||||
|
|
||||||
var filter bson.D
|
var filter bson.D
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
|
|||||||
18
go.mod
18
go.mod
@@ -3,14 +3,15 @@ module git.gsuntres.com/general/mongo
|
|||||||
go 1.25.0
|
go 1.25.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
git.gsuntres.com/general/commons v0.0.0-20260329160148-434ecef67a94
|
git.gsuntres.com/general/commons v0.0.0-20260425145405-80a923f150d3
|
||||||
git.gsuntres.com/general/sys v0.0.0-20260329160429-49966ca31027
|
git.gsuntres.com/general/events v0.0.0-20260424194951-506e91ff46a2
|
||||||
|
git.gsuntres.com/general/sys v0.0.1
|
||||||
github.com/go-viper/mapstructure/v2 v2.5.0
|
github.com/go-viper/mapstructure/v2 v2.5.0
|
||||||
github.com/google/go-cmp v0.7.0
|
github.com/google/go-cmp v0.7.0
|
||||||
github.com/matoous/go-nanoid/v2 v2.1.0
|
github.com/matoous/go-nanoid/v2 v2.1.0
|
||||||
github.com/testcontainers/testcontainers-go v0.41.0
|
github.com/testcontainers/testcontainers-go v0.41.0
|
||||||
github.com/testcontainers/testcontainers-go/modules/mongodb v0.41.0
|
github.com/testcontainers/testcontainers-go/modules/mongodb v0.41.0
|
||||||
go.mongodb.org/mongo-driver/v2 v2.5.0
|
go.mongodb.org/mongo-driver/v2 v2.5.1
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
@@ -37,7 +38,7 @@ require (
|
|||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
|
||||||
github.com/ianlancetaylor/jsonschema v0.0.0-20251021232724-46ecbf32a0a5 // indirect
|
github.com/ianlancetaylor/jsonschema v0.0.0-20251021232724-46ecbf32a0a5 // indirect
|
||||||
github.com/klauspost/compress v1.18.2 // indirect
|
github.com/klauspost/compress v1.18.5 // indirect
|
||||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
|
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
|
||||||
github.com/magiconair/properties v1.8.10 // indirect
|
github.com/magiconair/properties v1.8.10 // indirect
|
||||||
github.com/moby/docker-image-spec v1.3.1 // indirect
|
github.com/moby/docker-image-spec v1.3.1 // indirect
|
||||||
@@ -53,6 +54,7 @@ require (
|
|||||||
github.com/pkg/errors v0.9.1 // indirect
|
github.com/pkg/errors v0.9.1 // indirect
|
||||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
|
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
|
||||||
|
github.com/sergi/go-diff v1.4.0 // indirect
|
||||||
github.com/shirou/gopsutil/v4 v4.26.2 // indirect
|
github.com/shirou/gopsutil/v4 v4.26.2 // indirect
|
||||||
github.com/sirupsen/logrus v1.9.3 // indirect
|
github.com/sirupsen/logrus v1.9.3 // indirect
|
||||||
github.com/stretchr/testify v1.11.1 // indirect
|
github.com/stretchr/testify v1.11.1 // indirect
|
||||||
@@ -68,10 +70,10 @@ require (
|
|||||||
go.opentelemetry.io/otel v1.41.0 // indirect
|
go.opentelemetry.io/otel v1.41.0 // indirect
|
||||||
go.opentelemetry.io/otel/metric v1.41.0 // indirect
|
go.opentelemetry.io/otel/metric v1.41.0 // indirect
|
||||||
go.opentelemetry.io/otel/trace v1.41.0 // indirect
|
go.opentelemetry.io/otel/trace v1.41.0 // indirect
|
||||||
golang.org/x/crypto v0.48.0 // indirect
|
golang.org/x/crypto v0.50.0 // indirect
|
||||||
golang.org/x/sync v0.19.0 // indirect
|
golang.org/x/sync v0.20.0 // indirect
|
||||||
golang.org/x/sys v0.41.0 // indirect
|
golang.org/x/sys v0.43.0 // indirect
|
||||||
golang.org/x/text v0.34.0 // indirect
|
golang.org/x/text v0.36.0 // indirect
|
||||||
google.golang.org/grpc v1.79.1 // indirect
|
google.golang.org/grpc v1.79.1 // indirect
|
||||||
google.golang.org/protobuf v1.36.11 // indirect
|
google.golang.org/protobuf v1.36.11 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
|||||||
55
go.sum
55
go.sum
@@ -1,9 +1,15 @@
|
|||||||
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
|
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
|
||||||
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
|
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
|
||||||
git.gsuntres.com/general/commons v0.0.0-20260329160148-434ecef67a94 h1:U0R2Mg00oC9dWNkXWZMRCBj8Fx6out3HHNIR24srWJ8=
|
git.gsuntres.com/general/commons v0.0.0-20260423193720-28dcfb9e4ce9 h1:wbyyIEMTQqnfE/AfYlzpSwtqbfUW5RP9F6Tt84S7RMI=
|
||||||
git.gsuntres.com/general/commons v0.0.0-20260329160148-434ecef67a94/go.mod h1:gVqoj8oD7D81CnU7vWZbv2jbSYXQDtHBcXs4t6E3rWM=
|
git.gsuntres.com/general/commons v0.0.0-20260423193720-28dcfb9e4ce9/go.mod h1:S93xcBczrgN+gZU0JWkPRnTcAMvQuTp1ChyKkOd/I50=
|
||||||
git.gsuntres.com/general/sys v0.0.0-20260329160429-49966ca31027 h1:4pmcjxEDM4rzv+iimQ7wTgCAQ1VnAoeGiHLuf6wC6Fw=
|
git.gsuntres.com/general/commons v0.0.0-20260425141140-13c75f62b178 h1:+4W5P1MoGF3cis8/HOHXbfAOVY/7UD59UWcMge9d450=
|
||||||
git.gsuntres.com/general/sys v0.0.0-20260329160429-49966ca31027/go.mod h1:OVs7w4/tJO1GT7cLIeEsb90LuZqH2xYIVQODI5P1GJs=
|
git.gsuntres.com/general/commons v0.0.0-20260425141140-13c75f62b178/go.mod h1:S93xcBczrgN+gZU0JWkPRnTcAMvQuTp1ChyKkOd/I50=
|
||||||
|
git.gsuntres.com/general/commons v0.0.0-20260425145405-80a923f150d3 h1:OyKK8RNTKt3exIJjxLvuTd1198TUXyGxbdvKlcLS+DU=
|
||||||
|
git.gsuntres.com/general/commons v0.0.0-20260425145405-80a923f150d3/go.mod h1:S93xcBczrgN+gZU0JWkPRnTcAMvQuTp1ChyKkOd/I50=
|
||||||
|
git.gsuntres.com/general/events v0.0.0-20260424194951-506e91ff46a2 h1:nYzjFP7+foDz9GgGMkuiyMjKMm/N7S65zLU8TiTVqHQ=
|
||||||
|
git.gsuntres.com/general/events v0.0.0-20260424194951-506e91ff46a2/go.mod h1:IQEt0/YT7vYHLTmRhjpqdHgHhagIHZNaay83fndui7s=
|
||||||
|
git.gsuntres.com/general/sys v0.0.1 h1:JpGG6HCkJrTaCICR09kURhMTIc+/s8yb0lHQjo/TDVI=
|
||||||
|
git.gsuntres.com/general/sys v0.0.1/go.mod h1:OVs7w4/tJO1GT7cLIeEsb90LuZqH2xYIVQODI5P1GJs=
|
||||||
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=
|
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=
|
||||||
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
|
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
|
||||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=
|
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=
|
||||||
@@ -61,10 +67,13 @@ github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz
|
|||||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
|
||||||
github.com/ianlancetaylor/jsonschema v0.0.0-20251021232724-46ecbf32a0a5 h1:x2QxKV4w/sBEwwUUmBH/8cFjeOBZqwaB5dz5rcuFspU=
|
github.com/ianlancetaylor/jsonschema v0.0.0-20251021232724-46ecbf32a0a5 h1:x2QxKV4w/sBEwwUUmBH/8cFjeOBZqwaB5dz5rcuFspU=
|
||||||
github.com/ianlancetaylor/jsonschema v0.0.0-20251021232724-46ecbf32a0a5/go.mod h1:KtN3dTgXsLnC5GJBRNmOPd/HUInNcQ84lUCrKJPrvDc=
|
github.com/ianlancetaylor/jsonschema v0.0.0-20251021232724-46ecbf32a0a5/go.mod h1:KtN3dTgXsLnC5GJBRNmOPd/HUInNcQ84lUCrKJPrvDc=
|
||||||
github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk=
|
github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE=
|
||||||
github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||||
|
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||||
|
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||||
|
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=
|
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=
|
||||||
@@ -103,6 +112,8 @@ github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt
|
|||||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
||||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||||
|
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
|
||||||
|
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
|
||||||
github.com/shirou/gopsutil/v4 v4.26.2 h1:X8i6sicvUFih4BmYIGT1m2wwgw2VG9YgrDTi7cIRGUI=
|
github.com/shirou/gopsutil/v4 v4.26.2 h1:X8i6sicvUFih4BmYIGT1m2wwgw2VG9YgrDTi7cIRGUI=
|
||||||
github.com/shirou/gopsutil/v4 v4.26.2/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=
|
github.com/shirou/gopsutil/v4 v4.26.2/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=
|
||||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||||
@@ -110,6 +121,7 @@ github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVs
|
|||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||||
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
@@ -132,8 +144,8 @@ github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfS
|
|||||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
|
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
|
||||||
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
|
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
|
||||||
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
|
go.mongodb.org/mongo-driver/v2 v2.5.1 h1:j2U/Qp+wvueSpqitLCSZPT/+ZpVc1xzuwdHWwl7d8ro=
|
||||||
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
|
go.mongodb.org/mongo-driver/v2 v2.5.1/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
|
||||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 h1:jq9TW8u3so/bN+JPT166wjOI6/vQPF6Xe7nMNIltagk=
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 h1:jq9TW8u3so/bN+JPT166wjOI6/vQPF6Xe7nMNIltagk=
|
||||||
@@ -154,18 +166,18 @@ go.opentelemetry.io/proto/otlp v1.0.0 h1:T0TX0tmXU8a3CbNXzEKGeU5mIVOdf0oykP+u2lI
|
|||||||
go.opentelemetry.io/proto/otlp v1.0.0/go.mod h1:Sy6pihPLfYHkr3NkUbEhGHFhINUSI/v80hjKIs5JXpM=
|
go.opentelemetry.io/proto/otlp v1.0.0/go.mod h1:Sy6pihPLfYHkr3NkUbEhGHFhINUSI/v80hjKIs5JXpM=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||||
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=
|
||||||
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
|
||||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||||
golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
|
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
|
||||||
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
|
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
|
||||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
@@ -175,18 +187,18 @@ golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBc
|
|||||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
||||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg=
|
golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY=
|
||||||
golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM=
|
golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY=
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||||
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
|
||||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
|
||||||
golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 h1:vVKdlvoWBphwdxWKrFZEuM0kGgGLxUOYcY4U/2Vjg44=
|
golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 h1:vVKdlvoWBphwdxWKrFZEuM0kGgGLxUOYcY4U/2Vjg44=
|
||||||
golang.org/x/time v0.0.0-20220210224613-90d013bbcef8/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
golang.org/x/time v0.0.0-20220210224613-90d013bbcef8/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
@@ -203,8 +215,11 @@ google.golang.org/grpc v1.79.1/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhH
|
|||||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
68
insert.go
68
insert.go
@@ -2,19 +2,13 @@ package mongo
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"time"
|
"slices"
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"go.mongodb.org/mongo-driver/v2/bson"
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
"github.com/matoous/go-nanoid/v2"
|
|
||||||
|
|
||||||
// "git.gsuntres.com/boxtep/boxtep/core"
|
"git.gsuntres.com/general/commons"
|
||||||
)
|
)
|
||||||
|
|
||||||
const alphabet = "0123456789abcdefghijclmnopqrstuvwxyz"
|
|
||||||
|
|
||||||
const maxLen = 10
|
|
||||||
|
|
||||||
// InsertOneWithStruct can be used to insert defined structs.
|
// InsertOneWithStruct can be used to insert defined structs.
|
||||||
func (c *MongoClient) InsertOneFromStruct(ctx context.Context, database, name string, data any) (bson.M, error) {
|
func (c *MongoClient) InsertOneFromStruct(ctx context.Context, database, name string, data any) (bson.M, error) {
|
||||||
o, err := ToMap(data)
|
o, err := ToMap(data)
|
||||||
@@ -26,15 +20,36 @@ func (c *MongoClient) InsertOneFromStruct(ctx context.Context, database, name st
|
|||||||
}
|
}
|
||||||
|
|
||||||
// InsertOne will add missing ids and the created date before saving to the database.
|
// InsertOne will add missing ids and the created date before saving to the database.
|
||||||
func (c *MongoClient) InsertOne(ctx context.Context, database, name string, data bson.M) (bson.M, error) {
|
func (c *MongoClient) InsertOne(ctx context.Context, database, name string, original bson.M) (bson.M, error) {
|
||||||
collection := c.GetCollection(database, name)
|
collection := c.GetCollection(database, name)
|
||||||
|
|
||||||
|
data := commons.BsonClone(original)
|
||||||
|
|
||||||
prepareForInsert(data, c.GetIdPrefix(name))
|
prepareForInsert(data, c.GetIdPrefix(name))
|
||||||
|
|
||||||
|
if err := c.DiscriminatorCheckAndApplyToData(ctx, name, data); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
if _, err := collection.InsertOne(ctx, data); err != nil {
|
if _, err := collection.InsertOne(ctx, data); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ignoreAudit := slices.Contains(c.IgnoreAudit, name)
|
||||||
|
|
||||||
|
if c.WithAudit && !ignoreAudit {
|
||||||
|
contx := commons.ContextSerialize(ctx, c.ContextFields)
|
||||||
|
audit := &AuditResult {
|
||||||
|
Entity: name,
|
||||||
|
Op: OpInsert,
|
||||||
|
Data: original,
|
||||||
|
After: data,
|
||||||
|
Context: contx,
|
||||||
|
}
|
||||||
|
|
||||||
|
(*c.OnAudit)(audit)
|
||||||
|
}
|
||||||
|
|
||||||
return data, nil
|
return data, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,38 +61,3 @@ func prepareForInsert(data bson.M, idPrefix string) {
|
|||||||
ensureCreatedAt(data)
|
ensureCreatedAt(data)
|
||||||
ensureUpdatedAt(data)
|
ensureUpdatedAt(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ensureId adds the id property when missing or when it's an empty string.
|
|
||||||
func ensureId(data bson.M, idPrefix string) string {
|
|
||||||
maybeId, hasId := data["_id"]
|
|
||||||
|
|
||||||
var id, finalId string
|
|
||||||
if !hasId || maybeId == "" {
|
|
||||||
id, _ = gonanoid.Generate(alphabet, maxLen)
|
|
||||||
if idPrefix != "" {
|
|
||||||
finalId = fmt.Sprintf("%s_%s", idPrefix, id)
|
|
||||||
} else {
|
|
||||||
finalId = id
|
|
||||||
}
|
|
||||||
|
|
||||||
data["_id"] = finalId
|
|
||||||
}
|
|
||||||
|
|
||||||
return finalId
|
|
||||||
}
|
|
||||||
|
|
||||||
func ensureCreatedAt(data bson.M) time.Time {
|
|
||||||
now := time.Now().UTC().Truncate(time.Millisecond)
|
|
||||||
|
|
||||||
data["created_at"] = now
|
|
||||||
|
|
||||||
return now
|
|
||||||
}
|
|
||||||
|
|
||||||
func ensureUpdatedAt(data bson.M) time.Time {
|
|
||||||
now := time.Now().UTC().Truncate(time.Millisecond)
|
|
||||||
|
|
||||||
data["updated_at"] = now
|
|
||||||
|
|
||||||
return now
|
|
||||||
}
|
|
||||||
|
|||||||
192
insert_test.go
192
insert_test.go
@@ -2,10 +2,10 @@ package mongo
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
|
"fmt"
|
||||||
"context"
|
"context"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"testing/synctest"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
|
||||||
"go.mongodb.org/mongo-driver/v2/bson"
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
@@ -122,54 +122,186 @@ func TestPrepareForInsert_ExistingId(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestEnsureId(t *testing.T) {
|
func TestInsertOne_Discriminate(t *testing.T) {
|
||||||
data := map[string]any {
|
// 1. Register schemas
|
||||||
"Name": "My Name Is",
|
schemaStore, err := os.ReadFile("./.test/store.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
schemaOffer, err := os.ReadFile("./.test/offer.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
var store bson.M
|
||||||
|
if err := json.Unmarshal(schemaStore, &store); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaStore), schemaStore[:4])
|
||||||
}
|
}
|
||||||
|
|
||||||
ensureId(data, "")
|
var offer bson.M
|
||||||
|
if err := json.Unmarshal(schemaOffer, &offer); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaOffer), schemaOffer[:4])
|
||||||
|
}
|
||||||
|
|
||||||
if id, okid := data["_id"]; !okid || id == "" {
|
client := GetMongoClient()
|
||||||
t.Fatal("Failed to add Id")
|
client.AddDefinition(store)
|
||||||
|
client.AddDefinition(offer)
|
||||||
|
|
||||||
|
// Test
|
||||||
|
ctx := context.Background()
|
||||||
|
ctx = context.WithValue(ctx, "account", "xxxxxx")
|
||||||
|
ctx = context.WithValue(ctx, "store", "str_1234")
|
||||||
|
|
||||||
|
// 2. Insert data
|
||||||
|
offer1 := map[string]any {
|
||||||
|
"name": "Offer 1",
|
||||||
|
}
|
||||||
|
|
||||||
|
saved, err := client.InsertOne(ctx, "mydb", "offer", offer1)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
v, ok := saved["store"]
|
||||||
|
if !ok || v != "str_1234" {
|
||||||
|
t.Fatalf("Should have set store not %s", v)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestEnsureId_EmptyId(t *testing.T) {
|
func TestInsertOne_Discriminate_NoStore(t *testing.T) {
|
||||||
data := map[string]any {
|
// 1. Register schemas
|
||||||
"_id": "myidxxxxxx",
|
schemaStore, err := os.ReadFile("./.test/store.json")
|
||||||
"name": "My Name Is",
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
schemaOffer, err := os.ReadFile("./.test/offer.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
var store bson.M
|
||||||
|
if err := json.Unmarshal(schemaStore, &store); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaStore), schemaStore[:4])
|
||||||
}
|
}
|
||||||
|
|
||||||
ensureId(data, "")
|
var offer bson.M
|
||||||
|
if err := json.Unmarshal(schemaOffer, &offer); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaOffer), schemaOffer[:4])
|
||||||
|
}
|
||||||
|
|
||||||
if data["_id"] == "" {
|
client := GetMongoClient()
|
||||||
t.Fatal("Id was updated")
|
client.AddDefinition(store)
|
||||||
|
client.AddDefinition(offer)
|
||||||
|
|
||||||
|
// Test
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
// 2. Insert data
|
||||||
|
offer1 := map[string]any {
|
||||||
|
"name": "Offer 1",
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = client.InsertOne(ctx, "mydb", "offer", offer1)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Should have required store")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestEnsureId_ExistingId(t *testing.T) {
|
func TestInsertOne_Discriminate_EnsureStore(t *testing.T) {
|
||||||
data := map[string]any {
|
// 1. Register schemas
|
||||||
"_id": "",
|
schemaStore, err := os.ReadFile("./.test/store.json")
|
||||||
"name": "My Name Is",
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
schemaOffer, err := os.ReadFile("./.test/offer.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
var store bson.M
|
||||||
|
if err := json.Unmarshal(schemaStore, &store); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaStore), schemaStore[:4])
|
||||||
}
|
}
|
||||||
|
|
||||||
ensureId(data, "")
|
var offer bson.M
|
||||||
|
if err := json.Unmarshal(schemaOffer, &offer); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaOffer), schemaOffer[:4])
|
||||||
|
}
|
||||||
|
|
||||||
if id, okid := data["_id"]; !okid || id == "" {
|
client := GetMongoClient()
|
||||||
t.Fatal("Failed to add Id")
|
client.AddDefinition(store)
|
||||||
|
client.AddDefinition(offer)
|
||||||
|
|
||||||
|
// Test
|
||||||
|
ctx := context.Background()
|
||||||
|
ctx = context.WithValue(ctx, "store", "str_1234")
|
||||||
|
|
||||||
|
// 2. Insert data
|
||||||
|
offer1 := map[string]any {
|
||||||
|
"name": "Offer 100",
|
||||||
|
"store": "str_0000",
|
||||||
|
}
|
||||||
|
|
||||||
|
saved, err := client.InsertOne(ctx, "mydb", "offer", offer1)
|
||||||
|
|
||||||
|
if saved["store"] != "str_1234" {
|
||||||
|
t.Fatal("Wrong store")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestEnsureCreatedAt(t *testing.T) {
|
func TestInsertOne_WithAudit(t *testing.T) {
|
||||||
data := map[string]any {
|
client := GetMongoClient()
|
||||||
"name": "My Name Is",
|
|
||||||
}
|
|
||||||
|
|
||||||
synctest.Test(t, func(t *testing.T) {
|
var (
|
||||||
now := ensureCreatedAt(data)
|
onAudit_calls int
|
||||||
|
onAudit_after any
|
||||||
|
onAudit_context any
|
||||||
|
)
|
||||||
|
|
||||||
if createdAt, _ := data["created_at"]; createdAt != now {
|
cancel := client.Subscribe(func(audit *AuditResult) error {
|
||||||
t.Fatal("Failed to add CreatedAt")
|
onAudit_calls++
|
||||||
}
|
onAudit_after = audit.After
|
||||||
|
onAudit_context = audit.Context
|
||||||
|
|
||||||
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
|
data := map[string]any {
|
||||||
|
"_id": "su_123458",
|
||||||
|
"name": "MyNameTODelete",
|
||||||
|
"age": int32(25),
|
||||||
|
}
|
||||||
|
|
||||||
|
o, err := client.InsertOne(context.Background(), "mydb", "mycollection", data)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
ctx = context.WithValue(ctx, "account", "xxxxxx")
|
||||||
|
ctx = context.WithValue(ctx, "store", "str_4321")
|
||||||
|
err = client.DeleteOne(ctx, "mydb", "mycollection", bson.M{"_id": o["_id"].(string)})
|
||||||
|
if err != nil { t.Fatalf("Failed to deleteOne %#v", err) }
|
||||||
|
|
||||||
|
// raw query
|
||||||
|
var results bson.M
|
||||||
|
filter := bson.M{ "name": "MyNameTODelete" }
|
||||||
|
|
||||||
|
c := client.Client.Database("mydb").Collection("mycollection")
|
||||||
|
c.FindOne(context.Background(), filter).Decode(&results)
|
||||||
|
|
||||||
|
if results != nil {
|
||||||
|
t.Fatalf("Should have no results not %v", results)
|
||||||
|
}
|
||||||
|
|
||||||
|
if onAudit_calls != 1 {
|
||||||
|
t.Fatalf("ondelete should have been called once, not %d", onAudit_calls)
|
||||||
|
}
|
||||||
|
|
||||||
|
if onAudit_after != nil {
|
||||||
|
tp := fmt.Sprintf("%T", onAudit_after)
|
||||||
|
|
||||||
|
expectedType := fmt.Sprintf("%T", map[string]any{})
|
||||||
|
if tp != expectedType {
|
||||||
|
t.Fatalf("after has the wrong type %s", tp)
|
||||||
|
}
|
||||||
|
|
||||||
|
after := onAudit_after.(map[string]any)
|
||||||
|
|
||||||
|
AssertSubset(t, after, o, "Should have been equal")
|
||||||
|
}
|
||||||
|
|
||||||
|
if onAudit_context != nil {
|
||||||
|
ctx := onAudit_context.(map[string]any)
|
||||||
|
AssertSubset(t, ctx, map[string]any{"account": "xxxxxx", "store": "str_4321"}, "Should have been equal")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
288
main.go
288
main.go
@@ -17,8 +17,13 @@ import (
|
|||||||
|
|
||||||
"git.gsuntres.com/general/commons"
|
"git.gsuntres.com/general/commons"
|
||||||
"git.gsuntres.com/general/sys"
|
"git.gsuntres.com/general/sys"
|
||||||
|
"git.gsuntres.com/general/events"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
log.SetFlags(log.LstdFlags | log.Lshortfile)
|
||||||
|
}
|
||||||
|
|
||||||
// WithiSessionFunc will run operations on the database within the same session.
|
// WithiSessionFunc will run operations on the database within the same session.
|
||||||
// If this functions returns an error, the system will rollback the transaction.
|
// If this functions returns an error, the system will rollback the transaction.
|
||||||
// Sessions require a resplica set.
|
// Sessions require a resplica set.
|
||||||
@@ -36,6 +41,24 @@ type IMongoClient interface {
|
|||||||
|
|
||||||
// GetCollection returns the requested collection within an account. It will create it if it doesn't exist.
|
// GetCollection returns the requested collection within an account. It will create it if it doesn't exist.
|
||||||
GetCollection(database, name string) *mongo.Collection
|
GetCollection(database, name string) *mongo.Collection
|
||||||
|
|
||||||
|
SetRelaxed()
|
||||||
|
|
||||||
|
SetStrict()
|
||||||
|
}
|
||||||
|
|
||||||
|
type Timeseries struct {
|
||||||
|
TimeField string `bson:"timeField"`
|
||||||
|
MetaField string `bson:"metaField"`
|
||||||
|
Granularity string `bson:"granularity"`
|
||||||
|
BucketMaxSpan int64 `bson:"bucketMaxSpan"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Discriminator struct {
|
||||||
|
Field string `bson:"field"`
|
||||||
|
CtxField string `bson:"ctxField"`
|
||||||
|
Collection string `bson:"collection"`
|
||||||
|
Required bool `bson:"required,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type CollectionDefinition struct {
|
type CollectionDefinition struct {
|
||||||
@@ -45,10 +68,12 @@ type CollectionDefinition struct {
|
|||||||
IdPrefix string `bson:"idPrefix"`
|
IdPrefix string `bson:"idPrefix"`
|
||||||
IndexSpecs []map[string]any `bson:"indexSpecs"`
|
IndexSpecs []map[string]any `bson:"indexSpecs"`
|
||||||
Schema map[string]any `bson:"schema"`
|
Schema map[string]any `bson:"schema"`
|
||||||
|
Views map[string]any `bson:"views"`
|
||||||
|
Ttl int64 `bson:"ttl"`
|
||||||
|
Timeseries *Timeseries `bson:"timeseries,omitempty"`
|
||||||
|
Discriminator *Discriminator
|
||||||
}
|
}
|
||||||
|
|
||||||
// func (cd *CollectionDefinition) GetSchema(name string)
|
|
||||||
|
|
||||||
// MongoClient
|
// MongoClient
|
||||||
type MongoClient struct {
|
type MongoClient struct {
|
||||||
// Client the actual connected instance of mongo client.
|
// Client the actual connected instance of mongo client.
|
||||||
@@ -63,6 +88,40 @@ type MongoClient struct {
|
|||||||
DBPrefix string
|
DBPrefix string
|
||||||
// Registry holds critical information about collection's structure, like schema and indexes
|
// Registry holds critical information about collection's structure, like schema and indexes
|
||||||
Registry map[string]*CollectionDefinition
|
Registry map[string]*CollectionDefinition
|
||||||
|
// Alias collection names that map to a registered collection
|
||||||
|
Aliases map[string]string
|
||||||
|
// Relaxed if set to true will not enforce schema
|
||||||
|
Relaxed bool
|
||||||
|
// Context fields to serialize when needed
|
||||||
|
ContextFields []string
|
||||||
|
// WithAudit enable auditing functionality.
|
||||||
|
WithAudit bool
|
||||||
|
// OnAudit callback called when audit is enabled.
|
||||||
|
OnAudit *OnAudit
|
||||||
|
// EventBus
|
||||||
|
EventBus *events.TypedEventBus
|
||||||
|
// IgnoreAudit a list of entities to ignore
|
||||||
|
IgnoreAudit []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddAlias will add the alias only if it doesn't exist.
|
||||||
|
func (c *MongoClient) AddAlias(alias, name string) {
|
||||||
|
if c.Aliases == nil {
|
||||||
|
c.Aliases = make(map[string]string)
|
||||||
|
}
|
||||||
|
_, ok := c.Aliases[alias]
|
||||||
|
if !ok {
|
||||||
|
log.Printf("Registering alias %s to %s", alias, name)
|
||||||
|
c.Aliases[alias] = name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *MongoClient) SetRelaxed() {
|
||||||
|
c.Relaxed = true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *MongoClient) SetStrict() {
|
||||||
|
c.Relaxed = false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *MongoClient) GetIdPrefix(name string) string {
|
func (c *MongoClient) GetIdPrefix(name string) string {
|
||||||
@@ -74,34 +133,6 @@ func (c *MongoClient) GetIdPrefix(name string) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
const ADD_DEFINITION_SCHEMA = `
|
|
||||||
{
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"_name": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"idPrefix": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"indexSpecs": {
|
|
||||||
"type": "array"
|
|
||||||
},
|
|
||||||
"singular": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"system": {
|
|
||||||
"type": "boolean"
|
|
||||||
},
|
|
||||||
"plural": {
|
|
||||||
"type": "string"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": ["_name", "singular", "plural"],
|
|
||||||
"additionalProperties": true
|
|
||||||
}
|
|
||||||
`
|
|
||||||
|
|
||||||
func (c *MongoClient) AddDefinition(data map[string]any) {
|
func (c *MongoClient) AddDefinition(data map[string]any) {
|
||||||
if valid := commons.Validate(ADD_DEFINITION_SCHEMA, data); valid != nil {
|
if valid := commons.Validate(ADD_DEFINITION_SCHEMA, data); valid != nil {
|
||||||
log.Printf("failed to register data: %v", valid)
|
log.Printf("failed to register data: %v", valid)
|
||||||
@@ -124,6 +155,28 @@ func (c *MongoClient) AddDefinition(data map[string]any) {
|
|||||||
if len(cd.Name) > 0 {
|
if len(cd.Name) > 0 {
|
||||||
c.Registry[cd.Name] = &cd
|
c.Registry[cd.Name] = &cd
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if cd.Views != nil {
|
||||||
|
for k, _ := range cd.Views {
|
||||||
|
c.AddAlias(k, cd.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *MongoClient) DropDatabase_DANGER(database string) bool {
|
||||||
|
log.Printf("DANGER attempt to drop database: %s", database)
|
||||||
|
|
||||||
|
db := c.Client.Database(database)
|
||||||
|
|
||||||
|
if err := db.Drop(context.Background()); err != nil {
|
||||||
|
log.Printf("Failed to drop database: %v", err)
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Database %s deleted", database)
|
||||||
|
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *MongoClient) GetCollection(database, name string) *mongo.Collection {
|
func (c *MongoClient) GetCollection(database, name string) *mongo.Collection {
|
||||||
@@ -133,6 +186,9 @@ func (c *MongoClient) GetCollection(database, name string) *mongo.Collection {
|
|||||||
|
|
||||||
db := c.Client.Database(database)
|
db := c.Client.Database(database)
|
||||||
|
|
||||||
|
// To make sure we create the right collection when dealing with aliases.
|
||||||
|
actualName := name
|
||||||
|
|
||||||
// 1. List existing collections
|
// 1. List existing collections
|
||||||
names, err := db.ListCollectionNames(context.TODO(), bson.D{})
|
names, err := db.ListCollectionNames(context.TODO(), bson.D{})
|
||||||
|
|
||||||
@@ -143,38 +199,68 @@ func (c *MongoClient) GetCollection(database, name string) *mongo.Collection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 2. If collection exist return it, otherwise create it and then return it
|
// 2. If collection exist return it, otherwise create it and then return it
|
||||||
if slices.Contains(names, name) {
|
if slices.Contains(names, actualName) {
|
||||||
return db.Collection(name)
|
return db.Collection(actualName)
|
||||||
} else {
|
} else {
|
||||||
opts := options.CreateCollection()
|
opts := options.CreateCollection()
|
||||||
|
|
||||||
// maybe get from schema
|
// maybe get from schema
|
||||||
cdef, ok := c.Registry[name]
|
cdef, ok := c.Registry[actualName]
|
||||||
if ok {
|
if ok {
|
||||||
log.Printf("Schema found for %s; will use it", name)
|
|
||||||
|
|
||||||
|
actualName = cdef.Name
|
||||||
|
|
||||||
|
log.Printf("Schema found for %s; will use it", actualName)
|
||||||
|
|
||||||
|
ApplyTimeSeries(cdef, opts)
|
||||||
ApplySchema(cdef, opts)
|
ApplySchema(cdef, opts)
|
||||||
} else {
|
} else {
|
||||||
log.Printf("No schema for %s", name)
|
log.Printf("No schema for %s", actualName)
|
||||||
|
|
||||||
|
if c.Relaxed == false {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := db.CreateCollection(context.TODO(), name, opts); err != nil {
|
if err := db.CreateCollection(context.TODO(), actualName, opts); err != nil {
|
||||||
log.Printf("Failed to create collection: %#v", err)
|
log.Printf("Failed to create collection: %#v", err)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
collection := db.Collection(name)
|
collection := db.Collection(actualName)
|
||||||
|
|
||||||
c.CreateIndexes(collection, cdef)
|
c.CreateIndexes(collection, cdef)
|
||||||
|
|
||||||
|
if c.CreateViews(db, cdef) {
|
||||||
|
collection = db.Collection(name)
|
||||||
|
}
|
||||||
|
|
||||||
return collection
|
return collection
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ApplyTimeSeries(cdef *CollectionDefinition, opts *options.CreateCollectionOptionsBuilder) {
|
||||||
|
if cdef.Timeseries != nil {
|
||||||
|
tsOpts := options.TimeSeries().
|
||||||
|
SetTimeField(cdef.Timeseries.TimeField).
|
||||||
|
SetMetaField(cdef.Timeseries.MetaField).
|
||||||
|
SetGranularity(cdef.Timeseries.Granularity)
|
||||||
|
|
||||||
|
if cdef.Timeseries.BucketMaxSpan > 0 {
|
||||||
|
tsOpts.SetBucketMaxSpan(time.Duration(cdef.Timeseries.BucketMaxSpan) * time.Second)
|
||||||
|
}
|
||||||
|
|
||||||
|
opts.SetTimeSeriesOptions(tsOpts)
|
||||||
|
|
||||||
|
opts.SetExpireAfterSeconds(cdef.Ttl)
|
||||||
|
} else {
|
||||||
|
log.Printf("No timeseries")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func ApplySchema(cdef *CollectionDefinition, opts *options.CreateCollectionOptionsBuilder) {
|
func ApplySchema(cdef *CollectionDefinition, opts *options.CreateCollectionOptionsBuilder) {
|
||||||
// Add schema validation
|
// Add schema validation
|
||||||
if cdef.Schema != nil {
|
if cdef.Schema != nil && cdef.Timeseries == nil {
|
||||||
schemaBson, err := bson.Marshal(cdef.Schema)
|
schemaBson, err := bson.Marshal(cdef.Schema)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("failed to parse schema: %v", err)
|
log.Printf("failed to parse schema: %v", err)
|
||||||
@@ -188,13 +274,15 @@ func ApplySchema(cdef *CollectionDefinition, opts *options.CreateCollectionOptio
|
|||||||
opts.SetValidator(validator)
|
opts.SetValidator(validator)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log.Printf("Invalid schema, do nothing.")
|
log.Printf("Validation disabled")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var client *MongoClient = &MongoClient{
|
var client *MongoClient = &MongoClient{
|
||||||
Limit: 10,
|
Limit: 10,
|
||||||
Registry: make(map[string]*CollectionDefinition, 0),
|
Registry: make(map[string]*CollectionDefinition, 0),
|
||||||
|
Relaxed: false,
|
||||||
|
IgnoreAudit: []string{"event"},
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetMongoClient() *MongoClient {
|
func GetMongoClient() *MongoClient {
|
||||||
@@ -225,6 +313,11 @@ type MongoStartProps struct {
|
|||||||
MongoPass string
|
MongoPass string
|
||||||
MongoDebugQuery bool
|
MongoDebugQuery bool
|
||||||
MongoDBPrefix string
|
MongoDBPrefix string
|
||||||
|
ContextFields []string
|
||||||
|
WithAudit bool
|
||||||
|
AutoCleanup bool
|
||||||
|
OnAudit *OnAudit
|
||||||
|
AllowTruncatingDoubles bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func Start(props *MongoStartProps) error {
|
func Start(props *MongoStartProps) error {
|
||||||
@@ -254,21 +347,34 @@ func Start(props *MongoStartProps) error {
|
|||||||
UseJSONStructTags: false,
|
UseJSONStructTags: false,
|
||||||
NilSliceAsEmpty: true,
|
NilSliceAsEmpty: true,
|
||||||
NilMapAsEmpty: true,
|
NilMapAsEmpty: true,
|
||||||
|
AllowTruncatingDoubles: props.AllowTruncatingDoubles,
|
||||||
}).
|
}).
|
||||||
SetRegistry(GetCustomRegistry())
|
SetRegistry(GetCustomRegistry())
|
||||||
|
|
||||||
|
colors := []string{
|
||||||
|
commons.EscapeGreen,
|
||||||
|
commons.EscapeRed,
|
||||||
|
commons.EscapeYellow,
|
||||||
|
commons.EscapeBlue,
|
||||||
|
commons.EscapeMagenta,
|
||||||
|
commons.EscapeCyan,
|
||||||
|
}
|
||||||
|
|
||||||
client.DebugQuery = props.MongoDebugQuery
|
client.DebugQuery = props.MongoDebugQuery
|
||||||
if client.DebugQuery {
|
if client.DebugQuery {
|
||||||
// Debug queries
|
// Debug queries
|
||||||
monitor := &event.CommandMonitor{
|
monitor := &event.CommandMonitor{
|
||||||
Started: func(_ context.Context, e *event.CommandStartedEvent) {
|
Started: func(_ context.Context, e *event.CommandStartedEvent) {
|
||||||
log.Printf("%d@Start %s#%s %s", e.RequestID, e.DatabaseName, e.CommandName, e.Command)
|
ecode := colors[e.RequestID % 6]
|
||||||
|
log.Printf("%s%d@Start%s %s#%s %s", ecode, e.RequestID, commons.EscapeReset, e.DatabaseName, e.CommandName, e.Command)
|
||||||
},
|
},
|
||||||
Succeeded: func(_ context.Context, e *event.CommandSucceededEvent) {
|
Succeeded: func(_ context.Context, e *event.CommandSucceededEvent) {
|
||||||
log.Printf("%d@OK in %s", e.RequestID, e.Reply)
|
ecode := colors[e.RequestID % 6]
|
||||||
|
log.Printf("%s%d@OK%s in %s", ecode, e.RequestID, commons.EscapeReset, e.Reply)
|
||||||
},
|
},
|
||||||
Failed: func(_ context.Context, e *event.CommandFailedEvent) {
|
Failed: func(_ context.Context, e *event.CommandFailedEvent) {
|
||||||
log.Printf("%d@Fail in %s", e.RequestID, e.Failure)
|
ecode := colors[e.RequestID % 6]
|
||||||
|
log.Printf("%s%d@Fail%s in %s", ecode, e.RequestID, commons.EscapeReset, e.Failure)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -278,6 +384,19 @@ func Start(props *MongoStartProps) error {
|
|||||||
// set DBPrefix
|
// set DBPrefix
|
||||||
client.DBPrefix = props.MongoDBPrefix
|
client.DBPrefix = props.MongoDBPrefix
|
||||||
|
|
||||||
|
client.ContextFields = props.ContextFields
|
||||||
|
|
||||||
|
client.WithAudit = props.WithAudit
|
||||||
|
|
||||||
|
client.EventBus = events.NewTypedEventBus()
|
||||||
|
|
||||||
|
if client.WithAudit {
|
||||||
|
var onAudit OnAudit = func(audit *AuditResult) error {
|
||||||
|
return events.Publish(client.EventBus, audit)
|
||||||
|
}
|
||||||
|
client.OnAudit = &onAudit
|
||||||
|
}
|
||||||
|
|
||||||
if err := cOptions.Validate(); err != nil {
|
if err := cOptions.Validate(); err != nil {
|
||||||
log.Fatalf("Failed to validate mongo options: %+v", err.Error())
|
log.Fatalf("Failed to validate mongo options: %+v", err.Error())
|
||||||
|
|
||||||
@@ -292,11 +411,13 @@ func Start(props *MongoStartProps) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if props.AutoCleanup {
|
||||||
sys.OnExit(func () {
|
sys.OnExit(func () {
|
||||||
if err := client.Client.Disconnect(context.TODO()); err != nil {
|
if err := Stop(); err != nil {
|
||||||
log.Fatalf("failed to disconnect: %v", err)
|
log.Fatalf("failed to disconnect: %v", err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// Register defaults.go
|
// Register defaults.go
|
||||||
var structfulDef bson.M
|
var structfulDef bson.M
|
||||||
@@ -307,6 +428,10 @@ func Start(props *MongoStartProps) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *MongoClient) Subscribe(h events.Handler[AuditResult]) (cancel func()) {
|
||||||
|
return events.Subscribe(c.EventBus, h)
|
||||||
|
}
|
||||||
|
|
||||||
func GetClient() *mongo.Client {
|
func GetClient() *mongo.Client {
|
||||||
return client.Client
|
return client.Client
|
||||||
}
|
}
|
||||||
@@ -350,3 +475,78 @@ func MapToBsonD(m map[string]any) (bson.D, error) {
|
|||||||
|
|
||||||
return d, nil
|
return d, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ADD_DEFINITION_SCHEMA = `
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"_name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"idPrefix": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"indexSpecs": {
|
||||||
|
"type": "array"
|
||||||
|
},
|
||||||
|
"singular": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"system": {
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
"plural": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"schema": {
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"views": {
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"ttl": {
|
||||||
|
"type": "integer",
|
||||||
|
"format": "int64"
|
||||||
|
},
|
||||||
|
"timeseries": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"timeField": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"metaField": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"granularity": {
|
||||||
|
"enum": [ "seconds", "minutes", "hours"]
|
||||||
|
},
|
||||||
|
"bucketMaxSpan": {
|
||||||
|
"type": "integer",
|
||||||
|
"format": "int64"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["timeField", "metaField", "granularity"]
|
||||||
|
},
|
||||||
|
"discriminator": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"field": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"ctxField": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"collection": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"required": {
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["field", "ctxField", "collection"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["_name", "singular", "plural"],
|
||||||
|
"additionalProperties": true
|
||||||
|
}
|
||||||
|
`
|
||||||
@@ -21,7 +21,8 @@ func (c *MongoClient) CreateIndexes(collection *mongo.Collection, cdef *Collecti
|
|||||||
indexModels := make([]mongo.IndexModel, 0)
|
indexModels := make([]mongo.IndexModel, 0)
|
||||||
|
|
||||||
for _, keyDef := range cdef.IndexSpecs {
|
for _, keyDef := range cdef.IndexSpecs {
|
||||||
log.Printf("Key Definition %s", keyDef["name"])
|
log.Printf("Key Definition [%s]%s", cdef.Name, keyDef["name"])
|
||||||
|
|
||||||
kdb, err := bson.Marshal(keyDef)
|
kdb, err := bson.Marshal(keyDef)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("failed to marshal %v", err)
|
log.Printf("failed to marshal %v", err)
|
||||||
@@ -44,7 +45,7 @@ func (c *MongoClient) CreateIndexes(collection *mongo.Collection, cdef *Collecti
|
|||||||
|
|
||||||
var keysBson bson.D
|
var keysBson bson.D
|
||||||
if err := bson.Unmarshal(keysVal.Value, &keysBson); err != nil {
|
if err := bson.Unmarshal(keysVal.Value, &keysBson); err != nil {
|
||||||
log.Printf("failed to unmarshal keys value %v", err)
|
log.Printf("failed to unmarshal keys value %v, %v", keysVal, err)
|
||||||
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -62,7 +63,12 @@ func (c *MongoClient) CreateIndexes(collection *mongo.Collection, cdef *Collecti
|
|||||||
}
|
}
|
||||||
|
|
||||||
partialVal := kdRaw.Lookup("partialFilterExpression")
|
partialVal := kdRaw.Lookup("partialFilterExpression")
|
||||||
if partialFilterExpression, ok := partialVal.BooleanOK(); ok {
|
if partialVal.Type == bson.TypeEmbeddedDocument {
|
||||||
|
var partialFilterExpression bson.M
|
||||||
|
if err := bson.Unmarshal(partialVal.Value, &partialFilterExpression); err != nil {
|
||||||
|
log.Printf("failed to unmarshal partial filter: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
opts = opts.SetPartialFilterExpression(partialFilterExpression)
|
opts = opts.SetPartialFilterExpression(partialFilterExpression)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
package mongo
|
package mongo
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
"context"
|
"context"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
"go.mongodb.org/mongo-driver/v2/bson"
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
)
|
)
|
||||||
@@ -22,8 +25,12 @@ func TestCreateIndexes(t *testing.T) {
|
|||||||
|
|
||||||
c := GetMongoClient()
|
c := GetMongoClient()
|
||||||
|
|
||||||
|
c.SetRelaxed()
|
||||||
|
|
||||||
collection := c.GetCollection("mydb", "mycol")
|
collection := c.GetCollection("mydb", "mycol")
|
||||||
|
|
||||||
|
c.SetStrict()
|
||||||
|
|
||||||
c.CreateIndexes(collection, cd)
|
c.CreateIndexes(collection, cd)
|
||||||
|
|
||||||
indexView := collection.Indexes()
|
indexView := collection.Indexes()
|
||||||
@@ -54,3 +61,59 @@ func TestCreateIndexes(t *testing.T) {
|
|||||||
t.Fatal("Should have register index idx_1")
|
t.Fatal("Should have register index idx_1")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCreateTimeSeries(t *testing.T) {
|
||||||
|
// 1. Register schemas
|
||||||
|
schemaEvent, err := os.ReadFile("./.test/event.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
var event bson.M
|
||||||
|
if err := json.Unmarshal(schemaEvent, &event); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaEvent), schemaEvent[:4])
|
||||||
|
}
|
||||||
|
|
||||||
|
client := GetMongoClient()
|
||||||
|
client.AddDefinition(event)
|
||||||
|
|
||||||
|
// 2. Insert data
|
||||||
|
event1 := map[string]any {
|
||||||
|
"name": "event1",
|
||||||
|
"createdAt": time.Now(),
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = client.InsertOne(context.Background(), "mydb", "event", event1)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
c := client.GetCollection("mydb", "event")
|
||||||
|
db := c.Database()
|
||||||
|
|
||||||
|
cmd := bson.D{
|
||||||
|
{Key: "listCollections", Value: 1},
|
||||||
|
{Key: "filter", Value: bson.D{
|
||||||
|
{Key: "name", Value: "event"},
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
|
||||||
|
var result struct {
|
||||||
|
Cursor struct {
|
||||||
|
FirstBatch []bson.M `bson:"firstBatch"`
|
||||||
|
} `bson:"cursor"`
|
||||||
|
}
|
||||||
|
err = db.RunCommand(context.Background(), cmd).Decode(&result)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
coll := result.Cursor.FirstBatch[0]
|
||||||
|
|
||||||
|
if coll["type"] != "timeseries" {
|
||||||
|
fmt.Println("❌ time series collection")
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts, ok := coll["options"].(bson.M); ok {
|
||||||
|
if _, ok := opts["timeseries"]; !ok {
|
||||||
|
t.Fatal("❌ time series collection")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -47,10 +47,15 @@ func TestMain(m *testing.M) {
|
|||||||
// 2. Get the connection string dynamically
|
// 2. Get the connection string dynamically
|
||||||
endpoint, _ := mongoContainer.ConnectionString(ctx)
|
endpoint, _ := mongoContainer.ConnectionString(ctx)
|
||||||
|
|
||||||
|
mongoDebug := os.Getenv("DEBUG") != ""
|
||||||
|
|
||||||
Start(&MongoStartProps{
|
Start(&MongoStartProps{
|
||||||
MongoUri: endpoint,
|
MongoUri: endpoint,
|
||||||
MongoUser: user,
|
MongoUser: user,
|
||||||
MongoPass: pass,
|
MongoPass: pass,
|
||||||
|
ContextFields: []string{"account", "store"},
|
||||||
|
MongoDebugQuery: mongoDebug,
|
||||||
|
WithAudit: true,
|
||||||
})
|
})
|
||||||
|
|
||||||
// 3. Run tests
|
// 3. Run tests
|
||||||
|
|||||||
92
main_views.go
Normal file
92
main_views.go
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
package mongo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||||
|
"go.mongodb.org/mongo-driver/v2/mongo/options"
|
||||||
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CreateViews will create views for the given collection and definition.
|
||||||
|
func (c *MongoClient) CreateViews(db *mongo.Database, cdef *CollectionDefinition) bool {
|
||||||
|
if cdef == nil || cdef.Views == nil {
|
||||||
|
log.Printf("No definition for views found.")
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
viewCreated := false
|
||||||
|
|
||||||
|
for name, defVal := range cdef.Views {
|
||||||
|
|
||||||
|
// 1. Decode definition
|
||||||
|
v, err := bson.Marshal(defVal)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("failed to marshal %v", err)
|
||||||
|
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Take the raw representation
|
||||||
|
vRaw := bson.Raw(v)
|
||||||
|
if err := vRaw.Validate(); err != nil {
|
||||||
|
log.Printf("failed to validate bson raw: %v", err)
|
||||||
|
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
pipelineVal := vRaw.Lookup("pipeline")
|
||||||
|
pipelineArr, ok := pipelineVal.ArrayOK()
|
||||||
|
if !ok {
|
||||||
|
log.Printf("Unable to extract pipeline")
|
||||||
|
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
pipeline := mongo.Pipeline{}
|
||||||
|
|
||||||
|
successPipeline := true
|
||||||
|
pipelineValues, _ := pipelineArr.Values()
|
||||||
|
for _, o := range pipelineValues {
|
||||||
|
var stage bson.D
|
||||||
|
if err := bson.Unmarshal(o.Value, &stage); err != nil {
|
||||||
|
log.Printf("failed to unmarshal stage %v, %v", o, err)
|
||||||
|
|
||||||
|
successPipeline = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
pipeline = append(pipeline, stage)
|
||||||
|
}
|
||||||
|
|
||||||
|
if successPipeline == false {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Specify the Collation option to set a default collation for the view.
|
||||||
|
opts := options.CreateView().SetCollation(&options.Collation{
|
||||||
|
Locale: "en_US",
|
||||||
|
})
|
||||||
|
|
||||||
|
viewonVal := vRaw.Lookup("viewOn")
|
||||||
|
viewOn, ok := viewonVal.StringValueOK();
|
||||||
|
if !ok {
|
||||||
|
log.Printf("failed to find viewOn")
|
||||||
|
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
err = db.CreateView(context.TODO(), name, viewOn, pipeline, opts)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("failed to create view %v", err)
|
||||||
|
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
viewCreated = true
|
||||||
|
}
|
||||||
|
|
||||||
|
return viewCreated
|
||||||
|
}
|
||||||
61
main_views_test.go
Normal file
61
main_views_test.go
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package mongo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"context"
|
||||||
|
"strings"
|
||||||
|
"encoding/json"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCreateViews(t *testing.T) {
|
||||||
|
// 1. Register schemas
|
||||||
|
schemaPerson, err := os.ReadFile("./.test/person.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
schemaActivity, err := os.ReadFile("./.test/activity.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
var person bson.M
|
||||||
|
if err := json.Unmarshal(schemaPerson, &person); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaPerson), schemaPerson[:4])
|
||||||
|
}
|
||||||
|
|
||||||
|
var activity bson.M
|
||||||
|
if err := json.Unmarshal(schemaActivity, &activity); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaActivity), schemaActivity[:4])
|
||||||
|
}
|
||||||
|
|
||||||
|
client := GetMongoClient()
|
||||||
|
client.AddDefinition(person)
|
||||||
|
client.AddDefinition(activity)
|
||||||
|
|
||||||
|
// 2. Insert data
|
||||||
|
p1 := map[string]any {
|
||||||
|
"name": "MyName112",
|
||||||
|
"age": int32(25),
|
||||||
|
}
|
||||||
|
|
||||||
|
o, err := client.InsertOne(context.Background(), "mydb", "person", p1)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
a1 := map[string]any {
|
||||||
|
"name": "Main activity",
|
||||||
|
"person": o["_id"],
|
||||||
|
}
|
||||||
|
|
||||||
|
o, err = client.InsertOne(context.Background(), "mydb", "activity", a1)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
// 3. Should have activityExpanded defined, let's query it.
|
||||||
|
var results bson.M
|
||||||
|
filter := map[string]any { "person.name": "MyName112" }
|
||||||
|
c := client.Client.Database("mydb").Collection("activityExpanded")
|
||||||
|
c.FindOne(context.Background(), filter).Decode(&results)
|
||||||
|
|
||||||
|
if !strings.HasPrefix(results["_id"].(string), "act_") {
|
||||||
|
t.Fatal("_id should have been prefixed")
|
||||||
|
}
|
||||||
|
}
|
||||||
35
options/deleteoneoptions.go
Normal file
35
options/deleteoneoptions.go
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
package options
|
||||||
|
|
||||||
|
type DeleteAudit struct {
|
||||||
|
Id string
|
||||||
|
Before any
|
||||||
|
Context any
|
||||||
|
}
|
||||||
|
|
||||||
|
type OnDeleteAudit func(audit *DeleteAudit)
|
||||||
|
|
||||||
|
type DeleteOneOptions struct {
|
||||||
|
OnDeleteAudit *OnDeleteAudit
|
||||||
|
}
|
||||||
|
|
||||||
|
type DeleteOneOptionsBuilder struct {
|
||||||
|
Opts []func(*DeleteOneOptions) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func DeleteOne() *DeleteOneOptionsBuilder{
|
||||||
|
return &DeleteOneOptionsBuilder{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (dao *DeleteOneOptionsBuilder) List() []func(*DeleteOneOptions) error {
|
||||||
|
return dao.Opts
|
||||||
|
}
|
||||||
|
|
||||||
|
func (dao *DeleteOneOptionsBuilder) WithOnDeleteAudit(oa *OnDeleteAudit) *DeleteOneOptionsBuilder {
|
||||||
|
dao.Opts = append(dao.Opts, func(opts *DeleteOneOptions) error {
|
||||||
|
opts.OnDeleteAudit = oa
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return dao
|
||||||
|
}
|
||||||
5
options/lister.go
Normal file
5
options/lister.go
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
package options
|
||||||
|
|
||||||
|
type Lister[T any] interface {
|
||||||
|
List() []func(*T) error
|
||||||
|
}
|
||||||
14
pipeline.go
14
pipeline.go
@@ -5,14 +5,11 @@ import (
|
|||||||
"go.mongodb.org/mongo-driver/v2/mongo"
|
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||||
)
|
)
|
||||||
|
|
||||||
func BuildPaginationPipeline(skip, limit int64, filter bson.M, sort bson.M) mongo.Pipeline {
|
func BuildPaginationPipeline(skip, limit int64, filter bson.M, sort bson.D) mongo.Pipeline {
|
||||||
return mongo.Pipeline{
|
pipe := mongo.Pipeline{
|
||||||
// 1. GLOBAL FILTER: Always filter first to use indexes
|
// 1. GLOBAL FILTER: Always filter first to use indexes
|
||||||
{{Key: "$match", Value: filter}},
|
{{Key: "$match", Value: filter}},
|
||||||
|
|
||||||
// 2. GLOBAL SORT: Sort here so both 'total' and 'data' facets use the same order
|
|
||||||
{{Key: "$sort", Value: sort}},
|
|
||||||
|
|
||||||
// 3. FACET: Split the pipeline into two parallel paths
|
// 3. FACET: Split the pipeline into two parallel paths
|
||||||
{{Key: "$facet", Value: bson.D{
|
{{Key: "$facet", Value: bson.D{
|
||||||
// Path A: Get the total count of documents matching the filter
|
// Path A: Get the total count of documents matching the filter
|
||||||
@@ -26,6 +23,13 @@ func BuildPaginationPipeline(skip, limit int64, filter bson.M, sort bson.M) mong
|
|||||||
}},
|
}},
|
||||||
}}},
|
}}},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 2. GLOBAL SORT: Sort here so both 'total' and 'data' facets use the same order
|
||||||
|
if sort != nil && len(sort) > 0 {
|
||||||
|
pipe = append(pipe, bson.D{{Key: "$sort", Value: sort}})
|
||||||
|
}
|
||||||
|
|
||||||
|
return pipe
|
||||||
}
|
}
|
||||||
|
|
||||||
func BuildPaginationPipelineNext(limit int64, filter bson.M, sort bson.M) mongo.Pipeline {
|
func BuildPaginationPipelineNext(limit int64, filter bson.M, sort bson.M) mongo.Pipeline {
|
||||||
|
|||||||
68
replace.go
Normal file
68
replace.go
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
package mongo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"slices"
|
||||||
|
|
||||||
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
|
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||||
|
|
||||||
|
"git.gsuntres.com/general/commons"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (c *MongoClient) Replace(ctx context.Context, database, name string, id string, original bson.M) (bson.M, error) {
|
||||||
|
collection := c.GetCollection(database, name)
|
||||||
|
|
||||||
|
data := commons.BsonClone(original)
|
||||||
|
|
||||||
|
filter := map[string]any { "_id": id }
|
||||||
|
|
||||||
|
var found bson.M
|
||||||
|
err := collection.FindOne(ctx, filter).Decode(&found)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
prepareForReplace(data, found)
|
||||||
|
|
||||||
|
if err := c.DiscriminatorCheckAndApplyToData(ctx, name, data); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
updateResult, err := collection.ReplaceOne(ctx, filter, data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
PostReplace(updateResult, data, id)
|
||||||
|
|
||||||
|
ignoreAudit := slices.Contains(c.IgnoreAudit, name)
|
||||||
|
|
||||||
|
if c.WithAudit && !ignoreAudit {
|
||||||
|
contx := commons.ContextSerialize(ctx, c.ContextFields)
|
||||||
|
audit := &AuditResult {
|
||||||
|
Entity: name,
|
||||||
|
Op: OpUpdate,
|
||||||
|
Data: original,
|
||||||
|
Before: found,
|
||||||
|
After: data,
|
||||||
|
Context: contx,
|
||||||
|
}
|
||||||
|
|
||||||
|
(*c.OnAudit)(audit)
|
||||||
|
}
|
||||||
|
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func PostReplace(updateResult *mongo.UpdateResult, data bson.M, id string) {
|
||||||
|
if updateResult.ModifiedCount == 1 {
|
||||||
|
data["_id"] = id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func prepareForReplace(data bson.M, old bson.M) {
|
||||||
|
ensureNoId(data)
|
||||||
|
ensureUpdatedAt(data)
|
||||||
|
ensureExistingCreatedAt(data, old)
|
||||||
|
}
|
||||||
265
replace_test.go
Normal file
265
replace_test.go
Normal file
@@ -0,0 +1,265 @@
|
|||||||
|
package mongo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"fmt"
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestReplace(t *testing.T) {
|
||||||
|
data := map[string]any {
|
||||||
|
"_id": "su_2b3c00",
|
||||||
|
"name": "Ava Thompson",
|
||||||
|
"age": int32(26),
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
// Insert to mycollection
|
||||||
|
o, err := client.InsertOne(ctx, "mydb", "mycollection", data)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
id := o["_id"].(string)
|
||||||
|
|
||||||
|
// Retrieve from mycollection
|
||||||
|
fetched, err := client.GetOne(ctx, "mydb", "mycollection", id)
|
||||||
|
if err != nil { t.Fatalf("Failed to fetch %#v", err) }
|
||||||
|
|
||||||
|
fetched["name"] = "Noah Patel"
|
||||||
|
|
||||||
|
|
||||||
|
// Replace in mycollection
|
||||||
|
replaced, err := client.Replace(ctx, "mydb", "mycollection", id, fetched)
|
||||||
|
if err != nil { t.Fatalf("Failed to replace %#v", err) }
|
||||||
|
|
||||||
|
if replaced["_id"] != fetched["_id"] {
|
||||||
|
t.Fatalf("Not the same entity")
|
||||||
|
}
|
||||||
|
|
||||||
|
if replaced["name"] != "Noah Patel" {
|
||||||
|
t.Fatal("unexpected name")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make sure discrimination field is used when replacing.
|
||||||
|
func TestReplace_Discrimination(t *testing.T) {
|
||||||
|
// 1. Register schemas
|
||||||
|
schemaStore, err := os.ReadFile("./.test/store.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
schemaOffer, err := os.ReadFile("./.test/offer.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
var store bson.M
|
||||||
|
if err := json.Unmarshal(schemaStore, &store); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaStore), schemaStore[:4])
|
||||||
|
}
|
||||||
|
|
||||||
|
var offer bson.M
|
||||||
|
if err := json.Unmarshal(schemaOffer, &offer); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaOffer), schemaOffer[:4])
|
||||||
|
}
|
||||||
|
|
||||||
|
client := GetMongoClient()
|
||||||
|
client.AddDefinition(store)
|
||||||
|
client.AddDefinition(offer)
|
||||||
|
|
||||||
|
// Save data
|
||||||
|
ctx1 := context.Background()
|
||||||
|
ctx1 = context.WithValue(ctx1, "account", "xxxxxx")
|
||||||
|
ctx1 = context.WithValue(ctx1, "store", "str_1234")
|
||||||
|
|
||||||
|
// Save offer
|
||||||
|
offer1 := map[string]any { "name": "OSRAM 10" }
|
||||||
|
saved, err := client.InsertOne(ctx1, "mydb", "offer", offer1)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
id := saved["_id"].(string)
|
||||||
|
|
||||||
|
// // Now replace it
|
||||||
|
saved["name"] = "** OSRAM 10 CHANGED **"
|
||||||
|
replaced, err := client.Replace(ctx1, "mydb", "offer", id, saved)
|
||||||
|
if err != nil { t.Fatalf("Failed to replace %#v", err) }
|
||||||
|
|
||||||
|
if replaced["name"] != "** OSRAM 10 CHANGED **" {
|
||||||
|
t.Fatal("Unexpected replaced object")
|
||||||
|
}
|
||||||
|
|
||||||
|
found, err := client.GetOne(ctx1, "mydb", "offer", id)
|
||||||
|
if err != nil { t.Fatalf("Failed to find %#v", err) }
|
||||||
|
|
||||||
|
if found["name"] != "** OSRAM 10 CHANGED **" {
|
||||||
|
t.Fatal("Updates did not persist")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReplace_Discrimination_NoStore(t *testing.T) {
|
||||||
|
// 1. Register schemas
|
||||||
|
schemaStore, err := os.ReadFile("./.test/store.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
schemaOffer, err := os.ReadFile("./.test/offer.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
var store bson.M
|
||||||
|
if err := json.Unmarshal(schemaStore, &store); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaStore), schemaStore[:4])
|
||||||
|
}
|
||||||
|
|
||||||
|
var offer bson.M
|
||||||
|
if err := json.Unmarshal(schemaOffer, &offer); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaOffer), schemaOffer[:4])
|
||||||
|
}
|
||||||
|
|
||||||
|
client := GetMongoClient()
|
||||||
|
client.AddDefinition(store)
|
||||||
|
client.AddDefinition(offer)
|
||||||
|
|
||||||
|
// Save data
|
||||||
|
ctx1 := context.Background()
|
||||||
|
ctx1 = context.WithValue(ctx1, "store", "str_1234")
|
||||||
|
|
||||||
|
// Save offer
|
||||||
|
offer1 := map[string]any { "name": "OSRAM 11" }
|
||||||
|
saved, err := client.InsertOne(ctx1, "mydb", "offer", offer1)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
id := saved["_id"].(string)
|
||||||
|
|
||||||
|
// // Now replace it
|
||||||
|
saved["name"] = "** OSRAM 11 CHANGED **"
|
||||||
|
_, err = client.Replace(context.Background(), "mydb", "offer", id, saved)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("should have required store")
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// Should save the right store regardless of the input
|
||||||
|
func TestReplace_Discrimination_EnsureStore(t *testing.T) {
|
||||||
|
// 1. Register schemas
|
||||||
|
schemaStore, err := os.ReadFile("./.test/store.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
schemaOffer, err := os.ReadFile("./.test/offer.json")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
var store bson.M
|
||||||
|
if err := json.Unmarshal(schemaStore, &store); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaStore), schemaStore[:4])
|
||||||
|
}
|
||||||
|
|
||||||
|
var offer bson.M
|
||||||
|
if err := json.Unmarshal(schemaOffer, &offer); err != nil {
|
||||||
|
t.Fatalf("Length: %d, First bytes: %x\n", len(schemaOffer), schemaOffer[:4])
|
||||||
|
}
|
||||||
|
|
||||||
|
client := GetMongoClient()
|
||||||
|
client.AddDefinition(store)
|
||||||
|
client.AddDefinition(offer)
|
||||||
|
|
||||||
|
// Save data
|
||||||
|
ctx1 := context.Background()
|
||||||
|
ctx1 = context.WithValue(ctx1, "store", "str_1234")
|
||||||
|
|
||||||
|
// Save offer
|
||||||
|
offer1 := map[string]any { "name": "OSRAM 12" }
|
||||||
|
saved, err := client.InsertOne(ctx1, "mydb", "offer", offer1)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
id := saved["_id"].(string)
|
||||||
|
|
||||||
|
// // Now replace it
|
||||||
|
saved["store"] = "str_0000"
|
||||||
|
changed, err := client.Replace(ctx1, "mydb", "offer", id, saved)
|
||||||
|
if err != nil { t.Fatalf("Failed to replace %v", err) }
|
||||||
|
if changed["store"] != "str_1234" {
|
||||||
|
t.Fatal("Should have ensured store")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReplace_WithAudit(t *testing.T) {
|
||||||
|
client := GetMongoClient()
|
||||||
|
|
||||||
|
// Insert sample
|
||||||
|
data := map[string]any {
|
||||||
|
"_id": "su_123458",
|
||||||
|
"name": "MyNameTODelete",
|
||||||
|
"age": int32(25),
|
||||||
|
}
|
||||||
|
|
||||||
|
before, err := client.InsertOne(context.Background(), "mydb", "mycollection", data)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
var (
|
||||||
|
onAudit_calls int
|
||||||
|
onAudit_data any
|
||||||
|
onAudit_before any
|
||||||
|
onAudit_after any
|
||||||
|
onAudit_context any
|
||||||
|
)
|
||||||
|
|
||||||
|
cancel := client.Subscribe(func(audit *AuditResult) error {
|
||||||
|
onAudit_calls++
|
||||||
|
onAudit_data = audit.Data
|
||||||
|
onAudit_before = audit.Before
|
||||||
|
onAudit_after = audit.After
|
||||||
|
onAudit_context = audit.Context
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
toupdate := map[string]any { "name": "** CHANGED NAME **" }
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
ctx = context.WithValue(ctx, "account", "xxxxxx")
|
||||||
|
ctx = context.WithValue(ctx, "store", "str_4321")
|
||||||
|
o, err := client.Replace(ctx, "mydb", "mycollection", "su_123458", toupdate)
|
||||||
|
if err != nil { t.Fatalf("Failed to replace %#v", err) }
|
||||||
|
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
if onAudit_calls != 1 {
|
||||||
|
t.Fatalf("ondelete should have been called once, not %d", onAudit_calls)
|
||||||
|
}
|
||||||
|
|
||||||
|
if onAudit_data != nil {
|
||||||
|
dta := onAudit_data.(bson.M)
|
||||||
|
AssertSubset(t, dta, toupdate, "Should have been equal")
|
||||||
|
} else {
|
||||||
|
t.Fatal("should have data")
|
||||||
|
}
|
||||||
|
|
||||||
|
if onAudit_before != nil {
|
||||||
|
bf := onAudit_before.(bson.M)
|
||||||
|
AssertSubset(t, bf, before, "Should have been equal")
|
||||||
|
} else {
|
||||||
|
t.Fatal("should have before")
|
||||||
|
}
|
||||||
|
|
||||||
|
if onAudit_after != nil {
|
||||||
|
tp := fmt.Sprintf("%T", onAudit_after)
|
||||||
|
|
||||||
|
expectedType := fmt.Sprintf("%T", map[string]any{})
|
||||||
|
if tp != expectedType {
|
||||||
|
t.Fatalf("after has the wrong type %s", tp)
|
||||||
|
}
|
||||||
|
|
||||||
|
after := onAudit_after.(map[string]any)
|
||||||
|
|
||||||
|
AssertSubset(t, after, o, "Should have been equal")
|
||||||
|
} else {
|
||||||
|
t.Fatal("should have after")
|
||||||
|
}
|
||||||
|
|
||||||
|
if onAudit_context != nil {
|
||||||
|
ctx := onAudit_context.(map[string]any)
|
||||||
|
AssertSubset(t, ctx, map[string]any{"account": "xxxxxx", "store": "str_4321"}, "Should have been equal")
|
||||||
|
} else {
|
||||||
|
t.Fatal("should have context")
|
||||||
|
}
|
||||||
|
}
|
||||||
70
update_set.go
Normal file
70
update_set.go
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
package mongo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"slices"
|
||||||
|
|
||||||
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
|
"git.gsuntres.com/general/commons"
|
||||||
|
)
|
||||||
|
|
||||||
|
// UpdateSet search documents using filter and updates the first it finds using the $set operator.
|
||||||
|
func (c *MongoClient) UpdateSet(ctx context.Context, database, name string, filter, original bson.M) (bool, error) {
|
||||||
|
collection := c.GetCollection(database, name)
|
||||||
|
|
||||||
|
data := commons.BsonClone(original)
|
||||||
|
|
||||||
|
prepareForUpdateSet(data)
|
||||||
|
|
||||||
|
if err := c.DiscriminatorCheckAndApplyToFilter(ctx, name, filter); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
f := Mongofy(&Query{ Filter: filter })
|
||||||
|
|
||||||
|
if err := c.DiscriminatorOmitInData(name, data); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var found bson.M
|
||||||
|
if c.WithAudit {
|
||||||
|
if err := collection.FindOne(ctx, f).Decode(&found); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
update := bson.M{ "$set": data }
|
||||||
|
updateResult, err := collection.UpdateOne(ctx, f, update)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
changed := updateResult.ModifiedCount != 0
|
||||||
|
|
||||||
|
ignoreAudit := slices.Contains(c.IgnoreAudit, name)
|
||||||
|
|
||||||
|
if changed && c.WithAudit && !ignoreAudit {
|
||||||
|
var after bson.M
|
||||||
|
if err := collection.FindOne(ctx, f).Decode(&after); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
contx := commons.ContextSerialize(ctx, c.ContextFields)
|
||||||
|
audit := &AuditResult {
|
||||||
|
Entity: name,
|
||||||
|
Op: OpUpdate,
|
||||||
|
Data: original,
|
||||||
|
Before: found,
|
||||||
|
After: after,
|
||||||
|
Context: contx,
|
||||||
|
}
|
||||||
|
|
||||||
|
(*c.OnAudit)(audit)
|
||||||
|
}
|
||||||
|
|
||||||
|
return changed, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func prepareForUpdateSet(data bson.M) {
|
||||||
|
ensureUpdatedAt(data)
|
||||||
|
}
|
||||||
97
update_set_test.go
Normal file
97
update_set_test.go
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
package mongo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUpdateSet_WithAudit(t *testing.T) {
|
||||||
|
client := GetMongoClient()
|
||||||
|
|
||||||
|
// Insert sample
|
||||||
|
data := map[string]any {
|
||||||
|
"_id": "su_122258",
|
||||||
|
"name": "MyNameToUpdateSet",
|
||||||
|
"age": int32(25),
|
||||||
|
}
|
||||||
|
|
||||||
|
before, err := client.InsertOne(context.Background(), "mydb", "mycollection", data)
|
||||||
|
if err != nil { t.Fatalf("Failed to insertOne %#v", err) }
|
||||||
|
|
||||||
|
var (
|
||||||
|
onAudit_calls int
|
||||||
|
onAudit_data any
|
||||||
|
onAudit_before any
|
||||||
|
onAudit_after any
|
||||||
|
onAudit_context any
|
||||||
|
)
|
||||||
|
|
||||||
|
cancel := client.Subscribe(func(audit *AuditResult) error {
|
||||||
|
onAudit_calls++
|
||||||
|
onAudit_data = audit.Data
|
||||||
|
onAudit_before = audit.Before
|
||||||
|
onAudit_after = audit.After
|
||||||
|
onAudit_context = audit.Context
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
toupdate := map[string]any { "name": "** CHANGED USING UPDATE SET **" }
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
ctx = context.WithValue(ctx, "account", "xxxxxx")
|
||||||
|
ctx = context.WithValue(ctx, "store", "str_4321")
|
||||||
|
ok, err := client.UpdateSet(ctx, "mydb", "mycollection", bson.M{"_id": "su_122258"}, toupdate)
|
||||||
|
if err != nil { t.Fatalf("Failed to update %#v", err) }
|
||||||
|
|
||||||
|
if !ok { t.Fatal("Should have updated") }
|
||||||
|
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
if onAudit_calls != 1 {
|
||||||
|
t.Fatalf("ondelete should have been called once, not %d", onAudit_calls)
|
||||||
|
}
|
||||||
|
|
||||||
|
if onAudit_data != nil {
|
||||||
|
dta := onAudit_data.(bson.M)
|
||||||
|
AssertSubset(t, dta, toupdate, "Should have been equal")
|
||||||
|
} else {
|
||||||
|
t.Fatal("should have data")
|
||||||
|
}
|
||||||
|
|
||||||
|
if onAudit_before != nil {
|
||||||
|
bf := onAudit_before.(bson.M)
|
||||||
|
AssertSubset(t, bf, before, "Should have been equal")
|
||||||
|
} else {
|
||||||
|
t.Fatal("should have before")
|
||||||
|
}
|
||||||
|
|
||||||
|
if onAudit_after != nil {
|
||||||
|
tp := fmt.Sprintf("%T", onAudit_after)
|
||||||
|
|
||||||
|
expectedType := fmt.Sprintf("%T", bson.M{})
|
||||||
|
if tp != expectedType {
|
||||||
|
t.Fatalf("after has the wrong type %s", tp)
|
||||||
|
}
|
||||||
|
|
||||||
|
after := onAudit_after.(bson.M)
|
||||||
|
|
||||||
|
before["name"] = "** CHANGED USING UPDATE SET **"
|
||||||
|
delete(before, "updatedAt")
|
||||||
|
delete(after, "updatedAt")
|
||||||
|
|
||||||
|
AssertSubset(t, after, before, "Should have been equal")
|
||||||
|
} else {
|
||||||
|
t.Fatal("should have after")
|
||||||
|
}
|
||||||
|
|
||||||
|
if onAudit_context != nil {
|
||||||
|
ctx := onAudit_context.(map[string]any)
|
||||||
|
AssertSubset(t, ctx, map[string]any{"account": "xxxxxx", "store": "str_4321"}, "Should have been equal")
|
||||||
|
} else {
|
||||||
|
t.Fatal("should have context")
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user